text:
/*****************************************************************************/
/* Include files                                                             */
/*****************************************************************************/
#include "simplelink.h"
#include "protocol.h"
#include "driver.h"

/*****************************************************************************/
/* Macro declarations                                                        */
/*****************************************************************************/
#define NETAPP_MDNS_OPTIONS_ADD_SERVICE_BIT					 ((_u32)0x1 << 31)

#ifdef SL_TINY
#define NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH         63
#else
#define NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH         255
#endif

/*****************************************************************************/
/* Functions prototypes                                                      */
/*****************************************************************************/
_SlReturnVal_t _sl_HandleAsync_DnsGetHostByName(void *pVoidBuf);

#ifndef SL_TINY_EXT
_SlReturnVal_t _sl_HandleAsync_DnsGetHostByService(void *pVoidBuf);
_SlReturnVal_t _sl_HandleAsync_PingResponse(void *pVoidBuf);
#endif

static void CopyPingResultsToReport(_PingReportResponse_t *pResults,SlPingReport_t *pReport);
_i16 sl_NetAppMDNSRegisterUnregisterService(const _i8* 		pServiceName,
											const _u8   ServiceNameLen,
											const _i8* 		pText,
											const _u8   TextLen,
											const _u16  Port,
											const _u32    TTL,
											const _u32    Options);

#if defined(sl_HttpServerCallback) || defined(EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS)
_u16 _sl_NetAppSendTokenValue(slHttpServerData_t * Token);
#endif
typedef union
{
	_NetAppStartStopCommand_t       Cmd;
	_NetAppStartStopResponse_t   Rsp;
}_SlNetAppStartStopMsg_u;

#if _SL_INCLUDE_FUNC(sl_NetAppStart)

static const _SlCmdCtrl_t _SlNetAppStartCtrl =

{
    SL_OPCODE_NETAPP_START_COMMAND,
    (_SlArgSize_t)sizeof(_NetAppStartStopCommand_t),
    (_SlArgSize_t)sizeof(_NetAppStartStopResponse_t)
};

_i16 sl_NetAppStart(const _u32 AppBitMap)
{
    _SlNetAppStartStopMsg_u Msg;
    Msg.Cmd.appId = AppBitMap;

    /* verify no erorr handling in progress. if in progress than
    ignore the API execution and return immediately with an error */
    VERIFY_NO_ERROR_HANDLING_IN_PROGRESS();
    VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlNetAppStartCtrl, &Msg, NULL));

    return Msg.Rsp.status;
}
#endif

/*****************************************************************************
 sl_NetAppStop
*****************************************************************************/
#if _SL_INCLUDE_FUNC(sl_NetAppStop)

static const _SlCmdCtrl_t _SlNetAppStopCtrl =
{
    SL_OPCODE_NETAPP_STOP_COMMAND,
    (_SlArgSize_t)sizeof(_NetAppStartStopCommand_t),
    (_SlArgSize_t)sizeof(_NetAppStartStopResponse_t)
};

_i16 sl_NetAppStop(const _u32 AppBitMap)
{
    _SlNetAppStartStopMsg_u Msg;

    /* verify no erorr handling in progress. if in progress than
    ignore the API execution and return immediately with an error */
    VERIFY_NO_ERROR_HANDLING_IN_PROGRESS();
    Msg.Cmd.appId = AppBitMap;
    VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlNetAppStopCtrl, &Msg, NULL));

    return Msg.Rsp.status;
}
#endif

/******************************************************************************/
/* sl_NetAppGetServiceList */
/******************************************************************************/
typedef struct
{
    _u8  IndexOffest;
    _u8  MaxServiceCount;
    _u8  Flags;
    _i8  Padding;
}NetappGetServiceListCMD_t;

typedef union
{
	 NetappGetServiceListCMD_t      Cmd;
	_BasicResponse_t                Rsp;
}_SlNetappGetServiceListMsg_u;

#if _SL_INCLUDE_FUNC(sl_NetAppGetServiceList)

static const _SlCmdCtrl_t _SlGetServiceListeCtrl =
{
    SL_OPCODE_NETAPP_NETAPP_MDNS_LOOKUP_SERVICE,
    (_SlArgSize_t)sizeof(NetappGetServiceListCMD_t),
    (_SlArgSize_t)sizeof(_BasicResponse_t)
};

_i16 sl_NetAppGetServiceList(const _u8  IndexOffest,
						     const _u8  MaxServiceCount,
							 const _u8  Flags,
						           _i8  *pBuffer,
							 const _u32  RxBufferLength
							)
{

    _i32 					 retVal= 0;
    _SlNetappGetServiceListMsg_u Msg;
    _SlCmdExt_t                  CmdExt;
	_u16               ServiceSize = 0;
	_u16               BufferSize = 0;

    /* verify no erorr handling in progress. if in progress than
    ignore the API execution and return immediately with an error */
    VERIFY_NO_ERROR_HANDLING_IN_PROGRESS();

	/*
	Calculate RX pBuffer size
    WARNING:
    if this size is BufferSize than 1480 error should be returned because there
    is no place in the RX packet.
    */
    switch(Flags)
    {
        case SL_NET_APP_FULL_SERVICE_WITH_TEXT_IPV4_TYPE:
            ServiceSize =  (_u16)sizeof(SlNetAppGetFullServiceWithTextIpv4List_t);
            break;

        case SL_NET_APP_FULL_SERVICE_IPV4_TYPE:
            ServiceSize =  (_u16)sizeof(SlNetAppGetFullServiceIpv4List_t);
            break;

        case SL_NET_APP_SHORT_SERVICE_IPV4_TYPE:
            ServiceSize =  (_u16)sizeof(SlNetAppGetShortServiceIpv4List_t);
            break;

        default:
			ServiceSize =  (_u16)sizeof(_BasicResponse_t);
			break;
    }

	BufferSize =  MaxServiceCount * ServiceSize;

	/*Check the size of the requested services is smaller than size of the user buffer.
	  If not an error is returned in order to avoid overwriting memory. */
	if(RxBufferLength <= BufferSize)
	{
		return SL_ERROR_NETAPP_RX_BUFFER_LENGTH_ERROR;
	}

    _SlDrvResetCmdExt(&CmdExt);
    CmdExt.RxPayloadLen = (_i16)BufferSize;
    CmdExt.pRxPayload = (_u8 *)pBuffer;

    Msg.Cmd.IndexOffest		= IndexOffest;
    Msg.Cmd.MaxServiceCount = MaxServiceCount;
    Msg.Cmd.Flags			= Flags;
    Msg.Cmd.Padding			= 0;

    VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlGetServiceListeCtrl, &Msg, &CmdExt));
    retVal = Msg.Rsp.status;

    return (_i16)retVal;
}

#endif

/*****************************************************************************/
/* sl_mDNSRegisterService */
/*****************************************************************************/
/*
 * The below struct depicts the constant parameters of the command/API RegisterService.
 *
   1. ServiceLen                      - The length of the service should be smaller than NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH.
   2. TextLen                         - The length of the text should be smaller than NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH.
   3. port                            - The port on this target host.
   4. TTL                             - The TTL of the service
   5. Options                         - bitwise parameters:
                                        bit 0  - is unique (means if the service needs to be unique)
										bit 31  - for internal use if the service should be added or deleted (set means ADD).
                                        bit 1-30 for future.

   NOTE:

   1. There are another variable parameter is this API which is the service name and the text.
   2. According to now there is no warning and Async event to user on if the service is a unique.
*
 */

typedef struct
{
    _u8   ServiceNameLen;
    _u8   TextLen;
    _u16  Port;
    _u32   TTL;
    _u32   Options;
}NetappMdnsSetService_t;

typedef union
{
	 NetappMdnsSetService_t         Cmd;
	_BasicResponse_t                Rsp;
}_SlNetappMdnsRegisterServiceMsg_u;

#if _SL_INCLUDE_FUNC(sl_NetAppMDNSRegisterUnregisterService)

static const _SlCmdCtrl_t _SlRegisterServiceCtrl =
{
    SL_OPCODE_NETAPP_MDNSREGISTERSERVICE,
    (_SlArgSize_t)sizeof(NetappMdnsSetService_t),
    (_SlArgSize_t)sizeof(_BasicResponse_t)
};

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

    sl_NetAppMDNSRegisterService

    CALLER          user from its host

    DESCRIPTION:
                    Add/delete  service
					The function manipulates the command that register the service and call
					to the NWP in order to add/delete the service to/from the mDNS package and to/from the DB.

					This register service is a service offered by the application.
					This unregister service is a service offered by the application before.

					The service name should be full service name according to RFC
                    of the DNS-SD - means the value in name field in SRV answer.

					Example for service name:
                    1. PC1._ipp._tcp.local
                    2. PC2_server._ftp._tcp.local

                    If the option is_unique is set, mDNS probes the service name to make sure
                    it is unique before starting to announce the service on the network.
                    Instance is the instance portion of the service name.

    PARAMETERS:

                    The command is from constant parameters and variables parameters.

					Constant parameters are:

                    ServiceLen                          - The length of the service.
                    TextLen                             - The length of the service should be smaller than 64.
                    port                                - The port on this target host.
                    TTL                                 - The TTL of the service
                    Options                             - bitwise parameters:
                                                            bit 0  - is unique (means if the service needs to be unique)
                                                            bit 31  - for internal use if the service should be added or deleted (set means ADD).
                                                            bit 1-30 for future.

                   The variables parameters are:

                    Service name(full service name)     - The service name.
                                                          Example for service name:
                                                          1. PC1._ipp._tcp.local
                                                          2. PC2_server._ftp._tcp.local

                    Text                                - The description of the service.
                                                          should be as mentioned in the RFC
                                                          (according to type of the service IPP,FTP...)

					NOTE - pay attention

						1. Temporary -  there is an allocation on stack of internal buffer.
						Its size is NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH.
						It means that the sum of the text length and service name length cannot be bigger than
						NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH.
						If it is - An error is returned.

					    2. According to now from certain constraints the variables parameters are set in the
					    attribute part (contain constant parameters)

	  RETURNS:        Status - the immediate response of the command status.
							   0 means success.

******************************************************************************/
_i16 sl_NetAppMDNSRegisterUnregisterService(	const _i8* 		pServiceName,
											const _u8   ServiceNameLen,
											const _i8* 		pText,
											const _u8   TextLen,
											const _u16  Port,
											const _u32   TTL,
											const _u32   Options)

{
    _SlNetappMdnsRegisterServiceMsg_u			Msg;
    _SlCmdExt_t									CmdExt ;
 _i8 									ServiceNameAndTextBuffer[NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH];
 _i8 									*TextPtr;

	 /* verify no erorr handling in progress. if in progress than
	 ignore the API execution and return immediately with an error */
	 VERIFY_NO_ERROR_HANDLING_IN_PROGRESS();
	/*

	NOTE - pay attention

		1. Temporary -  there is an allocation on stack of internal buffer.
		Its size is NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH.
		It means that the sum of the text length and service name length cannot be bigger than
		NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH.
		If it is - An error is returned.

		2. According to now from certain constraints the variables parameters are set in the
		attribute part (contain constant parameters)

	*/

	/*build the attribute part of the command.
	  It contains the constant parameters of the command*/

	Msg.Cmd.ServiceNameLen	= ServiceNameLen;
	Msg.Cmd.Options			= Options;
	Msg.Cmd.Port			= Port;
	Msg.Cmd.TextLen			= TextLen;
	Msg.Cmd.TTL				= TTL;

	/*Build the payload part of the command
	 Copy the service name and text to one buffer.
	 NOTE - pay attention
	 			The size of the service length + the text length should be smaller than 255,
	 			Until the simplelink drive supports to variable length through SPI command. */
	if(TextLen + ServiceNameLen > (NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH - 1 )) /*-1 is for giving a place to set null termination at the end of the text*/
	{
		return -1;
	}

    _SlDrvMemZero(ServiceNameAndTextBuffer, (_u16)NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH);

	/*Copy the service name*/
	sl_Memcpy(ServiceNameAndTextBuffer,
		      pServiceName,
			  ServiceNameLen);

	if(TextLen > 0 )
	{

		TextPtr = &ServiceNameAndTextBuffer[ServiceNameLen];
		/*Copy the text just after the service name*/
		sl_Memcpy(TextPtr,
				  pText,
				  TextLen);

	}

    _SlDrvResetCmdExt(&CmdExt);
    CmdExt.TxPayloadLen = (TextLen + ServiceNameLen);
    CmdExt.pTxPayload   = (_u8 *)ServiceNameAndTextBuffer;

	VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlRegisterServiceCtrl, &Msg, &CmdExt));

	return (_i16)Msg.Rsp.status;

}
#endif

/**********************************************************************************************/
#if _SL_INCLUDE_FUNC(sl_NetAppMDNSRegisterService)

_i16 sl_NetAppMDNSRegisterService(	const _i8* 		pServiceName,
									const _u8   ServiceNameLen,
									const _i8* 		pText,
									const _u8   TextLen,
									const _u16  Port,
									const _u32    TTL,
									     _u32    Options)

{

    /* verify no erorr handling in progress. if in progress than
    ignore the API execution and return immediately with an error */
    VERIFY_NO_ERROR_HANDLING_IN_PROGRESS();

	/*

	NOTE - pay attention

	1. Temporary -  there is an allocation on stack of internal buffer.
	Its size is NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH.
	It means that the sum of the text length and service name length cannot be bigger than
	NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH.
	If it is - An error is returned.

	2. According to now from certain constraints the variables parameters are set in the
	attribute part (contain constant parameters)

	*/

	/*Set the add service bit in the options parameter.
	  In order not use different opcodes for the register service and unregister service
	  bit 31 in option is taken for this purpose. if it is set it means in NWP that the service should be added
	  if it is cleared it means that the service should be deleted and there is only meaning to pServiceName
	  and ServiceNameLen values. */
	Options |=  NETAPP_MDNS_OPTIONS_ADD_SERVICE_BIT;

    return  sl_NetAppMDNSRegisterUnregisterService(	pServiceName,
											        ServiceNameLen,
													pText,
													TextLen,
													Port,
													TTL,
													Options);

}
#endif
/**********************************************************************************************/

/**********************************************************************************************/
#if _SL_INCLUDE_FUNC(sl_NetAppMDNSUnRegisterService)

_i16 sl_NetAppMDNSUnRegisterService(	const _i8* 		pServiceName,
									const _u8   ServiceNameLen)

{
    _u32    Options = 0;

    /* verify no erorr handling in progress. if in progress than
    ignore the API execution and return immediately with an error */
    VERIFY_NO_ERROR_HANDLING_IN_PROGRESS();

	/*

	NOTE - pay attention

			The size of the service length  should be smaller than 255,
			Until the simplelink drive supports to variable length through SPI command.

	*/

	/*Clear the add service bit in the options parameter.
	  In order not use different opcodes for the register service and unregister service
	  bit 31 in option is taken for this purpose. if it is set it means in NWP that the service should be added
	  if it is cleared it means that the service should be deleted and there is only meaning to pServiceName
	  and ServiceNameLen values.*/

	Options &=  (~NETAPP_MDNS_OPTIONS_ADD_SERVICE_BIT);

    return  sl_NetAppMDNSRegisterUnregisterService(	pServiceName,
											        ServiceNameLen,
													NULL,
													0,
													0,
													0,
													Options);

}
#endif
/**********************************************************************************************/

/*****************************************************************************/
/* sl_DnsGetHostByService */
/*****************************************************************************/
/*
 * The below struct depicts the constant parameters of the command/API sl_DnsGetHostByService.
 *
   1. ServiceLen                      - The length of the service should be smaller than 255.
   2. AddrLen                         - TIPv4 or IPv6 (SL_AF_INET , SL_AF_INET6).
*
 */

typedef struct
{
	 _u8   ServiceLen;
	 _u8   AddrLen;
	 _u16  Padding;
}_GetHostByServiceCommand_t;

/*
 * The below structure depict the constant parameters that are returned in the Async event answer
 * according to command/API sl_DnsGetHostByService for IPv4 and IPv6.
 *
	1Status						- The status of the response.
	2.Address						- Contains the IP address of the service.
	3.Port							- Contains the port of the service.
	4.TextLen						- Contains the max length of the text that the user wants to get.
												it means that if the test of service is bigger that its value than
												the text is cut to inout_TextLen value.
										Output: Contain the length of the text that is returned. Can be full text or part
												of the text (see above).

*
 */
typedef struct
{
	_u16   Status;
	_u16   TextLen;
	_u32    Port;
	_u32    Address;
}_GetHostByServiceIPv4AsyncResponse_t;

typedef struct
{
	_u16   Status;
	_u16   TextLen;
	_u32    Port;
	_u32    Address[4];
}_GetHostByServiceIPv6AsyncResponse_t;

typedef union
{
    _GetHostByServiceIPv4AsyncResponse_t IpV4;
    _GetHostByServiceIPv6AsyncResponse_t IpV6;
}_GetHostByServiceAsyncResponseAttribute_u;

/*
 * The below struct contains pointers to the output parameters that the user gives
 *
 */
typedef struct
{
    _i16           Status;
	_u32   *out_pAddr;
	_u32   *out_pPort;
	_u16   *inout_TextLen; /* in: max len , out: actual len */
 _i8            *out_pText;
}_GetHostByServiceAsyncResponse_t;

typedef union
{
	_GetHostByServiceCommand_t      Cmd;
	_BasicResponse_t                Rsp;
}_SlGetHostByServiceMsg_u;

#if _SL_INCLUDE_FUNC(sl_NetAppDnsGetHostByService)

static const _SlCmdCtrl_t _SlGetHostByServiceCtrl =
{
    SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICE,
    (_SlArgSize_t)sizeof(_GetHostByServiceCommand_t),
    (_SlArgSize_t)sizeof(_BasicResponse_t)
};

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

_i32 sl_NetAppDnsGetHostByService(_i8 		*pServiceName,	/* string containing all (or only part): name + subtype + service */
								  const _u8  ServiceLen,
								  const _u8  Family,			/* 4-IPv4 , 16-IPv6 */
								  _u32  pAddr[],
								  _u32  *pPort,
								  _u16 *pTextLen, /* in: max len , out: actual len */
								  _i8          *pText
						         )
{
    _SlGetHostByServiceMsg_u         Msg;
    _SlCmdExt_t                      CmdExt ;
    _GetHostByServiceAsyncResponse_t AsyncRsp;
	_u8 ObjIdx = MAX_CONCURRENT_ACTIONS;

    /* verify no erorr handling in progress. if in progress than
    ignore the API execution and return immediately with an error */
    VERIFY_NO_ERROR_HANDLING_IN_PROGRESS();

/*
	Note:
	1. The return's attributes are belonged to first service that is found.
	It can be other services with the same service name will response to
	the query. The results of these responses are saved in the peer cache of the NWP, and
	should be read by another API.

	2. Text length can be 120 bytes only - not more
	It is because of constraints in the NWP on the buffer that is allocated for the Async event.

	3.The API waits to Async event by blocking. It means that the API is finished only after an Async event
	is sent by the NWP.

	4.No rolling option!!! - only PTR type is sent.

*/
	/*build the attribute part of the command.
	  It contains the constant parameters of the command */

	Msg.Cmd.ServiceLen = ServiceLen;
	Msg.Cmd.AddrLen    = Family;

	/*Build the payload part of the command
	  Copy the service name and text to one buffer.*/

    _SlDrvResetCmdExt(&CmdExt);
	CmdExt.TxPayloadLen = ServiceLen;
    CmdExt.pTxPayload   = (_u8 *)pServiceName;

	/*set pointers to the output parameters (the returned parameters).
	  This pointers are belonged to local struct that is set to global Async response parameter.
	  It is done in order not to run more than one sl_DnsGetHostByService at the same time.
	  The API should be run only if global parameter is pointed to NULL. */
	AsyncRsp.out_pText     = pText;
	AsyncRsp.inout_TextLen = (_u16* )pTextLen;
	AsyncRsp.out_pPort     = pPort;
	AsyncRsp.out_pAddr     = (_u32 *)pAddr;

    ObjIdx = _SlDrvProtectAsyncRespSetting((_u8*)&AsyncRsp, GETHOSYBYSERVICE_ID, SL_MAX_SOCKETS);

    if (MAX_CONCURRENT_ACTIONS == ObjIdx)
    {
        return SL_POOL_IS_EMPTY;
    }

	if (SL_AF_INET6 == Family)
	{
		g_pCB->ObjPool[ObjIdx].AdditionalData |= SL_NETAPP_FAMILY_MASK;
	}
    /* Send the command */
	VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlGetHostByServiceCtrl, &Msg, &CmdExt));

    /* If the immediate reponse is O.K. than  wait for aSYNC event response. */
	if(SL_RET_CODE_OK == Msg.Rsp.status)
    {
		SL_DRV_SYNC_OBJ_WAIT_FOREVER(&g_pCB->ObjPool[ObjIdx].SyncObj);

		/* If we are - it means that Async event was sent.
		   The results are copied in the Async handle return functions */

		Msg.Rsp.status = AsyncRsp.Status;
    }

    _SlDrvReleasePoolObj(ObjIdx);
    return Msg.Rsp.status;
}
#endif

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

/******************************************************************************
    _sl_HandleAsync_DnsGetHostByService

    CALLER          NWP - Async event on sl_DnsGetHostByService with IPv4 Family

    DESCRIPTION:

					Async event on sl_DnsGetHostByService command with IPv4 Family.
					Return service attributes like IP address, port and text according to service name.
					The user sets a service name Full/Part (see example below), and should get the:
					1. IP of the service
					2. The port of service.
					3. The text of service.

					Hence it can make a connection to the specific service and use it.
					It is similar to get host by name method.

					It is done by a single shot query with PTR type on the service name.

					Note:
					1. The return's attributes are belonged to first service that is found.
					It can be other services with the same service name will response to
					the query. The results of these responses are saved in the peer cache of the NWP, and
					should be read by another API.

	    PARAMETERS:

                  pVoidBuf - is point to opcode of the event.
				  it contains the outputs that are given to the user

				  outputs description:

				   1.out_pAddr[]					- output: Contain the IP address of the service.
				   2.out_pPort						- output: Contain the port of the service.
				   3.inout_TextLen					- Input:  Contain the max length of the text that the user wants to get.
															  it means that if the test of service is bigger that its value than
															  the text is cut to inout_TextLen value.
													  Output: Contain the length of the text that is returned. Can be full text or part
														      of the text (see above).

				   4.out_pText						- Contain the text of the service (full or part see above- inout_TextLen description).

  *

    RETURNS:        success or fail.

******************************************************************************/
#ifndef SL_TINY_EXT
_SlReturnVal_t _sl_HandleAsync_DnsGetHostByService(void *pVoidBuf)
{

	_GetHostByServiceAsyncResponse_t* Res;
	_u16 				  TextLen;
	_u16 				  UserTextLen;

	/*pVoidBuf - is point to opcode of the event.*/

	/*set pMsgArgs to point to the attribute of the event.*/
	_GetHostByServiceIPv4AsyncResponse_t   *pMsgArgs   = (_GetHostByServiceIPv4AsyncResponse_t *)_SL_RESP_ARGS_START(pVoidBuf);

    VERIFY_SOCKET_CB(NULL != g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs);

	/*IPv6*/
	if(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].AdditionalData & SL_NETAPP_FAMILY_MASK)
	{
		return SL_RET_CODE_OK;
	}
	/*IPv4*/
	else
	{
    /*************************************************************************************************

	1. Copy the attribute part of the evnt to the attribute part of the response
	sl_Memcpy(g_pCB->GetHostByServiceCB.pAsyncRsp, pMsgArgs, sizeof(_GetHostByServiceIPv4AsyncResponse_t));

    set to TextLen the text length of the service.*/
	TextLen = pMsgArgs->TextLen;

	/*Res pointed to mDNS global object struct */
		Res = (_GetHostByServiceAsyncResponse_t*)g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs;

	/*It is 4 bytes so we avoid from memcpy*/
	Res->out_pAddr[0]	= pMsgArgs->Address;
	Res->out_pPort[0]	= pMsgArgs->Port;
	Res->Status			= (_i16)pMsgArgs->Status;

	/*set to TextLen the text length of the user (input fromthe user).*/
	UserTextLen			= Res->inout_TextLen[0];

	/*Cut the service text if the user requested for smaller text.*/
	UserTextLen = (TextLen <= UserTextLen) ? TextLen : UserTextLen;
	Res->inout_TextLen[0] = UserTextLen ;

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

	2. Copy the payload part of the evnt (the text) to the payload part of the response
	the lenght of the copy is according to the text length in the attribute part. */

	sl_Memcpy(Res->out_pText          ,
		     (_i8 *)(& pMsgArgs[1])  ,   /* & pMsgArgs[1] -> 1st byte after the fixed header = 1st byte of variable text.*/
			 UserTextLen              );

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

		SL_DRV_SYNC_OBJ_SIGNAL(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj);
		return SL_RET_CODE_OK;
	}
}

/*****************************************************************************/
/*  _sl_HandleAsync_DnsGetHostByAddr */
/*****************************************************************************/
_SlReturnVal_t _sl_HandleAsync_DnsGetHostByAddr(void *pVoidBuf)
{
    SL_TRACE0(DBG_MSG, MSG_303, "STUB: _sl_HandleAsync_DnsGetHostByAddr not implemented yet!");
    (void)pVoidBuf;

    return SL_RET_CODE_OK;
}
#endif

/*****************************************************************************/
/* sl_DnsGetHostByName */
/*****************************************************************************/
typedef union
{
    _GetHostByNameIPv4AsyncResponse_t IpV4;
    _GetHostByNameIPv6AsyncResponse_t IpV6;
}_GetHostByNameAsyncResponse_u;

typedef union
{
	_GetHostByNameCommand_t         Cmd;
	_BasicResponse_t                Rsp;
}_SlGetHostByNameMsg_u;

#if _SL_INCLUDE_FUNC(sl_NetAppDnsGetHostByName)
static const _SlCmdCtrl_t _SlGetHostByNameCtrl =
{
    SL_OPCODE_NETAPP_DNSGETHOSTBYNAME,
    (_SlArgSize_t)sizeof(_GetHostByNameCommand_t),
    (_SlArgSize_t)sizeof(_BasicResponse_t)
};

_i16 sl_NetAppDnsGetHostByName(_i8 * hostname,const  _u16 usNameLen, _u32*  out_ip_addr,const _u8 family)
{
    _SlGetHostByNameMsg_u           Msg;
    _SlCmdExt_t                     ExtCtrl;
    _GetHostByNameAsyncResponse_u   AsyncRsp;
	_u8 ObjIdx = MAX_CONCURRENT_ACTIONS;

    /* verify no erorr handling in progress. if in progress than
    ignore the API execution and return immediately with an error */
    VERIFY_NO_ERROR_HANDLING_IN_PROGRESS();

    _SlDrvResetCmdExt(&ExtCtrl);
    ExtCtrl.TxPayloadLen = usNameLen;
    ExtCtrl.pTxPayload = (_u8 *)hostname;

    Msg.Cmd.Len = usNameLen;
    Msg.Cmd.family = family;

	/*Use Obj to issue the command, if not available try later */
	ObjIdx = (_u8)_SlDrvWaitForPoolObj(GETHOSYBYNAME_ID,SL_MAX_SOCKETS);
	if (MAX_CONCURRENT_ACTIONS == ObjIdx)
	{
		return SL_POOL_IS_EMPTY;
	}

    SL_DRV_PROTECTION_OBJ_LOCK_FOREVER();

	g_pCB->ObjPool[ObjIdx].pRespArgs =  (_u8 *)&AsyncRsp;
	/*set bit to indicate IPv6 address is expected */
	if (SL_AF_INET6 == family)
	{
		g_pCB->ObjPool[ObjIdx].AdditionalData |= SL_NETAPP_FAMILY_MASK;
	}

    SL_DRV_PROTECTION_OBJ_UNLOCK();

    VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlGetHostByNameCtrl, &Msg, &ExtCtrl));

    if(SL_RET_CODE_OK == Msg.Rsp.status)
    {
    	SL_DRV_SYNC_OBJ_WAIT_FOREVER(&g_pCB->ObjPool[ObjIdx].SyncObj);

        Msg.Rsp.status = (_i16)AsyncRsp.IpV4.status;

        if(SL_OS_RET_CODE_OK == (_i16)Msg.Rsp.status)
        {
            sl_Memcpy((_i8 *)out_ip_addr,
                      (_i8 *)&AsyncRsp.IpV4.ip0,
                      (SL_AF_INET == family) ? SL_IPV4_ADDRESS_SIZE : SL_IPV6_ADDRESS_SIZE);
        }
    }
    _SlDrvReleasePoolObj(ObjIdx);
    return Msg.Rsp.status;
}
#endif

/******************************************************************************/
/*  _sl_HandleAsync_DnsGetHostByName */
/******************************************************************************/
_SlReturnVal_t _sl_HandleAsync_DnsGetHostByName(void *pVoidBuf)
{
    _GetHostByNameIPv4AsyncResponse_t     *pMsgArgs   = (_GetHostByNameIPv4AsyncResponse_t *)_SL_RESP_ARGS_START(pVoidBuf);

    SL_DRV_PROTECTION_OBJ_LOCK_FOREVER();

    VERIFY_SOCKET_CB(NULL != g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs);

	/*IPv6 */
	if(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].AdditionalData & SL_NETAPP_FAMILY_MASK)
	{
		sl_Memcpy(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs, pMsgArgs, sizeof(_GetHostByNameIPv6AsyncResponse_t));
	}
	/*IPv4 */
	else
	{
		sl_Memcpy(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs, pMsgArgs, sizeof(_GetHostByNameIPv4AsyncResponse_t));
	}

	SL_DRV_SYNC_OBJ_SIGNAL(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj);
    SL_DRV_PROTECTION_OBJ_UNLOCK();

    return SL_RET_CODE_OK;
}

#ifndef SL_TINY_EXT
static void CopyPingResultsToReport(_PingReportResponse_t *pResults,SlPingReport_t *pReport)
{
    pReport->PacketsSent     = pResults->numSendsPings;
    pReport->PacketsReceived = pResults->numSuccsessPings;
    pReport->MinRoundTime    = pResults->rttMin;
    pReport->MaxRoundTime    = pResults->rttMax;
    pReport->AvgRoundTime    = pResults->rttAvg;
    pReport->TestTime        = pResults->testTime;
}

/*****************************************************************************/
/*  _sl_HandleAsync_PingResponse */
/*****************************************************************************/
_SlReturnVal_t _sl_HandleAsync_PingResponse(void *pVoidBuf)
{
    _PingReportResponse_t     *pMsgArgs   = (_PingReportResponse_t *)_SL_RESP_ARGS_START(pVoidBuf);
    SlPingReport_t            pingReport;

    if(pPingCallBackFunc)
    {
        CopyPingResultsToReport(pMsgArgs,&pingReport);
        pPingCallBackFunc(&pingReport);
    }
    else
    {

        SL_DRV_PROTECTION_OBJ_LOCK_FOREVER();

        VERIFY_SOCKET_CB(NULL != g_pCB->PingCB.PingAsync.pAsyncRsp);

		if (NULL != g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs)
		{
		   sl_Memcpy(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs, pMsgArgs, sizeof(_PingReportResponse_t));
		   SL_DRV_SYNC_OBJ_SIGNAL(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj);
		}
        SL_DRV_PROTECTION_OBJ_UNLOCK();
    }

	 return SL_RET_CODE_OK;
}
#endif

/*****************************************************************************/
/* sl_PingStart */
/*****************************************************************************/
typedef union
{
	_PingStartCommand_t   Cmd;
	_PingReportResponse_t  Rsp;
}_SlPingStartMsg_u;

typedef enum
{
  CMD_PING_TEST_RUNNING = 0,
  CMD_PING_TEST_STOPPED
}_SlPingStatus_e;

#if _SL_INCLUDE_FUNC(sl_NetAppPingStart)
_i16 sl_NetAppPingStart(const SlPingStartCommand_t* pPingParams,const _u8 family,SlPingReport_t *pReport,const P_SL_DEV_PING_CALLBACK pPingCallback)
{
    _SlCmdCtrl_t                CmdCtrl = {0, (_SlArgSize_t)sizeof(_PingStartCommand_t), (_SlArgSize_t)sizeof(_BasicResponse_t)};
    _SlPingStartMsg_u           Msg;
    _PingReportResponse_t       PingRsp;
    _u8 ObjIdx = MAX_CONCURRENT_ACTIONS;

    /* verify no erorr handling in progress. if in progress than
    ignore the API execution and return immediately with an error */
    VERIFY_NO_ERROR_HANDLING_IN_PROGRESS();

    if( 0 == pPingParams->Ip )
    {/* stop any ongoing ping */
       return _SlDrvBasicCmd(SL_OPCODE_NETAPP_PINGSTOP);
    }

    if(SL_AF_INET == family)
    {
        CmdCtrl.Opcode = SL_OPCODE_NETAPP_PINGSTART;
        sl_Memcpy(&Msg.Cmd.ip0, &pPingParams->Ip, SL_IPV4_ADDRESS_SIZE);
    }
    else
    {
        CmdCtrl.Opcode = SL_OPCODE_NETAPP_PINGSTART_V6;
        sl_Memcpy(&Msg.Cmd.ip0, &pPingParams->Ip, SL_IPV6_ADDRESS_SIZE);
    }

    Msg.Cmd.pingIntervalTime        = pPingParams->PingIntervalTime;
    Msg.Cmd.PingSize                = pPingParams->PingSize;
    Msg.Cmd.pingRequestTimeout      = pPingParams->PingRequestTimeout;
    Msg.Cmd.totalNumberOfAttempts   = pPingParams->TotalNumberOfAttempts;
    Msg.Cmd.flags                   = pPingParams->Flags;

    if( pPingCallback )
    {
       pPingCallBackFunc = pPingCallback;
    }
    else
    {
       /*Use Obj to issue the command, if not available try later */
	   ObjIdx = (_u8)_SlDrvWaitForPoolObj(PING_ID,SL_MAX_SOCKETS);
	   if (MAX_CONCURRENT_ACTIONS == ObjIdx)
	   {
		  return SL_POOL_IS_EMPTY;
	   }
       OSI_RET_OK_CHECK(sl_LockObjLock(&g_pCB->ProtectionLockObj, SL_OS_WAIT_FOREVER));
        /* async response handler for non callback mode */
       g_pCB->ObjPool[ObjIdx].pRespArgs = (_u8 *)&PingRsp;
       pPingCallBackFunc = NULL;
       OSI_RET_OK_CHECK(sl_LockObjUnlock(&g_pCB->ProtectionLockObj));
    }

    VERIFY_RET_OK(_SlDrvCmdOp(&CmdCtrl, &Msg, NULL));
	/*send the command*/
    if(CMD_PING_TEST_RUNNING == (_i16)Msg.Rsp.status || CMD_PING_TEST_STOPPED == (_i16)Msg.Rsp.status )
    {
        /* block waiting for results if no callback function is used */
        if( NULL == pPingCallback )
        {
#ifdef SL_TINY_EXT
            _SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj);
#else
			SL_DRV_SYNC_OBJ_WAIT_TIMEOUT(&g_pCB->ObjPool[ObjIdx].SyncObj,
                                                     SL_DRIVER_TIMEOUT_LONG,
                                                     SL_DRIVER_API_NETAPP_PING_START
                                                     );
#endif

            if( SL_OS_RET_CODE_OK == (_i16)PingRsp.status )
            {
                CopyPingResultsToReport(&PingRsp,pReport);
            }
            _SlDrvReleasePoolObj(ObjIdx);
        }
    }
    else
    {   /* ping failure, no async response */
        if( NULL == pPingCallback )
        {
            _SlDrvReleasePoolObj(ObjIdx);
        }
    }

    return (_i16)Msg.Rsp.status;
}
#endif

/*****************************************************************************/
/* sl_NetAppSet */
/*****************************************************************************/
typedef union
{
    _NetAppSetGet_t    Cmd;
    _BasicResponse_t   Rsp;
}_SlNetAppMsgSet_u;

#if _SL_INCLUDE_FUNC(sl_NetAppSet)

static const _SlCmdCtrl_t _SlNetAppSetCmdCtrl =
{
    SL_OPCODE_NETAPP_NETAPPSET,
    (_SlArgSize_t)sizeof(_NetAppSetGet_t),
    (_SlArgSize_t)sizeof(_BasicResponse_t)
};

_i32 sl_NetAppSet(const _u8 AppId ,const _u8 Option,const _u8 OptionLen,const  _u8 *pOptionValue)
{
    _SlNetAppMsgSet_u         Msg;
    _SlCmdExt_t               CmdExt;

    /* verify no erorr handling in progress. if in progress than
    ignore the API execution and return immediately with an error */
    VERIFY_NO_ERROR_HANDLING_IN_PROGRESS();

    _SlDrvResetCmdExt(&CmdExt);
	CmdExt.TxPayloadLen = (OptionLen+3) & (~3);
    CmdExt.pTxPayload = (_u8 *)pOptionValue;

    Msg.Cmd.AppId    = AppId;
    Msg.Cmd.ConfigLen   = OptionLen;
	Msg.Cmd.ConfigOpt   = Option;

    VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlNetAppSetCmdCtrl, &Msg, &CmdExt));

    return (_i16)Msg.Rsp.status;
}
#endif

/*****************************************************************************/
/* sl_NetAppSendTokenValue */
/*****************************************************************************/
typedef union
{
    sl_NetAppHttpServerSendToken_t    Cmd;
    _BasicResponse_t   Rsp;
}_SlNetAppMsgSendTokenValue_u;

#if defined(sl_HttpServerCallback) || defined(EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS)
const _SlCmdCtrl_t _SlNetAppSendTokenValueCmdCtrl =
{
    SL_OPCODE_NETAPP_HTTPSENDTOKENVALUE,
    (_SlArgSize_t)sizeof(sl_NetAppHttpServerSendToken_t),
    (_SlArgSize_t)sizeof(_BasicResponse_t)
};

_u16 _sl_NetAppSendTokenValue(slHttpServerData_t * Token_value)
{
	_SlNetAppMsgSendTokenValue_u    Msg;
    _SlCmdExt_t						CmdExt;

	CmdExt.TxPayloadLen = (Token_value->value_len+3) & (~3);
    CmdExt.RxPayloadLen = 0;
	CmdExt.pTxPayload = (_u8 *) Token_value->token_value;
    CmdExt.pRxPayload = NULL;

	Msg.Cmd.token_value_len = Token_value->value_len;
	Msg.Cmd.token_name_len = Token_value->name_len;
	sl_Memcpy(&Msg.Cmd.token_name[0], Token_value->token_name, Token_value->name_len);

	VERIFY_RET_OK(_SlDrvCmdSend((_SlCmdCtrl_t *)&_SlNetAppSendTokenValueCmdCtrl, &Msg, &CmdExt));

	return Msg.Rsp.status;
}
#endif

/*****************************************************************************/
/* sl_NetAppGet */
/*****************************************************************************/
typedef union
{
	_NetAppSetGet_t	    Cmd;
	_NetAppSetGet_t	    Rsp;
}_SlNetAppMsgGet_u;

#if _SL_INCLUDE_FUNC(sl_NetAppGet)
static const _SlCmdCtrl_t _SlNetAppGetCmdCtrl =
{
    SL_OPCODE_NETAPP_NETAPPGET,
    (_SlArgSize_t)sizeof(_NetAppSetGet_t),
    (_SlArgSize_t)sizeof(_NetAppSetGet_t)
};

_i32 sl_NetAppGet(const _u8 AppId,const  _u8 Option,_u8 *pOptionLen, _u8 *pOptionValue)
{
    _SlNetAppMsgGet_u         Msg;
    _SlCmdExt_t               CmdExt;

    /* verify no erorr handling in progress. if in progress than
    ignore the API execution and return immediately with an error */
    VERIFY_NO_ERROR_HANDLING_IN_PROGRESS();

       if (*pOptionLen == 0)
       {
              return SL_EZEROLEN;
       }

    _SlDrvResetCmdExt(&CmdExt);
    CmdExt.RxPayloadLen = (_i16)(*pOptionLen);
    CmdExt.pRxPayload = (_u8 *)pOptionValue;

    Msg.Cmd.AppId    = AppId;
    Msg.Cmd.ConfigOpt   = Option;
    VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlNetAppGetCmdCtrl, &Msg, &CmdExt));

       if (CmdExt.RxPayloadLen < CmdExt.ActualRxPayloadLen)
       {
              *pOptionLen = (_u8)CmdExt.RxPayloadLen;
              return SL_ESMALLBUF;
       }
       else
       {
              *pOptionLen = (_u8)CmdExt.ActualRxPayloadLen;
       }

    return (_i16)Msg.Rsp.Status;
}
#endif

/*****************************************************************************/
/* _SlDrvNetAppEventHandler */
/*****************************************************************************/
_SlReturnVal_t _SlDrvNetAppEventHandler(void* pArgs)
{
    _SlResponseHeader_t     *pHdr       = (_SlResponseHeader_t *)pArgs;
#if defined(sl_HttpServerCallback) || defined(EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS)
    SlHttpServerEvent_t		httpServerEvent;
    SlHttpServerResponse_t	httpServerResponse;
#endif

    switch(pHdr->GenHeader.Opcode)
    {
        case SL_OPCODE_NETAPP_DNSGETHOSTBYNAMEASYNCRESPONSE:
        case SL_OPCODE_NETAPP_DNSGETHOSTBYNAMEASYNCRESPONSE_V6:
            _sl_HandleAsync_DnsGetHostByName(pArgs);
            break;
#ifndef SL_TINY_EXT
        case SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICEASYNCRESPONSE:
        case SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICEASYNCRESPONSE_V6:
            _sl_HandleAsync_DnsGetHostByService(pArgs);
            break;
        case SL_OPCODE_NETAPP_PINGREPORTREQUESTRESPONSE:
            _sl_HandleAsync_PingResponse(pArgs);
            break;
#endif

#if defined(sl_HttpServerCallback) || defined(EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS)
		case SL_OPCODE_NETAPP_HTTPGETTOKENVALUE:
		{
			_u8 *pTokenName;
			slHttpServerData_t Token_value;
			sl_NetAppHttpServerGetToken_t *httpGetToken = (sl_NetAppHttpServerGetToken_t *)_SL_RESP_ARGS_START(pHdr);
                        pTokenName = (_u8 *)((sl_NetAppHttpServerGetToken_t *)httpGetToken + 1);

			httpServerResponse.Response = SL_NETAPP_HTTPSETTOKENVALUE;
			httpServerResponse.ResponseData.token_value.len = MAX_TOKEN_VALUE_LEN;

            /* Reuse the async buffer for getting the token value response from the user */
			httpServerResponse.ResponseData.token_value.data = (_u8 *)_SL_RESP_ARGS_START(pHdr) + MAX_TOKEN_NAME_LEN;

            httpServerEvent.Event = SL_NETAPP_HTTPGETTOKENVALUE_EVENT;
			httpServerEvent.EventData.httpTokenName.len = httpGetToken->token_name_len;
			httpServerEvent.EventData.httpTokenName.data = pTokenName;

			Token_value.token_name =  pTokenName;

            _SlDrvDispatchHttpServerEvents (&httpServerEvent, &httpServerResponse);

			Token_value.value_len = httpServerResponse.ResponseData.token_value.len;
			Token_value.name_len = httpServerEvent.EventData.httpTokenName.len;
			Token_value.token_value = httpServerResponse.ResponseData.token_value.data;

			_sl_NetAppSendTokenValue(&Token_value);
		}
		break;

		case SL_OPCODE_NETAPP_HTTPPOSTTOKENVALUE:
		{
			_u8 *pPostParams;

			sl_NetAppHttpServerPostToken_t *httpPostTokenArgs = (sl_NetAppHttpServerPostToken_t *)_SL_RESP_ARGS_START(pHdr);
			pPostParams = (_u8 *)((sl_NetAppHttpServerPostToken_t *)httpPostTokenArgs + 1);

			httpServerEvent.Event = SL_NETAPP_HTTPPOSTTOKENVALUE_EVENT;

			httpServerEvent.EventData.httpPostData.action.len = httpPostTokenArgs->post_action_len;
			httpServerEvent.EventData.httpPostData.action.data = pPostParams;
			pPostParams+=httpPostTokenArgs->post_action_len;

			httpServerEvent.EventData.httpPostData.token_name.len = httpPostTokenArgs->token_name_len;
			httpServerEvent.EventData.httpPostData.token_name.data = pPostParams;
			pPostParams+=httpPostTokenArgs->token_name_len;

			httpServerEvent.EventData.httpPostData.token_value.len = httpPostTokenArgs->token_value_len;
			httpServerEvent.EventData.httpPostData.token_value.data = pPostParams;

			httpServerResponse.Response = SL_NETAPP_RESPONSE_NONE;

			_SlDrvDispatchHttpServerEvents (&httpServerEvent, &httpServerResponse);

		}
		break;
#endif

        default:
            SL_ERROR_TRACE2(MSG_305, "ASSERT: _SlDrvNetAppEventHandler : invalid opcode = 0x%x = %1", pHdr->GenHeader.Opcode, pHdr->GenHeader.Opcode);
            VERIFY_PROTOCOL(0);
    }

	return SL_RET_CODE_OK;
}


text:
package com.bob.scala.webapi.utils

import java.util.concurrent.TimeUnit

import redis.clients.jedis.JedisCluster

/**
 * Created by bob on 16/3/21.
 */
trait DistributeLock {

  /**
   * 默认锁有效时间(单位毫秒)
   */
  val DEFAULT_LOCK_EXPIRE_TIME = 60000L

  /**
   * 默认睡眠时间(单位毫秒)
   */
  val DEFAULT_SLEEP_TIME = 100L

  /**
   * 尝试锁
   *
   * @param lock 锁的键
   * @param requestTimeout 请求超时 ms
   * @return 如果锁成功,则返回true;否则返回false
   */
  def tryLock(lock: String, requestTimeout: Long): Boolean

  /**
   * 尝试锁
   * @param lock 锁的键
   * @param lockExpireTime 锁有效期 ms
   * @param requestTimeout 请求超时 ms
   * @return 如果锁成功,则返回true;否则返回false
   */
  def tryLock(lock: String, lockExpireTime: Long, requestTimeout: Long): Boolean

  /**
   * 解锁
   * @param lock 锁的键
   */
  def unlock(lock: String): Unit
}

/**
 * 使用redis做为分布式锁
 */
class RedisDistributeLock(jedisCluster: JedisCluster) extends DistributeLock {

  import java.lang.{Long => JLong}

  /**
   * 尝试锁
   *
   * @param lock 锁的键
   * @param requestTimeout 请求超时 ms
   * @return 如果锁成功,则返回true;否则返回false
   */
  override def tryLock(lock: String, requestTimeout: Long): Boolean = {
    this.tryLock(lock, DEFAULT_LOCK_EXPIRE_TIME, requestTimeout)
  }

  /**
   * 尝试锁
   * @param lock 锁的键
   * @param lockExpireTime 锁有效期 ms
   * @param requestTimeout 请求超时 ms
   * @return 如果锁成功,则返回true;否则返回false
   */
  override def tryLock(lock: String, lockExpireTime: Long, requestTimeout: Long): Boolean = {
    require(lock != null && lock.trim.length > 0, "lock invalid")
    require(lockExpireTime > 0)
    require(requestTimeout > 0)

    var requireTimeout = requestTimeout
    while (requireTimeout > 0) {
      val expire: String = String.valueOf(System.currentTimeMillis + lockExpireTime + 1)
      val result: Long = jedisCluster.setnx(lock, expire)
      if (result > 0) {
        // 目前没有线程占用此锁
        jedisCluster.expire(lock, JLong.valueOf(lockExpireTime / 1000).intValue)
        return true
      }
      val currentValue: String = jedisCluster.get(lock)
      if (currentValue != null) {
        if (JLong.parseLong(currentValue) < System.currentTimeMillis) {
          val oldValue: String = jedisCluster.getSet(lock, expire)
          if (oldValue == null || (oldValue != null && (oldValue == currentValue))) {
            jedisCluster.expire(lock, JLong.valueOf(lockExpireTime / 1000).intValue)
            return true
          }
        }
      }
      var sleepTime: Long = 0
      if (requestTimeout > DEFAULT_SLEEP_TIME) {
        sleepTime = DEFAULT_SLEEP_TIME
        requireTimeout -= DEFAULT_SLEEP_TIME
      }
      else {
        sleepTime = requestTimeout
        requireTimeout = 0
      }
      try {
        TimeUnit.MILLISECONDS.sleep(sleepTime)
      }
      catch {
        case e: InterruptedException => {

        }
      }
    }
    false
  }

  /**
   * 解锁
   * @param lock 锁的键
   */
  override def unlock(lock: String): Unit = {
    val value: String = jedisCluster.get(lock)
    if (value != null && JLong.parseLong(value) > System.currentTimeMillis) {
      jedisCluster.del(lock)
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'

'-------------------------------------------------------------------------------------------'
' Inicio de clase "rResumen_Pago_INCE"
'-------------------------------------------------------------------------------------------'
Partial Class rResumen_Pago_INCE
    Inherits vis2formularios.frmReporte

    Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Try

            Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
            Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
            Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1))    'Recibo
            Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1))
            Dim lcParametro2Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))    'Contrato del Recibo
            Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2))
            Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3))    'Trabajador
            Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3))
            Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4))    'Contrato del Trabajador
            Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4))
            Dim lcParametro5Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5))    'Sucursal
            Dim lcParametro5Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5))
            Dim lcParametro6Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(6))    'Revisión
            Dim lcParametro6Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(6))

            Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
            Dim loComandoSeleccionar As New StringBuilder()

            loComandoSeleccionar.AppendLine("")
            loComandoSeleccionar.AppendLine("SELECT      RIGHT('0000'+CAST(YEAR(Recibos.Fecha) AS VARCHAR(4)),4)  AS Año,")
            loComandoSeleccionar.AppendLine("			CASE ")
            loComandoSeleccionar.AppendLine("				WHEN MONTH(Recibos.Fecha) IN(1,2,3) THEN 1")
            loComandoSeleccionar.AppendLine("				WHEN MONTH(Recibos.Fecha) IN(4,5,6) THEN 2")
            loComandoSeleccionar.AppendLine("				WHEN MONTH(Recibos.Fecha) IN(7,8,9) THEN 3")
            loComandoSeleccionar.AppendLine("				WHEN MONTH(Recibos.Fecha) IN(10,11,12) THEN 4")
            loComandoSeleccionar.AppendLine("			END														 AS Trimestre,")
            loComandoSeleccionar.AppendLine("            COUNT(DISTINCT Recibos.Cod_Tra)                          AS Trabajadores,")
            loComandoSeleccionar.AppendLine("			SUM(CASE Conceptos_Nomina.tipo")
            loComandoSeleccionar.AppendLine("					WHEN 'Asignacion' THEN Renglones_Recibos.mon_net")
            loComandoSeleccionar.AppendLine("					else -Renglones_Recibos.mon_net")
            loComandoSeleccionar.AppendLine("				END)												AS Monto_Devengado,")
            loComandoSeleccionar.AppendLine("			(SELECT TOP 1 val_num")
            loComandoSeleccionar.AppendLine("           FROM Constantes_Locales")
            loComandoSeleccionar.AppendLine("			WHERE COD_CON ='U004')*")
            loComandoSeleccionar.AppendLine("			SUM(CASE Conceptos_Nomina.tipo")
            loComandoSeleccionar.AppendLine("					WHEN 'Asignacion' THEN Renglones_Recibos.mon_net")
            loComandoSeleccionar.AppendLine("					else -Renglones_Recibos.mon_net")
            loComandoSeleccionar.AppendLine("				END)/100											AS Aporte")
            loComandoSeleccionar.AppendLine("FROM        Renglones_Recibos")
            loComandoSeleccionar.AppendLine("    JOIN    Recibos")
            loComandoSeleccionar.AppendLine("        ON  Recibos.Documento = Renglones_Recibos.Documento")
            loComandoSeleccionar.AppendLine("    JOIN    Conceptos_Nomina")
            loComandoSeleccionar.AppendLine("        ON  Conceptos_Nomina.cod_con = Renglones_Recibos.cod_con ")
            loComandoSeleccionar.AppendLine("    JOIN    Trabajadores")
            loComandoSeleccionar.AppendLine("        ON  Trabajadores.Cod_Tra = Recibos.Cod_Tra ")
            loComandoSeleccionar.AppendLine("WHERE       Conceptos_Nomina.tipo <> 'otro'")
            loComandoSeleccionar.AppendLine("    AND     Conceptos_Nomina.acumulados = 1")
            loComandoSeleccionar.AppendLine("    AND     Recibos.Status = 'Confirmado'")
            loComandoSeleccionar.AppendLine("    AND     Recibos.Fecha BETWEEN " & lcParametro0Desde & " AND " & lcParametro0Hasta)
            loComandoSeleccionar.AppendLine("    AND     Recibos.Documento BETWEEN " & lcParametro1Desde & " AND " & lcParametro1Hasta)
            loComandoSeleccionar.AppendLine("    AND     Recibos.Cod_Con BETWEEN " & lcParametro2Desde & " AND " & lcParametro2Hasta)
            loComandoSeleccionar.AppendLine("    AND     Trabajadores.Cod_Tra BETWEEN " & lcParametro3Desde & " AND " & lcParametro3Hasta)
            loComandoSeleccionar.AppendLine("    AND     Trabajadores.Cod_Con BETWEEN " & lcParametro4Desde & " AND " & lcParametro4Hasta)
            loComandoSeleccionar.AppendLine("    AND     Recibos.Cod_Suc BETWEEN " & lcParametro5Desde & " AND " & lcParametro5Hasta)
            loComandoSeleccionar.AppendLine("    AND     Recibos.Cod_Rev BETWEEN " & lcParametro6Desde & " AND " & lcParametro6Hasta)
            loComandoSeleccionar.AppendLine("GROUP BY    RIGHT('0000'+CAST(YEAR(Recibos.Fecha) as VARCHAR(4)),4),")
            loComandoSeleccionar.AppendLine("			CASE ")
            loComandoSeleccionar.AppendLine("				WHEN MONTH(Recibos.Fecha) IN(1,2,3) THEN 1")
            loComandoSeleccionar.AppendLine("				WHEN MONTH(Recibos.Fecha) IN(4,5,6) THEN 2")
            loComandoSeleccionar.AppendLine("				WHEN MONTH(Recibos.Fecha) IN(7,8,9) THEN 3")
            loComandoSeleccionar.AppendLine("				WHEN MONTH(Recibos.Fecha) IN(10,11,12) THEN 4")
            loComandoSeleccionar.AppendLine("            End")
            loComandoSeleccionar.AppendLine("ORDER BY    RIGHT('0000'+CAST(YEAR(Recibos.Fecha) as VARCHAR(4)),4),")
            loComandoSeleccionar.AppendLine("			CASE ")
            loComandoSeleccionar.AppendLine("				WHEN MONTH(Recibos.Fecha) IN(1,2,3) THEN 1")
            loComandoSeleccionar.AppendLine("				WHEN MONTH(Recibos.Fecha) IN(4,5,6) THEN 2")
            loComandoSeleccionar.AppendLine("				WHEN MONTH(Recibos.Fecha) IN(7,8,9) THEN 3")
            loComandoSeleccionar.AppendLine("				WHEN MONTH(Recibos.Fecha) IN(10,11,12) THEN 4")
            loComandoSeleccionar.AppendLine("            End")

            Dim loServicios As New cusDatos.goDatos

            'Me.mEscribirConsulta(loComandoSeleccionar.ToString())
            Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString(), "curReportes")

            loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rResumen_Pago_INCE", laDatosReporte)

            Me.mTraducirReporte(loObjetoReporte)

            Me.mFormatearCamposReporte(loObjetoReporte)

            Me.crvrResumen_Pago_INCE.ReportSource = loObjetoReporte

        Catch loExcepcion As Exception

            Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
                 "No se pudo Completar el Proceso: " & loExcepcion.Message, _
                  vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
                  "auto", _
                  "auto")

        End Try

    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload

        Try

            loObjetoReporte.Close()

        Catch loExcepcion As Exception

        End Try

    End Sub

End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo																			'
'-------------------------------------------------------------------------------------------'
' EAG: 02/10/15: Codigo inicial																'
'-------------------------------------------------------------------------------------------'


text:
package main
import (
	"./parser"
	"./utils"
)

func main(){
	tasks,err := parser.ReadAndParseJSONArray("./test/taskQueue.json")
	task := tasks[0]
	if(err != nil){
		panic(err)
	}
	cookie := task["cookie"].(map[string]interface{})
	needCookie := cookie["need"].(string)
	switch task["type"] {
		case "get":
			if(needCookie == "no"){
				response,err := utils.SimpleGet(task["url"].(string),task["params"].([]interface{}))
				if(err != nil){panic(nil)}
				matches,err := utils.Peek(response,task["pattern"].(string))
				if(err != nil){panic(nil)}
				utils.DBWork("tecentKt",matches)
			}
	}
}


text:
import matplotlib
from matplotlib import *
import matplotlib.pyplot as plt
from matplotlib.ticker import *

def rstyle(ax):
    """Styles an axes to appear like ggplot2
    Must be called after all plot and axis manipulation operations have been carried out (needs to know final tick spacing)
    """
    #set the style of the major and minor grid lines, filled blocks
    ax.grid(True, 'major', color='w', linestyle='-', linewidth=1.4)
    ax.grid(True, 'minor', color='0.92', linestyle='-', linewidth=0.7)
    ax.patch.set_facecolor('0.85')
    ax.set_axisbelow(True)

    #set minor tick spacing to 1/2 of the major ticks
    #ax.xaxis.set_minor_locator(MultipleLocator( (plt.xticks()[0][1]-plt.xticks()[0][0]) / 2.0 ))
    #ax.yaxis.set_minor_locator(MultipleLocator( (plt.yticks()[0][1]-plt.yticks()[0][0]) / 2.0 ))
    ax.xaxis.set_minor_locator(MultipleLocator( (ax.xaxis.get_ticklocs()[1]-ax.xaxis.get_ticklocs()[0]) / 2.0 ))
    ax.yaxis.set_minor_locator(MultipleLocator( (ax.yaxis.get_ticklocs()[1]-ax.yaxis.get_ticklocs()[0]) / 2.0 ))

    #remove axis border
    for child in ax.get_children():
        if isinstance(child, matplotlib.spines.Spine):
            child.set_alpha(0)

    #restyle the tick lines
    for line in ax.get_xticklines() + ax.get_yticklines():
        line.set_markersize(5)
        line.set_color("gray")
        line.set_markeredgewidth(1.4)

    #remove the minor tick lines
    for line in ax.xaxis.get_ticklines(minor=True) + ax.yaxis.get_ticklines(minor=True):
        line.set_markersize(0)

    #only show bottom left ticks, pointing out of axis
    rcParams['xtick.direction'] = 'out'
    rcParams['ytick.direction'] = 'out'
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')

    if (ax.legend_ is not None):
        lg = ax.legend_
        lg.get_frame().set_linewidth(0)
        lg.get_frame().set_alpha(0.5)

def rhist(ax, data, **keywords):
    """Creates a histogram with default style parameters to look like ggplot2
    Is equivalent to calling ax.hist and accepts the same keyword parameters.
    If style parameters are explicitly defined, they will not be overwritten
    """

    defaults = {
                'facecolor' : '0.3',
                'edgecolor' : '0.28',
                'linewidth' : '1',
                'bins' : 100
                }

    for k, v in defaults.items():
        if k not in keywords: keywords[k] = v

    return ax.hist(data, **keywords)

def rbox(ax, data, **keywords):
    """Creates a ggplot2 style boxplot, is eqivalent to calling ax.boxplot with the following additions:

    Keyword arguments:
    colors -- array-like collection of colours for box fills
    names -- array-like collection of box names which are passed on as tick labels

    """

    hasColors = 'colors' in keywords
    if hasColors:
        colors = keywords['colors']
        keywords.pop('colors')

    if 'names' in keywords:
        ax.tickNames = plt.setp(ax, xticklabels=keywords['names'] )
        keywords.pop('names')

    bp = ax.boxplot(data, **keywords)
    pylab.setp(bp['boxes'], color='black')
    pylab.setp(bp['whiskers'], color='black', linestyle = 'solid')
    pylab.setp(bp['fliers'], color='black', alpha = 0.9, marker= 'o', markersize = 3)
    pylab.setp(bp['medians'], color='black')

    numBoxes = len(data)
    for i in range(numBoxes):
        box = bp['boxes'][i]
        boxX = []
        boxY = []
        for j in range(5):
          boxX.append(box.get_xdata()[j])
          boxY.append(box.get_ydata()[j])
        boxCoords = zip(boxX,boxY)

        if hasColors:
            boxPolygon = Polygon(boxCoords, facecolor = colors[i % len(colors)])
        else:
            boxPolygon = Polygon(boxCoords, facecolor = '0.95')

        ax.add_patch(boxPolygon)
    return bp


text:
import { DocsDataTree } from "../../../lib/markdown/docs/get-docs-data";
import DocTree from "./DocTree";
import NavTop from "../../nav/NavTop";
import styles from "./DocsLayout.module.scss";
import NavSide from "../../nav/NavSide";
import { SidePanelContext } from "@rollem/ui/lib/contexts/sidepanel-context";
import { Button, Container, Hidden } from "@material-ui/core";

export default function DocsLayout({
  children,
  allDocsData,
}: {
  children: unknown;
  allDocsData: DocsDataTree[];
}) {
  return (

      <NavSide></NavSide>

          <NavTop></NavTop>

            <DocTree allDocsData={allDocsData}></DocTree>

            <Hidden mdUp>
              <SidePanelContext.Consumer>
                {({ toggleDocsDrawer }) => (
                  <Container maxWidth="xs">
                    <Button className={styles.wideButton} onClick={toggleDocsDrawer(true)}>Show Docs Menu</Button>
                  </Container>
                )}
              </SidePanelContext.Consumer>
            </Hidden>
            {children}

  );
}


text:
<?xml version="1.0"?>
<project xmlns="antlib:org.apache.tools.ant" name="antcc" basedir="." default="help" >
	<description>
	    Common include for all plugins
    </description>

	<dirname file="${ant.file.antcc}" property="antcc.home" />

	<import file="lib/bootstrap.xml" />

	<import file="lib/sagcc.xml" />
	<import file="lib/sagenv.xml" />
	<import file="lib/sagtest.xml" />
	<import file="lib/sagabe.xml" />
	<import file="lib/sagrepo.xml" />

	<target name="help" description="Usage help" depends="
		help-bootstrap,
		help-sagcc,
		help-sagenv,
		help-sagtest,
		help-sagabe
	" />

	<target name="all" description="End to end automation" depends="up,test" />

</project>


text:
package gobblin.source;

import gobblin.configuration.SourceState;
import gobblin.source.workunit.WorkUnitStream;

/**
 * A {@link Source} that produces a {@link WorkUnitStream}.
 *
 * Streamed sources may offer certain advantages over non-streamed sources if the job launcher supports them:
 *  * Low memory usage: If the {@link WorkUnitStream} is backed by a generator, the job launcher may optimize memory
 *    usage by never materializing all work units in memory.
 *  * Eager processing of slow sources: If the source is slow at producing work units, the job launcher may start
 *    processing available work units while future work units are still being computed.
 *  * Infinite work unit streams: in the future, some job launchers will support infinite streams of work units.
 */
public interface WorkUnitStreamSource<S, D> extends Source<S, D> {
  /**
   * Get the {@link WorkUnitStream} to process.
   */
  WorkUnitStream getWorkunitStream(SourceState state);
}


text:
#ifndef CONFIG_H_
#define CONFIG_H_

/*Debug options*/
#define CONFIG_DEBUG
#define CONFIG_KDB

/*Table sizes*/
enum {
	CONFIG_MAX_THREADS	= 32,
	CONFIG_MAX_KT_EVENTS	= 64,
	CONFIG_MAX_ASYNC_EVENTS	= 32,
	CONFIG_MAX_ADRESS_SPACES = 16,
	CONFIG_MAX_FPAGES = 256
};

#define CONFIG_KTIMER_HEARTBEAT		65536
#define CONFIG_KTIMER_MINTICKS		128

#define CONFIG_LARGEST_FPAGE_SHIFT	16
#define CONFIG_SMALLEST_FPAGE_SHIFT	8
#define CONFIG_SMALLEST_FPAGE_SIZE		(1 << CONFIG_SMALLEST_FPAGE_SHIFT)

#define CONFIG_INTR_THREAD_MAX	256

#define CONFIG_KIP_EXTRA_SIZE	128

#define CONFIG_BITMAP_BITBAND

#define CONFIG_PANIC_DUMP_STACK

#endif /* CONFIG_H_ */


text:
#ifndef simpleColorCode_H_
#define simpleColorCode_H_
#include "smartBlocksBlockCode.h"

static const int BROADCAST_MSG=1001;

using namespace SmartBlocks;

class SimpleColorCode : public SmartBlocksBlockCode {
private:
    int distance;
public :
	SimpleColorCode(SmartBlocksBlock *host):SmartBlocksBlockCode(host) {};
	~SimpleColorCode() {};

	void startup();
	void myBroadcastFunc(const MessageOf<int>*msg,P2PNetworkInterface *sender);

/*****************************************************************************/
/** needed to associate code to module                                      **/
	static BlockCode *buildNewBlockCode(BuildingBlock *host) {
	    return (new SimpleColorCode((SmartBlocksBlock*)host));
	};
/*****************************************************************************/
};
	void _myBroadcastFunc(BlockCode *,MessagePtr,P2PNetworkInterface *sender);
#endif /* simpleColorCode_H_ */


text:
<?php

/* editcontent/fields/_textarea.twig */
class __TwigTemplate_11384a4cb524d7df094ea2ea53c21221f2e1db91479fe993ca64c7855073f167 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 2
        echo "
";
        // line 3
        $context["option"] = array("class" => (($this->getAttribute(        // line 4
(isset($context["field"]) ? $context["field"] : null), "class", array(), "any", true, true)) ? (_twig_default_filter($this->getAttribute((isset($context["field"]) ? $context["field"] : null), "class", array()), "")) : ("")), "height" => (($this->getAttribute(        // line 5
(isset($context["field"]) ? $context["field"] : null), "height", array(), "any", true, true)) ? (_twig_default_filter($this->getAttribute((isset($context["field"]) ? $context["field"] : null), "height", array()), "")) : ("")), "label" => (($this->getAttribute(        // line 6
(isset($context["field"]) ? $context["field"] : null), "label", array(), "any", true, true)) ? (_twig_default_filter($this->getAttribute((isset($context["field"]) ? $context["field"] : null), "label", array()), "")) : ("")), "info" => (($this->getAttribute(        // line 7
(isset($context["field"]) ? $context["field"] : null), "info", array(), "any", true, true)) ? (_twig_default_filter($this->getAttribute((isset($context["field"]) ? $context["field"] : null), "info", array()), "")) : ("")), "required" => (($this->getAttribute(        // line 8
(isset($context["field"]) ? $context["field"] : null), "required", array(), "any", true, true)) ? (_twig_default_filter($this->getAttribute((isset($context["field"]) ? $context["field"] : null), "required", array()), false)) : (false)), "errortext" => (($this->getAttribute(        // line 9
(isset($context["field"]) ? $context["field"] : null), "error", array(), "any", true, true)) ? (_twig_default_filter($this->getAttribute((isset($context["field"]) ? $context["field"] : null), "error", array()), "")) : ("")));
        // line 11
        echo "
";
        // line 13
        echo "
";
        // line 14
        $context["attr_text"] = array("class" => $this->getAttribute(        // line 15
(isset($context["option"]) ? $context["option"] : null), "class", array()), "name" =>         // line 16
(isset($context["name"]) ? $context["name"] : null), "required" => $this->getAttribute(        // line 17
(isset($context["option"]) ? $context["option"] : null), "required", array()), "style" => (($this->getAttribute(        // line 18
(isset($context["option"]) ? $context["option"] : null), "height", array())) ? ((("height: " . $this->getAttribute((isset($context["option"]) ? $context["option"] : null), "height", array())) . ";")) : ("")), "data_errortext" => $this->getAttribute(        // line 19
(isset($context["option"]) ? $context["option"] : null), "errortext", array()));
        // line 21
        echo "
";
        // line 23
        echo "
<fieldset class=\"textarea\">

        ";
        // line 27
        echo twig_escape_filter($this->env, (($this->getAttribute((isset($context["option"]) ? $context["option"] : null), "info", array())) ? ($this->getAttribute((isset($context["macro"]) ? $context["macro"] : null), "infopop", array(0 => (isset($context["labelkey"]) ? $context["labelkey"] : null), 1 => $this->getAttribute((isset($context["option"]) ? $context["option"] : null), "info", array())), "method")) : ((isset($context["labelkey"]) ? $context["labelkey"] : null))), "html", null, true);
        echo "
        <textarea";
        // line 28
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["macro"]) ? $context["macro"] : null), "attr", array(0 => (isset($context["attr_text"]) ? $context["attr_text"] : null)), "method"), "html", null, true);
        echo ">";
        echo twig_escape_filter($this->env, (($this->getAttribute($this->getAttribute((isset($context["context"]) ? $context["context"] : null), "content", array(), "any", false, true), "get", array(0 => (isset($context["contentkey"]) ? $context["contentkey"] : null)), "method", true, true)) ? (_twig_default_filter($this->getAttribute($this->getAttribute((isset($context["context"]) ? $context["context"] : null), "content", array(), "any", false, true), "get", array(0 => (isset($context["contentkey"]) ? $context["contentkey"] : null)), "method"), "")) : ("")), "html", null, true);
        echo "</textarea>

</fieldset>
";
    }

    public function getTemplateName()
    {
        return "editcontent/fields/_textarea.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  56 => 28,  52 => 27,  46 => 23,  43 => 21,  41 => 19,  40 => 18,  39 => 17,  38 => 16,  37 => 15,  36 => 14,  33 => 13,  30 => 11,  28 => 9,  27 => 8,  26 => 7,  25 => 6,  24 => 5,  23 => 4,  22 => 3,  19 => 2,);
    }
}
/* {#=== OPTIONS ========================================================================================================#}*/
/* */
/* {% set option = {*/
/*     class:     field.class|default(''),*/
/*     height:    field.height|default(''),*/
/*     label:     field.label|default(''),*/
/*     info:      field.info|default(''),*/
/*     required:  field.required|default(false),*/
/*     errortext: field.error|default(''),*/
/* } %}*/
/* */
/* {#=== INIT ===========================================================================================================#}*/
/* */
/* {% set attr_text = {*/
/*     class:     option.class,*/
/*     name:      name,*/
/*     required:  option.required,*/
/*     style:     option.height ? 'height: ' ~ option.height ~ ';' : '',*/
/*     data_errortext: option.errortext,*/
/* } %}*/
/* */
/* {#=== FIELDSET =======================================================================================================#}*/
/* */
/* <fieldset class="textarea">*/
/* */
/*
*/
/*         {{ (option.info) ? macro.infopop(labelkey, option.info) : labelkey }}*/
/*         <textarea{{ macro.attr(attr_text) }}>{{ context.content.get(contentkey)|default('') }}</textarea>*/
/*
*/
/* */
/* </fieldset>*/
/* */


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Barbequed Scallops Hoisin</title>
      <categories>
        <cat>Seafood</cat>
        <cat>Scallops</cat></categories>
      <yield>4</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>1 1/4</qty>
          <unit>pounds</unit></amt>
        <item>Bay or sea scallops</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>medium</unit></amt>
        <item>Red peppers; cut into inch squares</item></ing>
      <ing>
        <amt>
          <qty>3</qty>
          <unit>tablespoons</unit></amt>
        <item>Hoisin sauce</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>tablespoon</unit></amt>
        <item>Soy sauce</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>tablespoons</unit></amt>
        <item>Dry sherry</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>tablespoon</unit></amt>
        <item>Sugar</item></ing></ingredients>
    <directions>
      <step>  Alternately thread the red pepper and scallops on wooden skewers, beginning
  and ending with peppers.

  Mix together the Hoisin, soy, sherry, and sugar. Brush the shellfish and
  peppers with the sauce, coating well.

  Grill the kebobs over hot coals 4 inches from the heat source, 3 to 4
  minutes per side. Remove to a platter and serve.

  Scallops and red pepper are skewered and brushed with a Hoisin-inspired
  barbecue sauce before being char-grilled for an Oriental flavor sensation.
  Posted to MC-Recipe Digest V1 #929 by Nancy Berry <nlberry@prodigy.net> on
  Nov 28, 1997

</step></directions></recipe></recipeml>


text:
describe("webworks.handset system", function () {
    var system = ripple('platform/webworks.core/2.0.0/server/system'),
        systemEvent = ripple('platform/webworks.handset/2.0.0/server/systemEvent'),
        client = ripple('platform/webworks.handset/2.0.0/client/system'),
        transport = ripple('platform/webworks.core/2.0.0/client/transport'),
        utils = ripple('utils');

    describe("using webworks.handset server", function () {
        it("exposes the system module", function () {
            var webworks = ripple('platform/webworks.handset/2.0.0/server'),
                obj = {};
            obj.event = systemEvent;
            utils.mixin(system, obj);
            expect(webworks.blackberry.system).toEqual(obj);
        });
    });

    describe("client", function () {
        describe("setHomeScreenBackground", function () {
            it("calls the transport with id and properties", function () {
                spyOn(transport, "call");
                client.setHomeScreenBackground("filepath");
                expect(transport.call).toHaveBeenCalledWith("blackberry/system/setHomeScreenBackground", {
                    get: {filePath: "filepath"},
                    async: true
                });
            });
        });
    });
});


text:
// Copyright (c) MOSA Project. Licensed under the New BSD License.

using Mosa.Compiler.Framework;
using System;

namespace Mosa.Platform.x86.Instructions
{
	/// <summary>
	/// Representations the x86 inc instruction.
	/// </summary>
	public sealed class Inc : X86Instruction
	{
		#region Data Members

		private static readonly OpCode INC8 = new OpCode(new byte[] { 0xFE }, 0);
		private static readonly OpCode INC16 = new OpCode(new byte[] { 0x66, 0xFF }, 0);
		private static readonly OpCode INC32 = new OpCode(new byte[] { 0xFF }, 0);

		#endregion Data Members

		#region Construction

		/// <summary>
		/// Initializes a new instance of <see cref="Inc"/>.
		/// </summary>
		public Inc() :
			base(1, 1)
		{
		}

		#endregion Construction

		#region Methods

		/// <summary>
		/// Computes the opcode.
		/// </summary>
		/// <param name="destination">The destination operand.</param>
		/// <param name="source">The source operand.</param>
		/// <param name="third">The third operand.</param>
		/// <returns></returns>
		protected override OpCode ComputeOpCode(Operand destination, Operand source, Operand third)
		{
			if (destination.IsByte) return INC8;
			if (destination.IsShort || destination.IsChar) return INC16;
			if (destination.IsInt) return INC32;

			throw new ArgumentException(@"No opcode for operand type.");
		}

		/// <summary>
		/// Emits the specified platform instruction.
		/// </summary>
		/// <param name="node">The node.</param>
		/// <param name="emitter">The emitter.</param>
		protected override void Emit(InstructionNode node, MachineCodeEmitter emitter)
		{
			OpCode opCode = ComputeOpCode(node.Result, null, null);
			emitter.Emit(opCode, node.Result);
		}

		/// <summary>
		/// Allows visitor based dispatch for this instruction object.
		/// </summary>
		/// <param name="visitor">The visitor object.</param>
		/// <param name="context">The context.</param>
		public override void Visit(IX86Visitor visitor, Context context)
		{
			visitor.Inc(context);
		}

		#endregion Methods
	}
}


text:
import scala.collection.immutable._

object Test extends dotty.runtime.LegacyApp {
  val res0 = TreeSet(1, 2, 3, 4, 5, 6)
  val res1 = res0.map(x => x)
  println(res0.toList == res1.toList)
  println(res1.getClass)
}


text:
module Archive
  module ApplicationHelper
  end
end


text:
package com.khartec.waltz.common.exception;

public class UpdateFailedException extends RuntimeException {

    private final String code;

    public UpdateFailedException(String code, String message) {
        super(message);
        this.code = code;
    }

    public UpdateFailedException(String code, String message, Throwable cause) {
        super(message, cause);
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
  <id>z37f0n3A05</id>
  <first-name>Craig</first-name>
  <last-name>Walls</last-name>
  <location>
    <name>Dallas/Fort Worth Area</name>
    <country>
      us
    </country>
  </location>
  <headline>Just a guy</headline>
  <industry>Computer Software</industry>
  <num-recommenders>15</num-recommenders>
  <connections total="234" />
  <positions total="0" />
  <educations total="0" />
  <member-url-resources total="0" />
  <api-public-profile-request>
    <url>http://api.linkedin.com/v1/people/url=http%3A%2F%2Fwww%2Elinkedin%2Ecom%2Fin%2Fhabuma:public</url>
  </api-public-profile-request>
  <site-public-profile-request>
    <url>http://www.linkedin.com/in/habuma</url>
  </site-public-profile-request>
  <site-standard-profile-request>
    <url>http://www.linkedin.com/standardProfileUrl</url>
  </site-standard-profile-request>
  <public-profile-url>http://www.linkedin.com/in/habuma</public-profile-url>
  <picture-url>http://media.linkedin.com/pictureUrl</picture-url>
</person>


text:
#if !defined(LIMITS_CHECKER_HPP)
#define LIMITS_CHECKER_HPP

#include "LimitLibrary.hpp"
#include "MetricOptions.hpp"
#include "MetricUnit.hpp"

class LimitsChecker {
  protected:
    static std::string check(const MetricUnit *const p_topLevel, const MetricOptions &p_options,
                             const LimitLibrary &p_limits);

  public:
    static void dump(const MetricUnit *const p_topLevel, const MetricOptions &p_options);
    static void dump(const MetricUnit *const p_topLevel, const MetricOptions &p_options,
                     const LimitLibrary &p_limits);
};

#endif


text:
namespace gles2_conform_support {
namespace egl {

class Config {
 public:
  explicit Config(EGLint surface_type);

  Config(const Config&) = delete;
  Config& operator=(const Config&) = delete;

  ~Config();
  bool Matches(const EGLint* attrib_list) const;
  bool GetAttrib(EGLint attribute, EGLint* value) const;
  static bool ValidateAttributeList(const EGLint* attrib_list);

 private:
  // Total color component bits in the color buffer.
  EGLint buffer_size_;
  // Bits of Red in the color buffer.
  EGLint red_size_;
  // Bits of Green in the color buffer.
  EGLint green_size_;
  // Bits of Blue in the color buffer.
  EGLint blue_size_;
  // Bits of Luminance in the color buffer.
  EGLint luminance_size_;
  // Bits of Alpha in the color buffer.
  EGLint alpha_size_;
  // Bits of Alpha Mask in the mask buffer.
  EGLint alpha_mask_size_;
  // True if bindable to RGB textures.
  EGLBoolean bind_to_texture_rgb_;
  // True if bindable to RGBA textures.
  EGLBoolean bind_to_texture_rgba_;
  // Color buffer type.
  EGLenum color_buffer_type_;
  // Any caveats for the configuration.
  EGLenum config_caveat_;
  // Unique EGLConfig identifier.
  EGLint config_id_;
  // Whether contexts created with this config are conformant.
  EGLint conformant_;
  // Bits of Z in the depth buffer.
  EGLint depth_size_;
  // Frame buffer level.
  EGLint level_;
  // Maximum width of pbuffer.
  EGLint max_pbuffer_width_;
  // Maximum height of pbuffer.
  EGLint max_pbuffer_height_;
  // Maximum size of pbuffer.
  EGLint max_pbuffer_pixels_;
  // Minimum swap interval.
  EGLint min_swap_interval_;
  // Maximum swap interval.
  EGLint max_swap_interval_;
  // True if native rendering APIs can render to surface.
  EGLBoolean native_renderable_;
  // Handle of corresponding native visual.
  EGLint native_visual_id_;
  // Native visual type of the associated visual.
  EGLint native_visual_type_;
  // Which client rendering APIs are supported.
  EGLint renderable_type_;
  // Number of multisample buffers.
  EGLint sample_buffers_;
  // Number of samples per pixel.
  EGLint samples_;
  // Bits of Stencil in the stencil buffer.
  EGLint stencil_size_;
  // Which types of EGL surfaces are supported.
  EGLint surface_type_;
  // Type of transparency supported
  EGLenum transparent_type_;
  // Transparent red value
  EGLint transparent_red_value_;
  // Transparent green value
  EGLint transparent_green_value_;
  // Transparent blue value
  EGLint transparent_blue_value_;
};

}  // namespace egl
}  // namespace gles2_conform_support

#endif  // GPU_GLES2_CONFORM_SUPPORT_EGL_CONFIG_H_


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.02.25 at 12:05:09 AM CET
//

package com.hack23.cia.model.internal.application.data.committee.impl;

import java.util.Date;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import com.hack23.cia.model.common.api.ModelObject;
import com.hack23.cia.model.common.impl.xml.XmlDateTypeAdapter;

/**
 *
Java class for RiksdagenCommitteeDecisionTypeOrgSummaryEmbeddedId complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="RiksdagenCommitteeDecisionTypeOrgSummaryEmbeddedId">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="decision_date" type="{http://www.w3.org/2001/XMLSchema}date"/>
 *         <element name="decision_type" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="org" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RiksdagenCommitteeDecisionTypeOrgSummaryEmbeddedId", propOrder = {
    "decisionDate",
    "decisionType",
    "org"
})
@Embeddable
public class RiksdagenCommitteeDecisionTypeOrgSummaryEmbeddedId
    implements ModelObject
{

    /**
	 *
	 */
	private static final long serialVersionUID = 1L;
	@XmlElement(name = "decision_date", required = true, type = String.class)
    @XmlJavaTypeAdapter(XmlDateTypeAdapter.class)
    @XmlSchemaType(name = "date")
    protected Date decisionDate;
    @XmlElement(name = "decision_type", required = true)
    protected String decisionType;
    @XmlElement(required = true)
    protected String org;

    /**
     * Gets the value of the decisionDate property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    @Basic
    @Column(name = "DECISION_DATE")
    @Temporal(TemporalType.DATE)
    public Date getDecisionDate() {
        return decisionDate;
    }

    /**
     * Sets the value of the decisionDate property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDecisionDate(final Date value) {
        this.decisionDate = value;
    }

    /**
     * Gets the value of the decisionType property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    @Basic
    @Column(name = "DECISION_TYPE")
    public String getDecisionType() {
        return decisionType;
    }

    /**
     * Sets the value of the decisionType property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDecisionType(final String value) {
        this.decisionType = value;
    }

    /**
     * Gets the value of the org property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    @Basic
    @Column(name = "ORG")
    public String getOrg() {
        return org;
    }

    /**
     * Sets the value of the org property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setOrg(final String value) {
        this.org = value;
    }

    public RiksdagenCommitteeDecisionTypeOrgSummaryEmbeddedId withDecisionDate(final Date value) {
        setDecisionDate(value);
        return this;
    }

    public RiksdagenCommitteeDecisionTypeOrgSummaryEmbeddedId withDecisionType(final String value) {
        setDecisionType(value);
        return this;
    }

    public RiksdagenCommitteeDecisionTypeOrgSummaryEmbeddedId withOrg(final String value) {
        setOrg(value);
        return this;
    }

	@Override
	public final String toString() {
		return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
	}

	@Override
	public final boolean equals(final Object obj) {
		return EqualsBuilder.reflectionEquals(this, obj);
	}

	@Override
	public final int hashCode() {
		return HashCodeBuilder.reflectionHashCode(this);
	}

}