text:
#include "OS_Types.h"
#include "Task.h"
#include "OS_cfg.h"
#include "common.h"
/*******************************************************************************
**                                                                            **
** FUNC-NAME     :                                                            **
**                                                                            **
** DESCRIPTION   :                                                            **
**                                                                            **
** PRECONDITIONS :                                                            **
**                                                                            **
** PARAMETER     :                                                            **
**                                                                            **
** RETURN        :                                                            **
**                                                                            **
** REMARKS       :                                                            **
**                                                                            **
*******************************************************************************/
void AddReady(TaskType TaskID)
{
//#if 0
	TaskPriorityType    priority;
	TaskRefType         readylist;
	TaskTotalType       maxtasks;
	TaskTotalType       position;

	/* get task priority */
	priority = TasksConst[TaskID].StaticPriority;

	/* set the start priority for this task */
	TasksVar[TaskID].ActualPriority = priority;

	/* conver the priority to the array index */
	/* do not remove the -1 is needed. for example if READYLIST_COUNT is 4
	* the valida entries for this array are between 0 and 3, so the -1 is needed
	* since the lower priority is 0.
	*/
	priority = (TASKS_COUNT-1)-priority;

	/* get ready list */
	readylist = ReadyConst[priority].TaskRef;
	/* get max number of entries */
	maxtasks = ReadyConst[priority].ListLength;

	/* get position incrementtion */
	position = ReadyVar[priority].ListStart + ReadyVar[priority].ListCount;

	/* go arround maxtasks */
	/* this if works like  % instruction */
	if (position >= maxtasks)
	{
		position =  (TaskTotalType)(position - maxtasks);
	}

	/* set the task id in ready the list */
	readylist[position] = TaskID;
	/* increment the list counter */
	ReadyVar[priority].ListCount++;
//#endif
}

/*******************************************************************************
**                                                                            **
** FUNC-NAME     :                                                            **
**                                                                            **
** DESCRIPTION   :                                                            **
**                                                                            **
** PRECONDITIONS :                                                            **
**                                                                            **
** PARAMETER     :                                                            **
**                                                                            **
** RETURN        :                                                            **
**                                                                            **
** REMARKS       :                                                            **
**                                                                            **
*******************************************************************************/
StatusType ActivateTask(TaskType TaskID)
{

	/* \req OSEK_SYS_3.1 The system service StatusType
	 * ActivateTask ( TaskType TaskID ) shall be defined. */

	/* \req OSEK_SYS_3.1.3 The service may be called from interrupt category 2
    * level and from task level. */
	/* nothing to do for this req. */

	/* \req OSEK_SYS_3.1.7-1/3 Possible return values in Standard mode are E_OK or E_OS_LIMIT */
	StatusType ret = E_OK;

#if (ERROR_CHECKING_TYPE == ERROR_CHECKING_EXTENDED)
	/* check if the task id is valid */
	if ( TaskID >= TASKS_COUNT )
	{
		/* if an invalid task id return E_OS_ID */
		/* \req OSEK_SYS_3.1.5-1/3 If other than E_OK is returned the activation
		 * is ignored */
		/* \req OSEK_SYS_3.1.8 Added possible return values in Extended mode is
		 * E_OS_ID */
		ret = E_OS_ID;
	}
	else
#endif
	{
		IntSecure_Start();

		/* check if the task is susspended */
		/* \req OSEK_SYS_3.1.1-1/2 The task TaskID shall be transferred from the
		 * suspended state into the ready state. */
		if ( TasksVar[TaskID].Flags.State == SUSPENDED )
		{
			/* increment activation counter */
			TasksVar[TaskID].Activations++;
			/* if the task was suspended set it to ready */
			/* OSEK_SYS_3.1.1-2/2 The task TaskID shall be transferred from the
			 * suspended state into the ready state.*/
			TasksVar[TaskID].Flags.State = READY;
			/* clear all events */
			/* \req OSEK_SYS_3.1.6 When an extended task is transferred from
			 * suspended state into ready state all its events are cleared. */
			TasksVar[TaskID].Events = 0;
			/* add the task to the ready list */
			AddReady(TaskID);
		}
		else
		{
			/* task is not suspended */

			/* check if the task is a extended task */
			if ( TasksConst[TaskID].ConstFlags.Extended )
			{
				/* return E_OS_LIMIT */
				/* \req OSEK_SYS_3.1.5-2/3 If other than E_OK is returned the activation
				 * is ignored */
				/* \req OSEK_SYS_3.1.7-2/3 Possible return values in Standard mode are
				 * E_OK or E_OS_LIMIT */
				ret = E_OS_LIMIT;
			}
			else
			{
				/* check if more activations are allowed */
				if ( TasksVar[TaskID].Activations < TasksConst[TaskID].MaxActivations )
				{
					/* increment activation counter */
					TasksVar[TaskID].Activations++;
					/* add the task to the ready list */
					AddReady(TaskID);
				}
				else
				{
					/* maximal activation reached, return E_OS_LIMIT */
					/* \req OSEK_SYS_3.1.5-3/3 If other than E_OK is returned the
					 * activation is ignored */
					/* \req OSEK_SYS_3.1.7-3/3 Possible return values in Standard mode are
					 * E_OK or E_OS_LIMIT */
					ret = E_OS_LIMIT;
				}
			}
		}

		IntSecure_End();
#if (NON_PREEMPTIVE == DISABLE)

		if ( ( TasksConst[GetRunningTask()].ConstFlags.Preemtive ) &&
			  ( ret == E_OK )	)
		{
			/* \req OSEK_SYS_3.1.4 Rescheduling shall take place only if called from a
			 * preemptable task. */
			(void)Schedule();
		}

#endif /* #if (NON_PREEMPTIVE == DISABLE) */
	}

	return ret;
}

/*******************************************************************************
**                                                                            **
** FUNC-NAME     :                                                            **
**                                                                            **
** DESCRIPTION   :                                                            **
**                                                                            **
** PRECONDITIONS :                                                            **
**                                                                            **
** PARAMETER     :                                                            **
**                                                                            **
** RETURN        :                                                            **
**                                                                            **
** REMARKS       :                                                            **
**                                                                            **
*******************************************************************************/
TaskType GetNextTask(void)
{
	BYTE loopi;
	boolean found = FALSE;
	TaskType ret = INVALID_TASK;

	/* check in all ready lists */
	for (loopi = 0; ( loopi < TASKS_COUNT ) && (!found) ; loopi++)
	{
		/* if one or more tasks are ready */
		if (ReadyVar[loopi].ListCount > 0)
		{
			/* return the first ready task */
			ret = ReadyConst[loopi].TaskRef[ReadyVar[loopi].ListStart];

			/* set found true */
			found = TRUE;
		}
	}

	return ret;
}
/*******************************************************************************
**                                                                            **
** FUNC-NAME     :                                                            **
**                                                                            **
** DESCRIPTION   :                                                            **
**                                                                            **
** PRECONDITIONS :                                                            **
**                                                                            **
** PARAMETER     :                                                            **
**                                                                            **
** RETURN        :                                                            **
**                                                                            **
** REMARKS       :                                                            **
**                                                                            **
*******************************************************************************/
void RemoveTask(TaskType TaskID)
{
	TaskPriorityType priority;
	TaskTotalType maxtasks;

	/* get task priority */
	priority = TasksConst[TaskID].StaticPriority;
	/* conver the priority to the array index */
	/* do not remove the -1 is needed. for example if READYLIST_COUNT is 4
	* the valida entries for this array are between 0 and 3, so the -1 is needed
	* since the lower priority is 0.
	*/
	priority = (TASKS_COUNT-1)-priority;
	/* get max number of entries */
	maxtasks = ReadyConst[priority].ListLength;

	/* increment the ListStart */
	ReadyVar[priority].ListStart = ReadyVar[priority].ListStart + 1;

	/* go arround maxtasks */
	/* this if works like a % instruction */
	if (ReadyVar[priority].ListStart >= maxtasks)
	{
		ReadyVar[priority].ListStart -= maxtasks;
	}

	/* decrement the count of ready tasks */
	ReadyVar[priority].ListCount--;
}

/*******************************************************************************
**                                                                            **
** FUNC-NAME     :                                                            **
**                                                                            **
** DESCRIPTION   :                                                            **
**                                                                            **
** PRECONDITIONS :                                                            **
**                                                                            **
** PARAMETER     :                                                            **
**                                                                            **
** RETURN        :                                                            **
**                                                                            **
** REMARKS       :                                                            **
**                                                                            **
*******************************************************************************/
StatusType TerminateTask(void)
{
	/* \req OSEK_SYS_3.2 The system service StatusType TerminateTask ( void )
	 ** shall be defined. */

	StatusType ret = E_OK;

	/* \req OSEK_SYS_3.2.4 If the version with extended status is used, the
	 ** service returns in case of error, and provides a status which can be
	 ** evaluated in the application. */
#if (ERROR_CHECKING_TYPE == ERROR_CHECKING_EXTENDED)
	if ( GetCallingContext() != CONTEXT_TASK )
	{
		/* \req OSEK_SYS_3.2.7-1/2 Possibly return values in Extended mode are
		 ** E_OS_RESOURCE or E_OS_CALLEVEL */
		ret = E_OS_CALLEVEL;
	}

#if ( (RESOURCES_COUNT != 0) || (NO_RES_SCHEDULER == DISABLE) )
	/* check if on or more resources are ocupied */
	else if (
#if (RESOURCES_COUNT != 0)
				 ( TasksVar[GetRunningTask()].Resources != 0 )
#endif /* #if (RESOURCES_COUNT != 0) */
#if ( (RESOURCES_COUNT != 0) && (NO_RES_SCHEDULER == DISABLE) )
					||
#endif /* #if ( (RESOURCES_COUNT != 0) && (NO_RES_SCHEDULER == DISABLE) ) */
#if (NO_RES_SCHEDULER == DISABLE)
				 ( TasksVar[GetRunningTask()].ActualPriority == TASK_MAX_PRIORITY )
#endif /* #if (NO_RES_SCHEDULER == DISABLE) */
			  )
	{
		/* \req OSEK_SYS_3.2.7-2/2 Possibly return values in Extended mode are
		 ** E_OS_RESOURCE or E_OS_CALLEVEL */
		ret = E_OS_RESOURCE;
	}
#endif /* #if ( (RESOURCES_COUNT != 0) || (NO_RES_SCHEDULER == DISABLE) ) */
	else
#endif /* #if (ERROR_CHECKING_TYPE == ERROR_CHECKING_EXTENDED) */
	{

#if (HOOK_POSTTASKHOOK == ENABLE)
		PostTaskHook();
#endif /* #if (HOOK_POSTTASKHOOK == ENABLE) */

		IntSecure_Start();

		/* release internal resources */
		/* \req OSEK_SYS_3.2.2 If an internal resource is assigned to the calling
		 ** task, it is automatically released. */
		ReleaseInternalResources();

		/* There is a bug here - Activations become -1 Krisitan TODO:*/
		if (TasksVar[GetRunningTask()].Activations > 0)
			/* decrement activations for this task */
		{
			TasksVar[GetRunningTask()].Activations--;
		}
		//else
		//{while(1);}
		if (TasksVar[GetRunningTask()].Activations == 0)
		{
			/* if no more activations set state to suspended */
			/* \req OSEK_SYS_3.2.1 The calling task shall be transferred from the
			 ** running state into the suspended state. */
			TasksVar[GetRunningTask()].Flags.State = SUSPENDED;
			/* remove ready list */
			RemoveTask(GetRunningTask());
		}
		else
		{
			/* if more activations set state to ready */
			TasksVar[GetRunningTask()].Flags.State = READY;
		}

		/* set entry point for this task again */
		/* \req OSEK_SYS_3.1.2-3/3 The operating system shall ensure that the task
		 ** code is being executed from the first statement. */
		//SetEntryPoint(GetRunningTask()); //Kristian

		/* set running task to invalid */
		SetRunningTask(INVALID_TASK);
		/* set actual context SYS */
		SetActualContext(CONTEXT_SYS);

		IntSecure_End();

		/* call scheduler, never returns */
		/* \req OSEK_SYS_3.2.3 If the call was successful, TerminateTask does not
		 ** return to the call level and the status can not be evaluated. */
		/* \req OSEK_SYS_3.2.5 If the service TerminateTask is called
		 ** successfully, it enforces a rescheduling. */
		/* \req OSEK_SYS_3.2.6 This function will never returns in Standard
		 ** mode. */
		(void)Schedule();
	}

#if (HOOK_ERRORHOOK == ENABLE)
	/* \req OSEK_ERR_1.3-2/xx The ErrorHook hook routine shall be called if a
	 ** system service returns a StatusType value not equal to E_OK.*/
	/* \req OSEK_ERR_1.3.1-2/xx The hook routine ErrorHook is not called if a
	 ** system service is called from the ErrorHook itself. */
//	if ( ( ret != E_OK ) && (ErrorHookRunning != 1))
//	{
//		SetError_Api(OSServiceId_TerminateTask);
//		SetError_Ret(ret);
//		SetError_Msg("Terminate Task returns != than E_OK");
//		SetError_ErrorHook();
//	}
#endif

	return ret;
}
/*******************************************************************************
**                                                                            **
** FUNC-NAME     :                                                            **
**                                                                            **
** DESCRIPTION   :                                                            **
**                                                                            **
** PRECONDITIONS :                                                            **
**                                                                            **
** PARAMETER     :                                                            **
**                                                                            **
** RETURN        :                                                            **
**                                                                            **
** REMARKS       :                                                            **
**                                                                            **
*******************************************************************************/
StatusType GetTaskState
(
	TaskType TaskID,
	TaskStateRefType State
)
{
	/* \req OSEK_SYS_3.6 The system service StatusType
	 ** GetTaskState ( TaskType TaskID, TaskStateRefType State ) shall be
	 ** defined. */

	/* \req OSEK_SYS_3.6.3Possible return values in Standard mode is E_OK */
	StatusType ret = E_OK;

#if (ERROR_CHECKING_TYPE == ERROR_CHECKING_EXTENDED)
	/* check if TaskID is in a valid range */
	if ( TaskID >= TASKS_COUNT )
	{
		/* TaskID is out of range */
		/* return E_OS_ID */
		/* \req OSEK_SYS_3.6.4 Extra possible return values in Extended mode is
		 ** E_OS_ID */
		ret = E_OS_ID;

		/* set invalid task value to the state */
		*State = INVALID_STATE;
	}
	else
#endif
	{

		/* \req OSEK_SYS_3.6.1 The service shall returns the state of a task
		 ** (running, ready, waiting, suspended) at the time of calling
		 ** GetTaskState */
		/* \req OSEK_SYS_3.6.2 When the service is called for a task, which is
		 ** activated more than once, the state is set to running if any instance
		 ** of the task is running. */
		*State = (TaskStateType) TasksVar[TaskID].Flags.State;
	}

#if ( (ERROR_CHECKING_TYPE == ERROR_CHECKING_EXTENDED) && \
		(HOOK_ERRORHOOK == ENABLE) )
	/* \req OSEK_ERR_1.3-5/xx The ErrorHook hook routine shall be called if a
	 ** system service returns a StatusType value not equal to E_OK.*/
	/* \req OSEK_ERR_1.3.1-5/xx The hook routine ErrorHook is not called if a
	 ** system service is called from the ErrorHook itself. */
   if ( ( ret != E_OK ) && (ErrorHookRunning != 1))
	{
		SetError_Api(OSServiceId_GetTaskState);
		SetError_Param1(TaskID);
		SetError_Param2((unsigned int)State);
		SetError_Ret(ret);
		SetError_Msg("GetTaskState returns != than E_OK");
		SetError_ErrorHook();
	}
#endif

	return ret;
}
/*******************************************************************************
**                                                                            **
** FUNC-NAME     :                                                            **
**                                                                            **
** DESCRIPTION   :                                                            **
**                                                                            **
** PRECONDITIONS :                                                            **
**                                                                            **
** PARAMETER     :                                                            **
**                                                                            **
** RETURN        :                                                            **
**                                                                            **
** REMARKS       :                                                            **
**                                                                            **
*******************************************************************************/
StatusType GetTaskID
(
	TaskRefType TaskID
)
{
	/* \req OSEK_SYS_3.5 The system service StatusType
	 ** GetTaskID ( TaskRefType TaskID ) shall be defined */

	/* \req OSEK_SYS_3.5.1 Shall returns the information about the TaskID of
	 ** the task which is currently running */
	/* \req OSEK_SYS_3.5.2 If no task is currently running, the service returns
	 ** INVALID_TASK as TaskType */
	*TaskID = GetRunningTask();

	/* \req OSEK_SYS_3.5.3 This function returns always E_OK */
	return E_OK;
}


text:
 Function UninstallOldApplication($Description) {
      #Declare Local Memory
      Set-Variable -Name AppName -Scope Local -Force
      Set-Variable -Name Arguments -Scope Local -Force
      Set-Variable -Name Code -Scope Local -Force
      Set-Variable -Name GUID -Scope Local -Force
      Set-Variable -Name Output -Scope Local -Force
      #Change '%application%' to whatever app you are calling
      $Description = [char]34+"description like"+[char]32+[char]39+[char]37+$Description+[char]37+[char]39+[char]34
      $Output = wmic product where $Description get IdentifyingNumber
      $Output1 = wmic product where $Description get Description
      $Output1 | ForEach-Object {
           $_ = $_.Trim()
        if(($_ -ne "Description")-and($_ -ne "")){
          $AppName = $_
        }
      }
      Write-Host "Uninstalling"$AppName"....." -NoNewline
      $Output | ForEach-Object {
           $_ = $_.Trim()
        if(($_ -ne "IdentifyingNumber")-and($_ -ne "")){
          $GUID = $_
        }
      }
      $Arguments = "/X"+[char]32+$GUID+[char]32+"/qb- /norestart"
      $Code = (Start-Process -FilePath "msiexec.exe" -ArgumentList $Arguments -Wait -Passthru).ExitCode
      If ($Code -eq 0) {
           Write-Host "Uninstalled" -ForegroundColor Yellow
      } else {
           Write-Host "Failed" -ForegroundColor Red
      }
      #Cleanup Local Memory
      Remove-Variable -Name AppName -Scope Local -Force
      Remove-Variable -Name Arguments -Scope Local -Force
      Remove-Variable -Name Code -Scope Local -Force
      Remove-Variable -Name GUID -Scope Local -Force
      Remove-Variable -Name Output -Scope Local -Force
      Remove-Variable -Name Output1 -Scope Local -Force
 }

redpajama_set_name: RedPajamaGithub


text:
package com.restfb.types;

import static org.junit.jupiter.api.Assertions.*;

import com.restfb.AbstractJsonMapperTests;
import com.restfb.types.webhook.Change;
import com.restfb.types.webhook.ChangeValue;
import com.restfb.types.webhook.PermissionChangeValue;
import com.restfb.types.webhook.WebhookObject;
import org.junit.jupiter.api.Test;

class WebhookPermissionTest extends AbstractJsonMapperTests {

  @Test
  void manageFundraisers() {
    WebhookObject webhookObject =
        createJsonMapper().toJavaObject(jsonFromClasspath("webhooks/permission-granted.wh-2"), WebhookObject.class);
    assertNotNull(webhookObject);
    assertEquals(1, webhookObject.getEntryList().size());
    assertEquals(1, webhookObject.getEntryList().get(0).getChanges().size());
    Change change = webhookObject.getEntryList().get(0).getChanges().get(0);
    assertTrue(change.getValue() instanceof PermissionChangeValue);
    PermissionChangeValue changeValue = (PermissionChangeValue) change.getValue();
    assertEquals(ChangeValue.Verb.GRANTED, changeValue.getVerb());
    assertEquals(2, changeValue.getTargetIds().size());
  }

  @Test
  void connected() {
    WebhookObject webhookObject =
        createJsonMapper().toJavaObject(jsonFromClasspath("webhooks/permission-granted.wh-1"), WebhookObject.class);
    assertNotNull(webhookObject);
    assertNotNull(webhookObject);
    assertEquals(1, webhookObject.getEntryList().size());
    assertEquals(1, webhookObject.getEntryList().get(0).getChanges().size());
    Change change = webhookObject.getEntryList().get(0).getChanges().get(0);
    assertTrue(change.getValue() instanceof PermissionChangeValue);
    PermissionChangeValue changeValue = (PermissionChangeValue) change.getValue();
    assertEquals(ChangeValue.Verb.GRANTED, changeValue.getVerb());
    assertEquals(0, changeValue.getTargetIds().size());
  }
}


text:
.row1{
	outline: none;
	margin: 0px 0 0px 0px;
	overflow: auto;
	padding-bottom: 15px;
	height: 162px;
}
.sky-form h4{
	font-size: 0.85em;
	font-weight: 600;
	padding: 10px 0;
	text-transform: uppercase;
	color: #026466;
}
section.sky-form{
	border-top:1px solid #eee;
	padding:1em 0;
}
.sky-form .input,
.sky-form .select,
.sky-form .textarea,
.sky-form .radio,
.sky-form .checkbox,
.sky-form .toggle,
.sky-form .button {
	position: relative;
	display: block;
}

/* radios and checkboxes */
.sky-form .radio,.sky-form .checkbox {
	outline: none;
	border: none;
	margin-bottom: 4px;
	padding-left: 27px;
	font-size: 14px;
	line-height: 30px;
	font-weight: 400;
	color: #555555;
	cursor: pointer;
	text-transform: capitalize;
	width: 100%;
	margin-top: 0;
	  font-family: 'Arimo', sans-serif;
}

.sky-form .radio:last-child,
.sky-form .checkbox:last-child {
	margin-bottom: 0;
}
.sky-form .radio input,
.sky-form .checkbox input {
	position: absolute;
	left: -9999px;
}
.sky-form .radio i,
.sky-form .checkbox i {
	position: absolute;
	top: 9px;
	left: 0;
	display: block;
	width: 13px;
	height: 13px;
	outline: none;
	border-width: 2px;
	border-style: solid;
	background: #fff;
}
.sky-form .radio i {
	border-radius: 50%;
}
.sky-form .radio input + i:after,
.sky-form .checkbox input + i:after {
	position: absolute;
	opacity: 0;
	transition: opacity 0.1s;
	-o-transition: opacity 0.1s;
	-ms-transition: opacity 0.1s;
	-moz-transition: opacity 0.1s;
	-webkit-transition: opacity 0.1s;
}

.sky-form .radio input:checked + i:after,
.sky-form .checkbox input:checked + i:after {
	opacity: 1;
}

.sky-form .inline-group .radio,
.sky-form .inline-group .checkbox {
	float: left;
	margin-right: 30px;
}
.sky-form .inline-group .radio:last-child,
.sky-form .inline-group .checkbox:last-child {
	margin-bottom: 4px;
}
.sky-form .checkbox input + i:after {
	content:'';
	top: -1px;
	left: -5px;
	width: 15px;
	height: 15px;
	background: url(../images/b-arrow.png);
	text-align: center;
}
.sky-form .checkbox input + i:after {
  color:#fff;
}
.sky-form .radio input:checked + i,
.sky-form .checkbox input:checked + i,
.sky-form .toggle input:checked + i {
	border-color:#888;
}
/*-- start scrollpane --*/
.jspContainer{
	overflow: hidden;
	position: relative;
}
.jspPane{
	position: absolute;
	outline: none;
}
.jspVerticalBar{
	position: absolute;
	top: 0;
	right:40px;
	width:3px;
	height: 100%;
}
.jspHorizontalBar{
	position: absolute;
	bottom: 0;
	left: 0;
	width: 100%;
	height: 16px;
	background: red;
}
.jspCap{
	display: none;
}
.jspHorizontalBar .jspCap{
	float: left;
}
.jspTrack{
	background: #f0f0f0;
	position: relative;
}
.jspDrag{
	background: #777777;
	position: relative;
	top: 0;
	left: 0;
	cursor: pointer;
}
.jspHorizontalBar .jspTrack,.jspHorizontalBar .jspDrag{
	float: left;
	height: 100%;
}
.jspArrow{
	background: #50506d;
	text-indent: -20000px;
	display: block;
	cursor: pointer;
	padding: 0;
	margin: 0;
}
.jspArrow.jspDisabled{
	cursor: default;
	background: #80808d;
}
.jspVerticalBar .jspArrow{
	height: 16px;
}
.jspHorizontalBar .jspArrow{
	width: 16px;
	float: left;
	height: 100%;
}
.jspVerticalBar .jspArrow:focus{
	outline: none;
}
.jspCorner{
	background: #eeeef4;
	float: left;
	height: 100%;
}
@media screen and (max-width:1024px){
	.sky-form h4 {
		font-size: 0.95em;
		padding: 8px;
	}
}
@media screen and (max-width:640px){
	.row1 {
		margin: 10px 0 0px 10px;
		padding-bottom: 5px;
		height: 160px;
	}
	.sky-form .radio, .sky-form .checkbox {
		font-size: 12px;
	}
}


text:
{-# LANGUAGE OverloadedStrings #-}

-- | This provides an enumerator interface over the aeson JSON library.

module Text.Bakers12.JSON.Enumerators
    ( toJSONE
    ) where

import           Control.Monad.Trans (lift)
import           Data.Aeson (ToJSON(..))
import           Data.Aeson.Encode (fromValue)
import           Data.Enumerator hiding (map)
import qualified Data.Enumerator.List as EL
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Builder as TLB

-- | This takes a stream of ToJSON objects and interprets them as an array.  To
-- do this, it breaks strict monad laws by outputting a '[' before starting to
-- process the stream and by outputting a ']' when the stream is done.
toJSONE :: (ToJSON a, Monad m) => Enumeratee a T.Text m b
toJSONE = loop 0
    where
        loop n cont@(Continue k) = do
            maybeItem <- EL.head

            -- Ugly, ugly, ugly. There's probably something monadic I can do to
            -- pretty it up.
            case maybeItem of
                Just item -> do
                    let chunks = Chunks [prefix n, jsonize item]
                    next <- lift $ runIteratee $ k $ chunks
                    loop (n + 1) next
                Nothing   ->
                    case (suffix n) of
                        Just close -> do
                            next <- lift $ runIteratee $ k $ Chunks [close]
                            loop 0 next
                        Nothing    -> return cont

        loop _ step = return step

        prefix :: Int -> T.Text
        prefix 0 = "["
        prefix _ = ","

        suffix :: Int -> Maybe T.Text
        suffix 0 = Nothing
        suffix _ = Just "]"

        jsonize = TL.toStrict . TLB.toLazyText . fromValue . toJSON


text:
* Proposal: [SDL-0178](0178-GetInteriorVehicleData.md)
* Author: [Zhimin Yang](https://github.com/smartdevicelink/yang1070)
* Status: **Accepted**
* Impacted Platforms: [Core / Web / RPC ]

## Introduction

This proposal is for improving the process of GetInteriorVehicleData RPC in SDL core. This proposal can reduce the number of messages between SDL and HMI, and improves the response time of GetInteriorVehicleData a lot. It accomplishes this by introducing a cache of the interior vehicle data and maintains SDL's subscription status of a module(Type).

## Motivation

The following sequence diagram shows the current behavior of SDL regarding GetInteriorVehicleData.

![../assets/proposals/0178-getInteriorVehicleData/GetInteriorVehicleData_current.png](../assets/proposals/0178-getInteriorVehicleData/GetInteriorVehicleData_current.png)

#### 1. SDL always forwards a valid GetInteriorVehicleData request from any app to HMI regardless of whether the parameter `subscribe` is included or not.
#### 2. SDL expects HMI to manage each app's subscription status (per moduleType) and maintains a local status to keep track of each application's subscription (per moduleType).
#### 3. SDL mainly works as a pass-through/forwarder with little intelligence
- If there is no subscribe parameter in GetInteriorVehicleData, SDL forwards the request to HMI.
- If parameter `subscribe=true` and the app has not subscribed to the module yet, SDL forwards the whole request to HMI.
- If parameter `subscribe=true` and the app has already subscribed to the module, SDL cuts off `subscribe=true` from the request and forwards it to HMI.
- If parameter `subscribe=false` and the app has not subscribed to the module yet, SDL cuts off  `subscribe=false` from the request and forwards it to HMI.
- If parameter `subscribe=false` and the app has already subscribed to the module, SDL forwards the whole request to HMI.

### Advantages:
- A simple SDL. Just forwarding the GetInteriorVehicleData requests and response between the app and the HMI.

### Shortcomings:
- The operation of GetInteriorVehicleData and subscribe InteriorVehicleData on HMI side may be a time consuming task.
- If app1 has already subscribed data change notification for a moduleType, SDL still needs to include parameter `subscribe=true` when forwarding requests from other apps, i.e. to re-subscribe the data again. There are extra messages and extra processing time.
- If app1 has not subscribed data change notification for a moduleType, SDL still needs to include parameter `subscribe=false` when forwarding requests from other apps, i.e. to unsubscribe the data per app. There are extra messages and extra processing time.
- If app1 has already subscribed data change notification for a moduleType, and HMI returns the data to SDL in response,  SDL still forwards new GetInteriorVehicleData requests (from same app or different app regarding same moduleType) to HMI. However, SDL has the module data already and can keep the data up to date since SDL will get OnInteriorVehicleData notifications whenever there is any data change in the same moduleType. There are extra messages and extra processing time.
- It is not very clean. SDL still maintains the local status and makes some filtering (cut off parameter `subscribe` in certain cases), why not always forward original message if we want to keep SDL simple.

## Proposed solution

The following sequence diagram shows the proposed behavior of SDL regarding GetInteriorVehicleData.

![../assets/proposals/0178-getInteriorVehicleData/GetInteriorVehicleData_new_subscribe.png](../assets/proposals/0178-getInteriorVehicleData/GetInteriorVehicleData_new_subscribe.png)

SDL maintains the module (Type) subscription status as a whole. SDL needs to subscribe to a module if there is at least one app that subscribes to the module. SDL needs to unsubscribe from a module if no apps subscribe to the module. Or equivalently
- SDL shall only include parameter `subscribe=true` if SDL has not (equivalently there is no app) subscribed to the module data when forwarding GetInteriorVehicleData with `subscribe=true`.
- SDL shall only include parameter `subscribe=false` if it is the last app to unsubscribe to the module data when forwarding GetInteriorVehicleData with `subscribe=false`.

SDL maintains a cache of module data only when there is at least one application subscribed to the module.
- SDL creates a cache for the module when it receives a successful GetInteriorVehicleData response with `isSubscribed=true`.
- SDL updates the cache (only the part that changes) when it receives an OnInteriorVehicleData notification.
- SDL removes the cache for the module when SDL receives a successful GetInteriorVehicleData response with `isSubscribed=false`.

SDL only forwards a GetInteriorVehicleData request to HMI if there is no cached data available for the requested module or it needs to unsubscribe to the module from HMI. Otherwise, SDL responds to the request with the cached data and there is no need to forward it and wait for a response from HMI.

In addition, when there is no cache available and before SDL forwards a GetInteriorVehicleData request to HMI, SDL shall apply a rate limitation scheme similar to that of the GetVehicleData request. SDL allows `x` number of GetVehicleData requests per second. The number `x` is 5 and it can be configured in smartDeviceLink.ini file. Similarly, SDL allows `y` number of GetInteriorVehicleData requests to forward to HMI. The number `y` shall be configurable in ini file. Since there are multiple moduleTypes defined for RC, ideally SDL shall apply rate limitation per moduleType. To simplify the implementation it can be regardless of moduleType. However, in this case, `y` shall be much greater than `x`.

```
; Limitation for a number of GetVehicleData requests (the 1st value) per (the 2nd value) seconds
GetVehicleDataRequest = 5, 1
+; Limitation for a number of GetInteriorVehicleDataRequest requests (the 1st value) per (the 2nd value) seconds
+GetInteriorVehicleDataRequest = 20, 1
```

## Potential downsides

- SDL core needs more memory for the data cache. In case there is something wrong with the HMI subsription, SDL will not get data updated. GetInteriorVehicleData will have aged data.
- It makes SDL smarter but also more complex.
- Ideally, the newly added function belongs to the integration with the vehicle data, and it shall be implemented in the vehicle/HMI side.

## Impact on existing code

- There is no change to the mobile API.
- Parameter `appID` is no longer needed in HMI API. This may cause a major version change of HMI spec.

```xml
<function name="GetInteriorVehicleData" messagetype="request">
  <param name="moduleType" type="Common.ModuleType" mandatory="true" >
    <description>The module data to retrieve from the vehicle for that type</description>
  </param>
  <param name="subscribe" type="Boolean" mandatory="false" defvalue="false">
    <description>If subscribe is true, the head unit will send onInteriorVehicleData notifications for the module type</description>
  </param>
-  <param name="appID" type="Integer" mandatory="true">
-    <description>Internal SDL-assigned ID of the related application</description>
-  </param>
</function>
```

- SDL core code needs update.

## Alternatives considered

None


text:
namespace policy {
namespace switches {

// Specifies the URL at which to fetch configuration policy from the device
// management backend.
const char kDeviceManagementUrl[]           = "device-management-url";

// Disables fetching and storing cloud policy for components.
const char kDisableComponentCloudPolicy[]   = "disable-component-cloud-policy";

// Disables the verification of policy signing keys.
// TODO(atwilson): Remove this once all test servers have been updated to
// produce verification signatures.
const char kDisablePolicyKeyVerification[]  = "disable-policy-key-verification";

#if defined(OS_ANDROID) || defined(OS_IOS)
// Registers for cloud policy using the BROWSER client type instead of the
// ANDROID_BROWSER or IOS_BROWSER types.
// This allows skipping the server whitelist.
// TODO(joaodasilva): remove this. http://crbug.com/248527
const char kFakeCloudPolicyType[]           = "fake-cloud-policy-type";
#endif  // defined(OS_ANDROID) || defined(OS_IOS)

}  // namespace switches
}  // namespace policy


text:
package org.apache.wiki.tags;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Sets or gets Cookie values. This implementation makes the following
 * assumptions:
 *

 *
The cookie contains any number of name-value pairs
 *
Name-value pairs are separated by "&" in the encoded cookie value string
 *
An encoded name-value pair is compatible with JavaScript's
 * encodeURIComponent(). Notably, spaces are encoded as "%20".
 *
A decoded name-value pair separates the name and value with a "="
 *

 *
 *
The value of a cookie carrying values n1="v1" and n2="v2 with space"
 * would thus be
 *

 *   n1%3Dv1&n2%3Dv2%20with%20space
 *

 *
 *
Usage:
 *
 *

 * <wiki:cookie name="cookiename" var="contextvariable" scope="page" />
 *

 * - Returns the value of the named cookie, or an empty string if not set.
 * If 'var' is specified, the value is set into a context variable of this name.
 * The 'scope' parameter may be added to specify the context: "session",
 * "page", "request". If var is omitted, the output is placed directly into
 * the JSP page.
 *
 *

 * <wiki:cookie name="cookiename" value="encoded_value" />
 *

 * - Sets the named cookie to the given value. If the value string is empty,
 * the cookie value is set to empty; otherwise the cookie encoding rules of
 * this class must be followed for the value.
 *
 *

 * <wiki:cookie name="cookiename" item="parameter_name" />
 *

 * - Assumes that the cookie contains URLEncoded name-value pairs,
 * with name and value separated by an equals sign, and returns the value
 * of the specified item.
 *
 * <wiki:cookie name="cookiename" item="parameter_name" value="value" />
 *

 * - Sets the value of 'parameter_name' in the named cookie to 'value'.
 *
 *

 * <wiki:cookie name="cookiename" clear="parameter_name" />
 *

 * - Removes the named parameter from the cookie.
 *
 *

 * <wiki:cookie clear="cookiename" />
 *

 * - Removes the named cookie. Clear may be used at the same time as a value
 * is retrieved (or set, despite the dubious usefulness of that operation).
 */
public class CookieTag
    extends TagSupport
{
    private static final long serialVersionUID = 0L;

    private static final Logger LOG = LogManager.getLogger( CookieTag.class );

    /** Name of the cookie value. Required. */
    private String m_name;
    /** Name of the cookie nvp item. Optional. */
    private String m_item;
    /** A value to echo or set. Optional. */
    private String m_value;
    /** Name of a context variable to set result in. Optional, defaults to out.*/
    private String m_var;
    /** Scope of m_var: request, session, page. */
    private String m_scope;
    /** Name of a cookie or a cookie nvp to clear. */
    private String m_clear;

    /**
     *  Set the "name" parameter.
     *
     *  @param s The name.
     */
    public void setName(final String s )
    {
        m_name = s;
    }

    /**
     *  Set the "item" parameter.
     *
     *  @param s The item.
     */
    public void setItem(final String s )
    {
        m_item = s;
    }

    /**
     *  Set the "value" parameter.
     *
     *  @param s The value.
     */
    public void setValue(final String s )
    {
        m_value = s;
    }

    /**
     *  Set the "var" parameter.
     *
     *  @param s The parameter.
     */
    public void setVar(final String s )
    {
        m_scope = s;
    }

    /**
     *  Set the "clear" parameter.
     *
     *  @param s The parameter.
     */
    public void setClear(final String s )
    {
        m_clear = s;
    }

    /**
     *  Set the "scope" parameter.
     *
     *  @param s The scope.
     */
    public void setScope(final String s )
    {
        m_scope = s;
    }

    /**
     *  {@inheritDoc}
     */
    @Override
    public void release()
    {
        m_name = m_item = m_var = m_value = m_clear = m_scope = null;
        super.release();
    }

    /**
     * Examines the parameter and returns the corresponding scope identifier:
     * "request" maps to PageContext.REQUEST_SCOPE, and so on.
     * Possible values are "page", "session", "application", and "request",
     * which is the default return value.
     */
    private int getScope(final String s )
    {
        if( s == null )
        {
            return PageContext.REQUEST_SCOPE;
        }
        if( "page".equals( m_scope ) )
        {
            return PageContext.PAGE_SCOPE;
        }
        if( "session".equals( m_scope ) )
        {
            return PageContext.SESSION_SCOPE;
        }
        if( "application".equals( m_scope ) )
        {
            return PageContext.APPLICATION_SCOPE;
        }

        return PageContext.REQUEST_SCOPE;
    }

    /**
     *  {@inheritDoc}
     */
    @Override
    public int doEndTag()
    {
        String out = null;
        final Cookie cookie = findCookie( m_name );
        boolean changed = false;

        if( m_value != null )
        {
            if( m_item != null )
            {
                setItemValue( cookie, m_item, m_value );
            }
            else
            {
                cookie.setValue( m_value );
            }
            changed = true;
        }
        else
        {
            if( m_item != null )
            {
                out = getItemValue( cookie, m_item );
            }
            else
            {
                out = cookie.getValue();
            }
        }

        if( out != null )
        {
            if( m_var != null )
            {
                final int scope = getScope( m_scope );
                pageContext.setAttribute( m_var, out,  scope );
            }
            else
            {
                try
                {
                    pageContext.getOut().print( out );
                }
                catch( final IOException ioe )
                {
                    LOG.warn( "Failed to write to JSP page: " + ioe.getMessage(), ioe );
                }
            }
        }

        Cookie cleared = null;
        if( m_clear != null )
        {
            cleared = findCookie( m_clear );
            if( m_item != null )
            {
                setItemValue( cookie, m_item, null );
            }
            else
            {
                cleared.setValue( null );
            }
        }

        final HttpServletResponse res = (HttpServletResponse)pageContext.getResponse();
        if( changed )
        {
            res.addCookie( cookie );
        }
        if( cleared != null )
        {
            res.addCookie( cleared );
        }

        return EVAL_PAGE;
    }

    /**
     * Sets a single name-value pair in the given cookie.
     */
    private void setItemValue(final Cookie c, final String item, final String value )
    {
        if( c == null )
        {
            return;
        }
        final String in = c.getValue();
        final Map<String, String> values = parseCookieValues( in );
        values.put( item, value );
        final String cv = encodeValues( values );
        c.setValue( cv );
    }

    /**
     * Returns the value of the given item in the cookie.
     */
    private String getItemValue(final Cookie c, final String item )
    {
        if( c == null || item == null ) {
            return null;
        }
        final String in = c.getValue();
        final Map< String, String > values = parseCookieValues( in );
        return values.get( item );
    }

    /**
     * Parses a cookie value, of format name1%3Fvalue1&name2%3Fvalue2...,
     * into a Map<String,String>.
     */
    private Map<String, String> parseCookieValues(final String s )
    {
        final Map< String, String > rval = new HashMap<>();
        if( s == null ) {
            return rval;
        }
        final String[] nvps = s.split( "&" );
        if( nvps.length == 0 ) {
            return rval;
        }
        for (final String value : nvps) {
            final String nvp = decode(value);
            final String[] nv = nvp.split("=");
            if (nv[0] != null && !nv[0].trim().isEmpty()) {
                rval.put(nv[0], nv[1]);
            }
        }

        return rval;
    }

    /**
     * Encodes name-value pairs in the map into a single string, in a format
     * understood by this class and JavaScript decodeURIComponent().
     */
    private String encodeValues(final Map<String, String> values )
    {
        final StringBuilder rval = new StringBuilder();
        if( values == null || values.size() == 0 ) {
            return rval.toString();
        }

        final Iterator< Map.Entry< String, String > > it = values.entrySet().iterator();
        while( it.hasNext() ) {
            final Map.Entry< String, String > e = it.next();
            final String n = e.getKey();
            final String v = e.getValue();
            if( v != null ) {
                final String nv = n + "=" + v;
                rval.append( encode( nv ) );
            }
        }

        return rval.toString();
    }

    /**
     * Converts a String to an encoding understood by JavaScript
     * decodeURIComponent.
     */
    private String encode(final String nvp )
    {
        String coded = "";
        try
        {
            coded = URLEncoder.encode( nvp, StandardCharsets.UTF_8.name() );
        }
        catch( final UnsupportedEncodingException e )
        {
            /* never happens */
            LOG.info( "Failed to encode UTF-8", e );
        }
        return coded.replaceAll( "\\+", "%20" );
    }

    /**
     * Converts a cookie value (set by this class, or by a JavaScript
     * encodeURIComponent call) into a plain string.
     */
    private String decode(final String envp )
    {
        final String rval;
        try
        {
            rval = URLDecoder.decode( envp , StandardCharsets.UTF_8.name() );
            return rval;
        }
        catch( final UnsupportedEncodingException e )
        {
            LOG.error( "Failed to decode cookie", e );
            return envp;
        }
    }

    /**
     * Locates the named cookie in the request, or creates a new one if it
     * doesn't exist.
     */
    private Cookie findCookie(final String cname )
    {
        final HttpServletRequest req = (HttpServletRequest)pageContext.getRequest();
        if( req != null )
        {
            final Cookie[] cookies = req.getCookies();
            if( cookies != null )
            {
                for (final Cookie cookie : cookies) {
                    if (cookie.getName().equals(cname)) {
                        return cookie;
                    }
                }
            }
        }

        return new Cookie( cname, null );
    }

}


text:
package org.apereo.cas.support.oauth.validator.token;

import org.apereo.cas.AbstractOAuth20Tests;
import org.apereo.cas.authentication.principal.PrincipalFactoryUtils;
import org.apereo.cas.authentication.principal.WebApplicationServiceFactory;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.mock.MockTicketGrantingTicket;
import org.apereo.cas.services.RegisteredServiceAccessStrategyAuditableEnforcer;
import org.apereo.cas.services.RegisteredServiceTestUtils;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.support.oauth.OAuth20Constants;
import org.apereo.cas.support.oauth.OAuth20GrantTypes;
import org.apereo.cas.support.oauth.OAuth20ResponseTypes;
import org.apereo.cas.support.oauth.authenticator.Authenticators;
import org.apereo.cas.support.oauth.authenticator.OAuth20DefaultCasAuthenticationBuilder;
import org.apereo.cas.support.oauth.profile.DefaultOAuth20ProfileScopeToAttributesFilter;
import org.apereo.cas.support.oauth.services.OAuthRegisteredService;
import org.apereo.cas.support.oauth.web.endpoints.OAuth20ConfigurationContext;
import org.apereo.cas.ticket.ExpirationPolicy;
import org.apereo.cas.ticket.ExpirationPolicyBuilder;
import org.apereo.cas.ticket.code.OAuth20Code;
import org.apereo.cas.ticket.code.OAuth20CodeExpirationPolicy;
import org.apereo.cas.ticket.code.OAuth20DefaultOAuthCodeFactory;
import org.apereo.cas.util.CollectionUtils;

import lombok.val;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.pac4j.core.context.JEEContext;
import org.pac4j.core.context.session.JEESessionStore;
import org.pac4j.core.profile.CommonProfile;
import org.pac4j.core.util.Pac4jConstants;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

import java.util.HashMap;
import java.util.HashSet;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

/**
 * This is {@link OAuth20AuthorizationCodeGrantTypeTokenRequestValidatorTests}.
 *
 * @author Misagh Moayyed
 * @since 6.0.0
 */
@Tag("OAuth")
public class OAuth20AuthorizationCodeGrantTypeTokenRequestValidatorTests extends AbstractOAuth20Tests {
    private OAuth20Code supportingServiceTicket;

    private OAuth20Code nonSupportingServiceTicket;

    private OAuth20Code promiscuousServiceTicket;

    private OAuth20TokenRequestValidator validator;

    @BeforeEach
    public void before() {
        val supportingService = RequestValidatorTestUtils.getService(
            RegisteredServiceTestUtils.CONST_TEST_URL,
            RequestValidatorTestUtils.SUPPORTING_CLIENT_ID,
            RequestValidatorTestUtils.SUPPORTING_CLIENT_ID,
            RequestValidatorTestUtils.SHARED_SECRET,
            CollectionUtils.wrapSet(OAuth20GrantTypes.AUTHORIZATION_CODE));
        val nonSupportingService = RequestValidatorTestUtils.getService(
            RegisteredServiceTestUtils.CONST_TEST_URL2,
            RequestValidatorTestUtils.NON_SUPPORTING_CLIENT_ID,
            RequestValidatorTestUtils.NON_SUPPORTING_CLIENT_ID,
            RequestValidatorTestUtils.SHARED_SECRET,
            CollectionUtils.wrapSet(OAuth20GrantTypes.PASSWORD));
        val promiscuousService = RequestValidatorTestUtils.getPromiscuousService(
            RegisteredServiceTestUtils.CONST_TEST_URL3,
            RequestValidatorTestUtils.PROMISCUOUS_CLIENT_ID,
            RequestValidatorTestUtils.PROMISCUOUS_CLIENT_ID,
            RequestValidatorTestUtils.SHARED_SECRET);

        this.supportingServiceTicket = registerTicket(supportingService);
        this.nonSupportingServiceTicket = registerTicket(nonSupportingService);
        this.promiscuousServiceTicket = registerTicket(promiscuousService);

        this.servicesManager.deleteAll();
        this.servicesManager.save(supportingService, nonSupportingService, promiscuousService);

        val context = OAuth20ConfigurationContext.builder()
            .servicesManager(this.servicesManager)
            .sessionStore(JEESessionStore.INSTANCE)
            .ticketRegistry(this.ticketRegistry)
            .webApplicationServiceServiceFactory(serviceFactory)
            .registeredServiceAccessStrategyEnforcer(new RegisteredServiceAccessStrategyAuditableEnforcer())
            .build();
        this.validator = new OAuth20AuthorizationCodeGrantTypeTokenRequestValidator(context);
    }

    @Test
    public void verifyBadToken() {
        val request = new MockHttpServletRequest();
        val response = new MockHttpServletResponse();
        val profile = new CommonProfile();
        profile.setClientName(Authenticators.CAS_OAUTH_CLIENT_BASIC_AUTHN);
        profile.setId(RequestValidatorTestUtils.SUPPORTING_CLIENT_ID);
        val session = request.getSession(true);
        assertNotNull(session);
        session.setAttribute(Pac4jConstants.USER_PROFILES,
            CollectionUtils.wrapLinkedHashMap(profile.getClientName(), profile));
        request.setParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.AUTHORIZATION_CODE.getType());
        request.setParameter(OAuth20Constants.REDIRECT_URI, RegisteredServiceTestUtils.CONST_TEST_URL);

        request.setParameter(OAuth20Constants.CODE, "UnknownToken");
        assertFalse(this.validator.validate(new JEEContext(request, response)));
    }

    @Test
    public void verifyBadService() {
        val request = new MockHttpServletRequest();
        val response = new MockHttpServletResponse();
        val profile = new CommonProfile();
        profile.setClientName(Authenticators.CAS_OAUTH_CLIENT_BASIC_AUTHN);
        profile.setId(RequestValidatorTestUtils.SUPPORTING_CLIENT_ID);
        val session = request.getSession(true);
        assertNotNull(session);
        session.setAttribute(Pac4jConstants.USER_PROFILES,
            CollectionUtils.wrapLinkedHashMap(profile.getClientName(), profile));
        request.setParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.AUTHORIZATION_CODE.getType());
        request.setParameter(OAuth20Constants.REDIRECT_URI, RegisteredServiceTestUtils.CONST_TEST_URL);

        request.setParameter(OAuth20Constants.CODE, nonSupportingServiceTicket.getId());
        assertFalse(this.validator.validate(new JEEContext(request, response)));
    }

    @Test
    public void verifyBadRequest() {
        val request = new MockHttpServletRequest();
        val response = new MockHttpServletResponse();
        val profile = new CommonProfile();
        profile.setClientName(Authenticators.CAS_OAUTH_CLIENT_BASIC_AUTHN);
        profile.setId(RequestValidatorTestUtils.SUPPORTING_CLIENT_ID);
        val session = request.getSession(true);
        assertNotNull(session);
        session.setAttribute(Pac4jConstants.USER_PROFILES,
            CollectionUtils.wrapLinkedHashMap(profile.getClientName(), profile));
        request.setParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.AUTHORIZATION_CODE.getType());
        request.setParameter(OAuth20Constants.REDIRECT_URI, RegisteredServiceTestUtils.CONST_TEST_URL);
        assertFalse(this.validator.validate(new JEEContext(request, response)));
    }

    @Test
    public void verifyUnknownCodeRevokesPreviousAccessTokens() {
        val request = new MockHttpServletRequest();
        val response = new MockHttpServletResponse();
        val profile = new CommonProfile();
        profile.setClientName(Authenticators.CAS_OAUTH_CLIENT_BASIC_AUTHN);
        profile.setId(RequestValidatorTestUtils.SUPPORTING_CLIENT_ID);
        val session = request.getSession(true);
        assertNotNull(session);
        session.setAttribute(Pac4jConstants.USER_PROFILES,
            CollectionUtils.wrapLinkedHashMap(profile.getClientName(), profile));

        val principal = PrincipalFactoryUtils.newPrincipalFactory().createPrincipal("casuser");
        val at = addAccessToken(principal, addRegisteredService());

        val code = ticketRegistry.getTicket(at.getToken(), OAuth20Code.class);
        assertNotNull(code);
        code.markTicketExpired();

        request.setParameter(OAuth20Constants.CODE, code.getId());
        profile.setId(RequestValidatorTestUtils.PROMISCUOUS_CLIENT_ID);
        request.setParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.AUTHORIZATION_CODE.getType());
        request.setParameter(OAuth20Constants.REDIRECT_URI, RegisteredServiceTestUtils.CONST_TEST_URL3);
        session.setAttribute(Pac4jConstants.USER_PROFILES,
            CollectionUtils.wrapLinkedHashMap(profile.getClientName(), profile));
        assertFalse(this.validator.validate(new JEEContext(request, response)));
        assertNull(ticketRegistry.getTicket(at.getToken()));
    }

    @Test
    public void verifyOperation() {
        val request = new MockHttpServletRequest();
        val response = new MockHttpServletResponse();
        val profile = new CommonProfile();
        profile.setClientName(Authenticators.CAS_OAUTH_CLIENT_BASIC_AUTHN);
        profile.setId(RequestValidatorTestUtils.SUPPORTING_CLIENT_ID);
        val session = request.getSession(true);
        assertNotNull(session);
        session.setAttribute(Pac4jConstants.USER_PROFILES,
            CollectionUtils.wrapLinkedHashMap(profile.getClientName(), profile));

        request.setParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.AUTHORIZATION_CODE.getType());
        request.setParameter(OAuth20Constants.REDIRECT_URI, RegisteredServiceTestUtils.CONST_TEST_URL);

        request.setParameter(OAuth20Constants.CODE, supportingServiceTicket.getId());
        assertTrue(this.validator.validate(new JEEContext(request, response)));

        request.setParameter(OAuth20Constants.GRANT_TYPE, "unsupported");
        assertFalse(this.validator.validate(new JEEContext(request, response)));

        request.setParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.PASSWORD.getType());
        assertFalse(this.validator.validate(new JEEContext(request, response)));
        request.setParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.AUTHORIZATION_CODE.getType());

        request.setParameter(OAuth20Constants.CODE, nonSupportingServiceTicket.getId());
        request.setParameter(OAuth20Constants.REDIRECT_URI, RegisteredServiceTestUtils.CONST_TEST_URL2);
        profile.setId(RequestValidatorTestUtils.NON_SUPPORTING_CLIENT_ID);
        session.setAttribute(Pac4jConstants.USER_PROFILES,
            CollectionUtils.wrapLinkedHashMap(profile.getClientName(), profile));
        assertFalse(this.validator.validate(new JEEContext(request, response)));

        request.setParameter(OAuth20Constants.CODE, promiscuousServiceTicket.getId());
        profile.setId(RequestValidatorTestUtils.PROMISCUOUS_CLIENT_ID);
        request.setParameter(OAuth20Constants.REDIRECT_URI, RegisteredServiceTestUtils.CONST_TEST_URL3);
        session.setAttribute(Pac4jConstants.USER_PROFILES,
            CollectionUtils.wrapLinkedHashMap(profile.getClientName(), profile));
        assertTrue(this.validator.validate(new JEEContext(request, response)));
    }

    private OAuth20Code registerTicket(final OAuthRegisteredService service) {
        val builder = new OAuth20DefaultCasAuthenticationBuilder(
            PrincipalFactoryUtils.newPrincipalFactory(),
            new WebApplicationServiceFactory(),
            new DefaultOAuth20ProfileScopeToAttributesFilter(),
            new CasConfigurationProperties());
        val oauthCasAuthenticationBuilderService = builder.buildService(service, null, false);
        val expirationPolicy = new ExpirationPolicyBuilder() {
            private static final long serialVersionUID = 3911344031977989503L;

            @Override
            public ExpirationPolicy buildTicketExpirationPolicy() {
                return new OAuth20CodeExpirationPolicy(1, 60);
            }

            @Override
            public Class getTicketType() {
                return OAuth20Code.class;
            }
        };

        val oauthCode = new OAuth20DefaultOAuthCodeFactory(expirationPolicy, mock(ServicesManager.class))
            .create(oauthCasAuthenticationBuilderService, RegisteredServiceTestUtils.getAuthentication(),
                new MockTicketGrantingTicket("casuser"), new HashSet<>(),
                null, null, "clientid12345",
                new HashMap<>(), OAuth20ResponseTypes.CODE, OAuth20GrantTypes.AUTHORIZATION_CODE);
        this.ticketRegistry.addTicket(oauthCode);
        return oauthCode;
    }
}


text:
package com.wlangiewicz

import java.io.File
import org.bitcoinj.kits.WalletAppKit
import org.bitcoinj.params.MainNetParams
import org.bitcoinj.wallet.DeterministicSeed

/**
 * The following example shows you how to restore a HD wallet from a previously generated deterministic seed.
 * It uses WalletAppKit which provides a restoreWalletFromSeed function to load a wallet from a deterministic seed.
 * Usage:
 *    sbt "run-main com.wlangiewicz.RestoreFromSeedWalletAppKit"
 *
 */
object RestoreFromSeedWalletAppKit extends App {
  override def main(args: Array[String]): Unit = {
    val params = MainNetParams.get
    val dir = new File(".")
    val filePrefix = "restored"
    val walletAppkit: WalletAppKit = new WalletAppKit(params, dir, filePrefix)

    val seedCode = args mkString(" ")
    val passphrase = ""
    val creationTime = System.currentTimeMillis()

    val seed = new DeterministicSeed(seedCode, null, passphrase, creationTime)

    walletAppkit.restoreWalletFromSeed(seed)
  }
}


text:
/**
 * Stuff the wrong type object into an array.
 */
public class Main {
    public static void main(String args[]) {
        String[] strArray = new String[1];

        Object[] objArray = strArray;

        try {
            objArray[0] = new Integer(1);
            System.out.println("Array store succeeded?!");
        } catch (ArrayStoreException ase) {
            System.out.println("Got correct array store exception");
        }
    }
}


text:
import babel from 'rollup-plugin-babel'
import filesize from 'rollup-plugin-filesize'
import uglify from 'rollup-plugin-uglify'

export default {
  entry: 'src/index.js',
  format: 'cjs',
  plugins: [
    babel({
      exclude: 'node_modules/**'
    }),
    uglify(),
    filesize()
  ],
  dest: 'dist/sww.min.js',
  sourceMap: true
}


text:
module WeeklyhoursHelper
end


text:
package com.xiaoshangxing.data.bean;

import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;

/**
 * Created by FengChaoQun
 * on 2016/10/27
 * 聊天背景
 */

public class BackGround extends RealmObject {
    public static final String DEFAULT = "0";
    @PrimaryKey
    private String id;
    private String selfId;
    private String objectId;
    private String imgae;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getSelfId() {
        return selfId;
    }

    public void setSelfId(String selfId) {
        this.selfId = selfId;
    }

    public String getObjectId() {
        return objectId;
    }

    public void setObjectId(String objectId) {
        this.objectId = objectId;
    }

    public String getImgae() {
        return imgae;
    }

    public void setImgae(String imgae) {
        this.imgae = imgae;
    }

    @Override
    public String toString() {
        return "BackGround{" +
                "id='" + id + '\'' +
                ", selfId='" + selfId + '\'' +
                ", objectId='" + objectId + '\'' +
                ", imgae='" + imgae + '\'' +
                '}';
    }
}


text:
<?php
require '../Include/Config.php';
require '../Include/Functions.php';

// This file is generated by Composer
require_once dirname(__FILE__).'/../vendor/autoload.php';

use ChurchCRM\dto\SystemConfig;
use ChurchCRM\Slim\Middleware\AuthMiddleware;
use ChurchCRM\Slim\Middleware\VersionMiddleware;
use Slim\App;
use Slim\Container;

$container = new Container;
if (SystemConfig::debugEnabled()) {
    $container["settings"]['displayErrorDetails'] = true;
}

// Add middleware to the application
$app = new App($container);

$app->add(new VersionMiddleware());
$app->add(new AuthMiddleware());

// Set up
require __DIR__.'/../Include/slim/error-handler.php';

require __DIR__.'/routes/common/mvc-helper.php';

// admin routes
require __DIR__.'/routes/admin/admin.php';
require __DIR__.'/routes/user.php';

// people routes
require __DIR__.'/routes/root.php';

require __DIR__.'/routes/people.php';
require __DIR__.'/routes/family.php';
require __DIR__.'/routes/person.php';

require __DIR__.'/routes/email.php';
require __DIR__.'/routes/calendar.php';
require __DIR__.'/routes/cart.php';

require __DIR__.'/routes/user-current.php';

// Run app
$app->run();


text:
package com.google.javascript.jscomp;

import com.google.common.collect.ImmutableList;
import com.google.javascript.rhino.Node;
import com.google.protobuf.TextFormat;
import java.io.IOException;
import java.util.List;

/**
 * Tests for {@link InstrumentFunctions}
 *
 */
public final class InstrumentFunctionsTest extends CompilerTestCase {
  private String instrumentationPb;

  public InstrumentFunctionsTest() {
    this.instrumentationPb = null;
  }

  @Override
  protected void setUp() {
    this.instrumentationPb = null;
    validateAstChangeMarking(false);
  }

  @Override
  protected CompilerPass getProcessor(Compiler compiler) {
    return new NameAndInstrumentFunctions(compiler);
  }

  @Override
  protected int getNumRepetitions() {
    // This pass is not idempotent.
    return 1;
  }

  public void testInstrument() {
    final String kPreamble =
        "var $$toRemoveDefinition1, $$notToRemove;\n"
        + "var $$toRemoveDefinition2, $$toRemoveDefinition3;\n";

    // build instrumentation template and init code strings for use in
    // tests below.
    List<String> initCodeList = ImmutableList.of(
        "var $$Table = [];",
        "function $$TestDefine(id) {",
        "  $$Table[id] = 0;",
        "};",
        "function $$TestInstrument(id) {",
        "  $$Table[id]++;",
        "};");
    StringBuilder initCodeBuilder = new StringBuilder();
    StringBuilder pbBuilder = new StringBuilder();
    for (String line : initCodeList) {
      initCodeBuilder.append(line).append("\n");
      pbBuilder.append("init: \"").append(line).append("\"\n");
    }

    pbBuilder.append("report_call: \"$$testInstrument\"")
        .append("report_defined: \"$$testDefine\"")
        .append("declaration_to_remove: \"$$toRemoveDefinition1\"")
        .append("declaration_to_remove: \"$$toRemoveDefinition2\"")
        .append("declaration_to_remove: \"$$toRemoveDefinition3\"");

    final String initCode = initCodeBuilder.toString();
    this.instrumentationPb = pbBuilder.toString();

    // Test basic instrumentation
    test("function a(){b}",
         initCode + "$$testDefine(0,\"a\");"
         + "function a(){$$testInstrument(0,\"a\",arguments);b}");

    // Test declaration_to_remove
    test(kPreamble + "function a(){b}",
         initCode
         + "$$testDefine(0,\"a\");"
         + "var $$notToRemove;"
         + "function a(){$$testInstrument(0,\"a\",arguments);b}");

    // Test object literal declarations
    test(kPreamble + "var a = { b: function(){c} }",
         initCode
         + "var $$notToRemove;"
         + "$$testDefine(0,\"<anonymous>\");"
         + "var a = { b: function(){"
         + "$$testInstrument(0,\"<anonymous>\",arguments);c} }");

    // Test multiple object literal declarations
    test(kPreamble
         + "var a = { b: function(){c}, d: function(){e} }",
         initCode
         + "var $$notToRemove;"
         + "$$testDefine(0,\"<anonymous>\");"
         + "$$testDefine(1,\"<anonymous>\");"
         + "var a={b:function(){"
         + "$$testInstrument(0,\"<anonymous>\",arguments);c},"
         + "d:function(){$$testInstrument(1,\"<anonymous>\",arguments);e}}");

    // Test recursive object literal declarations
    test(kPreamble
         + "var a = { b: { f: function(){c} }, d: function(){e} }",
         initCode
         + "var $$notToRemove;"
         + "$$testDefine(0,\"<anonymous>\");"
         + "$$testDefine(1,\"<anonymous>\");"
         + "var a={b:{f:function(){"
         + "$$testInstrument(0,\"<anonymous>\",arguments);c}},"
         + "d:function(){$$testInstrument(1,\"<anonymous>\",arguments);e}}");
  }

  public void testEmpty() {
    this.instrumentationPb = "";
    testSame("function a(){b}");
  }

  public void testAppNameSetter() {
    this.instrumentationPb = "app_name_setter: \"setAppName\"";
    test("function a(){b}", "setAppName(\"testfile.js\");function a(){b}");
  }

  public void testInit() {
    this.instrumentationPb = "init: \"var foo = 0;\"\n"
        + "init: \"function f(){g();}\"\n";
    test("function a(){b}",
         "var foo = 0;function f(){g()}function a(){b}");
  }

  public void testDeclare() {
    this.instrumentationPb = "report_defined: \"$$testDefine\"";
    test("function a(){b}", "$$testDefine(0,\"a\");function a(){b}");
  }

  public void testCall() {
    this.instrumentationPb = "report_call: \"$$testCall\"";
    test("function a(){b}", "function a(){$$testCall(0,\"a\",arguments);b}");
  }

  public void testNested() {
    this.instrumentationPb = "report_call: \"$$testCall\"\n"
        + "report_defined: \"$$testDefine\"";
    test("function a(){ function b(){}}",
         "$$testDefine(1,\"a\");$$testDefine(0,\"a::b\");"
         + "function a(){$$testCall(1,\"a\",arguments);"
         + "function b(){$$testCall(0,\"a::b\",arguments)}}");
  }

  public void testExitPaths() {
    this.instrumentationPb = "report_exit: \"$$testExit\"";
    test("function a(){return}",
         "function a(){return $$testExit(0,undefined,\"a\")}");

    test("function b(){return 5}",
         "function b(){return $$testExit(0,5,\"b\")}");

    test("function a(){if(2 != 3){return}else{return 5}}",
         "function a(){if(2!=3){return $$testExit(0,undefined,\"a\")}"
         + "else{return $$testExit(0,5,\"a\")}}");

    test("function a(){if(2 != 3){return}else{return 5}}b()",
         "function a(){if(2!=3){return $$testExit(0,undefined,\"a\")}"
         + "else{return $$testExit(0,5,\"a\")}}b()");

    test("function a(){if(2 != 3){return}else{return 5}}",
         "function a(){if(2!=3){return $$testExit(0,undefined,\"a\")}"
         + "else{return $$testExit(0,5,\"a\")}}");
  }

  public void testExitNoReturn() {
    this.instrumentationPb = "report_exit: \"$$testExit\"";
    test("function a(){}",
         "function a(){$$testExit(0,undefined,\"a\");}");

    test("function a(){b()}",
         "function a(){b();$$testExit(0,undefined,\"a\");}");
  }

  public void testPartialExitPaths() {
    this.instrumentationPb = "report_exit: \"$$testExit\"";
    test("function a(){if (2 != 3) {return}}",
         "function a(){if (2 != 3){return $$testExit(0,undefined,\"a\")}"
         + "$$testExit(0,undefined,\"a\")}");
  }

  public void testExitTry() {
    this.instrumentationPb = "report_exit: \"$$testExit\"";
    test("function a(){try{return}catch(err){}}",
         "function a(){try{return $$testExit(0,undefined,\"a\")}catch(err){}"
         + "$$testExit(0,undefined,\"a\")}");

    test("function a(){try{}catch(err){return}}",
         "function a(){try{}catch(err){return $$testExit(0,undefined,\"a\")}"
         + "$$testExit(0,undefined,\"a\")}");

    test("function a(){try{return}finally{}}",
         "function a(){try{return $$testExit(0,undefined,\"a\")}finally{}"
         + "$$testExit(0,undefined,\"a\")}");

    test("function a(){try{return}catch(err){}finally{}}",
         "function a(){try{return $$testExit(0,undefined,\"a\")}catch(err){}"
         + "finally{}$$testExit(0,undefined,\"a\")}");

    test("function a(){try{return 1}catch(err){return 2}}",
         "function a(){try{return $$testExit(0,1,\"a\")}"
         + "catch(err){return $$testExit(0,2,\"a\")}}");

    test("function a(){try{return 1}catch(err){return 2}finally{}}",
         "function a(){try{return $$testExit(0,1,\"a\")}"
         + "catch(err){return $$testExit(0,2,\"a\")}"
         + "finally{}$$testExit(0,undefined,\"a\")}");

    test("function a(){try{return 1}catch(err){return 2}finally{return}}",
         "function a(){try{return $$testExit(0,1,\"a\")}"
         + "catch(err){return $$testExit(0,2,\"a\")}finally{"
         + "return $$testExit(0,undefined,\"a\")}}");

    test("function a(){try{}catch(err){}finally{return}}",
         "function a(){try{}catch(err){}finally{"
         + "return $$testExit(0,undefined,\"a\")}}");
  }

  public void testNestedExit() {
    this.instrumentationPb = "report_exit: \"$$testExit\"\n"
        + "report_defined: \"$$testDefine\"";
    test("function a(){ return function(){ return c;}}",
         "$$testDefine(1,\"a\");"
         + "function a(){$$testDefine(0,\"a::<anonymous>\");"
         + "return $$testExit(1,function(){"
         + "return $$testExit(0,c,\"a::<anonymous>\");},\"a\");}");
  }

  private class NameAndInstrumentFunctions implements CompilerPass {
    private final Compiler compiler;
    NameAndInstrumentFunctions(Compiler compiler) {
      this.compiler = compiler;
    }

    @Override
    public void process(Node externs, Node root) {
      FunctionNames functionNames = new FunctionNames(compiler);
      functionNames.process(externs, root);

      Instrumentation.Builder builder = Instrumentation.newBuilder();
      try {
        TextFormat.merge(instrumentationPb, builder);
      } catch (IOException e) {
        e.printStackTrace();
      }

      InstrumentFunctions instrumentation = new InstrumentFunctions(
          compiler, functionNames, builder.build(), "testfile.js");
      instrumentation.process(externs, root);
    }
  }
}


text:
<!--
 ~ Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 ~
 ~ WSO2 Inc. licenses this file to you under the Apache License,
 ~ Version 2.0 (the "License"); you may not use this file except
 ~ in compliance with the License.
 ~ You may obtain a copy of the License at
 ~
 ~    http://www.apache.org/licenses/LICENSE-2.0
 ~
 ~ Unless required by applicable law or agreed to in writing,
 ~ software distributed under the License is distributed on an
 ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 ~ KIND, either express or implied.  See the License for the
 ~ specific language governing permissions and limitations
 ~ under the License.
 -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

<parent>
          <groupId>org.wso2.andes</groupId>
          <artifactId>andes-parent</artifactId>
          <version>3.0.0-SNAPSHOT</version>
           <relativePath>../../../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <groupId>org.wso2.andes.wso2</groupId>
    <artifactId>andes-client</artifactId>
    <packaging>bundle</packaging>
    <name>andes.wso2</name>
    <description>This bundle exports packages from andes jar files</description>
    <url>http://wso2.org</url>

    <dependencies>
        <dependency>
            <groupId>org.wso2.andes</groupId>
            <artifactId>andes-client</artifactId>
            <version>${andes.version}</version>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.wso2.andes</groupId>
            <artifactId>andes-common</artifactId>
            <version>${andes.version}</version>
            <optional>true</optional>
        </dependency>
		<dependency>
			<groupId>org.apache.mina</groupId>
			<artifactId>mina-core</artifactId>
			<version>${mina.core.version}</version>
			<optional>true</optional>
			<exclusions>
                <exclusion>
                    <groupId>backport-util-concurrent</groupId>
                    <artifactId>backport-util-concurrent</artifactId>
                </exclusion>
            </exclusions>
		</dependency>
	<dependency>
		<groupId>org.apache.mina</groupId>
		<artifactId>mina-filter-ssl</artifactId>
		<version>${mina.core.version}</version>
	</dependency>
        <dependency>
            <groupId>slf4j.wso2</groupId>
	    	<artifactId>slf4j</artifactId>
			<version>1.5.10.wso2v1</version>
			<optional>true</optional>
			<exclusions>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
	<dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.13</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>

                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                        <Bundle-Name>${project.artifactId}</Bundle-Name>
						<!--<Private-Package>org.apache.qpid.wso2.internal.*</Private-Package>-->
                        <Export-Package>
                            org.wso2.andes.*;-split-package:=merge-last,
			    org.apache.mina.*;-split-package:=merge-last
                        </Export-Package>
                        <Import-Package>
                            !org.wso2.andes.*,
                        </Import-Package>
                        <DynamicImport-Package>*</DynamicImport-Package>
		    		</instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <commons-cli.version>1.2.0</commons-cli.version>
        <commons-configuration.version>1.6.0</commons-configuration.version>
        <commons-lang.version>2.3.0</commons-lang.version>
        <geronimo-jms_1.1_spec.version>1.1.0</geronimo-jms_1.1_spec.version>
        <mina.core.version>1.1.7</mina.core.version>
    </properties>

</project>


text:
using NUnit.Framework;

namespace CerealBox.Tests
{
    [TestFixture]
    class When_converting_json_with_dash_in_property_name_to_dynamic
    {
        dynamic dynamic;

        [TestFixtureSetUp]
        public void TestFixtureSetUp()
        {
            var json = @"{""animals"":{""crazy-mad-badger"":{""name"":""Steve Badger"",""age"":3}}}";
            dynamic = json.ToDynamic();
        }

        [Test]
        public void Then_crazymadbadger_name_should_be_Steve()
        {
            string name = dynamic.animals.crazymadbadger.name;
            Assert.AreEqual("Steve Badger", name);
        }

        [Test]
        public void Then_crazymadbadger_name_ToString_should_be_Steve()
        {
            Assert.AreEqual("Steve Badger", dynamic.animals.crazymadbadger.name.ToString());
        }

        [Test]
        public void Then_crazymadbadger_age_should_be_3()
        {
            int age = dynamic.animals.crazymadbadger.age;
            Assert.AreEqual(3, age);
        }

    }
}


text:
using Gigya.Microdot.System_Reflection.DispatchProxy;
using System.Reflection;

namespace Gigya.Microdot.ServiceProxy.Rewrite
{
    public interface IProxyable
    {
        object Invoke(MethodInfo targetMethod, object[] args);
    }

    public static class ProxyableExtentions
    {
        public static TInterface ToProxy<TInterface>(IProxyable proxyable)
        {
            var proxy = DispatchProxy.Create<TInterface, DelegatingDispatchProxy>();
            ((DelegatingDispatchProxy)(object)proxy).InvokeDelegate = proxyable.Invoke;
            return proxy;
        }
    }
}


text:
// Copyright 2021 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Unit tests for the DragAndDropSortInput interaction.
 */

import { NO_ERRORS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { InteractiveDragAndDropSortInputComponent } from './oppia-interactive-drag-and-drop-sort-input.component';
import { CurrentInteractionService } from 'pages/exploration-player-page/services/current-interaction.service';
import { InteractionAttributesExtractorService } from 'interactions/interaction-attributes-extractor.service';
import { CdkDragDrop, CdkDropList, CdkDrag } from '@angular/cdk/drag-drop';
import { InteractionSpecsKey } from 'pages/interaction-specs.constants';
import { DragAndDropAnswer } from 'interactions/answer-defs';
import { SubtitledHtml } from 'domain/exploration/subtitled-html.model';

interface ContainerModel<T> {
  id: string;
  data: T[];
  index: number;
}

describe('Drag and drop sort input interactive component', () => {
  let component: InteractiveDragAndDropSortInputComponent;
  let fixture: ComponentFixture<InteractiveDragAndDropSortInputComponent>;
  let currentInteractionService: CurrentInteractionService;

  class MockInteractionAttributesExtractorService {
    getValuesFromAttributes(
        interactionId: InteractionSpecsKey, attributes: Record<string, string>
    ) {
      return {
        choices: {
          value: JSON.parse(attributes.choicesWithValue)
        },
        allowMultipleItemsInSamePosition: {
          value: JSON.parse(
            attributes.allowMultipleItemsInSamePositionWithValue)
        }
      };
    }
  }

  class MockCurrentInteractionService {
    onSubmit(
        answer: DragAndDropAnswer, rulesService: CurrentInteractionService
    ) {}

    registerCurrentInteraction(
        submitAnswerFn: Function, validateExpressionFn: Function) {
      submitAnswerFn();
    }
  }
  class DragAndDropEventClass<T> {
    createInContainerEvent(
        containerId: string, data: T[], fromIndex: number, toIndex: number
    ): CdkDragDrop<T[], T[]> {
      const event = this.createEvent(fromIndex, toIndex);
      const container = { id: containerId, data: data };
      event.container = container as CdkDropList<T[]>;
      event.previousContainer = event.container;
      event.item = { data: data[fromIndex] } as CdkDrag<T>;
      return event;
    }

    createCrossContainerEvent(
        from: ContainerModel<T>, to: ContainerModel<T>
    ): CdkDragDrop<T[], T[]> {
      const event = this.createEvent(from.index, to.index);
      event.container = this.createContainer(to);
      event.previousContainer = this.createContainer(from);
      event.item = { data: from.data[from.index] } as CdkDrag<T>;
      return event;
    }

    private createEvent(
        previousIndex: number, currentIndex: number
    ): CdkDragDrop<T[], T[]> {
      return {
        previousIndex: previousIndex,
        currentIndex: currentIndex,
        isPointerOverContainer: true,
        distance: { x: 0, y: 0 }
      } as CdkDragDrop<T[], T[]>;
    }

    private createContainer(
        model: ContainerModel<T>
    ): CdkDropList<T[]> {
      const container = { id: model.id, data: model.data };
      return container as CdkDropList<T[]>;
    }
  }

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        InteractiveDragAndDropSortInputComponent,
      ],
      providers: [
        {
          provide: InteractionAttributesExtractorService,
          useClass: MockInteractionAttributesExtractorService
        },
        {
          provide: CurrentInteractionService,
          useClass: MockCurrentInteractionService
        },
      ],
      schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
  }));

  beforeEach(() => {
    currentInteractionService = TestBed.inject(CurrentInteractionService);
    fixture = TestBed.createComponent(InteractiveDragAndDropSortInputComponent);
    component = fixture.componentInstance;
  });

  describe('when multiple items in the same position are allowed', () => {
    beforeEach(() => {
      fixture = TestBed.createComponent(
        InteractiveDragAndDropSortInputComponent);
      component = fixture.componentInstance;
      component.choicesWithValue = '[' +
        '{' +
        '    "html": "
choice 1
",' +
        '    "contentId": "ca_choices_1"' +
        '},' +
        '{' +
        '    "html": "
choice 2
",' +
        '    "contentId": "ca_choices_2"' +
        '},' +
        '{' +
        '    "html": "
choice 3
",' +
        '    "contentId": "ca_choices_3"' +
        '},' +
        '{' +
        '    "html": "
choice 4
",' +
        '    "contentId": "ca_choices_4"' +
        '}' +
    ']';
      component.allowMultipleItemsInSamePositionWithValue = 'true';
      component.savedSolution = [
        [
          'ca_choices_1'
        ],
        [
          'ca_choices_2',
          'ca_choices_3'
        ],
        [
          'ca_choices_4'
        ]
      ];
      component.dragStarted = false;
      component.hide = [];
      component.highlightedGroup = -1;
      component.noShow = -1;
      component.rootHeight = 40;
    });

    it('should initialise component when user adds interaction', () => {
      spyOn(currentInteractionService, 'registerCurrentInteraction');

      component.ngOnInit();

      expect(component.allowMultipleItemsInSamePosition).toBe(true);
      expect(component.multipleItemsInSamePositionArray).toEqual([
        [],
        [
          '
choice 1
'
        ],
        [],
        [
          '
choice 2
',
          '
choice 3
'
        ],
        [],
        [
          '
choice 4
'
        ],
        []
      ]);
      expect(component.choices).toEqual([
        '
choice 1
',
        '
choice 2
',
        '
choice 3
',
        '
choice 4
'
      ]);
      expect(
        currentInteractionService.registerCurrentInteraction
      ).toHaveBeenCalled();
    });

    it('should make a default list of lists when user did not save a solution',
      () => {
        component.savedSolution = null;
        component.ngOnInit();

        expect(component.allowMultipleItemsInSamePosition).toBe(true);
        expect(component.multipleItemsInSamePositionArray).toEqual([
          [],
          [
            '
choice 1
'
          ],
          [],
          [
            '
choice 2
'
          ],
          [],
          [
            '
choice 3
'
          ],
          [],
          [
            '
choice 4
'
          ],
          []
        ]);
      });

    it('should move items inside same list', () => {
      component.noShow = 1;
      component.hide = [1, 2, 3, 4];
      component.dragStarted = true;

      const containerData = [
        '
choice 1
',
        '
choice 2
',
      ];
      const dragAndDropEventClass = new DragAndDropEventClass<string>();
      const dragDropEvent = dragAndDropEventClass.createInContainerEvent(
        'selectedItems', containerData, 1, 0);

      component.dropItemInAnyList(dragDropEvent);

      expect(component.noShow).toBe(-1);
      expect(component.hide).toEqual([]);
      expect(component.dragStarted).toBeFalse();
    });

    it('should throw error if story url fragment is not present', () => {
      component.choicesValue = [
        {
          html: '
choice 1
',
          contentId: null
        },
        {
          html: '
choice 2
',
          contentId: 'ca_choices_2'
        },
        {
          html: '
choice 3
',
          contentId: 'ca_choices_3'
        },
        {
          html: '
choice 4
',
          contentId: 'ca_choices_4'
        },
      ] as SubtitledHtml[];

      component.choices = [
        '
choice 1
',
        '
choice 2
',
        '
choice 3
',
        '
choice 4
'
      ];

      expect(() => {
        component.getContentIdOfHtml('
choice 1
');
      }).toThrowError('contentId cannot be null');
    });

    it('should throw error if content id not exist', () => {
      component.choicesValue = [
        {
          html: '
choice 1
',
          contentId: 'ca_choices_1'
        },
        {
          html: '
choice 2
',
          contentId: 'ca_choices_2'
        },
        {
          html: '
choice 3
',
          contentId: 'ca_choices_3'
        },
        {
          html: '
choice 4
',
          contentId: 'ca_choices_4'
        },
      ] as SubtitledHtml[];

      expect(() => {
        component.getHtmlOfContentId('ca_choices_5');
      }).toThrowError('contentId not found');
    });

    it('should move items between lists', () => {
      component.noShow = 1;
      component.hide = [1, 2, 3, 4];
      component.dragStarted = true;
      component.highlightedGroup = 1;
      component.multipleItemsInSamePositionArray = [
        [],
        [
          '
choice 1
'
        ],
        [],
        [
          '
choice 2
',
          '
choice 3
',
          '
choice 4
',
          '
choice 5
'
        ],
        [],
        [
          '
choice 6
',
          '
choice 7
',
          '
choice 8
',
        ],
        []
      ];

      const from: ContainerModel<string> = {
        id: 'availableItems',
        data: component.multipleItemsInSamePositionArray[5],
        index: 0
      };
      const to: ContainerModel<string> = {
        id: 'selectedItems',
        data: component.multipleItemsInSamePositionArray[3],
        index: 3
      };
      const dragAndDropEventClass = new DragAndDropEventClass<string>();
      const dragDropEvent = (
        dragAndDropEventClass.createCrossContainerEvent(from, to));

      component.dropItemInAnyList(dragDropEvent);

      expect(component.multipleItemsInSamePositionArray).toEqual([
        [],
        [
          '
choice 1
'
        ],
        [],
        [
          '
choice 2
',
          '
choice 3
',
          '
choice 4
',
          '
choice 6
',
          '
choice 5
'
        ],
        [],
        [
          '
choice 7
',
          '
choice 8
'
        ],
        []
      ]);
      expect(component.noShow).toBe(-1);
      expect(component.hide).toEqual([]);
      expect(component.dragStarted).toBeFalse();
      expect(component.highlightedGroup).toBe(-1);
    });

    it('should move list inside list of lists', fakeAsync(() => {
      spyOn(component, 'resetArray').and.callFake(() => {});

      component.multipleItemsInSamePositionArray = [
        [],
        [
          '
choice 1
'
        ],
        [],
        [
          '
choice 2
',
          '
choice 3
'
        ],
        []
      ];
      const dragAndDropEventClass = new DragAndDropEventClass<string[]>();
      const dragDropEvent = dragAndDropEventClass.createInContainerEvent(
        'selectedlists', component.multipleItemsInSamePositionArray, 3, 0);

      component.dropList(dragDropEvent);
      tick();

      expect(component.resetArray).toHaveBeenCalled();
    }));

    it('should remove highlighted group', () => {
      component.highlightedGroup = 1;

      component.removeHighlight();

      expect(component.highlightedGroup).toBe(-1);
    });

    it('should add highlighted group if it is not set', () => {
      component.highlightedGroup = -1;

      component.addHighlight(2);

      // Value should change, when drag is started
      // and highlighted group is not yet set.
      expect(component.highlightedGroup).toBe(2);
    });

    it('should add not highlighted group if it is already set', () => {
      component.highlightedGroup = 2;
      component.dragStarted = true;

      component.addHighlight(2);

      // Value should not change, when drag started
      // and highlighted group is already set.
      expect(component.highlightedGroup).toBe(2);
    });

    it('should set root placeholder height', () => {
      spyOn(
        fixture.elementRef.nativeElement, 'getElementsByClassName'
      ).withArgs('child-dnd-2').and.returnValue([
        {
          offsetHeight: 80
        }
      ]);

      component.rootHeight = 40;
      component.setRootPlaceHolderHeight(2);

      expect(component.rootHeight).toBe(80);
    });

    it('should hide item when drag is ended', () => {
      component.dragStarted = false;
      component.multipleItemsInSamePositionArray = [
        [],
        [
          '
choice 1
'
        ],
        [],
        [
          '
choice 2
',
          '
choice 3
'
        ],
        []
      ];

      const containerData = component.multipleItemsInSamePositionArray[1];
      const dragAndDropEventClass = new DragAndDropEventClass<string>();
      const dragDropEvent = dragAndDropEventClass.createInContainerEvent(
        'selectedItems', containerData, 0, 0);
      component.hideElement(dragDropEvent);

      expect(component.noShow).toBe(1);
      expect(component.hide).toEqual([1, 2]);
      expect(component.dragStarted).toBeTrue();
    });

    it('should not hide item when drag is started', () => {
      component.dragStarted = true;

      const containerData = [
        '
choice 1
',
      ];
      const dragAndDropEventClass = new DragAndDropEventClass<string>();
      const dragDropEvent = dragAndDropEventClass.createInContainerEvent(
        'selectedItems', containerData, 0, 0);
      component.hideElement(dragDropEvent);

      expect(component.noShow).toBe(-1);
      expect(component.hide).toEqual([]);
    });

    it('should return true if child element have border', () => {
      component.noShow = -1;

      expect(component.isChildElementHaveBorder(1)).toBeTrue();
    });

    it('should return true if child element have zero height', () => {
      component.hide = [1, 2];

      expect(component.isChildElementHaveZeroHeight(1)).toBeTrue();
    });
  });

  describe('when multiple items in the same position are not allowed', () => {
    beforeEach(() => {
      fixture = TestBed.createComponent(
        InteractiveDragAndDropSortInputComponent);
      component = fixture.componentInstance;
      component.choicesWithValue = '[' +
        '{' +
        '    "html": "
choice 1
",' +
        '    "contentId": "ca_choices_1"' +
        '},' +
        '{' +
        '    "html": "
choice 2
",' +
        '    "contentId": "ca_choices_2"' +
        '},' +
        '{' +
        '    "html": "
choice 3
",' +
        '    "contentId": "ca_choices_3"' +
        '}' +
    ']';
      component.allowMultipleItemsInSamePositionWithValue = 'false';
      component.savedSolution = [
        [
          'ca_choices_1'
        ],
        [
          'ca_choices_3',
        ],
        [
          'ca_choices_2'
        ]
      ];
      component.dragStarted = false;
      component.hide = [];
      component.highlightedGroup = -1;
      component.noShow = -1;
      component.rootHeight = 40;
    });

    it('should initialise component when user adds interaction', () => {
      component.ngOnInit();

      expect(component.allowMultipleItemsInSamePosition).toBe(false);
      expect(component.singleItemInSamePositionArray).toEqual([
        '
choice 1
',
        '
choice 3
',
        '
choice 2
'
      ]);
      expect(component.choices).toEqual([
        '
choice 1
',
        '
choice 2
',
        '
choice 3
',
      ]);
    });

    it('should make a default list when user did not save a solution',
      () => {
        component.savedSolution = null;
        component.ngOnInit();

        expect(component.allowMultipleItemsInSamePosition).toBe(false);
        expect(component.singleItemInSamePositionArray).toEqual([
          '
choice 1
',
          '
choice 2
',
          '
choice 3
'
        ]);
      });

    it('should move item inside list', () => {
      component.singleItemInSamePositionArray = [
        '
choice 1
',
        '
choice 2
',
        '
choice 3
'
      ];
      const dragAndDropEventClass = new DragAndDropEventClass<string>();
      const dragDropEvent = dragAndDropEventClass.createInContainerEvent(
        'selectedlists', component.singleItemInSamePositionArray, 2, 1);

      component.dropItemInSameList(dragDropEvent);

      expect(component.singleItemInSamePositionArray).toEqual([
        '
choice 1
',
        '
choice 3
',
        '
choice 2
'
      ]);
    });
  });
});


text:
package com.amazonaws.services.resiliencehub.model;

import javax.annotation.Generated;

/**
 * <p>
 * You have exceeded your service quota. To perform the requested action, remove some of the relevant resources, or use
 * Service Quotas to request a service quota increase.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ServiceQuotaExceededException extends com.amazonaws.services.resiliencehub.model.AWSResilienceHubException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new ServiceQuotaExceededException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public ServiceQuotaExceededException(String message) {
        super(message);
    }

}


text:
pimcore.registerNS("pimcore.object.classes.data.lastname");
pimcore.object.classes.data.lastname = Class.create(pimcore.object.classes.data.data, {

    type: "input",
    /**
     * define where this datatype is allowed
     */
    allowIn: {
        object: true,
        objectbrick: false,
        fieldcollection: false,
        localizedfield: false
    },

    initialize: function (treeNode, initData) {
        this.type = "lastname";

        if(!initData["name"]) {
            initData = {
                title: t("lastname")
            };
        }

        initData.fieldtype = "lastname";
        initData.datatype = "data";
        initData.name = "lastname";
        treeNode.setText("lastname");

        this.initData(initData);

        this.treeNode = treeNode;
    },

    getTypeName: function () {
        return t("lastname");
    },

    getGroup: function () {
            return "crm";
    },

    getIconClass: function () {
        return "pimcore_icon_lastname";
    },

    getLayout: function ($super) {

        $super();

        var nameField = this.layout.getComponent("standardSettings").getComponent("name");
        nameField.disable();

        this.specificPanel.removeAll();
        this.specificPanel.add([
            {
                xtype: "spinnerfield",
                fieldLabel: t("width"),
                name: "width",
                value: this.datax.width
            },{
                xtype: "spinnerfield",
                fieldLabel: t("columnlength"),
                name: "columnLength",
                value: this.datax.columnLength
            }
        ]);

        return this.layout;
    }

});


text:
<html>

<head>
        <title>Sadhbh - Crawlers</title>
       <script Language="javascript" src="sketch.js"></script>
       <script Language="javascript" src="Crawler.js"></script>
        <script Language="javascript" src="p5/p5.js"></script>
</head>

<body bgcolor=pink>

</body>

</html>