text:
/*******************************************************************************
 * INCLUDES
 */
#include "ZComDef.h"
#include "OSAL.h"
#include "zcl.h"
#include "zcl_general.h"
#include "zcl_ss.h"

#if defined ( INTER_PAN )
  #include "stub_aps.h"
#endif

/*******************************************************************************
 * MACROS
 */
#define zclSS_ZoneTypeSupported( a ) ( (a) == SS_IAS_ZONE_TYPE_STANDARD_CIE              || \
                                       (a) == SS_IAS_ZONE_TYPE_MOTION_SENSOR             || \
                                       (a) == SS_IAS_ZONE_TYPE_CONTACT_SWITCH            || \
                                       (a) == SS_IAS_ZONE_TYPE_FIRE_SENSOR               || \
                                       (a) == SS_IAS_ZONE_TYPE_WATER_SENSOR              || \
                                       (a) == SS_IAS_ZONE_TYPE_GAS_SENSOR                || \
                                       (a) == SS_IAS_ZONE_TYPE_PERSONAL_EMERGENCY_DEVICE || \
                                       (a) == SS_IAS_ZONE_TYPE_VIBRATION_MOVEMENT_SENSOR || \
                                       (a) == SS_IAS_ZONE_TYPE_REMOTE_CONTROL            || \
                                       (a) == SS_IAS_ZONE_TYPE_KEY_FOB                   || \
                                       (a) == SS_IAS_ZONE_TYPE_KEYPAD                    || \
                                       (a) == SS_IAS_ZONE_TYPE_STANDARD_WARNING_DEVICE )

/*******************************************************************************
 * CONSTANTS
 */

/*******************************************************************************
 * TYPEDEFS
 */
typedef struct zclSSCBRec
{
  struct zclSSCBRec       *next;
  uint8                   endpoint; // Used to link it into the endpoint descriptor
  zclSS_AppCallbacks_t    *CBs;     // Pointer to Callback function
} zclSSCBRec_t;

typedef struct zclSS_ZoneItem
{
  struct zclSS_ZoneItem   *next;
  uint8                   endpoint; // Used to link it into the endpoint descriptor
  IAS_ACE_ZoneTable_t     zone;     // Zone info
} zclSS_ZoneItem_t;

/*******************************************************************************
 * GLOBAL VARIABLES
 */
const uint8 zclSS_UknownIeeeAddress[8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };

/*******************************************************************************
 * GLOBAL FUNCTIONS
 */

/*******************************************************************************
 * LOCAL VARIABLES
 */
static zclSSCBRec_t *zclSSCBs = (zclSSCBRec_t *)NULL;
static uint8 zclSSPluginRegisted = FALSE;

#if defined(ZCL_ZONE) || defined(ZCL_ACE)
static zclSS_ZoneItem_t *zclSS_ZoneTable = (zclSS_ZoneItem_t *)NULL;
#endif // ZCL_ZONE || ZCL_ACE

/*******************************************************************************
 * LOCAL FUNCTIONS
 */
static ZStatus_t zclSS_HdlIncoming( zclIncoming_t *pInHdlrMsg );
static ZStatus_t zclSS_HdlInSpecificCommands( zclIncoming_t *pInMsg );
static zclSS_AppCallbacks_t *zclSS_FindCallbacks( uint8 endpoint );

#ifdef ZCL_ZONE
static ZStatus_t zclSS_ProcessInZoneStatusCmdsServer( zclIncoming_t *pInMsg, zclSS_AppCallbacks_t *pCBs );
static ZStatus_t zclSS_ProcessInZoneStatusCmdsClient( zclIncoming_t *pInMsg, zclSS_AppCallbacks_t *pCBs );

static void zclSS_ProcessInCmd_ZoneStatus_ChangeNotification( zclIncoming_t *pInMsg, zclSS_AppCallbacks_t *pCBs );
static ZStatus_t zclSS_ProcessInCmd_ZoneStatus_EnrollRequest( zclIncoming_t *pInMsg, zclSS_AppCallbacks_t *pCBs );
static void zclSS_ProcessInCmd_ZoneStatus_EnrollResponse( zclIncoming_t *pInMsg, zclSS_AppCallbacks_t *pCBs );
#endif // ZCL_ZONE

#ifdef ZCL_ACE
static ZStatus_t zclSS_ProcessInACECmdsServer( zclIncoming_t *pInMsg, zclSS_AppCallbacks_t *pCBs );
static ZStatus_t zclSS_ProcessInACECmdsClient( zclIncoming_t *pInMsg, zclSS_AppCallbacks_t *pCBs );

static ZStatus_t zclSS_ProcessInCmd_ACE_Arm( zclIncoming_t *pInMsg, zclSS_AppCallbacks_t *pCBs );
static void zclSS_ProcessInCmd_ACE_Bypass( zclIncoming_t *pInMsg, zclSS_AppCallbacks_t *pCBs );
static void zclSS_ProcessInCmd_ACE_Emergency( zclIncoming_t *pInMsg, zclSS_AppCallbacks_t *pCBs );
static void zclSS_ProcessInCmd_ACE_Fire( zclIncoming_t *pInMsg, zclSS_AppCallbacks_t *pCBs );
static void zclSS_ProcessInCmd_ACE_Panic( zclIncoming_t *pInMsg, zclSS_AppCallbacks_t *pCBs );
static ZStatus_t zclSS_ProcessInCmd_ACE_GetZoneIDMap( zclIncoming_t *pInMsg );
static ZStatus_t zclSS_ProcessInCmd_ACE_GetZoneInformation( zclIncoming_t *pInMsg );
static void zclSS_ProcessInCmd_ACE_ArmResponse( zclIncoming_t *pInMsg, zclSS_AppCallbacks_t *pCBs );
static void zclSS_ProcessInCmd_ACE_GetZoneIDMapResponse( zclIncoming_t *pInMsg, zclSS_AppCallbacks_t *pCBs );
static void zclSS_ProcessInCmd_ACE_GetZoneInformationResponse( zclIncoming_t *pInMsg, zclSS_AppCallbacks_t *pCBs );
#endif // ZCL_ACE

#ifdef ZCL_WD
static ZStatus_t zclSS_ProcessInWDCmds( zclIncoming_t *pInMsg, zclSS_AppCallbacks_t *pCBs );

static void zclSS_ProcessInCmd_WD_StartWarning( zclIncoming_t *pInMsg, zclSS_AppCallbacks_t *pCBs );
static void zclSS_ProcessInCmd_WD_Squawk( zclIncoming_t *pInMsg, zclSS_AppCallbacks_t *pCBs );
#endif // ZCL_WD

#ifdef ZCL_ZONE
static uint8 zclSS_GetNextFreeZoneID( void );
static ZStatus_t zclSS_AddZone( uint8 endpoint, IAS_ACE_ZoneTable_t *zone );
static uint8 zclSS_CountAllZones( void );
static uint8 zclSS_ZoneIDAvailable( uint8 zoneID );
#endif // ZCL_ZONE

#if defined(ZCL_ZONE) || defined(ZCL_ACE)
static IAS_ACE_ZoneTable_t *zclSS_FindZone( uint8 endpoint, uint8 zoneID );
#endif // ZCL_ZONE || ZCL_ACE

/******************************************************************************
 * @fn      zclSS_RegisterCmdCallbacks
 *
 * @brief   Register an applications command callbacks
 *
 * @param   endpoint - application's endpoint
 * @param   callbacks - pointer to the callback record.
 *
 * @return  ZMemError if not able to allocate
 */
ZStatus_t zclSS_RegisterCmdCallbacks( uint8 endpoint, zclSS_AppCallbacks_t *callbacks )
{
  zclSSCBRec_t *pNewItem;
  zclSSCBRec_t *pLoop;

  // Register as a ZCL Plugin
  if ( !zclSSPluginRegisted )
  {
    zcl_registerPlugin( ZCL_CLUSTER_ID_SS_IAS_ZONE,
                        ZCL_CLUSTER_ID_SS_IAS_WD,
                        zclSS_HdlIncoming );
    zclSSPluginRegisted = TRUE;
  }

  // Fill in the new profile list
  pNewItem = osal_mem_alloc( sizeof( zclSSCBRec_t ) );
  if ( pNewItem == NULL )
    return (ZMemError);

  pNewItem->next = (zclSSCBRec_t *)NULL;
  pNewItem->endpoint = endpoint;
  pNewItem->CBs = callbacks;

  // Find spot in list
  if ( zclSSCBs == NULL )
  {
    zclSSCBs = pNewItem;
  }
  else
  {
    // Look for end of list
    pLoop = zclSSCBs;
    while ( pLoop->next != NULL )
      pLoop = pLoop->next;

    // Put new item at end of list
    pLoop->next = pNewItem;
  }
  return ( ZSuccess );
}

#ifdef ZCL_ZONE
/*******************************************************************************
 * @fn      zclSS_Send_IAS_ZoneStatusChangeNotificationCmd
 *
 * @brief   Call to send out a Change Notification Command
 *
 * @param   srcEP - Sending application's endpoint
 * @param   dstAddr - where you want the message to go
 * @param   zoneStatus - current zone status - bit map
 * @param   extendedStatus - bit map, currently set to All zeros ( reserved)
 *
 * @return  ZStatus_t
 */
ZStatus_t zclSS_IAS_Send_ZoneStatusChangeNotificationCmd( uint8 srcEP, afAddrType_t *dstAddr,
                                       uint16 zoneStatus, uint8 extendedStatus,
                                       uint8 disableDefaultRsp, uint8 seqNum )
{
  uint8 buf[3];

  buf[0] = LO_UINT16( zoneStatus );
  buf[1] = HI_UINT16( zoneStatus );
  buf[2] = extendedStatus;

  return zcl_SendCommand( srcEP, dstAddr, ZCL_CLUSTER_ID_SS_IAS_ZONE,
                          COMMAND_SS_IAS_ZONE_STATUS_CHANGE_NOTIFICATION, TRUE,
                          ZCL_FRAME_SERVER_CLIENT_DIR, disableDefaultRsp, 0, seqNum, 3, buf );
}

/*******************************************************************************
 * @fn      zclSS_Send_IAS_ZoneStatusEnrollRequestCmd
 *
 * @brief   Call to send out a Enroll Request Command
 *
 * @param   srcEP - Sending application's endpoint
 * @param   dstAddr - where you want the message to go
 * @param   zoneType - 	  current value of Zone Type attribute
 * @param   manufacturerCode - manuf. code from node descriptor for the device
 *
 * @return  ZStatus_t
 */
ZStatus_t zclSS_IAS_Send_ZoneStatusEnrollRequestCmd( uint8 srcEP, afAddrType_t *dstAddr,
                                uint16 zoneType, uint16 manufacturerCode,
                                uint8 disableDefaultRsp, uint8 seqNum )
{
  uint8 buf[4];

  buf[0] = LO_UINT16( zoneType );
  buf[1] = HI_UINT16( zoneType );
  buf[2] = LO_UINT16( manufacturerCode );
  buf[3] = HI_UINT16( manufacturerCode );

  return zcl_SendCommand( srcEP, dstAddr, ZCL_CLUSTER_ID_SS_IAS_ZONE,
                          COMMAND_SS_IAS_ZONE_STATUS_ENROLL_REQUEST, TRUE,
                          ZCL_FRAME_SERVER_CLIENT_DIR, disableDefaultRsp, 0, seqNum, 4, buf );
}

/*******************************************************************************
 * @fn      zclSS_IAS_Send_ZoneStatusEnrollResponseCmd
 *
 * @brief   Call to send out a Enroll Response Command
 *
 * @param   srcEP - Sending application's endpoint
 * @param   dstAddr - where you want the message to go
 * @param   responseCode -  value of  response Code
 * @param   zoneID  - index to the zone table of the CIE
 *
 * @return  ZStatus_t
 */
ZStatus_t zclSS_IAS_Send_ZoneStatusEnrollResponseCmd( uint8 srcEP, afAddrType_t *dstAddr,
                                         uint8 responseCode, uint8 zoneID,
                                         uint8 disableDefaultRsp, uint8 seqNum )
{
  uint8 buf[2];

  buf[0] = responseCode;
  buf[1] = zoneID;

  return zcl_SendCommand( srcEP, dstAddr, ZCL_CLUSTER_ID_SS_IAS_ZONE,
                          COMMAND_SS_IAS_ZONE_STATUS_ENROLL_RESPONSE, TRUE,
                          ZCL_FRAME_CLIENT_SERVER_DIR, disableDefaultRsp, 0, seqNum, 2, buf );
}
#endif // ZCL_ZONE

#ifdef ZCL_ACE
/*******************************************************************************
 * @fn      zclSS_Send_IAS_ACE_ArmCmd
 *
 * @brief   Call to send out a Arm  Command  ( IAS ACE Cluster )
 *
 * @param   srcEP - Sending application's endpoint
 * @param   dstAddr - where you want the message to go
 * @param   armMode -  value of armMode
 *
 * @return  ZStatus_t
 */
ZStatus_t zclSS_Send_IAS_ACE_ArmCmd( uint8 srcEP, afAddrType_t *dstAddr,
                          uint8 armMode, uint8 disableDefaultRsp, uint8 seqNum )
{
  uint8 buf[1];

  buf[0] = armMode;

  return zcl_SendCommand( srcEP, dstAddr, ZCL_CLUSTER_ID_SS_IAS_ACE,
                          COMMAND_SS_IAS_ACE_ARM, TRUE,
                          ZCL_FRAME_CLIENT_SERVER_DIR, disableDefaultRsp, 0, seqNum, 1, buf );
}

/*********************************************************************
 * @fn      zclSS_Send_IAS_ACE_BypassCmd
 *
 * @brief   Call to send out a Bypass Command  ( IAS ACE Cluster )
 *
 * @param   srcEP - Sending application's endpoint
 * @param   dstAddr - where you want the message to go
 * @param   numberOfZones - one byte
 * @param   bypassBuf - zone IDs array of 256 entries one byte each
 *
 * @return  ZStatus_t
 */
ZStatus_t zclSS_Send_IAS_ACE_BypassCmd( uint8 srcEP, afAddrType_t *dstAddr,
                                        uint8 numberOfZones, uint8 *bypassBuf,
                                        uint8 disableDefaultRsp, uint8 seqNum )
{
  uint8 *buf;
  uint8 *pBuf;
  uint8 len = 1 + numberOfZones;
  ZStatus_t stat;

  buf = osal_mem_alloc( len );
  if ( buf )
  {
    pBuf = buf;

    *pBuf++ = numberOfZones;
    osal_memcpy( pBuf, bypassBuf, numberOfZones );

    stat = zcl_SendCommand( srcEP, dstAddr, ZCL_CLUSTER_ID_SS_IAS_ACE,
                            COMMAND_SS_IAS_ACE_BYPASS, TRUE,
                            ZCL_FRAME_CLIENT_SERVER_DIR, disableDefaultRsp, 0, seqNum, len, buf );
    osal_mem_free( buf );
  }
  else
    stat = ZFailure;

  return ( stat );
}

/*********************************************************************
 * @fn      zclSS_Send_IAS_ACE_GetZoneInformationCmd
 *
 * @brief   Call to send out a Get Zone Information Command ( IAS ACE Cluster )
 *
 * @param   srcEP - Sending application's endpoint
 * @param   dstAddr - where you want the message to go
 * @param   zoneID - 8 bit value from 0 to 255
 *
 * @return  ZStatus_t
 */
ZStatus_t zclSS_Send_IAS_ACE_GetZoneInformationCmd( uint8 srcEP, afAddrType_t *dstAddr,
                                  uint8 zoneID, uint8 disableDefaultRsp, uint8 seqNum )
{
  uint8 buf[1];

  buf[0] = zoneID;

  return zcl_SendCommand( srcEP, dstAddr, ZCL_CLUSTER_ID_SS_IAS_ACE,
                          COMMAND_SS_IAS_ACE_GET_ZONE_INFORMATION, TRUE,
                          ZCL_FRAME_CLIENT_SERVER_DIR, disableDefaultRsp, 0, seqNum, 1, buf );
}

/*******************************************************************************
 * @fn      zclSS_Send_IAS_ACE_ArmRespponse
 *
 * @brief   Call to send out a Arm Response Command ( IAS ACE Cluster )
 *
 * @param   srcEP - Sending application's endpoint
 * @param   dstAddr - where you want the message to go
 * @param   armNotification
 *
 * @return  ZStatus_t
 */
ZStatus_t zclSS_Send_IAS_ACE_ArmResponse( uint8 srcEP, afAddrType_t *dstAddr,
                  uint8 armNotification, uint8 disableDefaultRsp, uint8 seqNum )
{
  uint8 buf[1];

  buf[0] = armNotification;

  return zcl_SendCommand( srcEP, dstAddr, ZCL_CLUSTER_ID_SS_IAS_ACE,
                          COMMAND_SS_IAS_ACE_ARM_RESPONSE, TRUE,
                          ZCL_FRAME_SERVER_CLIENT_DIR, disableDefaultRsp, 0, seqNum, 1, buf );
}

/*********************************************************************
 * @fn      zclSS_Send_IAS_ACE_GetZoneIDMapResponseCmd
 *
 * @brief   Call to send out a Get Zone ID Map Response Cmd  ( IAS ACE Cluster )
 *
 * @param   srcEP - Sending application's endpoint
 * @param   dstAddr - where you want the message to go
 * @param   zoneIDMap - pointer to an array of 16 uint16
 *
 * @return  ZStatus_t
 */
ZStatus_t zclSS_Send_IAS_ACE_GetZoneIDMapResponseCmd( uint8 srcEP, afAddrType_t *dstAddr,
                                uint16 *zoneIDMap, uint8 disableDefaultRsp, uint8 seqNum )
{
  uint8 *buf;
  uint8 *pIndex;
  uint8 j,len = 32;
  ZStatus_t stat;

  buf = osal_mem_alloc( len );

  if ( buf )
  {
    pIndex = buf;

    for( j = 0; j < 16; j++ )
    {
      *pIndex++  = LO_UINT16( *zoneIDMap   );
      *pIndex++  = HI_UINT16( *zoneIDMap++ );
    }

    stat = zcl_SendCommand( srcEP, dstAddr, ZCL_CLUSTER_ID_SS_IAS_ACE,
                            COMMAND_SS_IAS_ACE_GET_ZONE_ID_MAP_RESPONSE, TRUE,
                            ZCL_FRAME_SERVER_CLIENT_DIR, disableDefaultRsp, 0, seqNum, len, buf );
    osal_mem_free( buf );
  }
  else
    stat = ZMemError;

  return ( stat );

}

/*******************************************************************************
 * @fn      zclSS_Send_IAS_ACE_GetZoneInformationResponseCmd
 *
 * @brief   Call to send out Get Zone Information Response Cmd (IAS ACE Cluster)
 *
 * @param   srcEP - Sending application's endpoint
 * @param   dstAddr - where you want the message to go
 * @param   zoneID - 8 bit value from 0 to 255
 * @param   zoneType - 16 bit
 * @param   ieeeAddress - pointer to 64 bit address ( 8bytes*8)
 *
 * @return  ZStatus_t
 */
ZStatus_t zclSS_Send_IAS_ACE_GetZoneInformationResponseCmd( uint8 srcEP, afAddrType_t *dstAddr,
                                             uint8 zoneID, uint16 zoneType, uint8 *ieeeAddress,
                                             uint8 disableDefaultRsp, uint8 seqNum )
{
  uint8 *buf;
  uint8 len = 11; // zoneID (1) + zoneType (2) + zoneAddress (8)
  ZStatus_t stat;

  buf = osal_mem_alloc( len );

  if ( buf )
  {
    buf[0] = zoneID;
    buf[1] = LO_UINT16( zoneType);
    buf[2] = HI_UINT16( zoneType);
    osal_cpyExtAddr( &buf[3], ieeeAddress );

    stat = zcl_SendCommand( srcEP, dstAddr, ZCL_CLUSTER_ID_SS_IAS_ACE,
                            COMMAND_SS_IAS_ACE_GET_ZONE_INFORMATION_RESPONSE, TRUE,
                            ZCL_FRAME_SERVER_CLIENT_DIR, disableDefaultRsp, 0, seqNum, len, buf );
    osal_mem_free( buf );
  }
  else
    stat = ZMemError;

  return ( stat );
}
#endif // ZCL_ACE

#ifdef ZCL_WD
/*******************************************************************************
 * @fn      zclSS_Send_IAS_WD_StartWarningCmd
 *
 * @brief   Call to send out a Start Warning  Command (IAS WD Cluster)
 *
 * @param   warning - 3 bytes  of type	zclCmdSSWDStartWarningPayload_t
 *
 * @return  ZStatus_t
 */
ZStatus_t zclSS_Send_IAS_WD_StartWarningCmd( uint8 srcEP, afAddrType_t *dstAddr,
                                       zclCmdSSWDStartWarningPayload_t *warning,
                                       uint8 disableDefaultRsp, uint8 seqNum )
{
  uint8 buf[3];

  buf[0] = warning->warningmessage.warningbyte;
  buf[1] = LO_UINT16( warning->duration );
  buf[2] = HI_UINT16( warning->duration );

  return zcl_SendCommand( srcEP, dstAddr, ZCL_CLUSTER_ID_SS_IAS_WD,
                          COMMAND_SS_IAS_WD_START_WARNING, TRUE,
                          ZCL_FRAME_CLIENT_SERVER_DIR, disableDefaultRsp, 0, seqNum, 3, buf );
}

/******************************************************************************
 * @fn      zclSS_Send_IAS_WD_StartWarningCmd
 *
 * @brief   Call to send out a Squawk Command  ( IAS WD Cluster )
 *
 * @param   squawk - one byte of type zclCmdSSWDSquawkPayload_t
 *
 * @return  ZStatus_t
 */
ZStatus_t zclSS_Send_IAS_WD_SquawkCmd( uint8 srcEP, afAddrType_t *dstAddr,
                                       zclCmdSSWDSquawkPayload_t *squawk,
                                       uint8 disableDefaultRsp, uint8 seqNum )
{
  uint8 buf[1];
  buf[0] = squawk->squawkbyte;

  return zcl_SendCommand( srcEP, dstAddr, ZCL_CLUSTER_ID_SS_IAS_WD,
                          COMMAND_SS_IAS_WD_SQUAWK, TRUE,
                          ZCL_FRAME_CLIENT_SERVER_DIR, disableDefaultRsp, 0, seqNum, 1, buf);
}
#endif // ZCL_WD

/*********************************************************************
 * @fn      zclSS_FindCallbacks
 *
 * @brief   Find the callbacks for an endpoint
 *
 * @param   endpoint
 *
 * @return  pointer to the callbacks
 */
static zclSS_AppCallbacks_t *zclSS_FindCallbacks( uint8 endpoint )
{
  zclSSCBRec_t *pCBs;

  pCBs = zclSSCBs;
  while ( pCBs )
  {
    if ( pCBs->endpoint == endpoint )
      return ( pCBs->CBs );
    pCBs = pCBs->next;
  }
  return ( (zclSS_AppCallbacks_t *)NULL );
}

/*********************************************************************
 * @fn      zclSS_HdlIncoming
 *
 * @brief   Callback from ZCL to process incoming Commands specific
 *          to this cluster library or Profile commands for attributes
 *          that aren't in the attribute list
 *
 * @param   pInMsg - pointer to the incoming message
 * @param   logicalClusterID
 *
 * @return  ZStatus_t
 */
static ZStatus_t zclSS_HdlIncoming( zclIncoming_t *pInMsg )
{
  ZStatus_t stat = ZSuccess;

#if defined ( INTER_PAN )
  if ( StubAPS_InterPan( pInMsg->msg->srcAddr.panId, pInMsg->msg->srcAddr.endPoint ) )
    return ( stat ); // Cluster not supported thru Inter-PAN
#endif
  if ( zcl_ClusterCmd( pInMsg->hdr.fc.type ) )
  {
    // Is this a manufacturer specific command?
    if ( pInMsg->hdr.fc.manuSpecific == 0 )
    {
      stat = zclSS_HdlInSpecificCommands( pInMsg );
    }
    else
    {
      // We don't support any manufacturer specific command -- ignore it.
      stat = ZFailure;
    }
  }
  else
  {
    // Handle all the normal (Read, Write...) commands
    stat = ZFailure;
  }
  return ( stat );
}

/*********************************************************************
 * @fn      zclSS_HdlInSpecificCommands
 *
 * @brief   Callback from ZCL to process incoming Commands specific
 *          to this cluster library

 * @param   pInMsg - pointer to the incoming message
 *
 * @return  ZStatus_t
 */
static ZStatus_t zclSS_HdlInSpecificCommands( zclIncoming_t *pInMsg )
{
  ZStatus_t stat = ZSuccess;
  zclSS_AppCallbacks_t *pCBs;

  // make sure endpoint exists
  pCBs = (void*)zclSS_FindCallbacks( pInMsg->msg->endPoint );
  if ( pCBs == NULL )
    return ( ZFailure );

  switch ( pInMsg->msg->clusterId )
  {
#ifdef ZCL_ZONE
    case ZCL_CLUSTER_ID_SS_IAS_ZONE:
      if ( zcl_ServerCmd( pInMsg->hdr.fc.direction ) )
        stat = zclSS_ProcessInZoneStatusCmdsServer( pInMsg, pCBs );
      else
        stat = zclSS_ProcessInZoneStatusCmdsClient( pInMsg, pCBs );
      break;
#endif // ZCL_ZONE

#ifdef ZCL_ACE
    case ZCL_CLUSTER_ID_SS_IAS_ACE:
      if ( zcl_ServerCmd( pInMsg->hdr.fc.direction ) )
        stat = zclSS_ProcessInACECmdsServer( pInMsg, pCBs );
      else
        stat = zclSS_ProcessInACECmdsClient( pInMsg, pCBs );
      break;
#endif // ZCL_ACE

#ifdef ZCL_WD
    case ZCL_CLUSTER_ID_SS_IAS_WD:
      stat = zclSS_ProcessInWDCmds( pInMsg, pCBs );
      break;
#endif // ZCL_WD

    default:
      stat = ZFailure;
      break;
  }

  return ( stat );
}

#ifdef ZCL_ZONE
/*********************************************************************
 * @fn      zclSS_ProcessInZoneStatusCmdsServer
 *
 * @brief   Callback from ZCL to process incoming Commands specific
 *          to this cluster library on a command ID basis

 * @param   pInMsg - pointer to the incoming message
 *
 * @return  ZStatus_t
 */
static ZStatus_t zclSS_ProcessInZoneStatusCmdsServer( zclIncoming_t *pInMsg,
                                                      zclSS_AppCallbacks_t *pCBs )
{
  ZStatus_t stat = ZSuccess;

  if ( pInMsg->hdr.commandID == COMMAND_SS_IAS_ZONE_STATUS_ENROLL_RESPONSE )
    zclSS_ProcessInCmd_ZoneStatus_EnrollResponse( pInMsg, pCBs );
  else
    stat = ZFailure;

  return ( stat );
}

/*********************************************************************
 * @fn      zclSS_ProcessInZoneStatusCmdsClient
 *
 * @brief   Callback from ZCL to process incoming Commands specific
 *          to this cluster library on a command ID basis

 * @param   pInMsg - pointer to the incoming message
 *
 * @return  ZStatus_t
 */
static ZStatus_t zclSS_ProcessInZoneStatusCmdsClient( zclIncoming_t *pInMsg,
                                                      zclSS_AppCallbacks_t *pCBs )
{
  ZStatus_t stat = ZSuccess;

  switch ( pInMsg->hdr.commandID )
  {
    case COMMAND_SS_IAS_ZONE_STATUS_CHANGE_NOTIFICATION:
      zclSS_ProcessInCmd_ZoneStatus_ChangeNotification( pInMsg, pCBs );
      break;

    case COMMAND_SS_IAS_ZONE_STATUS_ENROLL_REQUEST:
      stat = zclSS_ProcessInCmd_ZoneStatus_EnrollRequest( pInMsg, pCBs );
      break;

    default:
      stat = ZFailure;
      break;
  }

  return ( stat );
}
#endif // ZCL_ZONE

#ifdef ZCL_ACE
/*********************************************************************
 * @fn      zclSS_ProcessInACECmdsServer
 *
 * @brief   Callback from ZCL to process incoming Commands specific
 *          to this cluster library on a command ID basis

 * @param   pInMsg - pointer to the incoming message
 *
 * @return  ZStatus_t
 */
static ZStatus_t zclSS_ProcessInACECmdsServer( zclIncoming_t *pInMsg,
                                               zclSS_AppCallbacks_t *pCBs )
{
  ZStatus_t stat = ZSuccess;

  switch ( pInMsg->hdr.commandID )
  {
    case COMMAND_SS_IAS_ACE_ARM:
      stat = zclSS_ProcessInCmd_ACE_Arm( pInMsg, pCBs );
      break;

    case COMMAND_SS_IAS_ACE_BYPASS:
      zclSS_ProcessInCmd_ACE_Bypass( pInMsg, pCBs );
      break;

    case COMMAND_SS_IAS_ACE_EMERGENCY:
      zclSS_ProcessInCmd_ACE_Emergency( pInMsg, pCBs );
      break;

    case COMMAND_SS_IAS_ACE_FIRE:
      zclSS_ProcessInCmd_ACE_Fire( pInMsg, pCBs );
      break;

    case COMMAND_SS_IAS_ACE_PANIC:
      zclSS_ProcessInCmd_ACE_Panic( pInMsg, pCBs );
      break;

    case COMMAND_SS_IAS_ACE_GET_ZONE_ID_MAP:
      stat = zclSS_ProcessInCmd_ACE_GetZoneIDMap( pInMsg );
      break;

    case COMMAND_SS_IAS_ACE_GET_ZONE_INFORMATION:
      stat = zclSS_ProcessInCmd_ACE_GetZoneInformation( pInMsg );
      break;

    default:
      stat = ZFailure;
      break;
  }

  return ( stat );
}

/*********************************************************************
 * @fn      zclSS_ProcessInACECmdsClient
 *
 * @brief   Callback from ZCL to process incoming Commands specific
 *          to this cluster library on a command ID basis

 * @param   pInMsg - pointer to the incoming message
 *
 * @return  ZStatus_t
 */
static ZStatus_t zclSS_ProcessInACECmdsClient( zclIncoming_t *pInMsg,
                                               zclSS_AppCallbacks_t *pCBs )
{
  ZStatus_t stat = ZSuccess;

  switch ( pInMsg->hdr.commandID )
  {
    case COMMAND_SS_IAS_ACE_ARM_RESPONSE:
      zclSS_ProcessInCmd_ACE_ArmResponse( pInMsg, pCBs );
      break;

    case COMMAND_SS_IAS_ACE_GET_ZONE_ID_MAP_RESPONSE:
      zclSS_ProcessInCmd_ACE_GetZoneIDMapResponse( pInMsg, pCBs );
      break;

    case COMMAND_SS_IAS_ACE_GET_ZONE_INFORMATION_RESPONSE:
      zclSS_ProcessInCmd_ACE_GetZoneInformationResponse( pInMsg, pCBs );
      break;

    default:
      stat = ZFailure;
      break;
  }

  return ( stat );
}
#endif // ZCL_ACE

#ifdef ZCL_ZONE
/*********************************************************************
 * @fn      zclSS_AddZone
 *
 * @brief   Add a zone for an endpoint
 *
 * @param   endpoint -
 * @param   zone - new zone item
 *
 * @return  ZStatus_t
 */
static ZStatus_t zclSS_AddZone( uint8 endpoint, IAS_ACE_ZoneTable_t *zone )
{
  zclSS_ZoneItem_t *pNewItem;
  zclSS_ZoneItem_t *pLoop;

  // Fill in the new profile list
  pNewItem = osal_mem_alloc( sizeof( zclSS_ZoneItem_t ) );
  if ( pNewItem == NULL )
    return ( ZMemError );

  // Fill in the plugin record.
  pNewItem->next = (zclSS_ZoneItem_t *)NULL;
  pNewItem->endpoint = endpoint;
  osal_memcpy( (uint8*)&(pNewItem->zone), (uint8*)zone, sizeof ( IAS_ACE_ZoneTable_t ));

  // Find spot in list
  if (  zclSS_ZoneTable == NULL )
  {
    zclSS_ZoneTable = pNewItem;
  }
  else
  {
    // Look for end of list
    pLoop = zclSS_ZoneTable;
    while ( pLoop->next != NULL )
      pLoop = pLoop->next;

    // Put new item at end of list
    pLoop->next = pNewItem;
  }

  return ( ZSuccess );
}

/*********************************************************************
 * @fn      zclSS_CountAllZones
 *
 * @brief   Count the total number of zones
 *
 * @param   none
 *
 * @return  number of zones
 */
uint8 zclSS_CountAllZones( void )
{
  zclSS_ZoneItem_t *pLoop;
  uint8 cnt = 0;

  // Look for end of list
  pLoop = zclSS_ZoneTable;
  while ( pLoop )
  {
    cnt++;
    pLoop = pLoop->next;
  }
  return ( cnt );
}

/*********************************************************************
 * @fn      zclSS_GetNextFreeZoneID
 *
 * @brief   Get the next free zone ID
 *
 * @param   none
 *
 * @return  free zone ID (0-254)
 */
static uint8 zclSS_GetNextFreeZoneID( void )
{
  static uint8 nextAvailZoneID = 0;

  if ( zclSS_ZoneIDAvailable( nextAvailZoneID ) == FALSE )
  {
    uint8 zoneID = nextAvailZoneID;

    // Look for next available zone ID
    do
    {
      if ( ++zoneID == ZCL_SS_MAX_ZONE_ID )
        zoneID = 0; // roll over

    } while ( (zoneID != nextAvailZoneID) && (zclSS_ZoneIDAvailable( nextAvailZoneID ) == FALSE) );

    // Did we found a free zone ID?
    if ( zoneID != nextAvailZoneID )
      nextAvailZoneID = zoneID;
  }

  return ( nextAvailZoneID );
}

/*********************************************************************
 * @fn      zclSS_ZoneIDAvailable
 *
 * @brief   Check to see whether zoneID is available for use
 *
 * @param   zoneID - ID to look for zone
 *
 * @return  TRUE if zoneID is available, FALSE otherwise
 */
static uint8 zclSS_ZoneIDAvailable( uint8 zoneID )
{
  zclSS_ZoneItem_t *pLoop;

  if ( zoneID < ZCL_SS_MAX_ZONE_ID )
  {
    pLoop = zclSS_ZoneTable;
    while ( pLoop )
    {
      if ( pLoop->zone.zoneID == zoneID  )
      {
        return ( FALSE );
      }
      pLoop = pLoop->next;
    }

    // Zone ID not in use
    return ( TRUE );
  }

  return ( FALSE );
}
#endif // ZCL_ZONE

#if defined(ZCL_ZONE) || defined(ZCL_ACE)
/*********************************************************************
 * @fn      zclSS_FindZone
 *
 * @brief   Find a zone with endpoint and ZoneID
 *
 * @param   endpoint -
 * @param   zoneID - ID to look for zone
 *
 * @return  a pointer to the zone information, NULL if not found
 */
static IAS_ACE_ZoneTable_t *zclSS_FindZone( uint8 endpoint, uint8 zoneID )
{
  zclSS_ZoneItem_t *pLoop;

  // Look for end of list
  pLoop = zclSS_ZoneTable;
  while ( pLoop )
  {
    if ( pLoop->endpoint == endpoint && pLoop->zone.zoneID == zoneID  )
    {
      return ( &(pLoop->zone) );
    }
    pLoop = pLoop->next;
  }

  return ( (IAS_ACE_ZoneTable_t *)NULL );
}

/*********************************************************************
 * @fn      zclSS_RemoveZone
 *
 * @brief   Remove a zone with endpoint and zoneID
 *
 * @param   endpoint -
 * @param   zoneID - ID to look for zone
 *
 * @return  TRUE if removed, FALSE if not found
 */
uint8 zclSS_RemoveZone( uint8 endpoint, uint8 zoneID )
{
  zclSS_ZoneItem_t *pLoop;
  zclSS_ZoneItem_t *pPrev;

  // Look for end of list
  pLoop = zclSS_ZoneTable;
  pPrev = NULL;
  while ( pLoop )
  {
    if ( pLoop->endpoint == endpoint && pLoop->zone.zoneID == zoneID )
    {
      if ( pPrev == NULL )
        zclSS_ZoneTable = pLoop->next;
      else
        pPrev->next = pLoop->next;

      // Free the memory
      osal_mem_free( pLoop );

      return ( TRUE );
    }
    pPrev = pLoop;
    pLoop = pLoop->next;
  }

  return ( FALSE );
}

/*********************************************************************
 * @fn      zclSS_UpdateZoneAddress
 *
 * @brief   Update Zone Address for zoneID
 *
 * @param   endpoint -
 * @param   zoneID - ID to look for zone
 * @param   ieeeAddr - Device IEEE Address
 *
 * @return  none
 */
void zclSS_UpdateZoneAddress( uint8 endpoint, uint8 zoneID, uint8 *ieeeAddr )
{
  IAS_ACE_ZoneTable_t *zone;

  zone = zclSS_FindZone( endpoint, zoneID );
  if ( zone != NULL )
  {
    // Update the zone address
    osal_cpyExtAddr( zone->zoneAddress, ieeeAddr );
  }
}
#endif // ZCL_ZONE || ZCL_ACE

#ifdef ZCL_ZONE
/*******************************************************************************
 * @fn      zclSS_ProcessInCmd_ZoneStatus_ChangeNotification
 *
 * @brief   Process in the received StatusChangeNotification Command.
 *
 * @param   pInMsg - pointer to the incoming message
 *
 * @return  ZStatus_t
 */
static void zclSS_ProcessInCmd_ZoneStatus_ChangeNotification( zclIncoming_t *pInMsg,
                                                              zclSS_AppCallbacks_t *pCBs )
{
  if ( pInMsg->hdr.commandID != COMMAND_SS_IAS_ZONE_STATUS_CHANGE_NOTIFICATION )
    return;   // Error ignore the command

  if ( pCBs->pfnChangeNotification )
  {
    zclZoneChangeNotif_t cmd;

    cmd.zoneStatus = BUILD_UINT16( pInMsg->pData[0], pInMsg->pData[1] );
    cmd.extendedStatus = pInMsg->pData[2];

    pCBs->pfnChangeNotification( &cmd );
  }
}

/*******************************************************************************
 * @fn      zclSS_ProcessInCmd_ZoneStatus_EnrollRequest
 *
 * @brief   Process in the received StatusEnrollRequest Command.
 *
 * @param   pInMsg - pointer to the incoming message
 *
 * @return  ZStatus_t
 */
static ZStatus_t zclSS_ProcessInCmd_ZoneStatus_EnrollRequest( zclIncoming_t *pInMsg,
                                                              zclSS_AppCallbacks_t *pCBs )
{
  IAS_ACE_ZoneTable_t zone;
  uint16 zoneType;
  uint16 manuCode;
  uint8 zoneID;
  uint8 status;

  if ( pInMsg->hdr.commandID != COMMAND_SS_IAS_ZONE_STATUS_ENROLL_REQUEST )
    return ( ZFailure );   // Error ignore the command

  zoneType = BUILD_UINT16( pInMsg->pData[0], pInMsg->pData[1] );
  manuCode = BUILD_UINT16( pInMsg->pData[2], pInMsg->pData[3] );

  if ( zclSS_ZoneTypeSupported( zoneType ) )
  {
    // What if the entry already exists?????
    if ( zclSS_CountAllZones() < ZCL_SS_MAX_ZONES-1 )
    {
      // Add zone to the table
      zoneID = zclSS_GetNextFreeZoneID();

      zone.zoneID = zoneID;
      zone.zoneType = zoneType;

      // The application will fill in the right IEEE Address later
      osal_cpyExtAddr( zone.zoneAddress, (void *)zclSS_UknownIeeeAddress );

      if ( zclSS_AddZone( pInMsg->msg->endPoint, &zone ) == ZSuccess )
      {
        status = ZCL_STATUS_SUCCESS;
      }
      else
      {
        // CIE does not permit new zones to enroll at this time
        status = SS_IAS_ZONE_STATUS_ENROLL_RESPONSE_CODE_NO_ENROLL_PERMIT;
      }
    }
    else
    {
      // CIE reached its limit of number of enrolled zones
      status = SS_IAS_ZONE_STATUS_ENROLL_RESPONSE_CODE_TOO_MANY_ZONES;
    }
  }
  else
  {
    // Zone type is not known to CIE and is not supported
    status = SS_IAS_ZONE_STATUS_ENROLL_RESPONSE_CODE_NOT_SUPPORTED;
  }

  // Send a response back
  zclSS_IAS_Send_ZoneStatusEnrollResponseCmd( pInMsg->msg->endPoint, &(pInMsg->msg->srcAddr),
                                              status, zoneID, true, pInMsg->hdr.transSeqNum );
  if ( status == ZCL_STATUS_SUCCESS )
  {
    // Callback the application so it can fill in the Device IEEE Address
    if ( pCBs->pfnEnrollRequest )
    {
      zclZoneEnrollReq_t req;

      req.srcAddr = &(pInMsg->msg->srcAddr);
      req.zoneID = zoneID;
      req.zoneType = zoneType;
      req.manufacturerCode = manuCode;

      pCBs->pfnEnrollRequest( &req );
    }
  }

  return ( ZCL_STATUS_CMD_HAS_RSP );
}

/*******************************************************************************
 * @fn      zclSS_ProcessInCmd_ZoneStatus_EnrollResponse
 *
 * @brief   Process in the received STATUS_ENROLL_RESPONSE Command.
 *
 * @param   pInMsg - pointer to the incoming message
 *
 * @return  ZStatus_t
 */
static void zclSS_ProcessInCmd_ZoneStatus_EnrollResponse( zclIncoming_t *pInMsg,
                                                          zclSS_AppCallbacks_t *pCBs )
{
  if ( pInMsg->hdr.commandID != COMMAND_SS_IAS_ZONE_STATUS_ENROLL_RESPONSE )
    return;   // Error ignore the command

  if ( pCBs->pfnEnrollResponse )
  {
    zclZoneEnrollRsp_t rsp;

    rsp.responseCode = pInMsg->pData[0];
    rsp.zoneID = pInMsg->pData[1];

    pCBs->pfnEnrollResponse( &rsp );
  }
}
#endif // ZCL_ZONE

#ifdef ZCL_ACE
/*********************************************************************
 * @fn      zclSS_ProcessInCmd_ACE_Arm
 *
 * @brief   Process in the received Arm Command.
 *
 * @param   pInMsg - pointer to the incoming message
 *
 */
static ZStatus_t zclSS_ProcessInCmd_ACE_Arm( zclIncoming_t *pInMsg,
                                             zclSS_AppCallbacks_t *pCBs )
{
  uint8 armNotification;

  if  ( pInMsg->hdr.commandID != COMMAND_SS_IAS_ACE_ARM )
    return ( ZFailure );   // Error ignore the command

  if ( pCBs->pfnACE_Arm )
  {
    armNotification = pCBs->pfnACE_Arm( pInMsg->pData[0] );

    // Send a response back
    zclSS_Send_IAS_ACE_ArmResponse( pInMsg->msg->endPoint, &(pInMsg->msg->srcAddr),
                                    armNotification, true, pInMsg->hdr.transSeqNum );
  }

  return ( ZCL_STATUS_CMD_HAS_RSP );
}

/*********************************************************************
 * @fn      zclSS_ProcessInCmd_ACE_Bypass
 *
 * @brief   Process in the received Bypass Command.
 *
 * @param   pInMsg - pointer to the incoming message
 *
 */
static void zclSS_ProcessInCmd_ACE_Bypass( zclIncoming_t *pInMsg,
                                           zclSS_AppCallbacks_t *pCBs )
{
  if  ( pInMsg->hdr.commandID != COMMAND_SS_IAS_ACE_BYPASS )
    return;   // Error ignore the command

  if ( pCBs->pfnACE_Bypass )
  {
    zclACEBypass_t cmd;

    cmd.numberOfZones = pInMsg->pData[0];
    cmd.bypassBuf = &(pInMsg->pData[1]);

    pCBs->pfnACE_Bypass( &cmd ) ;
  }
}

/*********************************************************************
 * @fn      zclSS_ProcessInCmd_ACE_Emergency
 *
 * @brief   Process in the received Emergency Command.
 *
 * @param   pInMsg - pointer to the incoming message
 *
 */
static void zclSS_ProcessInCmd_ACE_Emergency( zclIncoming_t *pInMsg,
                                              zclSS_AppCallbacks_t *pCBs )
{
  if  ( pInMsg->hdr.commandID != COMMAND_SS_IAS_ACE_EMERGENCY )
    return;   // Error ignore the command

  if ( pCBs->pfnACE_Emergency )
    pCBs->pfnACE_Emergency();

}

/*********************************************************************
 * @fn      zclSS_ProcessInCmd_ACE_Fire
 *
 * @brief   Process in the received Fire Command.
 *
 * @param   pInMsg - pointer to the incoming message
 *
 */
static void zclSS_ProcessInCmd_ACE_Fire( zclIncoming_t *pInMsg,
                                         zclSS_AppCallbacks_t *pCBs )
{
  if  ( pInMsg->hdr.commandID != COMMAND_SS_IAS_ACE_FIRE )
    return;   // Error ignore the command

  if ( pCBs->pfnACE_Fire )
    pCBs->pfnACE_Fire();
}

/*********************************************************************
 * @fn      zclSS_ProcessInCmd_ACE_Panic
 *
 * @brief   Process in the received Panic Command.
 *
 * @param   pInMsg - pointer to the incoming message
 *
 */
static void zclSS_ProcessInCmd_ACE_Panic( zclIncoming_t *pInMsg,
                                          zclSS_AppCallbacks_t *pCBs )
{
  if  ( pInMsg->hdr.commandID != COMMAND_SS_IAS_ACE_PANIC )
    return;   // Error ignore the command

  if ( pCBs->pfnACE_Panic )
    pCBs->pfnACE_Panic();
}

/*********************************************************************
 * @fn      zclSS_ProcessInCmd_ACE_GetZoneIDMap
 *
 * @brief   Process in the received GetZoneIDMap Command.
 *
 * @param   pInMsg - pointer to the incoming message
 *
 */
static ZStatus_t zclSS_ProcessInCmd_ACE_GetZoneIDMap( zclIncoming_t *pInMsg )
{
  uint16 zoneIDMap[16];
  uint16 mapSection;
  uint8 zoneID;
  uint8 i, j;

  if  ( pInMsg->hdr.commandID != COMMAND_SS_IAS_ACE_GET_ZONE_ID_MAP )
    return ( ZFailure );   // Error ignore the command

  for ( i = 0; i < 16; i++ )
  {
    mapSection = 0;

    // Find out Zone IDs that are allocated for this map section
    for ( j = 0; j < 16; j++ )
    {
      zoneID = 16 * i + j;
      if ( zclSS_FindZone( pInMsg->msg->endPoint, zoneID ) != NULL )
      {
        // Set the corresponding bit
        mapSection |= (0x01 << j );
      }
    }
    zoneIDMap[i] = mapSection;
  }

  // Send a response back
  zclSS_Send_IAS_ACE_GetZoneIDMapResponseCmd( pInMsg->msg->endPoint, &(pInMsg->msg->srcAddr),
                                              zoneIDMap, true, pInMsg->hdr.transSeqNum );
  return ( ZCL_STATUS_CMD_HAS_RSP );
}

/*********************************************************************
 * @fn      zclSS_ProcessInCmd_ACE_GetZoneInformation
 *
 * @brief   Process in the received GetZoneInformation Command.
 *
 * @param   pInMsg - pointer to the incoming message
 *
 */
static ZStatus_t zclSS_ProcessInCmd_ACE_GetZoneInformation( zclIncoming_t *pInMsg )
{
  IAS_ACE_ZoneTable_t zone;
  IAS_ACE_ZoneTable_t *pZone;

  if  ( pInMsg->hdr.commandID != COMMAND_SS_IAS_ACE_GET_ZONE_INFORMATION )
    return ( ZFailure );   // Error ignore the command

  pZone = zclSS_FindZone( pInMsg->msg->endPoint, pInMsg->pData[0] );
  if ( pZone == NULL )
  {
    // Zone not found
    pZone = &zone;
    pZone->zoneID = pInMsg->pData[0];
    pZone->zoneType = SS_IAS_ZONE_TYPE_INVALID_ZONE_TYPE;
    osal_cpyExtAddr( pZone->zoneAddress, (void *)zclSS_UknownIeeeAddress );
  }

  // Send a response back
  zclSS_Send_IAS_ACE_GetZoneInformationResponseCmd( pInMsg->msg->endPoint, &(pInMsg->msg->srcAddr),
                                                    pZone->zoneID, pZone->zoneType,
                                                    pZone->zoneAddress, true, pInMsg->hdr.transSeqNum );
  return ( ZCL_STATUS_CMD_HAS_RSP );
}

/*********************************************************************
 * @fn      zclSS_ProcessInCmd_ACE_ArmResponse
 *
 * @brief   Process in the received Arm Response Command.
 *
 * @param   pInMsg - pointer to the incoming message
 *
 */
static void zclSS_ProcessInCmd_ACE_ArmResponse( zclIncoming_t *pInMsg,
                                                zclSS_AppCallbacks_t *pCBs )
{
  if  ( pInMsg->hdr.commandID != COMMAND_SS_IAS_ACE_ARM_RESPONSE )
    return;   // Error ignore the command

  if ( pCBs->pfnACE_ArmResponse )
    pCBs->pfnACE_ArmResponse(pInMsg->pData[0]);
}

/*********************************************************************
 * @fn      zclSS_ProcessInCmd_ACE_GetZoneIDMapResponse
 *
 * @brief   Process in the received GetZoneIDMapResponse Command.
 *
 * @param   pInMsg - pointer to the incoming message
 *
 */
static void zclSS_ProcessInCmd_ACE_GetZoneIDMapResponse( zclIncoming_t *pInMsg,
                                                         zclSS_AppCallbacks_t *pCBs )
{
  uint16 *buf;
  uint16 *pIndex;
  uint8 *pData;
  uint8 i, len = 32; // 16 fields of 2 octects

  if ( pInMsg->hdr.commandID != COMMAND_SS_IAS_ACE_GET_ZONE_ID_MAP_RESPONSE )
    return;   // Error ignore the command

  buf = osal_mem_alloc( len );

  if ( buf )
  {
    pIndex = buf;
    pData = pInMsg->pData;

    for ( i = 0; i < 16; i++ )
    {
      *pIndex++ = BUILD_UINT16( pData[0], pData[1] );
      pData += 2;
    }

    if ( pCBs->pfnACE_GetZoneIDMapResponse )
      pCBs->pfnACE_GetZoneIDMapResponse( buf );

    osal_mem_free( buf );
  }
}

/*********************************************************************
 * @fn      zclSS_ProcessInCmd_ACE_GetZoneInformationResponse
 *
 * @brief   Process in the received GetZoneInformationResponse Command.
 *
 * @param   pInMsg - pointer to the incoming message
 *
 */
static void zclSS_ProcessInCmd_ACE_GetZoneInformationResponse( zclIncoming_t *pInMsg,
                                                               zclSS_AppCallbacks_t *pCBs )
{
  if  ( pInMsg->hdr.commandID != COMMAND_SS_IAS_ACE_GET_ZONE_INFORMATION_RESPONSE )
    return;   // Error ignore the command

  if ( pCBs->pfnACE_GetZoneInformationResponse )
  {
    zclACEGetZoneInfoRsp_t rsp;

    rsp.zoneID = pInMsg->pData[0];
    rsp.zoneType = BUILD_UINT16( pInMsg->pData[1], pInMsg->pData[2] );
    rsp.ieeeAddr = &(pInMsg->pData[3]);

    pCBs->pfnACE_GetZoneInformationResponse( &rsp );
  }
}
#endif // ZCL_ACE

#ifdef ZCL_WD
/*********************************************************************
 * @fn      zclSS_ProcessInWDCmds
 *
 * @brief   Callback from ZCL to process incoming Commands specific
 *          to this cluster library on a command ID basis

 * @param   pInMsg - pointer to the incoming message
 *
 * @return  ZStatus_t
 */
static ZStatus_t zclSS_ProcessInWDCmds( zclIncoming_t *pInMsg,
                                        zclSS_AppCallbacks_t *pCBs )
{
  ZStatus_t stat = ZSuccess;

  switch ( pInMsg->hdr.commandID )
  {
    case COMMAND_SS_IAS_WD_START_WARNING:
      zclSS_ProcessInCmd_WD_StartWarning( pInMsg, pCBs );
      break;

    case COMMAND_SS_IAS_WD_SQUAWK:
      zclSS_ProcessInCmd_WD_Squawk( pInMsg, pCBs );
      break;

    default:
      stat = ZFailure;
      break;
  }

  return ( stat );
}

/*********************************************************************
 * @fn      zclSS_ProcessInCmd_WD_StartWarning
 *
 * @brief   Process in the received StartWarning Command.
 *
 * @param   pInMsg - pointer to the incoming message
 *
 */
static void zclSS_ProcessInCmd_WD_StartWarning( zclIncoming_t *pInMsg,
                                                zclSS_AppCallbacks_t *pCBs )
{
  if  ( pInMsg->hdr.commandID != COMMAND_SS_IAS_WD_START_WARNING )
    return;   // Error ignore the command

  if ( pCBs->pfnWD_StartWarning )
  {
    zclWDStartWarning_t cmd;

    cmd.warnings.warningbyte = pInMsg->pData[0];
    cmd.duration = BUILD_UINT16( pInMsg->pData[1], pInMsg->pData[2] );

    pCBs->pfnWD_StartWarning( &cmd );
  }
}

/*********************************************************************
 * @fn      zclSS_ProcessInCmd_WD_Squawk
 *
 * @brief   Process in the received Squawk Command.
 *
 * @param   pInMsg - pointer to the incoming message
 *
 */
static void zclSS_ProcessInCmd_WD_Squawk( zclIncoming_t *pInMsg,
                                          zclSS_AppCallbacks_t *pCBs )
{
  zclCmdSSWDSquawkPayload_t squawk;

  if  ( pInMsg->hdr.commandID != COMMAND_SS_IAS_WD_SQUAWK )
    return;   // Error ignore the command

  if ( pCBs->pfnWD_Squawk )
  {
    squawk.squawkbyte = pInMsg->pData[0];
    pCBs->pfnWD_Squawk( squawk );
  }
}
#endif // ZCL_WD

/*******************************************************************************
*******************************************************************************/


text:
/*
 * htmlviewer.c
 *
 *    This takes a directory of image files, optionally scales them,
 *    and generates html files to view the scaled images (and thumbnails).
 *
 *    Input:  dirin:  directory of input image files
 *            dirout: directory for output files
 *            rootname: root name for output files
 *            thumbwidth: width of thumb images, in pixels; use 0 for default
 *            viewwidth: max width of view images, in pixels; use 0 for default
 *
 *    Example:
 *         mkdir /tmp/lept/lion-in
 *         mkdir /tmp/lept/lion-out
 *         cp lion-page* /tmp/lept/lion-in
 *         htmlviewer /tmp/lept/lion-in /tmp/lept/lion-out lion 200 600
 *        ==> output:
 *            /tmp/lept/lion-out/lion.html         (main html file)
 *            /tmp/lept/lion-out/lion-links.html   (html file of links)
 */

#include <string.h>
#include "allheaders.h"

#ifdef _WIN32
#include <windows.h>   /* for CreateDirectory() */
#endif

static const l_int32  DEFAULT_THUMB_WIDTH = 120;
static const l_int32  DEFAULT_VIEW_WIDTH = 800;
static const l_int32  MIN_THUMB_WIDTH = 50;
static const l_int32  MIN_VIEW_WIDTH = 300;

static l_int32 pixHtmlViewer(const char *dirin, const char *dirout,
                             const char  *rootname, l_int32 thumbwidth,
                             l_int32 viewwidth);
static void WriteFormattedPix(char *fname, PIX *pix);

int main(int    argc,
         char **argv)
{
char        *dirin, *dirout, *rootname;
l_int32      thumbwidth, viewwidth;
static char  mainName[] = "htmlviewer";

    if (argc != 6)
        return ERROR_INT(
            " Syntax:  htmlviewer dirin dirout rootname thumbwidth viewwidth",
             mainName, 1);
    dirin = argv[1];
    dirout = argv[2];
    rootname = argv[3];
    thumbwidth = atoi(argv[4]);
    viewwidth = atoi(argv[5]);
    setLeptDebugOK(1);

    pixHtmlViewer(dirin, dirout, rootname, thumbwidth, viewwidth);
    return 0;
}

/*---------------------------------------------------------------------*
 *            Generate smaller images for viewing and write html       *
 *---------------------------------------------------------------------*/
/*!
 * \brief   pixHtmlViewer()
 *
 * \param[in]    dirin      directory of input image files
 * \param[in]    dirout     directory for output files
 * \param[in]    rootname   root name for output files
 * \param[in]    thumbwidth width of thumb images in pixels; use 0 for default
 * \param[in]    viewwidth  maximum width of view images no up-scaling
 *                          in pixels; use 0 for default
 * \return  0 if OK; 1 on error
 *
 *

 * Notes:
 *      (1) The thumb and view reduced images are generated,
 *          along with two html files:
 *             <rootname>.html and <rootname>-links.html
 *      (2) The thumb and view files are named
 *             <rootname>_thumb_xxx.jpg
 *             <rootname>_view_xxx.jpg
 *          With this naming scheme, any number of input directories
 *          of images can be processed into views and thumbs
 *          and placed in the same output directory.
 *

 */
static l_int32
pixHtmlViewer(const char  *dirin,
              const char  *dirout,
              const char  *rootname,
              l_int32      thumbwidth,
              l_int32      viewwidth)
{
char      *fname, *fullname, *outname;
char      *mainname, *linkname, *linknameshort;
char      *viewfile, *thumbfile;
char      *shtml, *slink;
char       buf[512];
char       htmlstring[] = "";
char       framestring[] = "</frameset>";
l_int32    i, nfiles, index, w, d, nimages, ret;
l_float32  factor;
PIX       *pix, *pixthumb, *pixview;
SARRAY    *safiles, *sathumbs, *saviews, *sahtml, *salink;

    PROCNAME("pixHtmlViewer");

    if (!dirin)
        return ERROR_INT("dirin not defined", procName, 1);
    if (!dirout)
        return ERROR_INT("dirout not defined", procName, 1);
    if (!rootname)
        return ERROR_INT("rootname not defined", procName, 1);

    if (thumbwidth == 0)
        thumbwidth = DEFAULT_THUMB_WIDTH;
    if (thumbwidth < MIN_THUMB_WIDTH) {
        L_WARNING("thumbwidth too small; using min value\n", procName);
        thumbwidth = MIN_THUMB_WIDTH;
    }
    if (viewwidth == 0)
        viewwidth = DEFAULT_VIEW_WIDTH;
    if (viewwidth < MIN_VIEW_WIDTH) {
        L_WARNING("viewwidth too small; using min value\n", procName);
        viewwidth = MIN_VIEW_WIDTH;
    }

        /* Make the output directory if it doesn't already exist */
#ifndef _WIN32
    snprintf(buf, sizeof(buf), "mkdir -p %s", dirout);
    ret = system(buf);
#else
    ret = CreateDirectory(dirout, NULL) ? 0 : 1;
#endif  /* !_WIN32 */
    if (ret) {
        L_ERROR("output directory %s not made\n", procName, dirout);
        return 1;
    }

        /* Capture the filenames in the input directory */
    if ((safiles = getFilenamesInDirectory(dirin)) == NULL)
        return ERROR_INT("safiles not made", procName, 1);

        /* Generate output text file names */
    snprintf(buf, sizeof(buf), "%s/%s.html", dirout, rootname);
    mainname = stringNew(buf);
    snprintf(buf, sizeof(buf), "%s/%s-links.html", dirout, rootname);
    linkname = stringNew(buf);
    linknameshort = stringJoin(rootname, "-links.html");

        /* Generate the thumbs and views */
    sathumbs = sarrayCreate(0);
    saviews = sarrayCreate(0);
    nfiles = sarrayGetCount(safiles);
    index = 0;
    for (i = 0; i < nfiles; i++) {
        fname = sarrayGetString(safiles, i, L_NOCOPY);
        fullname = genPathname(dirin, fname);
        fprintf(stderr, "name: %s\n", fullname);
        if ((pix = pixRead(fullname)) == NULL) {
            fprintf(stderr, "file %s not a readable image\n", fullname);
            lept_free(fullname);
            continue;
        }
        lept_free(fullname);

            /* Make and store the thumbnail images */
        pixGetDimensions(pix, &w, NULL, &d);
        factor = (l_float32)thumbwidth / (l_float32)w;
        pixthumb = pixScale(pix, factor, factor);
        snprintf(buf, sizeof(buf), "%s_thumb_%03d", rootname, index);
        sarrayAddString(sathumbs, buf, L_COPY);
        outname = genPathname(dirout, buf);
        WriteFormattedPix(outname, pixthumb);
        lept_free(outname);
        pixDestroy(&pixthumb);

            /* Make and store the view images */
        factor = (l_float32)viewwidth / (l_float32)w;
        if (factor >= 1.0)
            pixview = pixClone(pix);   /* no upscaling */
        else
            pixview = pixScale(pix, factor, factor);
        snprintf(buf, sizeof(buf), "%s_view_%03d", rootname, index);
        sarrayAddString(saviews, buf, L_COPY);
        outname = genPathname(dirout, buf);
        WriteFormattedPix(outname, pixview);
        lept_free(outname);
        pixDestroy(&pixview);
        pixDestroy(&pix);
        index++;
    }

        /* Generate the main html file */
    sahtml = sarrayCreate(0);
    sarrayAddString(sahtml, htmlstring, L_COPY);
    snprintf(buf, sizeof(buf), "<frameset cols=\"%d, *\">", thumbwidth + 30);
    sarrayAddString(sahtml, buf, L_COPY);
    snprintf(buf, sizeof(buf), "<frame name=\"thumbs\" src=\"%s\">",
             linknameshort);
    sarrayAddString(sahtml, buf, L_COPY);
    snprintf(buf, sizeof(buf), "<frame name=\"views\" src=\"%s\">",
            sarrayGetString(saviews, 0, L_NOCOPY));
    sarrayAddString(sahtml, buf, L_COPY);
    sarrayAddString(sahtml, framestring, L_COPY);
    shtml = sarrayToString(sahtml, 1);
    l_binaryWrite(mainname, "w", shtml, strlen(shtml));
    fprintf(stderr, "******************************************\n"
                    "Writing html file: %s\n"
                    "******************************************\n", mainname);
    lept_free(shtml);
    lept_free(mainname);

        /* Generate the link html file */
    nimages = sarrayGetCount(saviews);
    fprintf(stderr, "num. images = %d\n", nimages);
    salink = sarrayCreate(0);
    for (i = 0; i < nimages; i++) {
        viewfile = sarrayGetString(saviews, i, L_NOCOPY);
        thumbfile = sarrayGetString(sathumbs, i, L_NOCOPY);
        snprintf(buf, sizeof(buf),
                 "",
                 viewfile, thumbfile);
        sarrayAddString(salink, buf, L_COPY);
    }
    slink = sarrayToString(salink, 1);
    l_binaryWrite(linkname, "w", slink, strlen(slink));
    lept_free(slink);
    lept_free(linkname);
    lept_free(linknameshort);
    sarrayDestroy(&safiles);
    sarrayDestroy(&sathumbs);
    sarrayDestroy(&saviews);
    sarrayDestroy(&sahtml);
    sarrayDestroy(&salink);
    return 0;
}

static void
WriteFormattedPix(char  *fname,
                  PIX   *pix)
{
l_int32  d;

    d = pixGetDepth(pix);
    if (d == 1 || pixGetColormap(pix))
        pixWrite(fname, pix, IFF_PNG);
    else
        pixWrite(fname, pix, IFF_JFIF_JPEG);
    return;
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using ExactOnline.Client.Models;
using ExactOnline.Client.Sdk.Controllers;
using ExactOnline.Client.Sdk.TestContext;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ExactOnline.Client.Sdk.UserAcceptanceTests.UserLevel
{
	[TestClass]
	public class ModifyLinkedEntities
	{

		[TestMethod]
		[TestCategory("User Acceptance Tests")]
		public void UpdateLinkedEntities()
		{
			var toc = new TestObjectsCreator();
			var client = new ExactOnlineClient(toc.EndPoint, toc.GetOAuthAuthenticationToken);

			var salesInvoiceId = CreateSalesInvoice(client, 1);

			// Fetch sales invoice including sales invoice lines
			var salesInvoice = client.For<SalesInvoice>()
				.Select("InvoiceID,SalesInvoiceLines/ID,SalesInvoiceLines/InvoiceID,SalesInvoiceLines/Description")
				.Expand("SalesInvoiceLines")
				.GetEntity(salesInvoiceId);

			var salesInvoiceLines = (List<SalesInvoiceLine>)salesInvoice.SalesInvoiceLines;
			var orginialInvoiceline = salesInvoiceLines[0];

			// The original invoice line is not managed because it's taken as related entity from the sales invoice.
			// Call the api to get a managed invoice line that can be updated.
			var managedInvoiceLine = client.For<SalesInvoiceLine>().GetEntity(orginialInvoiceline.ID);
			managedInvoiceLine.Description = string.Format("Changed On {0}", DateTime.UtcNow);

			// Update and compare
			client.For<SalesInvoiceLine>().Update(managedInvoiceLine);
			Assert.AreNotEqual(orginialInvoiceline.Description, managedInvoiceLine.Description);
		}

		[TestMethod]
		[TestCategory("User Acceptance Tests")]
		public void CreateLinkedEntities()
		{
			var toc = new TestObjectsCreator();
			var client = new ExactOnlineClient(toc.EndPoint, toc.GetOAuthAuthenticationToken);

			// Fetch sales invoice
			var salesInvoiceId = CreateSalesInvoice(client, 1);
			var salesinvoice = client.For<SalesInvoice>().GetEntity(salesInvoiceId);

			// Fetch item
			var item = client.For<Item>().Top(1).Select("ID").Where("IsSalesItem+eq+true").Get().First();

			// add line
			var invoiceline = new SalesInvoiceLine
				{
					Description = "New Sales Invoice Line",
					InvoiceID = salesinvoice.InvoiceID,
					Item = item.ID
				};
			Assert.IsTrue(client.For<SalesInvoiceLine>().Insert(ref invoiceline));
		}

		[TestMethod]
		[TestCategory("User Acceptance Tests")]
		public void DeleteLinkedEntities()
		{
			var toc = new TestObjectsCreator();
			var client = new ExactOnlineClient(toc.EndPoint, toc.GetOAuthAuthenticationToken);

			// Create a sales invoice with 2 lines
			var salesInvoiceId = CreateSalesInvoice(client, 2);

			// Get one of the invoice lines
			var filter = string.Format("InvoiceID+eq+guid'{0}'", salesInvoiceId);
			var invoiceLine = client.For<SalesInvoiceLine>().Select("ID").Where(filter).Get().First();

			// Delete the line
			var deleted = client.For<SalesInvoiceLine>().Delete(invoiceLine);
			Assert.IsTrue(deleted);
		}

		private static Guid CreateSalesInvoice(ExactOnlineClient client, int numberOfLines)
		{
			var item = client.For<Item>().Top(1).Select("ID").Where("IsSalesItem+eq+true").Get().First();
			var customer = client.For<Account>().Top(1).Select("ID").Where("IsSales+eq+true").Get().First();

			var salesInvoice = new SalesInvoice
			{
				OrderedBy = customer.ID,
				Description = "SDK User level test"
			};

			var salesInvoiceLines = new List<SalesInvoiceLine>();

			for (int iterator = 0; iterator < numberOfLines; iterator++)
			{
				var salesInvoiceLine = new SalesInvoiceLine
				{
					Item = item.ID,
					Quantity = 1,
					Description = "Line " + iterator
				};

				salesInvoiceLines.Add(salesInvoiceLine);
			}
			salesInvoice.SalesInvoiceLines = salesInvoiceLines;
			client.For<SalesInvoice>().Insert(ref salesInvoice);

			return salesInvoice.InvoiceID;
		}
	}
}


text:
Sales phases

			{{salePhase.name}}
			Edit
			Delete
			{{phaseDates(salePhase)}}

			Phase name
			<input type="text"
			       name="phaseName_{{salePhase.name}}"
			       ng-class="{'invalid': $invalid && $touched}"
			       ng-required="true"
			       ng-model="salePhase.phaseName" />

			Start date
			<input datepicker-popup
			       type="text"
			       name="startDate_{{salePhase.name}}"
			       ng-class="{'invalid': $invalid && $touched}"
			       ng-required="true"
			       ng-model="salePhase.startDate"
			       ng-focus="salePhaseStartDateDatePicker = true"
			       is-open="salePhaseStartDateDatePicker"
			       min-date="editModeSaleStartDate || today" />

			End date
			<input datepicker-popup
			       type="text"
			       name="endDate_{{salePhase.name}}"
			       ng-class="{'invalid': $invalid && $touched}"
			       ng-required="true"
			       ng-model="salePhase.endDate"
			       ng-focus="salePhaseEndDateDatePicker = true"
			       is-open="salePhaseEndDateDatePicker"
			       min-date="salePhase.startDate" />

			Start price
			<input type="text"
			       name="startPrice_{{salePhase.name}}"
			       ng-class="{'invalid': $invalid && $touched}"
			       ng-required="true"
			       ng-model="salePhase.startPrice" />

			End price
			<input type="text"
			       name="endPrice_{{salePhase.name}}"
			       ng-class="{'invalid': $invalid && $touched}"
			       ng-required="true"
			       ng-model="salePhase.endPrice" />

		Save
		Cancel

	Add sale phase


text:
package org.statmantis.stat.common;

import org.statmantis.model.Play;
import org.statmantis.stat.StatisticInfo;
import org.statmantis.stat.StatisticType;
import org.statmantis.stat.StatisticUtils;

@StatisticInfo(
        name = "Sacrifice Flies",
        abbreviations = "SF",
        types = { StatisticType.BATTING, StatisticType.PITCHING })
public class SacrificeFlies extends PitcherAndBatterBasedPlayStatistic<Integer> {

    private int sacrificeFlies = 0;

    @Override
    public void applyPlay(Play play) {
        if (isPlayApplicable(play) && StatisticUtils.isSacrificeFly(play)) {
            sacrificeFlies++;
        }
    }

    @Override
    public Integer getCurrentValue() {
        return sacrificeFlies;
    }
}


text:
package com.github.akarnokd.msmr.model;

import hu.akarnokd.xml.*;
import it.unimi.dsi.fastutil.shorts.*;

public class Station implements XSerializable, ShortID {
    public short id;

    public final ShortSet machines = new ShortOpenHashSet();

    public final ShortSet employees = new ShortOpenHashSet();

    public Employee currentEmployee;

    @Override
    public short id() {
        return id;
    }

    @Override
    public void load(XElement source) {
        id = source.getShort("id");
        machines.clear();
        for (XElement xm : source.childrenWithName("machine")) {
            machines.add(xm.getShort("id"));
        }

        for (XElement xm : source.childrenWithName("employee")) {
            employees.add(xm.getShort("id"));
        }
    }

    @Override
    public void save(XElement xout) {
        xout.set("id", id);
        ShortIterator si = machines.iterator();
        while (si.hasNext()) {
            XElement xm = xout.add("machine");
            xm.set("id", si.next());
        }

        ShortIterator si2 = employees.iterator();
        while (si2.hasNext()) {
            XElement xm = xout.add("employee");
            xm.set("id", si2.next());
        }
    }
}


text:
#include <linux/kernel.h>

#ifndef _ARIZONA_PDATA_H
#define _ARIZONA_PDATA_H

#include <dt-bindings/mfd/arizona.h>

#define ARIZONA_GPN_DIR_MASK                     0x8000  /* GPN_DIR */
#define ARIZONA_GPN_DIR_SHIFT                        15  /* GPN_DIR */
#define ARIZONA_GPN_DIR_WIDTH                         1  /* GPN_DIR */
#define ARIZONA_GPN_PU_MASK                      0x4000  /* GPN_PU */
#define ARIZONA_GPN_PU_SHIFT                         14  /* GPN_PU */
#define ARIZONA_GPN_PU_WIDTH                          1  /* GPN_PU */
#define ARIZONA_GPN_PD_MASK                      0x2000  /* GPN_PD */
#define ARIZONA_GPN_PD_SHIFT                         13  /* GPN_PD */
#define ARIZONA_GPN_PD_WIDTH                          1  /* GPN_PD */
#define ARIZONA_GPN_LVL_MASK                     0x0800  /* GPN_LVL */
#define ARIZONA_GPN_LVL_SHIFT                        11  /* GPN_LVL */
#define ARIZONA_GPN_LVL_WIDTH                         1  /* GPN_LVL */
#define ARIZONA_GPN_POL_MASK                     0x0400  /* GPN_POL */
#define ARIZONA_GPN_POL_SHIFT                        10  /* GPN_POL */
#define ARIZONA_GPN_POL_WIDTH                         1  /* GPN_POL */
#define ARIZONA_GPN_OP_CFG_MASK                  0x0200  /* GPN_OP_CFG */
#define ARIZONA_GPN_OP_CFG_SHIFT                      9  /* GPN_OP_CFG */
#define ARIZONA_GPN_OP_CFG_WIDTH                      1  /* GPN_OP_CFG */
#define ARIZONA_GPN_DB_MASK                      0x0100  /* GPN_DB */
#define ARIZONA_GPN_DB_SHIFT                          8  /* GPN_DB */
#define ARIZONA_GPN_DB_WIDTH                          1  /* GPN_DB */
#define ARIZONA_GPN_FN_MASK                      0x007F  /* GPN_FN - [6:0] */
#define ARIZONA_GPN_FN_SHIFT                          0  /* GPN_FN - [6:0] */
#define ARIZONA_GPN_FN_WIDTH                          7  /* GPN_FN - [6:0] */

#define CLEARWATER_GPN_LVL                           0x8000  /* GPN_LVL */
#define CLEARWATER_GPN_LVL_MASK                      0x8000  /* GPN_LVL */
#define CLEARWATER_GPN_LVL_SHIFT                         15  /* GPN_LVL */
#define CLEARWATER_GPN_LVL_WIDTH                          1  /* GPN_LVL */

#define ARIZONA_MAX_GPIO_REGS 5
#define CLEARWATER_MAX_GPIO_REGS 80

#define ARIZONA_MAX_INPUT 12

#define ARIZONA_MAX_MICBIAS 4

#define ARIZONA_MAX_OUTPUT 6

#define ARIZONA_MAX_AIF 4

#define ARIZONA_HAP_ACT_ERM 0
#define ARIZONA_HAP_ACT_LRA 2

#define ARIZONA_MAX_PDM_SPK 2

/* Treat INT_MAX impedance as open circuit */
#define ARIZONA_HP_Z_OPEN INT_MAX

#define ARIZONA_MAX_DSP	7

struct regulator_init_data;

struct arizona_jd_state;

struct arizona_micbias {
	int mV;                    /** Regulated voltage */
	unsigned int ext_cap:1;    /** External capacitor fitted */
	unsigned int discharge:1;  /** Actively discharge */
	unsigned int soft_start:1; /** Disable aggressive startup ramp rate */
	unsigned int bypass:1;     /** Use bypass mode */
};

struct arizona_micd_config {
	unsigned int src;
	unsigned int bias;
	bool gpio;
};

struct arizona_micd_range {
	int max;  /** Ohms */
	int key;  /** Key to report to input layer */
};

struct arizona_pdata {
	int reset;      /** GPIO controlling /RESET, if any */
	int ldoena;     /** GPIO controlling LODENA, if any */

	/** Regulator configuration for MICVDD */
	struct regulator_init_data *micvdd;

	/** Regulator configuration for LDO1 */
	struct regulator_init_data *ldo1;

	/** If a direct 32kHz clock is provided on an MCLK specify it here */
	int clk32k_src;

	/** Mode for primary IRQ (defaults to active low) */
	unsigned int irq_flags;

	/* Base GPIO */
	int gpio_base;

	/** Pin state for GPIO pins
	 * Defines default pin function and state for each GPIO
	 *
	 * 0 = leave at chip default
	 * values 0x1..0xffff = set to this value
	 * >0xffff = set to 0
	 */
	unsigned int gpio_defaults[CLEARWATER_MAX_GPIO_REGS];

	/**
	 * Maximum number of channels clocks will be generated for,
	 * useful for systems where and I2S bus with multiple data
	 * lines is mastered.
	 */
	int max_channels_clocked[ARIZONA_MAX_AIF];

	/** Time in milliseconds to keep wake lock during jack detection */
	int jd_wake_time;

	/** GPIO5 is used for jack detection */
	bool jd_gpio5;

	/** Internal pull on GPIO5 is disabled when used for jack detection */
	bool jd_gpio5_nopull;

	/** set to true if jackdet contact opens on insert */
	bool jd_invert;

	/**
	* Set to true to support antenna cable. antenna cable is a 4 pole
	* cable with open circuit impedance and the usual 3 pole (headphone)
	* or 4 pole (headset) cables can be plugged into the antenna cable
	*/
	bool antenna_supported;

	/** If non-zero don't run headphone detection, report this value */
	int fixed_hpdet_imp;

	/** Use the headphone detect circuit to identify the accessory */
	bool hpdet_acc_id;

	/** Check for line output with HPDET method */
	bool hpdet_acc_id_line;

	/** GPIO used for mic isolation with HPDET */
	int hpdet_id_gpio;

	/** Callback notifying HPDET result */
	void (*hpdet_cb)(unsigned int measurement);

	/** Callback notifying mic presence */
	void (*micd_cb)(bool mic);

	/** If non-zero, specifies the maximum impedance in ohms
	 * that will be considered as a short circuit.
	 */
	int hpdet_short_circuit_imp;

	/**
	 * Channel to use for moisture detection, valid values are 0 for
	 * left and 1 for right
	 */
	unsigned int moisture_det_channel;

	/**
	* This value specifies the  threshold impedance in ohms above
	* which it will be considered a false detection
	*/
	int hpdet_moisture_imp;

	/** Software debounces for moisture detect */
	int hpdet_moisture_debounce;

	/**
	 * Channel to use for headphone detection, valid values are 0 for
	 * left and 1 for right
	 */
	int hpdet_channel;

	/** Use software comparison to determine mic presence */
	bool micd_software_compare;

	/** Extra debounce timeout used during initial mic detection (ms) */
	int micd_detect_debounce;

	/** Extra software debounces during button detection */
	int micd_manual_debounce;

	/** Software debounces during 3/4 pole plugin into antenna cable */
	int antenna_manual_debounce;

	/** Software debounces during 3/4 pole plugout from antenna cable */
	int antenna_manual_db_plugout;

	/** range around hp impedance to be rejected to prevent false button events */
	int antenna_hp_imp_range_lo;
	int antenna_hp_imp_range_hi;

	/** GPIO for mic detection polarity */
	int micd_pol_gpio;

	/** Mic detect ramp rate */
	int micd_bias_start_time;

	/** Mic detect sample rate */
	int micd_rate;

	/** Mic detect debounce level */
	int micd_dbtime;

	/** Mic detect timeout (ms) */
	int micd_timeout;

	/** Force MICBIAS on for mic detect */
	bool micd_force_micbias;

	/** Force MICBIAS on for initial mic detect only, not button detect */
	bool micd_force_micbias_initial;

	/** Declare an open circuit as a 4 pole jack */
	bool micd_open_circuit_declare;

	/** Delay between jack detection and MICBIAS ramp */
	int init_mic_delay;

	/** Mic detect level parameters */
	const struct arizona_micd_range *micd_ranges;
	int num_micd_ranges;

	/** Mic detect clamp function */
	unsigned int micd_clamp_mode;

	/** Headset polarity configurations */
	struct arizona_micd_config *micd_configs;
	int num_micd_configs;

	/** Reference voltage for DMIC inputs */
	int dmic_ref[ARIZONA_MAX_INPUT];

	/** MICBIAS configurations */
	struct arizona_micbias micbias[ARIZONA_MAX_MICBIAS];

	/**
	 * Mode of input structures
	 * One of the ARIZONA_INMODE_xxx values
	 * For most codecs the entries are [0]=IN1 [1]=IN2 [2]=IN3 [3]=IN4
	 * wm8998: [0]=IN1A [1]=IN2A [2]=IN1B [3]=IN2B
	 * cs47l85, wm8285: [0]=IN1L [1]=IN1R [2]=IN2L [3]=IN2R [4]=IN3L [5]=IN3R
	 */
	int inmode[ARIZONA_MAX_INPUT];

	/** Mode for outputs */
	bool out_mono[ARIZONA_MAX_OUTPUT];

	/** PDM speaker mute setting */
	unsigned int spk_mute[ARIZONA_MAX_PDM_SPK];

	/** PDM speaker format */
	unsigned int spk_fmt[ARIZONA_MAX_PDM_SPK];

	/** Haptic actuator type */
	unsigned int hap_act;

	/** GPIO for primary IRQ (used for edge triggered emulation) */
	int irq_gpio;

	/** General purpose switch control */
	unsigned int gpsw;

	/** Callback which is called when the trigger phrase is detected */
	void (*ez2ctrl_trigger)(void);

	/** wm5102t output power */
	unsigned int wm5102t_output_pwr;

	/** Override the normal jack detection */
	const struct arizona_jd_state *custom_jd;

	struct wm_adsp_fw_defs *fw_defs[ARIZONA_MAX_DSP];
	int num_fw_defs[ARIZONA_MAX_DSP];

	/** Some platforms add a series resistor for hpdet to suppress pops */
	int hpdet_ext_res;

	/** Load firmwares for specific chip revisions */
	bool rev_specific_fw;

	/**
	 * Specify an input to mute during headset button presses and jack
	 * removal: 1 - IN1L, 2 - IN1R, ..., n - IN[n]R
	 */
	unsigned int hs_mic;
};

#endif


text:
<?php

namespace Empleados\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;

class TipoEmpleadoTable extends AbstractTableGateway
{

  protected $table = 'tab_tipo_empleado';

  public function __construct(Adapter $adapter)
  {
    $this->adapter = $adapter;
  }

  public function save(Entity\TipoEmpleado $tipoEmpleado)
  {
    $data = array(
      'id_unidad' => $tipoEmpleado->getIdUnidad(),
      'tipo' => $tipoEmpleado->getTipo(),
      'descripcion' => $tipoEmpleado->getDescripcion(),
    );
    $id = (int)$tipoEmpleado->getId();
    if ($id == 0) {
      if (!$this->insert($data)) {
        return false;
      } else {
        return $this->getLastInsertValue();
      }
    } else {
      if (!$this->update($data, array('id' => $id))) {
        return false;
      } else {
        return $id;
      }
    }
  }

  public function fetchAll()
  {
    $sql = new Sql($this->adapter);
    $select = $sql->select();
    $select->from($this->table);

    $statement = $sql->prepareStatementForSqlObject($select);
    $resultSet = $statement->execute();

    $entities = array();
    foreach ($resultSet as $row) {
      $entity = new Entity\Empleado(array(
        'id' => $row["id"],
        'id_unidad' => $row["id_unidad"],
        'tipo' => $row["tipo"],
        'descripcion' => $row["descripcion"],
      ));
      $entities[] = $entity->toArray();
    }
    return $entities;
  }

  public function fetchAllByIdUnidad($id_unidad)
  {
    $sql = new Sql($this->adapter);
    $select = $sql->select();
    $select->from($this->table);

    $where = new  Where();
    $where->equalTo('tab_tipo_empleado.id_unidad', $id_unidad);
    $select->where($where);

    $statement = $sql->prepareStatementForSqlObject($select);
    $resultSet = $statement->execute();

    $entities = array();
    foreach ($resultSet as $row) {
      $entity = new Entity\Empleado(array(
        'id' => $row["id"],
        'id_unidad' => $row["id_unidad"],
        'tipo' => $row["tipo"],
        'descripcion' => $row["descripcion"],
      ));
      $entities[] = $entity->toArray();
    }
    return $entities;
  }

  public function fetch($id)
  {

    $sql = new Sql($this->adapter);
    $select = $sql->select();
    $select->from($this->table);

    $where = new  Where();
    $where->equalTo('tab_tipo_empleado.id', $id);
    $select->where($where);

    $statement = $sql->prepareStatementForSqlObject($select);
    $resultSet = $statement->execute();

    foreach ($resultSet as $row) {
      $entity = new Entity\Empleado(array(
        'id' => $row["id"],
        'id_unidad' => $row["id_unidad"],
        'tipo' => $row["tipo"],
        'descripcion' => $row["descripcion"],
      ));
      $entity = $entity->toArray();
    }

    if (isset($entity)) {
      return $entity;
    } else {
      return 0;
    }

  }

  public function fetchByTipo($tipo)
  {
    $row = $this->select(array('tipo' => $tipo))->current();
    if (!$row) {
      $entity = new Entity\Empleado(array(
        'id' => 0,
      ));
    } else {
      $entity = new Entity\Empleado(array(
        'id' => $row["id"],
        'id_unidad' => $row["id_unidad"],
        'tipo' => $row["tipo"],
        'descripcion' => $row["descripcion"],
      ));
    }
    return $entity->toArray();
  }

  public function removeEmpleado($id)
  {
    return $this->delete(array('id' => (int)$id));
  }

}


text:
module Code42
  module API
    module User
      ### Users :post, :get ###

      # Creates a user
      # @return [Code42::User] The created user
      # @param attrs [Hash] A hash of attributes to assign to created user
      # @example
      #   client.create_user(:username => 'testuser', password: 'letmein', email: 'test@example.com', org_id: 3)
      def create_user(attrs = {})
        object_from_response(Code42::User, :post, "user", attrs)
      end

      # Updates a user
      # @returns [Code42::User] The updated user
      # @param id [integer] The user id to be updated
      # @param attrs [Hash] A hash of attributes to update
      # @example
      #   client.update_user(2, email_promo: true, first_name: 'John')
      def update_user(id, attrs = {})
        object_from_response(Code42::User, :put, "user/#{id}", attrs)
      end

      # Returns information for a given user
      # @return [Code42::User] The requested user
      # @param id_or_username [String, Integer] A code42 user ID or username
      def user(id_or_username = "my", params = {})
        if id_or_username.is_a?(Fixnum) || id_or_username == 'my'
          find_user_by_id id_or_username, params
        else
          find_user_by_username id_or_username, params
        end
      end

      # Returns a user for a given id
      def find_user_by_id(id = 'my', params = {})
        object_from_response(Code42::User, :get, "user/#{id}", params)
      end

      # Returns a user for a given username
      def find_user_by_username(username, params = {})
        params.merge!(username: username)
        users(params).first
      end

      # Returns a user for a given channel id
      # @return [Code42::User] The requested user
      # @param channel_id [String, Integer] A code42 User
      def find_user_by_channel_id(channel_id = 1)
        object_from_response(Code42::User, :get, "userChannel?channelCustomerId=#{channel_id}")
      end

      # Returns a list of up to 100 users
      # @return [Array] An array of matching users
      # @param params [Hash] A hash of parameters to match results against
      def users(params = {})
        params.merge!(key: 'users')
        objects_from_response(Code42::User, :get, 'user', params)
      end

      # Check if user exists with given username.
      def user_exists?(username)
        users(username: username).present?
      end

      # Block a user from logging in
      # @return true if blocked
      # @params id [Integer, String] The user ID you want to block
      def block_user(id)
        put("UserBlock/#{id}")
      end

      # Unblock a previously blocked user
      # @return true if unblocked
      # @params id [Integer, String] The user ID you want to unblock
      def unblock_user(id)
        delete("UserBlock/#{id}")
      end

      def deactivate_user(id)
        put("UserDeactivation/#{id}")
      end

      def activate_user(id)
        delete("UserDeactivation/#{id}")
      end

      # Returns a list of permissions for the session user
      # @return [Array] An array of matching permissions
      def permissions
        objects_from_response(Code42::Permission, :get, 'permission')
      end

    end
  end
end


text:
define([
    'backbone',
    'marionette',
    'underscore',
    'hbs!app/applets/ccd_grid/modal/headerTemplate'
], function(Backbone, Marionette, _, HeaderTemplate) {
    'use strict';

    var theView;

    //Modal Navigation Item View
    return Backbone.Marionette.ItemView.extend({
        events: {
            'click #ccd-previous, #ccd-next': 'navigateModal'
        },

        navigateModal: function(e) {
            var $target = $(e.currentTarget),
                id = $target.attr('id');

            //what does the code below exist for the ternary is never assigned to anything?
            id === 'ccd-previous' ? this.theView.getPrevModal() : this.theView.getNextModal();
        },

        template: HeaderTemplate

    });

});


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const prefs = require("sdk/preferences/service");
const { id, name } = require("sdk/self");
const { Cc, Cu, Ci } = require("chrome");
const { loadSubScript } = Cc['@mozilla.org/moz/jssubscript-loader;1'].
                     getService(Ci.mozIJSSubScriptLoader);

const ADDON_LOG_LEVEL_PREF = "extensions." + id + ".sdk.console.logLevel";
const SDK_LOG_LEVEL_PREF = "extensions.sdk.console.logLevel";

const HAS_ORIGINAL_ADDON_LOG_LEVEL = prefs.has(ADDON_LOG_LEVEL_PREF);
const ORIGINAL_ADDON_LOG_LEVEL = prefs.get(ADDON_LOG_LEVEL_PREF);
const HAS_ORIGINAL_SDK_LOG_LEVEL = prefs.has(SDK_LOG_LEVEL_PREF);
const ORIGINAL_SDK_LOG_LEVEL = prefs.get(SDK_LOG_LEVEL_PREF);

exports.testPlainTextConsole = function(assert) {
  let prints = [];
  function print(message) {
    prints.push(message);
  }
  function lastPrint() {
    let last = prints.slice(-1)[0];
    prints = [];
    return last;
  }

  prefs.set(SDK_LOG_LEVEL_PREF, "all");
  prefs.reset(ADDON_LOG_LEVEL_PREF);

  let Console = require("sdk/console/plain-text").PlainTextConsole;
  let con = new Console(print);

  assert.ok("PlainTextConsole instantiates");

  con.log('testing', 1, [2, 3, 4]);
  assert.equal(lastPrint(), "console.log: " + name + ": testing 1 Array [2,3,4]\n",
                   "PlainTextConsole.log() must work.");

  con.info('testing', 1, [2, 3, 4]);
  assert.equal(lastPrint(), "console.info: " + name + ": testing 1 Array [2,3,4]\n",
                   "PlainTextConsole.info() must work.");

  con.warn('testing', 1, [2, 3, 4]);
  assert.equal(lastPrint(), "console.warn: " + name + ": testing 1 Array [2,3,4]\n",
                   "PlainTextConsole.warn() must work.");

  con.error('testing', 1, [2, 3, 4]);
  assert.equal(prints[0], "console.error: " + name + ": \n",
                   "PlainTextConsole.error() must work.");
  assert.equal(prints[1], "  testing\n")
  assert.equal(prints[2], "  1\n")
  assert.equal(prints[3], "Array\n    - 0 = 2\n    - 1 = 3\n    - 2 = 4\n    - length = 3\n");
  prints = [];

  con.debug('testing', 1, [2, 3, 4]);
  assert.equal(prints[0], "console.debug: " + name + ": \n",
                   "PlainTextConsole.debug() must work.");
  assert.equal(prints[1], "  testing\n")
  assert.equal(prints[2], "  1\n")
  assert.equal(prints[3], "Array\n    - 0 = 2\n    - 1 = 3\n    - 2 = 4\n    - length = 3\n");
  prints = [];

  con.log('testing', undefined);
  assert.equal(lastPrint(), "console.log: " + name + ": testing undefined\n",
                   "PlainTextConsole.log() must stringify undefined.");

  con.log('testing', null);
  assert.equal(lastPrint(), "console.log: " + name + ": testing null\n",
                   "PlainTextConsole.log() must stringify null.");

  // TODO: Fix console.jsm to detect custom toString.
  con.log("testing", { toString: function() "obj.toString()" });
  assert.equal(lastPrint(), "console.log: " + name + ": testing {}\n",
                   "PlainTextConsole.log() doesn't printify custom toString.");

  con.log("testing", { toString: function() { throw "fail!"; } });
  assert.equal(lastPrint(), "console.log: " + name + ": testing {}\n",
                   "PlainTextConsole.log() must stringify custom bad toString.");

  con.exception(new Error("blah"));

  assert.equal(prints[0], "console.error: " + name + ": \n");
  let tbLines = prints[1].split("\n");
  assert.equal(tbLines[0], "  Message: Error: blah");
  assert.equal(tbLines[1], "  Stack:");
  assert.ok(prints[1].indexOf(module.uri + ":84") !== -1);
  prints = []

  try {
    loadSubScript("invalid-url", {});
    assert.fail("successed in calling loadSubScript with invalid-url");
  }
  catch(e) {
    con.exception(e);
  }
  assert.equal(prints[0], "console.error: " + name + ": \n");
  assert.equal(prints[1], "  Error creating URI (invalid URL scheme?)\n");
  prints = [];

  con.trace();
  let tbLines = prints[0].split("\n");
  assert.equal(tbLines[0], "console.trace: " + name + ": ");
  assert.ok(tbLines[1].indexOf("_ain-text-console.js 105") == 0);
  prints = [];

  // Whether or not console methods should print at the various log levels,
  // structured as a hash of levels, each of which contains a hash of methods,
  // each of whose value is whether or not it should print, i.e.:
  // { [level]: { [method]: [prints?], ... }, ... }.
  let levels = {
    all:   { debug: true,  log: true,  info: true,  warn: true,  error: true  },
    debug: { debug: true,  log: true,  info: true,  warn: true,  error: true  },
    info:  { debug: false, log: true,  info: true,  warn: true,  error: true  },
    warn:  { debug: false, log: false, info: false, warn: true,  error: true  },
    error: { debug: false, log: false, info: false, warn: false, error: true  },
    off:   { debug: false, log: false, info: false, warn: false, error: false },
  };

  // The messages we use to test the various methods, as a hash of methods.
  let messages = {
    debug: "console.debug: " + name + ": \n  \n",
    log: "console.log: " + name + ": \n",
    info: "console.info: " + name + ": \n",
    warn: "console.warn: " + name + ": \n",
    error: "console.error: " + name + ": \n  \n",
  };

  for (let level in levels) {
    let methods = levels[level];
    for (let method in methods) {
      // We have to reset the log level pref each time we run the test
      // because the test runner relies on the console to print test output,
      // and test results would not get printed to the console for some
      // values of the pref.
      prefs.set(SDK_LOG_LEVEL_PREF, level);
      con[method]("");
      prefs.set(SDK_LOG_LEVEL_PREF, "all");
      assert.equal(prints.join(""),
                       (methods[method] ? messages[method] : ""),
                       "at log level '" + level + "', " + method + "() " +
                       (methods[method] ? "prints" : "doesn't print"));
      prints = [];
    }
  }

  prefs.set(SDK_LOG_LEVEL_PREF, "off");
  prefs.set(ADDON_LOG_LEVEL_PREF, "all");
  con.debug("");
  assert.equal(prints.join(""), messages["debug"],
                   "addon log level 'all' overrides SDK log level 'off'");
  prints = [];

  prefs.set(SDK_LOG_LEVEL_PREF, "all");
  prefs.set(ADDON_LOG_LEVEL_PREF, "off");
  con.error("");
  prefs.reset(ADDON_LOG_LEVEL_PREF);
  assert.equal(lastPrint(), null,
                   "addon log level 'off' overrides SDK log level 'all'");

  restorePrefs();
};

exports.testPlainTextConsoleBoundMethods = function(assert) {
  let prints = [];
  function print(message) {
    prints.push(message);
  }
  function lastPrint() {
    let last = prints.slice(-1)[0];
    prints = [];
    return last;
  }

  prefs.set(SDK_LOG_LEVEL_PREF, "all");
  prefs.reset(ADDON_LOG_LEVEL_PREF);

  let Console = require("sdk/console/plain-text").PlainTextConsole;
  let { log, info, warn, error, debug, exception, trace } = new Console(print);

  assert.ok("PlainTextConsole instantiates");

  log('testing', 1, [2, 3, 4]);
  assert.equal(lastPrint(), "console.log: " + name + ": testing 1 Array [2,3,4]\n",
                   "PlainTextConsole.log() must work.");

  info('testing', 1, [2, 3, 4]);
  assert.equal(lastPrint(), "console.info: " + name + ": testing 1 Array [2,3,4]\n",
                   "PlainTextConsole.info() must work.");

  warn('testing', 1, [2, 3, 4]);
  assert.equal(lastPrint(), "console.warn: " + name + ": testing 1 Array [2,3,4]\n",
                   "PlainTextConsole.warn() must work.");

  error('testing', 1, [2, 3, 4]);
  assert.equal(prints[0], "console.error: " + name + ": \n",
                   "PlainTextConsole.error() must work.");
  assert.equal(prints[1], "  testing\n")
  assert.equal(prints[2], "  1\n")
  assert.equal(prints[3], "Array\n    - 0 = 2\n    - 1 = 3\n    - 2 = 4\n    - length = 3\n");
  prints = [];

  debug('testing', 1, [2, 3, 4]);
  assert.equal(prints[0], "console.debug: " + name + ": \n",
                   "PlainTextConsole.debug() must work.");
  assert.equal(prints[1], "  testing\n")
  assert.equal(prints[2], "  1\n")
  assert.equal(prints[3], "Array\n    - 0 = 2\n    - 1 = 3\n    - 2 = 4\n    - length = 3\n");
  prints = [];

  exception(new Error("blah"));

  assert.equal(prints[0], "console.error: " + name + ": \n");
  let tbLines = prints[1].split("\n");
  assert.equal(tbLines[0], "  Message: Error: blah");
  assert.equal(tbLines[1], "  Stack:");
  assert.ok(prints[1].indexOf(module.uri + ":215") !== -1);
  prints = []

  trace();
  let tbLines = prints[0].split("\n");
  assert.equal(tbLines[0], "console.trace: " + name + ": ");
  assert.ok(tbLines[1].indexOf("_ain-text-console.js 224") === 0);
  prints = [];

  restorePrefs();
};

exports.testConsoleInnerID = function(assert) {
  let Console = require("sdk/console/plain-text").PlainTextConsole;
  let { log, info, warn, error, debug, exception, trace } = new Console(function() {}, "test ID");

  let messages = [];
  function onMessage({ subject }) {
    let message = subject.wrappedJSObject;
    messages.push({ msg: message.arguments[0], type: message.level, innerID: message.innerID });
  }

  const system = require("sdk/system/events");
  system.on("console-api-log-event", onMessage);

  log("Test log");
  warn("Test warning");
  error("Test error");

  assert.equal(messages.length, 3, "Should see 3 log events");
  assert.deepEqual(messages[0], { msg: "Test log", type: "log", innerID: "test ID" }, "Should see the right event");
  assert.deepEqual(messages[1], { msg: "Test warning", type: "warn", innerID: "test ID" }, "Should see the right event");
  assert.deepEqual(messages[2], { msg: "Test error", type: "error", innerID: "test ID" }, "Should see the right event");

  system.off("console-api-log-event", onMessage);
};

function restorePrefs() {
  if (HAS_ORIGINAL_ADDON_LOG_LEVEL)
    prefs.set(ADDON_LOG_LEVEL_PREF, ORIGINAL_ADDON_LOG_LEVEL);
  else
    prefs.reset(ADDON_LOG_LEVEL_PREF);

  if (HAS_ORIGINAL_SDK_LOG_LEVEL)
    prefs.set(SDK_LOG_LEVEL_PREF, ORIGINAL_SDK_LOG_LEVEL);
  else
    prefs.reset(SDK_LOG_LEVEL_PREF);
}

require("test").run(exports);


text:
.. _index:

=======================================
webassets - Asset management for Python
=======================================

------------
Introduction
------------

webassets is a general, dependency-independent library for managing
the assets of your web application. It can merge and compress your CSS
and JavaScript files, supporting a wide variety of different filters,
and supports working with compilers like CoffeeScript or Sass.

---------------------
Framework integration
---------------------

For some web frameworks, ``webassets`` provides special
integration. If you are using one of the supported frameworks, go to
the respective page:

.. toctree::
   :maxdepth: 1

   With Django <https://django-assets.readthedocs.io/en/latest/>
   With Flask <https://flask-assets.readthedocs.io/en/latest/>
   With Pyramid <https://github.com/sontek/pyramid_webassets>
   Other or no framework <generic/index>

----------------------
Detailed documentation
----------------------

This documentation also includes some pages which are applicable regardless
of the framework used:

.. toctree::
   :maxdepth: 2

   environment
   bundles
   script
   builtin_filters
   expiring
   custom_filters
   css_compilers
   loaders
   integration/index
   faq
   upgrading