text:
/******************************************************************************
 *
 *  This is the implementation of the API for GATT module of BTA.
 *
 ******************************************************************************/

#include "bt_target.h"
#include "allocator.h"

#if defined(GATTC_INCLUDED) && (GATTC_INCLUDED == TRUE)

#include <string.h>
#include "bta_sys.h"
#include "bta_gatt_api.h"
#include "bta_gattc_int.h"

/*****************************************************************************
**  Constants
*****************************************************************************/

static const tBTA_SYS_REG bta_gattc_reg = {
    bta_gattc_hdl_event,
    BTA_GATTC_Disable
};

/*******************************************************************************
**
** Function         BTA_GATTC_Disable
**
** Description      This function is called to disable GATTC module
**
** Parameters       None.
**
** Returns          None
**
*******************************************************************************/
void BTA_GATTC_Disable(void)
{
    BT_HDR  *p_buf;

    if (bta_sys_is_register(BTA_ID_GATTC) == FALSE) {
        APPL_TRACE_WARNING("GATTC Module not enabled/already disabled\n");
        return;
    }
    if ((p_buf = (BT_HDR *) osi_malloc(sizeof(BT_HDR))) != NULL) {
        p_buf->event = BTA_GATTC_API_DISABLE_EVT;
        bta_sys_sendmsg(p_buf);
    }
    bta_sys_deregister(BTA_ID_GATTC);

}

/*******************************************************************************
**
** Function         BTA_GATTC_AppRegister
**
** Description      This function is called to register application callbacks
**                    with BTA GATTC module.
**
** Parameters       p_app_uuid - applicaiton UUID
**                  p_client_cb - pointer to the application callback function.
**
** Returns          None
**
*******************************************************************************/
void BTA_GATTC_AppRegister(tBT_UUID *p_app_uuid, tBTA_GATTC_CBACK *p_client_cb)
{
    tBTA_GATTC_API_REG  *p_buf;

    if (bta_sys_is_register(BTA_ID_GATTC) == FALSE) {
        bta_sys_register(BTA_ID_GATTC, &bta_gattc_reg);
    }

    if ((p_buf = (tBTA_GATTC_API_REG *) osi_malloc(sizeof(tBTA_GATTC_API_REG))) != NULL) {
        p_buf->hdr.event    = BTA_GATTC_API_REG_EVT;
        if (p_app_uuid != NULL) {
            memcpy(&p_buf->app_uuid, p_app_uuid, sizeof(tBT_UUID));
        }
        p_buf->p_cback      = p_client_cb;

        bta_sys_sendmsg(p_buf);
    }
    return;
}

/*******************************************************************************
**
** Function         BTA_GATTC_AppDeregister
**
** Description      This function is called to deregister an application
**                  from BTA GATTC module.
**
** Parameters       client_if - client interface identifier.
**
** Returns          None
**
*******************************************************************************/
void BTA_GATTC_AppDeregister(tBTA_GATTC_IF client_if)
{
    tBTA_GATTC_API_DEREG  *p_buf;

    if ((p_buf = (tBTA_GATTC_API_DEREG *) osi_malloc(sizeof(tBTA_GATTC_API_DEREG))) != NULL) {
        p_buf->hdr.event = BTA_GATTC_API_DEREG_EVT;
        p_buf->client_if = client_if;
        bta_sys_sendmsg(p_buf);
    }
    return;
}

/*******************************************************************************
**
** Function         BTA_GATTC_Open
**
** Description      Open a direct connection or add a background auto connection
**                  bd address
**
** Parameters       client_if: server interface.
**                  remote_bda: remote device BD address.
**                  is_direct: direct connection or background auto connection
**                  transport: Transport to be used for GATT connection (BREDR/LE)
**
** Returns          void
**
*******************************************************************************/
void BTA_GATTC_Open(tBTA_GATTC_IF client_if, BD_ADDR remote_bda,
                    BOOLEAN is_direct, tBTA_GATT_TRANSPORT transport)
{
    tBTA_GATTC_API_OPEN  *p_buf;

    if ((p_buf = (tBTA_GATTC_API_OPEN *) osi_malloc(sizeof(tBTA_GATTC_API_OPEN))) != NULL) {
        p_buf->hdr.event = BTA_GATTC_API_OPEN_EVT;

        p_buf->client_if = client_if;
        p_buf->is_direct = is_direct;
        p_buf->transport = transport;
        memcpy(p_buf->remote_bda, remote_bda, BD_ADDR_LEN);

        bta_sys_sendmsg(p_buf);
    }
    return;
}

/*******************************************************************************
**
** Function         BTA_GATTC_CancelOpen
**
** Description      Cancel a direct open connection or remove a background auto connection
**                  bd address
**
** Parameters       client_if: server interface.
**                  remote_bda: remote device BD address.
**                  is_direct: direct connection or background auto connection
**
** Returns          void
**
*******************************************************************************/
void BTA_GATTC_CancelOpen(tBTA_GATTC_IF client_if, BD_ADDR remote_bda, BOOLEAN is_direct)
{
    tBTA_GATTC_API_CANCEL_OPEN  *p_buf;

    if ((p_buf = (tBTA_GATTC_API_CANCEL_OPEN *) osi_malloc(sizeof(tBTA_GATTC_API_CANCEL_OPEN))) != NULL) {
        p_buf->hdr.event = BTA_GATTC_API_CANCEL_OPEN_EVT;

        p_buf->client_if = client_if;
        p_buf->is_direct = is_direct;
        memcpy(p_buf->remote_bda, remote_bda, BD_ADDR_LEN);

        bta_sys_sendmsg(p_buf);
    }
    return;
}

/*******************************************************************************
**
** Function         BTA_GATTC_Close
**
** Description      Close a connection to a GATT server.
**
** Parameters       conn_id: connection ID to be closed.
**
** Returns          void
**
*******************************************************************************/
void BTA_GATTC_Close(UINT16 conn_id)
{
    BT_HDR  *p_buf;

    if ((p_buf = (BT_HDR *) osi_malloc(sizeof(BT_HDR))) != NULL) {
        p_buf->event = BTA_GATTC_API_CLOSE_EVT;

        p_buf->layer_specific = conn_id;

        bta_sys_sendmsg(p_buf);
    }
    return;

}
/*******************************************************************************
**
** Function         BTA_GATTC_ConfigureMTU
**
** Description      Configure the MTU size in the GATT channel. This can be done
**                  only once per connection.
**
** Parameters       conn_id: connection ID.
**                  mtu: desired MTU size to use.
**
** Returns          void
**
*******************************************************************************/
void BTA_GATTC_ConfigureMTU (UINT16 conn_id)
{
    tBTA_GATTC_API_CFG_MTU  *p_buf;

    if ((p_buf = (tBTA_GATTC_API_CFG_MTU *) osi_malloc(sizeof(tBTA_GATTC_API_CFG_MTU))) != NULL) {
        p_buf->hdr.event = BTA_GATTC_API_CFG_MTU_EVT;
        p_buf->hdr.layer_specific = conn_id;

        bta_sys_sendmsg(p_buf);
    }
    return;
}
/*******************************************************************************
**
** Function         BTA_GATTC_ServiceSearchRequest
**
** Description      This function is called to request a GATT service discovery
**                    on a GATT server. This function report service search result
**                  by a callback event, and followed by a service search complete
**                  event.
**
** Parameters       conn_id: connection ID.
**                  p_srvc_uuid: a UUID of the service application is interested in.
**                              If Null, discover for all services.
**
** Returns          None
**
*******************************************************************************/
void BTA_GATTC_ServiceSearchRequest (UINT16 conn_id, tBT_UUID *p_srvc_uuid)
{
    tBTA_GATTC_API_SEARCH  *p_buf;
    UINT16  len = sizeof(tBTA_GATTC_API_SEARCH) + sizeof(tBT_UUID);

    if ((p_buf = (tBTA_GATTC_API_SEARCH *) osi_malloc(len)) != NULL) {
        memset(p_buf, 0, len);

        p_buf->hdr.event = BTA_GATTC_API_SEARCH_EVT;
        p_buf->hdr.layer_specific = conn_id;

        if (p_srvc_uuid) {
            p_buf->p_srvc_uuid = (tBT_UUID *)(p_buf + 1);
            memcpy(p_buf->p_srvc_uuid, p_srvc_uuid, sizeof(tBT_UUID));
        } else {
            p_buf->p_srvc_uuid = NULL;
        }

        bta_sys_sendmsg(p_buf);
    }
    return;
}

/*******************************************************************************
**
** Function         BTA_GATTC_GetServices
**
** Description      This function is called to find the services on the given server.
**
** Parameters       conn_id: connection ID which identify the server.
**
** Returns          returns list_t of tBTA_GATTC_SERVICE or NULL.
**
*******************************************************************************/
const list_t* BTA_GATTC_GetServices(UINT16 conn_id)
{
    return bta_gattc_get_services(conn_id);
}

/*******************************************************************************
**
** Function         BTA_GATTC_GetCharacteristic
**
** Description      This function is called to find the characteristic on the given server.
**
** Parameters       conn_id - connection ID which identify the server.
**                  handle - characteristic handle
**
** Returns          returns pointer to tBTA_GATTC_CHARACTERISTIC or NULL.
**
*******************************************************************************/
const tBTA_GATTC_CHARACTERISTIC* BTA_GATTC_GetCharacteristic(UINT16 conn_id, UINT16 handle)
{
    return bta_gattc_get_characteristic(conn_id, handle);
}

/*******************************************************************************
**
** Function         BTA_GATTC_GetDescriptor
**
** Description      This function is called to find the characteristic on the given server.
**
** Parameters       conn_id - connection ID which identify the server.
**                  handle - descriptor handle
**
** Returns          returns pointer to tBTA_GATTC_DESCRIPTOR or NULL.
**
*******************************************************************************/
const tBTA_GATTC_DESCRIPTOR* BTA_GATTC_GetDescriptor(UINT16 conn_id, UINT16 handle)
{
    return bta_gattc_get_descriptor(conn_id, handle);
}

void BTA_GATTC_GetServiceWithUUID(UINT16 conn_id, tBT_UUID *svc_uuid,
                                  btgatt_db_element_t **db, int *count)
{
    bta_gattc_get_service_with_uuid(conn_id, svc_uuid, db, count);
}

void BTA_GATTC_GetAllChar(UINT16 conn_id, UINT16 start_handle, UINT16 end_handle,
                          btgatt_db_element_t **db, int *count)
{
    bta_gattc_get_db_with_opration(conn_id,
                                   GATT_OP_GET_ALL_CHAR,
                                   0,
                                   NULL,
                                   NULL,
                                   NULL,
                                   start_handle,
                                   end_handle,
                                   db,
                                   count);
}

void BTA_GATTC_GetAllDescriptor(UINT16 conn_id, UINT16 char_handle,
                                btgatt_db_element_t **db, int *count)
{
    bta_gattc_get_db_with_opration(conn_id,
                                   GATT_OP_GET_ALL_DESCRI,
                                   char_handle,
                                   NULL,
                                   NULL,
                                   NULL,
                                   0,
                                   0xFFFF,
                                   db,
                                   count);
}

void BTA_GATTC_GetCharByUUID(UINT16 conn_id, UINT16 start_handle, UINT16 end_handle, tBT_UUID char_uuid,
                             btgatt_db_element_t **db, int *count)
{
    bta_gattc_get_db_with_opration(conn_id,
                                   GATT_OP_GET_CHAR_BY_UUID,
                                   0,
                                   NULL,
                                   &char_uuid,
                                   NULL,
                                   start_handle,
                                   end_handle,
                                   db,
                                   count);
}

void BTA_GATTC_GetDescrByUUID(UINT16 conn_id, uint16_t start_handle, uint16_t end_handle,
                              tBT_UUID char_uuid, tBT_UUID descr_uuid,
                              btgatt_db_element_t **db, int *count)
{
    bta_gattc_get_db_with_opration(conn_id,
                                   GATT_OP_GET_DESCRI_BY_UUID,
                                   0,
                                   NULL,
                                   &char_uuid,
                                   &descr_uuid,
                                   start_handle,
                                   end_handle,
                                   db,
                                   count);
}

void BTA_GATTC_GetDescrByCharHandle(UINT16 conn_id, UINT16 char_handle, tBT_UUID descr_uuid,
                                    btgatt_db_element_t **db, int *count)
{
    bta_gattc_get_db_with_opration(conn_id,
                                   GATT_OP_GET_DESCRI_BY_HANDLE,
                                   char_handle,
                                   NULL,
                                   NULL,
                                   &descr_uuid,
                                   0,
                                   0xFFFF,
                                   db,
                                   count);
}

void BTA_GATTC_GetIncludeService(UINT16 conn_id, UINT16 start_handle, UINT16 end_handle,
                                 tBT_UUID *incl_uuid, btgatt_db_element_t **db, int *count)
{
    bta_gattc_get_db_with_opration(conn_id,
                                   GATT_OP_GET_INCLUDE_SVC,
                                   0,
                                   incl_uuid,
                                   NULL,
                                   NULL,
                                   start_handle,
                                   end_handle,
                                   db,
                                   count);
}

void BTA_GATTC_GetDBSize(UINT16 conn_id, UINT16 start_handle, UINT16 end_handle, int *count)
{
    bta_gattc_get_db_size_handle(conn_id, start_handle, end_handle, count);
}

void BTA_GATTC_GetDBSizeByType(UINT16 conn_id, bt_gatt_db_attribute_type_t type,
                               UINT16 start_handle, UINT16 end_handle, UINT16 char_handle, int *count)
{
    bta_gattc_get_db_size_with_type_handle(conn_id, type, start_handle, end_handle, char_handle, count);
}

/*******************************************************************************
**
** Function         BTA_GATTC_GetGattDb
**
** Description      This function is called to get the GATT database.
**
** Parameters       conn_id: connection ID which identify the server.
**                  db: output parameter which will contain the GATT database copy.
**                      Caller is responsible for freeing it.
**                  count: number of elements in database.
**
*******************************************************************************/
void  BTA_GATTC_GetGattDb(UINT16 conn_id, UINT16 start_handle, UINT16 end_handle,
                          btgatt_db_element_t **db, int *count)
{
    bta_gattc_get_gatt_db(conn_id, start_handle, end_handle, db, count);
}

/*******************************************************************************
**
** Function         BTA_GATTC_ReadCharacteristic
**
** Description      This function is called to read a characteristics value
**
** Parameters       conn_id - connection ID.
**                  handle - characteritic handle to read.
**
** Returns          None
**
*******************************************************************************/
void BTA_GATTC_ReadCharacteristic(UINT16 conn_id, UINT16 handle, tBTA_GATT_AUTH_REQ auth_req)
{
    tBTA_GATTC_API_READ  *p_buf;

    if ((p_buf = (tBTA_GATTC_API_READ *) osi_malloc(sizeof(tBTA_GATTC_API_READ))) != NULL) {
        memset(p_buf, 0, sizeof(tBTA_GATTC_API_READ));

        p_buf->hdr.event = BTA_GATTC_API_READ_EVT;
        p_buf->hdr.layer_specific = conn_id;
        p_buf->auth_req = auth_req;
        p_buf->handle = handle;
        p_buf->cmpl_evt = BTA_GATTC_READ_CHAR_EVT;

        bta_sys_sendmsg(p_buf);
    }
    return;
}

/*******************************************************************************
**
** Function         BTA_GATTC_ReadCharDescr
**
** Description      This function is called to read a descriptor value.
**
** Parameters       conn_id - connection ID.
**                  handle - descriptor handle to read.
**
** Returns          None
**
*******************************************************************************/
void BTA_GATTC_ReadCharDescr (UINT16 conn_id, UINT16 handle, tBTA_GATT_AUTH_REQ auth_req)
{
    tBTA_GATTC_API_READ  *p_buf;
    UINT16  len = (UINT16)(sizeof(tBTA_GATT_ID) + sizeof(tBTA_GATTC_API_READ));

    if ((p_buf = (tBTA_GATTC_API_READ *) osi_malloc(len)) != NULL) {
        memset(p_buf, 0, sizeof(tBTA_GATTC_API_READ));

        p_buf->hdr.event = BTA_GATTC_API_READ_EVT;
        p_buf->hdr.layer_specific = conn_id;
        p_buf->auth_req = auth_req;
        p_buf->handle = handle;
        p_buf->cmpl_evt = BTA_GATTC_READ_DESCR_EVT;

        bta_sys_sendmsg(p_buf);
    }
    return;

}
/*******************************************************************************
**
** Function         BTA_GATTC_ReadMultiple
**
** Description      This function is called to read multiple characteristic or
**                  characteristic descriptors.
**
** Parameters       conn_id - connection ID.
**                    p_read_multi - pointer to the read multiple parameter.
**
** Returns          None
**
*******************************************************************************/
void BTA_GATTC_ReadMultiple(UINT16 conn_id, tBTA_GATTC_MULTI *p_read_multi,
                            tBTA_GATT_AUTH_REQ auth_req)
{
    tBTA_GATTC_API_READ_MULTI  *p_buf;
    //tBTA_GATTC_API_READ_MULTI          *p_value;
    UINT16      len = (UINT16)(sizeof(tBTA_GATTC_API_READ_MULTI));

    if ((p_buf = (tBTA_GATTC_API_READ_MULTI *) osi_malloc(len)) != NULL) {
        memset(p_buf, 0, len);

        p_buf->hdr.event = BTA_GATTC_API_READ_MULTI_EVT;
        p_buf->hdr.layer_specific = conn_id;
        p_buf->auth_req = auth_req;
        p_buf->num_attr = p_read_multi->num_attr;
        p_buf->cmpl_evt = BTA_GATTC_READ_MUTIPLE_EVT;
        if (p_buf->num_attr > 0) {
            memcpy(p_buf->handles, p_read_multi->handles, sizeof(UINT16) * p_read_multi->num_attr);
	    }

        bta_sys_sendmsg(p_buf);
    }
    return;
}

/*******************************************************************************
**
** Function         BTA_GATTC_WriteCharValue
**
** Description      This function is called to write characteristic value.
**
** Parameters       conn_id - connection ID.
**                  handle - characteristic handle to write.
**                  write_type - type of write.
**                  len: length of the data to be written.
**                  p_value - the value to be written.
**
** Returns          None
**
*******************************************************************************/
void BTA_GATTC_WriteCharValue ( UINT16 conn_id,
                                UINT16 handle,
                                tBTA_GATTC_WRITE_TYPE  write_type,
                                UINT16 len,
                                UINT8 *p_value,
                                tBTA_GATT_AUTH_REQ auth_req)
{
    tBTA_GATTC_API_WRITE  *p_buf;

    if ((p_buf = (tBTA_GATTC_API_WRITE *) osi_malloc((UINT16)(sizeof(tBTA_GATTC_API_WRITE) + len))) != NULL) {
        memset(p_buf, 0, sizeof(tBTA_GATTC_API_WRITE) + len);

        p_buf->hdr.event = BTA_GATTC_API_WRITE_EVT;
        p_buf->hdr.layer_specific = conn_id;
        p_buf->auth_req = auth_req;
        p_buf->handle = handle;
        p_buf->cmpl_evt = BTA_GATTC_WRITE_CHAR_EVT;
        p_buf->write_type = write_type;
        p_buf->len = len;

        if (p_value && len > 0) {
            p_buf->p_value = (UINT8 *)(p_buf + 1);
            memcpy(p_buf->p_value, p_value, len);
        }

        bta_sys_sendmsg(p_buf);
    }
    return;
}
/*******************************************************************************
**
** Function         BTA_GATTC_WriteCharDescr
**
** Description      This function is called to write descriptor value.
**
** Parameters       conn_id - connection ID
**                  handle - descriptor hadle to write.
**                  write_type - write type.
**                  p_value - the value to be written.
**
** Returns          None
**
*******************************************************************************/
void BTA_GATTC_WriteCharDescr (UINT16 conn_id,
                               UINT16 handle,
                               tBTA_GATTC_WRITE_TYPE  write_type,
                               tBTA_GATT_UNFMT      *p_data,
                               tBTA_GATT_AUTH_REQ auth_req)
{
    size_t len = sizeof(tBTA_GATTC_API_WRITE);
    tBTA_GATTC_API_WRITE *p_buf;
    if (p_data != NULL) {
        len += p_data->len;
    }

    if ((p_buf = (tBTA_GATTC_API_WRITE *) osi_malloc(len)) != NULL) {
        memset(p_buf, 0, len);

        p_buf->hdr.event = BTA_GATTC_API_WRITE_EVT;
        p_buf->hdr.layer_specific = conn_id;
        p_buf->auth_req = auth_req;
        p_buf->handle = handle;
        p_buf->cmpl_evt = BTA_GATTC_WRITE_DESCR_EVT;
        p_buf->write_type = write_type;

        if (p_data && p_data->len != 0) {
            p_buf->p_value  = (UINT8 *)(p_buf + 1);
            p_buf->len      = p_data->len;
            /* pack the descr data */
            memcpy(p_buf->p_value, p_data->p_value, p_data->len);
        }

        bta_sys_sendmsg(p_buf);
    }
    return;

}
/*******************************************************************************
**
** Function         BTA_GATTC_PrepareWrite
**
** Description      This function is called to prepare write a characteristic value.
**
** Parameters       conn_id - connection ID.
**                    p_char_id - GATT characteritic ID of the service.
**                  offset - offset of the write value.
**                  len: length of the data to be written.
**                  p_value - the value to be written.
**
** Returns          None
**
*******************************************************************************/
void BTA_GATTC_PrepareWrite  (UINT16 conn_id, UINT16 handle,
                              UINT16 offset, UINT16 len, UINT8 *p_value,
                              tBTA_GATT_AUTH_REQ auth_req)
{
    tBTA_GATTC_API_WRITE  *p_buf;

    if ((p_buf = (tBTA_GATTC_API_WRITE *) osi_malloc((UINT16)(sizeof(tBTA_GATTC_API_WRITE) + len))) != NULL) {
        memset(p_buf, 0, sizeof(tBTA_GATTC_API_WRITE) + len);

        p_buf->hdr.event = BTA_GATTC_API_WRITE_EVT;
        p_buf->hdr.layer_specific = conn_id;
        p_buf->auth_req = auth_req;
        p_buf->handle = handle;

        p_buf->write_type = BTA_GATTC_WRITE_PREPARE;
        p_buf->offset   = offset;
        p_buf->len = len;

        if (p_value && len > 0) {
            p_buf->p_value = (UINT8 *)(p_buf + 1);
            memcpy(p_buf->p_value, p_value, len);
        }

        bta_sys_sendmsg(p_buf);
    }
    return;

}
/*******************************************************************************
**
** Function         BTA_GATTC_PrepareWriteCharDescr
**
** Description      This function is called to prepare write a characteristic descriptor value.
**
** Parameters       conn_id - connection ID.
**                  p_char_descr_id - GATT characteritic descriptor ID of the service.
**                  offset - offset of the write value.
**                  len: length of the data to be written.
**                  p_value - the value to be written.
**
** Returns          None
**
*******************************************************************************/
void BTA_GATTC_PrepareWriteCharDescr  (UINT16 conn_id, UINT16 handle,
                                       UINT16 offset,tBTA_GATT_UNFMT *p_data,
                                       tBTA_GATT_AUTH_REQ auth_req)
{
    tBTA_GATTC_API_WRITE  *p_buf;
    UINT16  len = sizeof(tBTA_GATTC_API_WRITE) + p_data->len;

    if (p_data != NULL) {
        len += p_data->len;
    }

    if ((p_buf = (tBTA_GATTC_API_WRITE *) osi_malloc(len)) != NULL) {
        memset(p_buf, 0, len);

        p_buf->hdr.event = BTA_GATTC_API_WRITE_EVT;
        p_buf->hdr.layer_specific = conn_id;
        p_buf->auth_req = auth_req;
        p_buf->handle = handle;
        p_buf->write_type = BTA_GATTC_WRITE_PREPARE;
        p_buf->offset = offset;

        if (p_data && p_data->len != 0) {
            p_buf->len      = p_data->len;
            p_buf->p_value = (UINT8 *)(p_buf + 1);
            /* pack the descr data */
            memcpy(p_buf->p_value, p_data->p_value, p_data->len);
        }

        bta_sys_sendmsg(p_buf);
    }
    return;

}
/*******************************************************************************
**
** Function         BTA_GATTC_ExecuteWrite
**
** Description      This function is called to execute write a prepare write sequence.
**
** Parameters       conn_id - connection ID.
**                    is_execute - execute or cancel.
**
** Returns          None
**
*******************************************************************************/
void BTA_GATTC_ExecuteWrite  (UINT16 conn_id, BOOLEAN is_execute)
{
    tBTA_GATTC_API_EXEC  *p_buf;

    if ((p_buf = (tBTA_GATTC_API_EXEC *) osi_malloc((UINT16)sizeof(tBTA_GATTC_API_EXEC))) != NULL) {
        memset(p_buf, 0, sizeof(tBTA_GATTC_API_EXEC));
        p_buf->hdr.event = BTA_GATTC_API_EXEC_EVT;
        p_buf->hdr.layer_specific = conn_id;

        p_buf->is_execute = is_execute;

        bta_sys_sendmsg(p_buf);
    }
    return;

}
/*******************************************************************************
**
** Function         BTA_GATTC_SendIndConfirm
**
** Description      This function is called to send handle value confirmation.
**
** Parameters       conn_id - connection ID.
**                    p_char_id - characteristic ID to confirm.
**
** Returns          None
**
*******************************************************************************/
void BTA_GATTC_SendIndConfirm (UINT16 conn_id, UINT16 handle)
{
    tBTA_GATTC_API_CONFIRM  *p_buf;

    APPL_TRACE_API("BTA_GATTC_SendIndConfirm conn_id=%d handle =0x%x",
                   conn_id, handle);

    if ((p_buf = (tBTA_GATTC_API_CONFIRM *) osi_malloc(sizeof(tBTA_GATTC_API_CONFIRM))) != NULL) {
        memset(p_buf, 0, sizeof(tBTA_GATTC_API_CONFIRM));
        p_buf->hdr.event = BTA_GATTC_API_CONFIRM_EVT;
        p_buf->hdr.layer_specific = conn_id;
        p_buf->handle = handle;

        bta_sys_sendmsg(p_buf);
    }
    return;

}

/*******************************************************************************
**
** Function         BTA_GATTC_RegisterForNotifications
**
** Description      This function is called to register for notification of a service.
**
** Parameters       client_if - client interface.
**                  bda - target GATT server.
**                  handle - GATT characteristic handle.
**
** Returns          OK if registration succeed, otherwise failed.
**
*******************************************************************************/
tBTA_GATT_STATUS BTA_GATTC_RegisterForNotifications (tBTA_GATTC_IF client_if,
                                                     BD_ADDR bda, UINT16 handle)
{
    tBTA_GATTC_RCB      *p_clreg;
    tBTA_GATT_STATUS    status = BTA_GATT_ILLEGAL_PARAMETER;
    UINT8               i;

    if (!handle)
    {
        APPL_TRACE_ERROR("deregistration failed, handle is 0");
        return status;
    }

    if ((p_clreg = bta_gattc_cl_get_regcb(client_if)) != NULL) {
        for (i = 0; i < BTA_GATTC_NOTIF_REG_MAX; i ++) {
            if ( p_clreg->notif_reg[i].in_use &&
                    !memcmp(p_clreg->notif_reg[i].remote_bda, bda, BD_ADDR_LEN) &&
                  p_clreg->notif_reg[i].handle == handle) {
                APPL_TRACE_WARNING("notification already registered");
                status = BTA_GATT_OK;
                break;
            }
        }
        if (status != BTA_GATT_OK) {
            for (i = 0; i < BTA_GATTC_NOTIF_REG_MAX; i ++) {
                if (!p_clreg->notif_reg[i].in_use) {
                    memset((void *)&p_clreg->notif_reg[i], 0, sizeof(tBTA_GATTC_NOTIF_REG));

                    p_clreg->notif_reg[i].in_use = TRUE;
                    memcpy(p_clreg->notif_reg[i].remote_bda, bda, BD_ADDR_LEN);

                    p_clreg->notif_reg[i].handle = handle;
                    status = BTA_GATT_OK;
                    break;
                }
            }
            if (i == BTA_GATTC_NOTIF_REG_MAX) {
                status = BTA_GATT_NO_RESOURCES;
                APPL_TRACE_ERROR("Max Notification Reached, registration failed.");
            }
        }
    } else {
        APPL_TRACE_ERROR("Client_if: %d Not Registered", client_if);
    }

    return status;
}

/*******************************************************************************
**
** Function         BTA_GATTC_DeregisterForNotifications
**
** Description      This function is called to de-register for notification of a service.
**
** Parameters       client_if - client interface.
**                  remote_bda - target GATT server.
**                  handle - GATT characteristic handle.
**
** Returns          OK if deregistration succeed, otherwise failed.
**
*******************************************************************************/
tBTA_GATT_STATUS BTA_GATTC_DeregisterForNotifications (tBTA_GATTC_IF client_if,
                                                       BD_ADDR bda, UINT16 handle)
{
    if (!handle) {
        APPL_TRACE_ERROR("%s: deregistration failed, handle is 0", __func__);
        return BTA_GATT_ILLEGAL_PARAMETER;
    }

    tBTA_GATTC_RCB *p_clreg = bta_gattc_cl_get_regcb(client_if);
    if (p_clreg == NULL) {
        APPL_TRACE_ERROR("%s client_if: %d not registered bd_addr:%02x:%02x:%02x:%02x:%02x:%02x",
            __func__, client_if, bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
        return BTA_GATT_ILLEGAL_PARAMETER;
    }

    for (int i = 0; i < BTA_GATTC_NOTIF_REG_MAX; i ++) {
        if (p_clreg->notif_reg[i].in_use &&
            !memcmp(p_clreg->notif_reg[i].remote_bda, bda, BD_ADDR_LEN) &&
            p_clreg->notif_reg[i].handle == handle) {
            APPL_TRACE_DEBUG("%s deregistered bd_addr:%02x:%02x:%02x:%02x:%02x:%02x",
                __func__, bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
            memset(&p_clreg->notif_reg[i], 0, sizeof(tBTA_GATTC_NOTIF_REG));
            return BTA_GATT_OK;
        }
    }

    APPL_TRACE_ERROR("%s registration not found bd_addr:%02x:%02x:%02x:%02x:%02x:%02x",
        __func__, bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
    return BTA_GATT_ERROR;
}

/*******************************************************************************
**
** Function         BTA_GATTC_Refresh
**
** Description      Refresh the server cache of the remote device
**
** Parameters       remote_bda: remote device BD address.
**
** Returns          void
**
*******************************************************************************/
void BTA_GATTC_Refresh(BD_ADDR remote_bda)
{
    tBTA_GATTC_API_OPEN  *p_buf;

    if ((p_buf = (tBTA_GATTC_API_OPEN *) osi_malloc(sizeof(tBTA_GATTC_API_OPEN))) != NULL) {
        p_buf->hdr.event = BTA_GATTC_API_REFRESH_EVT;
        memcpy(p_buf->remote_bda, remote_bda, BD_ADDR_LEN);

        bta_sys_sendmsg(p_buf);
    }
    return;
}

/*******************************************************************************
**
** Function         BTA_GATTC_Listen
**
** Description      Start advertisement to listen for connection request for a GATT
**                  client application.
**
** Parameters       client_if: server interface.
**                  start: to start or stop listening for connection
**                  remote_bda: remote device BD address, if listen to all device
**                              use NULL.
**
** Returns          void
**
*******************************************************************************/
void BTA_GATTC_Listen(tBTA_GATTC_IF client_if, BOOLEAN start, BD_ADDR_PTR target_bda)
{
    tBTA_GATTC_API_LISTEN  *p_buf;

    if ((p_buf = (tBTA_GATTC_API_LISTEN *) osi_malloc((UINT16)(sizeof(tBTA_GATTC_API_LISTEN) + BD_ADDR_LEN))) != NULL) {
        p_buf->hdr.event = BTA_GATTC_API_LISTEN_EVT;

        p_buf->client_if = client_if;
        p_buf->start = start;
        if (target_bda) {
            p_buf->remote_bda = (UINT8 *)(p_buf + 1);
            memcpy(p_buf->remote_bda, target_bda, BD_ADDR_LEN);
        } else {
            p_buf->remote_bda = NULL;
        }

        bta_sys_sendmsg(p_buf);
    }
    return;
}

/*******************************************************************************
**
** Function         BTA_GATTC_Broadcast
**
** Description      Start broadcasting (non-connectable advertisements)
**
** Parameters       client_if: client interface.
**                  start: to start or stop listening for connection
**
** Returns          void
**
*******************************************************************************/
void BTA_GATTC_Broadcast(tBTA_GATTC_IF client_if, BOOLEAN start)
{
    tBTA_GATTC_API_LISTEN  *p_buf;

    if ((p_buf = (tBTA_GATTC_API_LISTEN *) osi_malloc((UINT16)(sizeof(tBTA_GATTC_API_LISTEN) + BD_ADDR_LEN))) != NULL) {
        p_buf->hdr.event = BTA_GATTC_API_BROADCAST_EVT;
        p_buf->client_if = client_if;
        p_buf->start = start;
        bta_sys_sendmsg(p_buf);
    }
    return;
}

#endif /* defined(GATTC_INCLUDED) && (GATTC_INCLUDED == TRUE) */


text:
/*global angular*/
(function () {
    'use strict';

    //Setting up route
    angular.module('blueprints').config(['$stateProvider',
        function ($stateProvider) {
            // Slideshows state routing
            $stateProvider.
                state('blueprints', {
                    url: '/blueprints',
                    controller: 'BlueprintsController',
                    templateUrl: 'modules/blueprints/views/blueprints.client.view.html'
                });
        }]);
}());

redpajama_set_name: RedPajamaGithub


text:
package dk.brics.tajs.analysis.dom.event;

import dk.brics.tajs.analysis.*;
import dk.brics.tajs.analysis.dom.DOMFunctions;
import dk.brics.tajs.analysis.dom.DOMObjects;
import dk.brics.tajs.analysis.dom.DOMWindow;
import dk.brics.tajs.lattice.ObjectLabel;
import dk.brics.tajs.lattice.Value;
import dk.brics.tajs.util.AnalysisException;

import static dk.brics.tajs.analysis.dom.DOMFunctions.createDOMFunction;
import static dk.brics.tajs.analysis.dom.DOMFunctions.createDOMProperty;

/**
 * The Event interface is used to provide contextual information about an event
 * to the handler processing the event. An object which implements the Event
 * interface is generally passed as the first parameter to an event handler.
 * More specific context information is passed to event handlers by deriving
 * additional interfaces from Event which contain information directly relating
 * to the type of event they accompany. These derived interfaces are also
 * implemented by the object passed to the event listener.
 */
public class Event {

    public static ObjectLabel CONSTRUCTOR;
    public static ObjectLabel PROTOTYPE;
    public static ObjectLabel INSTANCES;

    public static void build(State s) {
        CONSTRUCTOR = new ObjectLabel(DOMObjects.EVENT_CONSTRUCTOR, ObjectLabel.Kind.FUNCTION);
        PROTOTYPE = new ObjectLabel(DOMObjects.EVENT_PROTOTYPE, ObjectLabel.Kind.OBJECT);
        INSTANCES = new ObjectLabel(DOMObjects.EVENT_INSTANCES, ObjectLabel.Kind.OBJECT);

        // Constructor Object
        s.newObject(CONSTRUCTOR);
        s.writePropertyWithAttributes(CONSTRUCTOR, "length", Value.makeNum(0).setAttributes(true, true, true));
        s.writePropertyWithAttributes(CONSTRUCTOR, "prototype", Value.makeObject(PROTOTYPE).setAttributes(true, true, true));
        s.writeInternalPrototype(CONSTRUCTOR, Value.makeObject(InitialStateBuilder.OBJECT_PROTOTYPE));
        s.writeProperty(DOMWindow.WINDOW, "Event", Value.makeObject(CONSTRUCTOR));

        // Prototype object
        s.newObject(PROTOTYPE);
        s.writeInternalPrototype(PROTOTYPE, Value.makeObject(InitialStateBuilder.OBJECT_PROTOTYPE));

        // Multiplied object
        s.newObject(INSTANCES);
        s.writeInternalPrototype(INSTANCES, Value.makeObject(PROTOTYPE));

        /*
         * Properties.
         */
        createDOMProperty(s, PROTOTYPE, "type", Value.makeAnyStr().setReadOnly());
        createDOMProperty(s, PROTOTYPE, "target", DOMFunctions.makeAnyHTMLElement().setReadOnly());
        createDOMProperty(s, PROTOTYPE, "currentTarget", DOMFunctions.makeAnyHTMLElement().setReadOnly());
        createDOMProperty(s, PROTOTYPE, "eventPhase", Value.makeAnyNumUInt().setReadOnly());
        createDOMProperty(s, PROTOTYPE, "bubbles", Value.makeAnyBool().setReadOnly());
        createDOMProperty(s, PROTOTYPE, "cancelable", Value.makeAnyBool().setReadOnly());
        createDOMProperty(s, PROTOTYPE, "timeStamp", Value.makeAnyNumUInt().setReadOnly());

        // DOM LEVEL 0
        createDOMProperty(s, PROTOTYPE, "pageX", Value.makeAnyNumUInt());
        createDOMProperty(s, PROTOTYPE, "pageY", Value.makeAnyNumUInt());

        s.multiplyObject(INSTANCES);
        INSTANCES = INSTANCES.makeSingleton().makeSummary();

        /*
         * Constants (PhaseType).
         */
        createDOMProperty(s, PROTOTYPE, "CAPTURING_PHASE", Value.makeNum(1));
        createDOMProperty(s, PROTOTYPE, "AT_TARGET", Value.makeNum(2));
        createDOMProperty(s, PROTOTYPE, "BUBBLING_PHASE", Value.makeNum(3));

        /*
         * Functions.
         */
        createDOMFunction(s, PROTOTYPE, DOMObjects.EVENT_STOP_PROPAGATION, "stopPropagation", 0);
        createDOMFunction(s, PROTOTYPE, DOMObjects.EVENT_PREVENT_DEFAULT, "preventDefault", 0);
        createDOMFunction(s, PROTOTYPE, DOMObjects.EVENT_INIT_EVENT, "initEvent", 3);

    }

    /*
     * Transfer function.
     */

    public static Value evaluate(DOMObjects nativeObject, FunctionCalls.CallInfo call, State s, Solver.SolverInterface c) {
        switch (nativeObject) {
            case EVENT_INIT_EVENT: {
                NativeFunctions.expectParameters(nativeObject, call, c, 3, 3);
                /* Value eventType =*/ Conversion.toString(NativeFunctions.readParameter(call, s, 0), c);
                /* Value canBubble =*/ Conversion.toBoolean(NativeFunctions.readParameter(call, s, 0));
                /* Value cancelable =*/ Conversion.toBoolean(NativeFunctions.readParameter(call, s, 0));
                return Value.makeUndef();
            }
            case EVENT_PREVENT_DEFAULT: {
                NativeFunctions.expectParameters(nativeObject, call, c, 0, 0);
                return Value.makeUndef();
            }
            case EVENT_STOP_PROPAGATION: {
                NativeFunctions.expectParameters(nativeObject, call, c, 0, 0);
                return Value.makeUndef();
            }
            default: {
                throw new AnalysisException("Unsupported Native Object: " + nativeObject);
            }
        }
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections;
using System.Xml;

using Microsoft.Build.BuildEngine.Shared;

using error = Microsoft.Build.BuildEngine.Shared.ErrorUtilities;

namespace Microsoft.Build.BuildEngine
{
    /// <summary>
    /// Class representing a When block (also used to represent the Otherwise
    /// block on a Choose).
    /// </summary>
    internal class When
    {
        #region Member Data

        public enum Options
        {
            ProcessWhen,
            ProcessOtherwise,
        };

        private GroupingCollection propertyAndItemLists = null;
        private Project parentProject = null;

        // This is the "Condition" attribute on the <PropertyGroup> element above.
        private XmlAttribute conditionAttribute = null;

        #endregion

        #region Constructors

        /// <summary>
        /// Constructor for the When block.  Parses the contents of the When block (property
        /// groups, item groups, and nested chooses) and stores them.
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <owner>DavidLe</owner>
        /// <param name="parentProject"></param>
        /// <param name="parentGroupingCollection"></param>
        /// <param name="whenElement"></param>
        /// <param name="importedFromAnotherProject"></param>
        /// <param name="options"></param>
        /// <param name="nestingDepth">stack overflow guard</param>
        internal When(
            Project parentProject,
            GroupingCollection parentGroupingCollection,
            XmlElement whenElement,
            bool importedFromAnotherProject,
            Options options,
            int nestingDepth
            )
        {
            // Make sure the <When> node has been given to us.
            error.VerifyThrow(whenElement != null, "Need valid (non-null) <When> element.");

            // Make sure this really is the <When> node.
            error.VerifyThrow(whenElement.Name == XMakeElements.when || whenElement.Name == XMakeElements.otherwise,
                "Expected <{0}> or <{1}> element; received <{2}> element.",
                XMakeElements.when, XMakeElements.otherwise, whenElement.Name);

            this.propertyAndItemLists = new GroupingCollection(parentGroupingCollection);
            this.parentProject = parentProject;

            string elementName = ((options == Options.ProcessWhen) ? XMakeElements.when : XMakeElements.otherwise);

            if (options == Options.ProcessWhen)
            {
                conditionAttribute = ProjectXmlUtilities.GetConditionAttribute(whenElement, /*verify sole attribute*/ true);
                ProjectErrorUtilities.VerifyThrowInvalidProject(conditionAttribute != null, whenElement, "MissingCondition", XMakeElements.when);
            }
            else
            {
                ProjectXmlUtilities.VerifyThrowProjectNoAttributes(whenElement);
            }

            ProcessWhenChildren(whenElement, parentProject, importedFromAnotherProject, nestingDepth);
        }
        #endregion

        #region Properties

        /// <summary>
        /// Property containing the condition for the When clause.
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <owner>DavidLe</owner>
        /// <returns>string</returns>
        internal string Condition
        {
            get
            {
                return (this.conditionAttribute == null) ? String.Empty : this.conditionAttribute.Value;
            }
        }

        /// <summary>
        /// Property containing the condition for the When clause.
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <owner>DavidLe</owner>
        /// <returns>string</returns>
        internal XmlAttribute ConditionAttribute
        {
            get
            {
                return this.conditionAttribute;
            }
        }
        #endregion

        /// <summary>
        /// The collection of all sub-groups (item/property groups and chooses) inside this When
        /// </summary>
        internal GroupingCollection PropertyAndItemLists
        {
            get
            {
                return this.propertyAndItemLists;
            }
        }

        #region Methods

        /// <summary>
        /// Helper method for processing the children of a When. Only parses Choose,
        /// PropertyGroup, and ItemGroup. All other tags result in an error.
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <owner>DavidLe</owner>
        /// <param name="parentNode"></param>
        /// <param name="parentProjectForChildren"></param>
        /// <param name="importedFromAnotherProject"></param>
        /// <param name="options"></param>
        /// <param name="nestingDepth">Number of parent <Choose> elements this is nested inside</param>
        private void ProcessWhenChildren
            (
            XmlElement parentNode,
            Project parentProjectForChildren, bool importedFromAnotherProject,
            int nestingDepth
            )
        {
            // Loop through the child nodes of the <When> element.
            foreach (XmlNode whenChildNode in parentNode)
            {
                switch (whenChildNode.NodeType)
                {
                    // Handle XML comments under the <When> node (just ignore them).
                    case XmlNodeType.Comment:
                    // fall through
                    case XmlNodeType.Whitespace:
                        // ignore whitespace
                        break;

                    case XmlNodeType.Element:
                        {
                            // Make sure this element doesn't have a custom namespace
                            ProjectXmlUtilities.VerifyThrowProjectValidNamespace((XmlElement)whenChildNode);

                            // The only three types of child nodes that a <When> element can contain
                            // are <PropertyGroup>, <ItemGroup> and <Choose>.
                            switch (whenChildNode.Name)
                            {
                                case XMakeElements.itemGroup:
                                    BuildItemGroup newItemGroup = new BuildItemGroup((XmlElement)whenChildNode, importedFromAnotherProject, parentProjectForChildren);
                                    this.propertyAndItemLists.InsertAtEnd(newItemGroup);
                                    break;

                                // Process the <PropertyGroup> element.
                                case XMakeElements.propertyGroup:
                                    BuildPropertyGroup newPropertyGroup = new BuildPropertyGroup(parentProjectForChildren, (XmlElement)whenChildNode, importedFromAnotherProject);
                                    newPropertyGroup.EnsureNoReservedProperties();
                                    this.propertyAndItemLists.InsertAtEnd(newPropertyGroup);
                                    break;

                                // Process the <Choose> element.
                                case XMakeElements.choose:
                                    Choose newChoose = new Choose(parentProjectForChildren, this.PropertyAndItemLists, (XmlElement)whenChildNode,
                                                                    importedFromAnotherProject, nestingDepth);
                                    this.propertyAndItemLists.InsertAtEnd(newChoose);
                                    break;

                                default:
                                    {
                                        ProjectXmlUtilities.ThrowProjectInvalidChildElement(whenChildNode);
                                        break;
                                    }
                            }
                        }
                        break;

                    default:
                        {
                            ProjectXmlUtilities.ThrowProjectInvalidChildElement(whenChildNode);
                            break;
                        }
                }
            }
        }

       /// <summary>
        /// Evaluates a When clause.  Checks if the condition is true, and if it is,
        /// applies all of the contained property group, item lists, and import statements.
        /// Returns true if the When clause is process (because the condition is true), false
        /// otherwise.
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <owner>DavidLe</owner>
        /// <param name="parentPropertyBag"></param>
        /// <param name="conditionedPropertiesTable"></param>
        /// <returns>bool</returns>
        internal bool EvaluateCondition
        (
            BuildPropertyGroup parentPropertyBag,
            Hashtable conditionedPropertiesTable
        )
        {
            if  (
                    (this.Condition != null)
                    &&
                    !Utilities.EvaluateCondition(this.Condition, this.ConditionAttribute,
                        new Expander(parentPropertyBag, parentProject.EvaluatedItemsByName),
                        conditionedPropertiesTable, ParserOptions.AllowProperties, this.parentProject.ParentEngine.LoggingServices, this.parentProject.ProjectBuildEventContext)
                )
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// Evaluates a When clause.  Checks if the condition is true, and if it is,
        /// applies all of the contained property group, item lists, and import statements.
        /// Returns true if the When clause is process (because the condition is true), false
        /// otherwise.
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <owner>DavidLe</owner>
        /// <param name="parentPropertyBag"></param>
        /// <param name="ignoreCondition"></param>
        /// <param name="honorCondition"></param>
        /// <param name="conditionedPropertiesTable"></param>
        /// <param name="pass"></param>
        /// <returns>bool</returns>
        internal void Evaluate
        (
            BuildPropertyGroup parentPropertyBag,
            bool ignoreCondition, bool honorCondition,
            Hashtable conditionedPropertiesTable,
            ProcessingPass pass
        )
        {
            foreach (IItemPropertyGrouping propOrItem in this.propertyAndItemLists)
            {
                // This is where we selectively evaluate PropertyGroups or Itemgroups during their respective passes.
                // Once we go to a one-pass model, we'll simple spin through all the children and evaluate.
                if (propOrItem is BuildPropertyGroup &&
                    pass == ProcessingPass.Pass1)
                {
                    ((BuildPropertyGroup) propOrItem).Evaluate(parentPropertyBag, conditionedPropertiesTable, pass);
                }
                else if (propOrItem is BuildItemGroup &&
                    pass == ProcessingPass.Pass2)
                {
                    ((BuildItemGroup) propOrItem).Evaluate(parentPropertyBag, parentProject.EvaluatedItemsByName, ignoreCondition, honorCondition, pass);
                }
                else if (propOrItem is Choose)
                {
                    ((Choose) propOrItem).Evaluate(parentPropertyBag, ignoreCondition, honorCondition, conditionedPropertiesTable, pass);
                }
            }
        }

        #endregion
    }
}


text:
/**
 *
 */
package com.tuliomir.smallbatchmaker;

import java.util.Random;

/**
 * @author tuliomiranda
 *
 */
public class Util {

	private static Random randomGenerator;

	/**
	 * Returns a pseudo-random number between min and max, inclusive.
	 * The difference between min and max can be at most
	 * Integer.MAX_VALUE - 1.
	 *
	 * @param min Minimum value
	 * @param max Maximum value.  Must be greater than min.
	 * @return Integer between min and max, inclusive.
	 * @see java.util.Random#nextInt(int)
	 */
	public static int randomInt(int min, int max) {

	    randomGenerator = new Random();

	    // nextInt is normally exclusive of the top value,
	    // so add 1 to make it inclusive
	    int randomNum = randomGenerator.nextInt((max - min) + 1) + min;

	    return randomNum;
	}

	public static void println(String string) {
		System.out.println(string);
	}
}


text:
VSS.init({
    usePlatformStyles: false
});

function showResult(data) {
    document.getElementById("networkResult").style.display = "block";
    document.getElementById("networkResult").value = JSON.stringify(data, null, 4);
}

function getClient() {
    // Using xdm promise implementation, as jquery isn't loaded yet
    var deferred = XDM.createDeferred();
    VSS.require(["VSS/Service", "TFS/Dashboards/RestClient"], function (VSS_Service, dashboardsApi) {
        deferred.resolve(VSS_Service.getCollectionClient(dashboardsApi.DashboardHttpClient3));
    });
    return deferred.promise;
}

function getTeamContext(){
    var webcontext = VSS.getWebContext();
    return {
      projectId : webcontext.project.id,
      teamId: webcontext.team.id
    };
}

function getDashboards() {
    getClient().then(function(client){
        client.getDashboards(getTeamContext())
            .then(function (dashboards) {
                var result = "";
                for (i in dashboards.dashboardEntries) {
                    result += "
" + dashboards.dashboardEntries[i].id + " " + dashboards.dashboardEntries[i].name+"";
                }
                document.getElementById("dashboardList").innerHTML = result;
                showResult(dashboards);
            },function(error){
                showResult(error);
            });
    });
}

function pickDashboard(id){
    document.getElementById("getDashboardId").value = id;
    document.getElementById("deleteDashboardId").value = id;
    document.getElementById("widgetsDashboardId").value = id;
}

function createDashboard() {
    getClient().then(function(client){
        client.createDashboard(
            JSON.parse(document.getElementById("createDashboardPayload").value),
            getTeamContext())
            .then(function (result) {
                showResult(result);
            },function(error){
                showResult(error);
            });
    });
}

function getDashboard() {
    getClient().then(function(client){
        client.getDashboard(getTeamContext(), document.getElementById("getDashboardId").value)
            .then(function (result) {
                showResult(result);
            },function(error){
                showResult(error);
            });
    });
}

function deleteDashboard() {
    getClient().then(function(client){
        client.deleteDashboard(getTeamContext(), document.getElementById("deleteDashboardId").value)
            .then(function (result) {
                showResult(result);
            },function(error){
                showResult(error);
            });
    });
}

function pickWidget(id){
    document.getElementById("getWidgetId").value = id;
    document.getElementById("updateWidgetId").value = id;
    document.getElementById("replaceWidgetId").value = id;
    document.getElementById("deleteWidgetId").value = id;
}

function getWidgets() {
    getClient().then(function(client){
        client.getWidgets(getTeamContext(), document.getElementById("widgetsDashboardId").value)
            .then(function(widgets){
                var result = "";
                for (i in widgets.widgets) {
                    result += "
" +  widgets.widgets[i].id + " " + widgets.widgets[i].name+"";
                }
                document.getElementById("widgetsList").innerHTML = result;
                showResult(widgets);
            },function(error){
                showResult(error);
            });
    });
}

function getWidget() {
    getClient().then(function(client){
        client.getWidget(getTeamContext(), document.getElementById("widgetsDashboardId").value, document.getElementById("getWidgetId").value)
            .then(function (result) {
                showResult(result);
            },function(error){
                showResult(error);
            });
    });
}

function createWidget() {
    getClient().then(function(client){
        client.createWidget(
            JSON.parse(document.getElementById("createWidgetPayload").value),
            getTeamContext(), document.getElementById("widgetsDashboardId").value
            )
            .then(function (result) {
                showResult(result);
            },function(error){
                showResult(error);
            });
    });
}

function updateWidget() {
    getClient().then(function(client){
        client.updateWidget(
            JSON.parse(document.getElementById("updateWidgetPayload").value),
            getTeamContext(), document.getElementById("widgetsDashboardId").value,
            document.getElementById("updateWidgetId").value
            )
            .then(function (result) {
                showResult(result);
            },function(error){
                showResult(error);
            });
    });
}

function replaceWidget() {
    getClient().then(function(client){
        client.replaceWidget(
            JSON.parse(document.getElementById("replaceWidgetPayload").value),
            getTeamContext(), document.getElementById("widgetsDashboardId").value,
            document.getElementById("replaceWidgetId").value
            )
            .then(function (result) {
                showResult(result);
            },function(error){
                showResult(error);
            });
    });
}

function deleteWidget() {
    getClient().then(function(client){
        client.deleteWidget(
            getTeamContext(), document.getElementById("widgetsDashboardId").value,
            document.getElementById("deleteWidgetId").value
            )
            .then(function (result) {
                showResult(result);
            },function(error){
                showResult(error);
            });
    });
}

function replaceWidgets() {
    getClient().then(function(client){
        client.replaceWidgets(
            JSON.parse(document.getElementById("replaceWidgetsPayload").value),
            getTeamContext(), document.getElementById("widgetsDashboardId").value,
            document.getElementById("replaceWidgetsETag").value
            )
            .then(function (result) {
                showResult(result);
            },function(error){
                showResult(error);
            });
    });
}

function updateWidgets() {
    getClient().then(function(client){
        client.updateWidgets(
            JSON.parse(document.getElementById("updateWidgetsPayload").value),
            getTeamContext(), document.getElementById("widgetsDashboardId").value,
            document.getElementById("updateWidgetsETag").value
            )
            .then(function (result) {
                showResult(result);
            },function(error){
                showResult(error);
            });
    });
}


text:
package apps::microsoft::hyperv::2012::local::mode::listnodevms;

use base qw(centreon::plugins::mode);

use strict;
use warnings;
use centreon::plugins::misc;
use centreon::common::powershell::hyperv::2012::listnodevms;
use apps::microsoft::hyperv::2012::local::mode::resources::types qw($node_vm_state);
use JSON::XS;

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options);
    bless $self, $class;

    $options{options}->add_options(arguments => {
        'timeout:s'         => { name => 'timeout', default => 50 },
        'command:s'         => { name => 'command' },
        'command-path:s'    => { name => 'command_path' },
        'command-options:s' => { name => 'command_options' },
        'no-ps'             => { name => 'no_ps' },
        'ps-exec-only'      => { name => 'ps_exec_only' },
        'ps-display'        => { name => 'ps_display' }
    });

    return $self;
}

sub check_options {
    my ($self, %options) = @_;
    $self->SUPER::init(%options);

    centreon::plugins::misc::check_security_command(
        output => $self->{output},
        command => $self->{option_results}->{command},
        command_options => $self->{option_results}->{command_options},
        command_path => $self->{option_results}->{command_path}
    );

    $self->{option_results}->{command} = 'powershell.exe'
        if (!defined($self->{option_results}->{command}) || $self->{option_results}->{command} eq '');
    $self->{option_results}->{command_options} = '-InputFormat none -NoLogo -EncodedCommand'
        if (!defined($self->{option_results}->{command_options}) || $self->{option_results}->{command_options} eq '');
}

sub manage_selection {
    my ($self, %options) = @_;

    #[
    #   { "name": "XXXX1", "state": 2, "status": "Operating normally", "is_clustered": true, "note": null },
    #   { "name": "XXXX2", "state": 2, "status": "Operating normally", "is_clustered": false, "note": null },
    #   { "name": "XXXX3", "state": 2, "status": "Operating normally", "is_clustered": true, "note": null }
    #]
    my $decoded;
    eval {
        $decoded = JSON::XS->new->decode($options{stdout});
    };
    if ($@) {
        $self->{output}->add_option_msg(short_msg => "Cannot decode json response: $@");
        $self->{output}->option_exit();
    }
    return $decoded;
}

sub run {
    my ($self, %options) = @_;

    if (!defined($self->{option_results}->{no_ps})) {
        my $ps = centreon::common::powershell::hyperv::2012::listnodevms::get_powershell();
        if (defined($self->{option_results}->{ps_display})) {
            $self->{output}->output_add(
                severity => 'OK',
                short_msg => $ps
            );
            $self->{output}->display(nolabel => 1, force_ignore_perfdata => 1, force_long_output => 1);
            $self->{output}->exit();
        }

        $self->{option_results}->{command_options} .= " " . centreon::plugins::misc::powershell_encoded($ps);
    }

    my ($stdout) = centreon::plugins::misc::execute(
        output => $self->{output},
        options => $self->{option_results},
        command => $self->{option_results}->{command},
        command_path => $self->{option_results}->{command_path},
        command_options => $self->{option_results}->{command_options}
    );
    if (defined($self->{option_results}->{ps_exec_only})) {
        $self->{output}->output_add(
            severity => 'OK',
            short_msg => $stdout
        );
    } else {
        $self->{output}->output_add(
            severity => 'OK',
            short_msg => 'List virtual machines:'
        );

        my $decoded = $self->manage_selection(stdout => $stdout);
        foreach my $node (@$decoded) {
            $self->{output}->output_add(
                long_msg => sprintf(
                    "'%s' [state = %s] [status = %s]",
                    $node->{name},
                    $node_vm_state->{ $node->{state} },
                    $node->{status}
                )
            );
        }
    }

    $self->{output}->display(nolabel => 1, force_ignore_perfdata => 1, force_long_output => 1);
    $self->{output}->exit();
}

sub disco_format {
    my ($self, %options) = @_;

    $self->{output}->add_disco_format(elements => ['name', 'state', 'status', 'is_clustered', 'note']);
}

sub disco_show {
    my ($self, %options) = @_;

    if (!defined($self->{option_results}->{no_ps})) {
        my $ps = centreon::common::powershell::hyperv::2012::listnodevms::get_powershell();
        $self->{option_results}->{command_options} .= " " . centreon::plugins::misc::powershell_encoded($ps);
    }

    my ($stdout) = centreon::plugins::misc::execute(
        output => $self->{output},
        options => $self->{option_results},
        command => $self->{option_results}->{command},
        command_path => $self->{option_results}->{command_path},
        command_options => $self->{option_results}->{command_options}
    );

    my $decoded = $self->manage_selection(stdout => $stdout);

    foreach my $node (@$decoded) {
        $self->{output}->add_disco_entry(
            name => $node->{name},
            state => $node_vm_state->{ $node->{state} },
            status => $node->{status},
            is_clustered => $node->{is_clustered} =~ /True|1/i ? 1 : 0,
            note => defined($node->{note}) ? $node->{note} : ''
        );
    }
}

1;

__END__

=head1 MODE

List virtual machines on hyper-v node.

=over 8

=item B<--timeout>

Set timeout time for command execution (Default: 50 sec)

=item B<--no-ps>

Don't encode powershell. To be used with --command and 'type' command.

=item B<--command>

Command to get information (Default: 'powershell.exe').
Can be changed if you have output in a file. To be used with --no-ps option!!!

=item B<--command-path>

Command path (Default: none).

=item B<--command-options>

Command options (Default: '-InputFormat none -NoLogo -EncodedCommand').

=item B<--ps-display>

Display powershell script.

=item B<--ps-exec-only>

Print powershell output.

=back

=cut


text:
package de.philipphager.disclosure.database.app.model;

import android.os.Parcelable;
import android.support.annotation.Nullable;
import com.google.auto.value.AutoValue;
import de.philipphager.disclosure.database.util.adapters.LocalDateTimeColumnAdapter;
import org.threeten.bp.LocalDateTime;

@AutoValue public abstract class App implements AppModel, Parcelable {
  public static final Factory<App> FACTORY = new Factory<>(
      (id, label, packageName, process, sourceDir, targetSdk, flags, analyzedAt) -> builder().id(id)
          .label(label)
          .packageName(packageName)
          .process(process)
          .sourceDir(sourceDir)
          .targetSdk(targetSdk)
          .flags(flags)
          .analyzedAt(analyzedAt)
          .build(), new LocalDateTimeColumnAdapter());

  public static Builder builder() {
    return new AutoValue_App.Builder();
  }

  @Nullable public abstract Long id();

  public abstract String label();

  public abstract String packageName();

  public abstract String process();

  public abstract String sourceDir();

  public abstract Integer targetSdk();

  public abstract Integer flags();

  @Nullable public abstract LocalDateTime analyzedAt();

  public abstract App withAnalyzedAt(LocalDateTime analyzedAt);

  @AutoValue.Builder public interface Builder {
    Builder id(Long id);

    Builder label(String label);

    Builder packageName(String name);

    Builder process(String name);

    Builder sourceDir(String path);

    Builder targetSdk(Integer targetSdk);

    Builder flags(Integer flags);

    Builder analyzedAt(@Nullable LocalDateTime analyzedAt);

    App build();
  }
}


text:
This code simulates the command interface of a LSTM accelerator including data-movement and computation commands.
## Run main.cpp
```
g++ main.cpp
./a.out
```
## Hardware Architecture
* Hardware includes
  * Input SRAM for x(t), h(t-1)
  * Weight SRAM for Wx, Wh, bx, bh
  * Output SRAM for h(t)
  * Cellstate SRAM for c(t)
* During computation, the hardware will update h(t) and c(t) according to input and weight

## C++ Files
* LSTM.h: software lstm written in cpp
* LSTMAcc.h: lstm hardware that simulates command interface of the accelerator
* main.cpp: testing code with verification
* Utils: Matrix and vector functions

## Notes
* The function of LSTM refers to [torch.nn.lstm] in Pytorch with the same order of gates (i, f, g, o).
* Hidden state and cell state are treated different that hidden state input must be set explicitly for every timestep, but cell state is updated internally.
* As the hardware is performing computation in vector size of 16, the sizes of LSTM must be multiples of 16.

[torch.nn.lstm]: https://pytorch.org/docs/master/generated/torch.nn.LSTM.html#torch.nn.LSTM


text:
You can import Project data right out of PhotosynQ into R. All you need is a login to <https://photosynq.org> and the ID for the Project you want to analyze. You can find this ID on the left side of the Project page or in the list of Projects on your User page. Otherwise you can import Project data into R studio by reading the data from a csv file on your computer.

## Import Libraries

```r
library(PhotosynQ)
```

If you don't have the library installed go to <https://github.com/PhotosynQ/PhotosynQ-R> and follow the instructions on how to install the library with R.

## Access the Project Data

We will use the same Project for all three R tutorials in this section. Project data is also available for download as a csv so that you can follow along and, hopefully, get the same results!

```r
# Call the function to add the Project data into a Data Frame
# 243 equals the Project ID for the data that you want to import into R for data analysis.
df <- PhotosynQ::getProject("john.doe@domain.com",243)

```

Replace the ID and the email address with your information. A popup window will ask you to enter your password.

## View the Project Data

Now we want to view all of the data in our Project. In this example we used two different protocols, so we need to create a unique data-frame for each protocol. If you are using the MultispeQ v1.0 we have created a new default protocol (Leaf Photosynthesis MultispeQ V1.0) that includes all of the standard PhotosynQ parameters in a single protocol.

Also, unless we tell R otherwise, we will import all of the data from the Project. In this example, we will limit the data-frame to only measurements that were not flagged (if a data point is not flagged, then its status is listed as 'submitted'), and only the measurements where 'top' was the answer to the Project questions "Leaf.Location".

```r
# Select a Protocol from the List of Data Frames. This is based on the measurement protocol that your Project uses.
# This line of code also filters out "flagged" data points and any measurements that have an answer other than "Top" for the Leaf.Location question.
chlorophyll <- subset(df$`Chlorophyll content (SPAD) I`, status == "submitted" & Leaf.location == "Top")
photosynthesis <- subset(df$`The One Protocol (Phi2, PSI, NPQ) II`, status == "submitted" & Leaf.location == "Top")

# View the Protocol Output
View(chlorophyll)
View(photosynthesis)
```

## Transform Data

Many of the parameters measured by the MultispeQ Instrument are affected by factors including:

+ light intensity
+ time of measurement
+ temperature (the temperature data on the MultispeQ beta device was not accurate and can be ignored. However, if you are using the new MultispeQ v1.0, you should take temperature into account)
+ spatial location in the field, this is usually as a identified by 'block' or 'replicate'
+ leaf age and position in the canopy
+ growth stage when data was collected
+ Instrument/User variation. This could be caused user bias in selection of which leaf to measure or by device to device variation (especially in the MultispeQ Beta Instruments, the new MultispeQ v1.0 Instruments are much more consistent across Instruments)
+ this is not an exhaustive list, but rather a summary of the most common factors affecting photosynthesis measurements.

In order to account for these factors, we will need to transform some of the data that we have imported from <https://photosynq.org> so that we can incorporate them into the statistical models.

Standard transformations include:
+transform the light intensity by its square root to make its effect on photosynthetic parameters linear. This is important when you are using linear models like the ANOVA and Mixed Effects models in the next two tutorials
+Convert the time data from the date/time column to a numeric variable.

```r
# We are calculating the square root of the light intensity (PAR). This transformation helps to make the effect of light intensity on Phi2 linear.
photosynthesis$sqrtPAR <- sqrt(photosynthesis$light_intensity)

# We translate the date into a number (0 to 24)
photosynthesis$TimeOfDay <- as.POSIXlt(photosynthesis$time)$hour + as.POSIXlt(photosynthesis$time)$min/60 + as.POSIXlt(photosynthesis$time)$sec/3600
```

## Uploading csv Data

You may need to upload data from a csv into R for analysis. You can do this using the following code.

```r
# Set the main folder location for your data
your_location = "C:/.../"
# The main data file, located in the main folder, is called...
file_name = "sun2.csv"
# Let's pull that data file into R and call it data_raw
my_data = read.csv(str_c(your_location, file_name))
View(my_data)
```


text:
<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\Product;
use AppBundle\Form\Type\ProductType;

class ProductController extends Controller
{
    /**
     * @Route("/new_product", name="new_product")
     */
    public function newProductAction(Request $request)
    {
        $id = $request->query->get('id', false);
        $product = $id ? $this->get('app.product_repository_manager')->getById($id) : new Product();
        $product->setUser($this->getUser());

        $formHandler = $this->get('app.form_handler');
        $form = $formHandler->create(ProductType::class, $product, [
            'categories' => $this->getParameter('categories')
        ]);

        if($formHandler->handle($request)){
            $this->addFlash('info', 'Product added to shop!');

            return $this->redirectToRoute('index');
        }

        return $this->render('AppBundle:Product:new.html.twig', [
            'form' => $form->createView()
        ]);
    }

    /**
     * @Route("/edit_product/{id}", name="edit_product")
     */
    public function editProductAction(Request $request, int $id)
    {
        return $this->redirectToRoute('new_product', [
            'id' => $id
        ]);
    }

    /**
     * @Route("/show_product/{id}", name="show_product")
     */
    public function showProductAction(int $id)
    {
        $product = $this->get('app.product_repository_manager')->getById($id);

        return $this->render('AppBundle:Product:item.html.twig', [
            'product' => $product
        ]);
    }

    /**
     * @Route("/your_products", name="your_products")
     */
    public function yourProductsAction(Request $request){
        $products = $this->get('app.product_repository_manager')->getAll($this->getUser());
        $pagination = $this->get('app.paginator')->paginate($products);

    	return $this->render('AppBundle:Product:list_user_products.html.twig', [
    		'pagination' => $pagination,
	]);
    }

    /**
     * @Route("your_buy_requests", name="your_buy_requests")
     */
    public function listBuyRequests(Request $request)
    {
        $products = $this->get('app.product_repository_manager')->getAll($this->getUser());
        $pagination = $this->get('app.paginator')->paginate($products);

    	return $this->render('AppBundle:Product:list_user_buy_requests.html.twig', [
    		'pagination' => $pagination,
	]);
    }

    /**
     * @Route("remove_product/{id}", name="remove_product")
     */
    public function removeProductAction(int $id)
    {
        $productRepositoryManager = $this->get('app.product_repository_manager');
        $product = $productRepositoryManager->removeById($id);

        $this->addFlash('info', 'Item removed from shop');

        return $this->redirectToRoute('your_products');
    }

    /**
     * @Route("order_by/{by}/{direction}", options={"expose"=true}, name="order_by")
     */
    public function orderByAction(string $by, string $direction)
    {
        $products = $this->container->get('app.product_repository_manager')->getOrdered($by, $direction);
        $pagination = $this->container->get('app.paginator')->paginate($products);
        $categories = $this->getParameter('categories');

    	return $this->render('AppBundle:Index:index.html.twig', array(
            'pagination' => $pagination,
            'categories' => $categories
        ));
    }

    /**
     * @Route("filter_by/{by}/{value}", options={"expose"=true}, name="filter_by")
     */
    public function filterByAction(string $by, string $value)
    {
        $products = $this->container->get('app.product_repository_manager')->getFiltered($by, $value);
        $pagination = $this->container->get('app.paginator')->paginate($products);
        $categories = $this->getParameter('categories');

    	return $this->render('AppBundle:Index:index.html.twig', array(
            'pagination' => $pagination,
            'categories' => $categories
        ));
    }

}