text:
module RuboCop
  module Cop
    module Layout
      # Checks for spaces inside ordinary round parentheses.
      #
      # @example EnforcedStyle: no_space (default)
      #   # The `no_space` style enforces that parentheses do not have spaces.
      #
      #   # bad
      #   f( 3)
      #   g = (a + 3 )
      #
      #   # good
      #   f(3)
      #   g = (a + 3)
      #
      # @example EnforcedStyle: space
      #   # The `space` style enforces that parentheses have a space at the
      #   # beginning and end.
      #   # Note: Empty parentheses should not have spaces.
      #
      #   # bad
      #   f(3)
      #   g = (a + 3)
      #   y( )
      #
      #   # good
      #   f( 3 )
      #   g = ( a + 3 )
      #   y()
      #
      class SpaceInsideParens < Cop
        include SurroundingSpace
        include RangeHelp
        include ConfigurableEnforcedStyle

        MSG       = 'Space inside parentheses detected.'
        MSG_SPACE = 'No space inside parentheses detected.'

        def investigate(processed_source)
          @processed_source = processed_source

          if style == :space
            each_missing_space(processed_source.tokens) do |range|
              add_offense(range, location: range, message: MSG_SPACE)
            end
          else
            each_extraneous_space(processed_source.tokens) do |range|
              add_offense(range, location: range)
            end
          end
        end

        def autocorrect(range)
          lambda do |corrector|
            if style == :space
              corrector.insert_before(range, ' ')
            else
              corrector.remove(range)
            end
          end
        end

        private

        def each_extraneous_space(tokens)
          tokens.each_cons(2) do |token1, token2|
            next unless parens?(token1, token2)

            # If the second token is a comment, that means that a line break
            # follows, and that the rules for space inside don't apply.
            next if token2.comment?
            next unless same_line?(token1, token2) && token1.space_after?

            yield range_between(token1.end_pos, token2.begin_pos)
          end
        end

        def each_missing_space(tokens)
          tokens.each_cons(2) do |token1, token2|
            next if can_be_ignored?(token1, token2)

            if token1.left_parens?
              yield range_between(token2.begin_pos, token2.begin_pos + 1)
            elsif token2.right_parens?
              yield range_between(token2.begin_pos, token2.end_pos)
            end
          end
        end

        def same_line?(token1, token2)
          token1.line == token2.line
        end

        def parens?(token1, token2)
          token1.left_parens? || token2.right_parens?
        end

        def can_be_ignored?(token1, token2)
          return true unless parens?(token1, token2)

          # If the second token is a comment, that means that a line break
          # follows, and that the rules for space inside don't apply.
          return true if token2.comment?

          return true unless same_line?(token1, token2) && !token1.space_after?
        end
      end
    end
  end
end


text:
package org.wikipedia.editing;

import android.os.Parcel;
import android.os.Parcelable;

public class SuccessEditResult extends EditingResult {
    private final int revID;
    public SuccessEditResult(int revID) {
        super("Success");
        this.revID = revID;
    }

    private SuccessEditResult(Parcel in) {
        super(in);
        revID = in.readInt();
    }

    public int getRevID() {
        return revID;
    }

    public static final Parcelable.Creator<SuccessEditResult> CREATOR
            = new Parcelable.Creator<SuccessEditResult>() {
        public SuccessEditResult createFromParcel(Parcel in) {
            return new SuccessEditResult(in);
        }

        public SuccessEditResult[] newArray(int size) {
            return new SuccessEditResult[size];
        }
    };
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;

class ReverseDigits
{
    private static void PrintDidigts(List<int> numArr)
    {
        foreach (int num in numArr)
        {
            Console.Write(num);
        }
        Console.WriteLine();
    }

    private static void ReverseDigitsOfNum(List<int> numArr, int inputNum)
    {
        int counter = 0;
        int lastNum = 0;
        while (inputNum / 10 != 0)
        {
            lastNum = inputNum - (inputNum / 10) * 10;
            numArr.Add(lastNum);
            counter++;
            inputNum = (inputNum - lastNum) / 10;
        }
        numArr.Add(inputNum);
    }

    static void Main()
    {
        int inputNum = int.Parse(Console.ReadLine());
        List<int> numArr = new List<int>();
        ReverseDigitsOfNum(numArr, inputNum);
        PrintDidigts(numArr);
    }
}


text:
/* tslint:disable:no-unused-variable */
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {DebugElement, EventEmitter} from '@angular/core';

import {TodoListComponent} from './todo-list.component';
import {MaterialModule} from "@angular/material";
import {TodoResource} from "../../models/todoResource";
import {TodoItem} from "../../models/todoItem";
import {LinkItem} from "../../models/linkItem";
import {AccessedItem} from "../../models/accessedItem";
import {PageMetadata} from "../../models/pageMetadata";

describe('TodoListComponent', () => {
  let component: TodoListComponent;
  let fixture: ComponentFixture<TodoListComponent>;
  let eventEmitter: EventEmitter<any>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [MaterialModule.forRoot()],
      declarations: [TodoListComponent]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TodoListComponent);
    component = fixture.componentInstance;
    component.todoResources = new MockedTodoResource("1");
    eventEmitter = new EventEmitter();
    component.delete = eventEmitter;
    fixture.detectChanges();
  });

  it('should be initialized correctly', () => {
    expect(component).toBeTruthy();
    expect(component.todoResources["mockId"]).toBe("1");
  });

  it('todo resource can be set', () => {
    expect(component.todoResources).not.toBeUndefined();
  });

  it('displays correct information', () => {
    let element = fixture.nativeElement;
    fixture.detectChanges();
    expect(element.querySelector('.card-content').innerText).toBe("mockedDescription")
  });
});

class MockedTodoResource implements TodoResource {
  todoResources: TodoItem[] = [{
    resourceId: "1",
    title: "mockedTitle",
    description: "mockedDescription",
    markedDone: true,
    createdAt: "_",
  }];
  _links: LinkItem = {} as LinkItem;
  accessed: AccessedItem = {} as AccessedItem;
  page: PageMetadata = {} as PageMetadata;

  mockId: string;

  constructor(mockedId: string) {
    this.mockId = mockedId;
  }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Suppl. pl. succ. 52. 1819

#### Original name
null

### Remarks
null


text:
package org.ofbiz.minilang.method.entityops;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.collections.FlexibleMapAccessor;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.minilang.MiniLangException;
import org.ofbiz.minilang.MiniLangValidate;
import org.ofbiz.minilang.SimpleMethod;
import org.ofbiz.minilang.method.MethodContext;
import org.ofbiz.minilang.method.MethodOperation;
import org.w3c.dom.Element;

/**
 * Implements the <create-value> element.
 *
 * @see Mini-language Reference
 */
public final class CreateValue extends MethodOperation {

    public static final String module = CreateValue.class.getName();

    private final boolean createOrStore;
    @Deprecated
    private final boolean doCacheClear;
    private final FlexibleMapAccessor<GenericValue> valueFma;

    public CreateValue(Element element, SimpleMethod simpleMethod) throws MiniLangException {
        super(element, simpleMethod);
        if (MiniLangValidate.validationOn()) {
            MiniLangValidate.attributeNames(simpleMethod, element, "value-field", "do-cache-clear", "or-store");
            MiniLangValidate.requiredAttributes(simpleMethod, element, "value-field");
            MiniLangValidate.expressionAttributes(simpleMethod, element, "value-field");
            MiniLangValidate.constantAttributes(simpleMethod, element, "do-cache-clear", "or-store");
            MiniLangValidate.noChildElements(simpleMethod, element);
        }
        valueFma = FlexibleMapAccessor.getInstance(element.getAttribute("value-field"));
        doCacheClear = !"false".equals(element.getAttribute("do-cache-clear"));
        createOrStore = "true".equals(element.getAttribute("or-store"));
    }

    @Override
    public boolean exec(MethodContext methodContext) throws MiniLangException {
        GenericValue value = valueFma.get(methodContext.getEnvMap());
        if (value == null) {
            String errMsg = "In <create-value> the value \"" + valueFma + "\" was not found, not creating";
            Debug.logWarning(errMsg, module);
            simpleMethod.addErrorMessage(methodContext, errMsg);
            return false;
        }
        try {
            if (createOrStore) {
                value.getDelegator().createOrStore(value);
            } else {
                value.getDelegator().create(value);
            }
        } catch (GenericEntityException e) {
            String errMsg = "Exception thrown while creating the \"" + valueFma +"\" GenericValue: " + e.getMessage();
            Debug.logWarning(e, errMsg, module);
            simpleMethod.addErrorMessage(methodContext, errMsg);
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("<create-value ");
        sb.append("value-field=\"").append(this.valueFma).append("\" ");
        if (!this.doCacheClear) {
            sb.append("do-cache-clear=\"false\"");
        }
        if (this.createOrStore) {
            sb.append("or-store=\"true\"");
        }
        sb.append("/>");
        return sb.toString();
    }

    /**
     * A factory for the <create-value> element.
     */
    public static final class CreateValueFactory implements Factory<CreateValue> {
        @Override
        public CreateValue createMethodOperation(Element element, SimpleMethod simpleMethod) throws MiniLangException {
            return new CreateValue(element, simpleMethod);
        }

        @Override
        public String getName() {
            return "create-value";
        }
    }
}


text:
#include "GlobalDef.h"
#include "Periodic.h"
#include "Led.h"
#include "EEPROM.h"
#include "ProgrammedModule.h"
#include "Delay.h"
#include "Tach.h"
#include "DoorStatus.h"
#include "Relay.h"
#include "Keysense.h"
#include "ModeSelection.h"
#include "Data.h"
#include "J1850.h"
#include "VSource.h"
#include "ProgSwitch.h"
#include "GenericBypass.h"
#include "Generic_App.h"
#include "AnalogSource.h"
#include "CAN_App.h"
#include "CAN.h"
#include "Scheduler.h"
#include "Chrono.h"
#include "Input.h"
#include "Ignition.h"
#include "SecureTakeOver.h"

#if defined(HW_BLADE)
	#include "UartSwitch.h"
#else
	#include "AlarmPort.h"
#endif

#if defined(IDATASTART)
	#include "IDL2W_IDM_RsAccess.h"
	#include "Ignition.h"
#endif

#include "NI7.h"
#include "NI7_Database.h"

#if defined(VEHICLEDEBUG_ENABLE)
	#include "VehicleDebug.h"
#endif

#if defined(PROGOPTION_ENABLE)
	#include "ProgramOptions.h"
#endif

// Protos
static void NI7_RefreshRAM(void);
static void NI7_Tach(void);
static void NI7_RemoteStart(void);

// CAN functions
static void NI7_CAN_tach15C(void);
static void NI7_CAN_VSS18E(void);
static void NI7_CAN_DoorBrake454(void);
static void NI7_CAN_OEM_FOB_456(void);

// Analog function
static void NI7_ManageDoorlock(void);

#if defined(VEHICLEDEBUG_ENABLE)
static void NI7_LoadDebugParameters(void);
#endif

void NI7_BackDoor(void);

#if defined(IDATASTART)
	static void NI7_IdataStart_Init(void);
	void NI7_SetDebugInfo(void);
#endif

#define CloseLoopImmo(State)			Relay_SetState(State)
#define PushStartButton(State)			Data_SetPullUpUBP(((!State)&0x01));Data_SetGroundUBP(State)
#define NI7_SetBrakeToStart(State)		J1850_SetState(State)
//#define NI7_SetBrakeOutput(State)		Data_SetPullUpISO(State);Data_SetGroundISO(((!State)&0x01))
#define NI7_SetBrakeOutput(State)		Data_SetVadj0(State);Data_SetGround0(((!State)&0x01))
#define NI7_SetEbrakeState(State)		Keysense_SetState(State)

#if defined(IDATASTART)
	#define NI7_RAP_Shutdown(State) 	((State == OFF) ? (Relay2_SetState(OFF)) : (Relay2_SetState(ON)))
#else
	#define NI7_RAP_Shutdown(State) 	((State == OFF) ? (GenericBypass_SetBypass(BYPASS_OPEN)) : (GenericBypass_SetBypass(BYPASS_CLOSE)))
#endif
// Globals
extern volatile Uint8 Learned;
static volatile Uint8 NissanPlatform;
static volatile Uint8 VINFound=0;
static volatile Uint8 IgnoreBrake=OFF;
static volatile Uint8 AnyDoorOpen=NO;
static volatile Uint8 idleModeReady = OFF;
static volatile Uint8 idleMode = OFF;
static volatile Uint8 ShutDown = OFF;
static volatile Uint8 startDone = NO;
static volatile Uint8 FOB_Detected = NO;
static volatile Uint8 Brake_Validated=0;
static volatile Uint8 ShutDownByBrake = NO;
static volatile Uint8 LastKeylessCommand=0;
static volatile Uint8 NI7_VSS_Detected = NO;

////////////////////////////////////////////////////////////////////
// Init Mazda Firmware
////////////////////////////////////////////////////////////////////
Uint8 NI7_Init(void)
{
	// Called by Generic_App_Init()
	// System already Init
	#if defined(IDATASTART)
	NI7_IdataStart_Init();
	#endif

	#if defined(HW_BLADE)
		Ignition_SetSource(IGNITION_SOURCE_PINK_BLADE);
	#endif

	CAN_App_Init(App_CAN0);

	// Config CAN Speed & CAN MOB
	CAN_SetSpeed(CAN_500K);
	CAN_Set_MOB(MOB_STANDARD_RX);
	CAN_Clear_MOB();
	CAN_HSCAN_NormalMode();

	PushStartButton(OFF);
	#if defined(HW_ALCA)
	NI7_SetEbrakeState(OFF);
	#endif

	VSource_SetTransponderVoltage12V();
	VSource_SetDoorlockVoltage12V();

	Periodic_Disable(PERIODIC_RAP_SHUTDOWN_TIMEOUT);

		// Must make LUTs to Set Supported by Platform !!!
		IDL2W_AlarmTrigger_SetSupportedZoneOn(FDSD_ZONE);
		IDL2W_AlarmTrigger_SetSupportedZoneOn(FPSD_ZONE);
		IDL2W_AlarmTrigger_SetSupportedZoneOn(RDSD_ZONE);
		IDL2W_AlarmTrigger_SetSupportedZoneOn(RPSD_ZONE);
		IDL2W_AlarmTrigger_SetSupportedZoneOn(TLG_ZONE);
		//IDL2W_AlarmTrigger_SetSupportedZoneOn(HD_ZONE);
		IDL2W_SetBrakeSupportedOn(BRAKE_PEDAL);
		IDL2W_SetBrakeSupportedOn(EBRAKE);
		IDL2W_SetTachSupported(ON);

	NI7_RefreshRAM();

	if(ProgrammedModule_Check()==NO)
	{
		CAN_Disable_Interrupts();
		CAN_HSCAN_SleepMode();
		CAN_SetSpeed(CAN_500K);
		CAN_Set_MOB(MOB_STANDARD_RX);
		CAN_Clear_MOB();
		CAN_App_SetUpRxMOB(MOB_STANDARD_RX,(tAddr)NI7_Learn_CanFilterSettings);
		CAN_HSCAN_NormalMode();
		CAN_Enable_Interrupts();

		// Verify IGN wire
		while(Input_GetState(IGNITION_STATE)==OFF)
		{
			wdt_reset();
		}

		LED_Steady(LED_BYPASS, RED);

		// Wait for 3 seconds to see if VIN available
/*		while((VINFound!=0x31)&&(i<3))
		{
			wdt_reset();

			if(Periodic_GetState(PERIODIC_TAKEOVER_TIMEOUT)==ON)
				i++;
		}

		// Write VIN to eeprom if available
		if(VINFound==0x31)
		{
			for(i=0;i<17;i++)
			{
				EEPROM_Write(PROGRAM_MEMORY_VIN_PTR+i,VIN[i]);
			}
		}
*/
		// Everything required is learned so save
		ProgrammedModule_Save();
	}

	// Start a periodic for 2sec timeout for OEM keyless arm/disarm
	Periodic_Enable(PERIODIC_KEYLESS_TIMEOUT,200);

	NissanPlatform=PLATFORM_NI7_ROGUE_2014_PTS;

	// Save current platform in EEPROM
	EEPROM_Write(PLATFORM_2_PTR,NissanPlatform);

	Learned=YES;

	CAN_Disable_Interrupts();
	CAN_HSCAN_SleepMode();
	CAN_SetSpeed(CAN_500K);
	CAN_Set_MOB(MOB_STANDARD_RX);
	CAN_Clear_MOB();
	CAN_App_SetUpRxMOB(MOB_STANDARD_RX,(tAddr)NI7_CanFilterSettings);
	CAN_HSCAN_NormalMode();
	CAN_Enable_Interrupts();

	#if defined(PROTOCOL_IDM)
	IDL2W_SetVSSSupported(YES);
	IDL2W_SetVINSupported(YES);
	IDL2W_SetVIN((Uint8*)VIN);
	#endif

	#if defined(VEHICLEDEBUG_ENABLE)
	VehicleDebug_AssignCustomApp(&NI7_BackDoor);
	#endif

	#if defined(PROGOPTION_ENABLE)
	ProgramOptions_SetBit(PROGRAM_OPTION_GWR_CONTROL_WITH_IGNITION,YES);
	#endif

	// System_FinalizeBeforeMain() called by Generic_App_Init()
	// System will do:
	// IDL2W_RefreshOption()
	// LED_Confirmation()
	// Manage BladeLock

	return SUCCESS;
}

////////////////////////////////////////////////////////////////////
// Learn Functions
////////////////////////////////////////////////////////////////////
void NI7_CAN_ID_LearnManager(void)
{
	//Uint8 i,Data[8];
	Uint16 Id;

	if(VINFound == 0x31)
		return;

	CAN_Get_STD_ID(Id);
/*
	if(Id==0x40A)
	{
		CAN_Get_Data(Data);

		// Get all the VIN
		if(Data[1]==0x00)
		{
			for(i=0;i<6;i++)
				VIN[i]=Data[2+i];

			VINFound |= 0x01;
		}

		if(Data[1]==0x01)
		{
			for(i=0;i<6;i++)
				VIN[6+i]=Data[2+i];

			VINFound |= 0x10;
		}

		if(Data[1]==0x02)
		{
			for(i=0;i<5;i++)
				VIN[12+i]=Data[2+i];

			VINFound |= 0x20;
		}
	}*/
}

// Refresh RAM at init and GWR
static void NI7_RefreshRAM(void)
{
	CAN_App_RefreshRAM(App_CAN0);

	WakeupInputMask=(WAKEON_LOCK_BUFFER|WAKEON_UNLOCK_BUFFER|WAKEON_IGNITION|WAKEON_STARTER|WAKEON_PROGSW|WAKEON_GWR);

	// Load EEPROM
	//NissanPlatform=EEPROM_Read(PLATFORM_2_PTR);
	NissanPlatform = PLATFORM_NI7_ROGUE_2014_PTS;
	CAN_SendFrame();
}

////////////////////////////////////////////////////////////////////
// MAIN Functions
////////////////////////////////////////////////////////////////////
void NI7_Main(void)
{
	NI7_ManageDoorlock();

	NI7_RemoteStart();

	NI7_Tach();

	SecureTakeOver_Main(NissanPlatform);

	CAN_SendFrame();

	#if defined(VEHICLEDEBUG_ENABLE)
		// Manage vehicle debug...
		VehicleDebug_Execute();
		NI7_LoadDebugParameters();
	#endif

	CAN_App_CheckSleep();

	wdt_reset();
}

////////////////////////////////////////////////////////////////////
// Doorlock features
////////////////////////////////////////////////////////////////////
void NI7_ManageDoorlock(void)
{
	if(Input_GetState(UNLOCK_DRIVER_ON))
	{
		SecureTakeOver_Unlock();
		LastKeylessCommand = 2;
	}

	if(Input_GetState(UNLOCK_ON))
	{
		SecureTakeOver_Unlock();
		LastKeylessCommand = 2;
	}

	if(Input_GetState(TRUNK_ON))
	{
		SecureTakeOver_Unlock();
		LastKeylessCommand = 2;
	}

	if(Input_GetState(LOCK_ON))
	{
		SecureTakeOver_Lock();
		LastKeylessCommand = 1;
	}

	Input_GetState(RIGHT_SLIDING_DOOR_ON);
	Input_GetState(LEFT_SLIDING_DOOR_ON);
}

////////////////////////////////////////////////////////////////////
// Remote Start function
////////////////////////////////////////////////////////////////////
static void NI7_RemoteStart(void)
{
	static Uint8 counterStarterSec = 0;
	Uint8 counterPTS = 0;

	// if we detect a falling edge on ground when running, add a disarm job
	if(Input_GetState(GROUND_OUT_ON)==ON)
	{
		SecureTakeOver_Init();

		LED_DisplayPlatform(LED_BYPASS, NissanPlatform+1);

		if(Input_GetState(IGNITION_STATE)==ON)
		{
			idleModeReady = ON;
		}
		else
		{
			CloseLoopImmo(ON);
			Delay(25);
			// Check if brake is ON for shutdown!
			// If not, apply brake to prepare
			if(Brake_Validated < 4)
			{
				//brakes status from CAN will not be monitor
				IgnoreBrake=ON;
				Delay(5);
				NI7_SetBrakeToStart(ON);
				Periodic_Enable(PERIODIC_PTS_TIMEOUT,100);
			}
		}

		NI7_RefreshRAM();
	}

	if(Input_GetState(GROUND_OUT_OFF)==ON)
	{
		IgnoreBrake=OFF;

		LED_DisplayPlatformOff(LED_BYPASS);

		CloseLoopImmo(OFF);

		//if the car is started and the engin is running
		if((NI7_VSS_Detected == NO)&&(idleModeReady==idleMode))
		{
			//Will check for the key if shutdown by brake
			if((ShutDownByBrake == YES) && (AnyDoorOpen == NO))
			{
				if(FOB_Detected == NO)
				{
					while(Input_GetState(IGNITION_STATE)==ON)
					{
						PushStartButton(ON);
						Delay(80);
						PushStartButton(OFF);
						Delay(20);

						if(counterPTS < 3)
							counterPTS++;
						else
							break;
					}
				}
			}
			else  // Will shutdown the vehicle if no brake is pushed.
			{
				while(Input_GetState(IGNITION_STATE)==ON)
				{
					PushStartButton(ON);
					Delay(80);
					PushStartButton(OFF);
					Delay(20);

					if(counterPTS < 3)
						counterPTS++;
					else
						break;
				}
				Periodic_Enable(PERIODIC_RAP_SHUTDOWN_TIMEOUT,50);
			}
		}

		PushStartButton(OFF);
		ShutDown=OFF;
		idleModeReady = OFF;
		ShutDownByBrake = NO;

		Periodic_Disable(PERIODIC_PTS_TIMEOUT);
		counterStarterSec = 0;
	}

	if(Input_GetState(STARTER_ON)==ON)
	{
		if((Input_GetState(GROUND_OUT_STATE)==ON))
		{
			if(FOB_Detected)
			{
				if((startDone==NO)&&(AnyDoorOpen==NO))
				{
					LED_Steady(LED_BYPASS, RED);

					PushStartButton(ON);
				}
			}
			else
			{
				LED_Blink(LED_BYPASS, RED,5);
			}
		}
	}

	if((Input_GetState(STARTER_OFF)==ON) || (counterStarterSec > 15))
	{
		if((Input_GetState(GROUND_OUT_STATE)==ON))
		{
			LED_DisplayPlatform(LED_BYPASS, NissanPlatform+1);

			Delay(50);

			PushStartButton(OFF);
			NI7_SetBrakeToStart(OFF);

			Delay(30);

			CloseLoopImmo(OFF);
			IgnoreBrake=OFF;
			Periodic_Disable(PERIODIC_PTS_TIMEOUT);
			counterStarterSec = 0;
		}
	}

	if((Input_GetState(GROUND_OUT_STATE)==ON))
	{
		if(ShutDown==ON)
		{
			//brakes status from CAN will not be monitor
			IgnoreBrake=ON;

			//Brake to RS ON
			NI7_SetBrakeOutput(HIGH);

			IDL2W_SetBrakeOn(BRAKE_PEDAL);

			LED_Blink(LED_BYPASS, RED,25);
			Delay(100);

			//Brake to RS OFF
			NI7_SetBrakeOutput(LOW);

			IDL2W_SetBrakeOff(BRAKE_PEDAL);

			//brakes status from CAN will be monitor
			IgnoreBrake=OFF;
		}

		// unpush PTS if problem with starter state
		if(Periodic_GetState(PERIODIC_PTS_TIMEOUT)==ON)
		{
			if(counterStarterSec < 20)
				counterStarterSec++;
		}
	}

	if((Input_GetState(GROUND_OUT_STATE)==OFF)&&(Input_GetState(IGNITION_STATE)==OFF))
	{
		IgnoreBrake=OFF;
		startDone=NO;
		ShutDown=OFF;

		idleModeReady = OFF;
		idleMode = OFF;

		CloseLoopImmo(OFF);
		PushStartButton(OFF);
		NI7_SetBrakeToStart(OFF);
		LED_DisplayPlatformOff(LED_BYPASS);
		Periodic_Disable(PERIODIC_PTS_TIMEOUT);
		counterStarterSec = 0;

		if(Periodic_GetState(PERIODIC_RAP_SHUTDOWN_TIMEOUT)==ON)
		{
			NI7_RAP_Shutdown(ON);
			Delay(80);
			NI7_RAP_Shutdown(OFF);
			Periodic_Disable(PERIODIC_RAP_SHUTDOWN_TIMEOUT);
		}
	}
}

////////////////////////////////////////////////////////////////////
// Tach function
////////////////////////////////////////////////////////////////////
static void NI7_Tach(void)
{
	if(Input_GetState(IGNITION_ON))
	{
		IDL2W_SendVehicleIgnitionState(ON);
		Tach_Start();
	}

	if(Input_GetState(IGNITION_OFF))
	{
		Tach_Stop();
		IDL2W_SendVehicleIgnitionState(OFF);
	}

	if(Input_GetState(IGNITION_STATE)==OFF)
	{
		// Reset Brake status to OFF (No status from vehicle with ignition off)
		if(Input_GetState(GROUND_OUT_STATE)==OFF)
		{
			NI7_SetBrakeOutput(LOW);
			IDL2W_SetBrakeOff(BRAKE_PEDAL);
		}
	}
}

////////////////////////////////////////////////////////////////////
// CAN Manager
////////////////////////////////////////////////////////////////////
void NI7_CAN_ID_Manager(void)
{
	Uint16 id;

	CAN_Get_STD_ID(id);

	switch(id)
	{
		// Tach
		case 0x15C:
			NI7_CAN_tach15C();
			return;

		// Tach
		case 0x18E:
			NI7_CAN_VSS18E();
			return;

		// Doors status
		// Trunk status
		// Brake status
		// Ebrake status
		case 0x454:
			NI7_CAN_DoorBrake454();
			return;

		// Ebrake status
		case 0x456:
			NI7_CAN_OEM_FOB_456();
			return;
	}
}

//*******************************************************************************/
// Rogue 2014			15C			 TT TT XX XX XX XX XX XX (Tach)
//*******************************************************************************/
// Tach * 8
//*******************************************************************************/
static void NI7_CAN_tach15C(void)
{
	Uint8 Data[8];

	CAN_Get_Data(Data);

	if(Input_GetState(IGNITION_STATE)==ON)
	{
		// Tach is higher then 200 RPM!
		if(Data[0] > 0x06)
		{
			// Tach lib needs 4x and car is 8x... so div by 2 before sending to tach lib.
			Tach_SetRPM((((((Uint16)Data[0])<<8)|(Uint16)Data[1])>>1));
			startDone=YES;
		}
		else
		{
			Tach_ForceRPM(0);
			startDone=NO;
		}
	}
}

//*******************************************************************************/
// Rogue 2014			18E			 VS SS XX XX XX XX XX XX (VSS)
//*******************************************************************************/
// VSS / 42
//*******************************************************************************/
static void NI7_CAN_VSS18E(void)
{
	Uint8 Data[8];

	CAN_Get_Data(Data);

	if(Input_GetState(IGNITION_STATE)==ON)
	{
		if(Data[1] != 0x00)
		{
			NI7_VSS_Detected = YES;
		}
		else
		{
			NI7_VSS_Detected = NO;
		}
	}
	else
	{
		NI7_VSS_Detected = NO;
	}
}

//*******************************************************************************/
// Rogue 2014			454			xx xx xx xx xx AA xx xx (Doors Status)
// Rogue 2014			454			xx xx xx xx xx xx 8x xx (Trunk Status)
// Rogue 2014			454			xx xx xx xx xx xx xx 1x (Ebrake Status)
// Rogue 2014			454			xx xx xx xx xx xx 4x xx (Brake Status)
//*******************************************************************************/
// Door/Trunk/Hood @ 500ms
//*******************************************************************************/
static void NI7_CAN_DoorBrake454(void)
{
	static Uint8 EBrakeOff_Validated=0;
	static Uint8 Brake_Validated=0;
	static Uint8 DoorTriggerDelay=0;
	Uint8 Data[8];
	CAN_Get_Data(Data);

	// All Door Close
	if((Data[5]&0xAA)==0x00)
	{
		// Reset the sequence. Will be in normal RS sequence if we see a door open and then close.
		if(AnyDoorOpen)
		{
			// DSE and compuStar shut the car when door close in Reservation mode
			// We need to shut the car in case of PTS+Manual
			if(idleMode)
			{
				SecureTakeOver_Lock();
			}

			idleMode = OFF;
			idleModeReady = OFF;
		}

		Periodic_Disable(PERIODIC_TIMEOUT2_EVENT);
		DoorTriggerDelay=0;

		#if defined(HW_ALCA)
			DoorStatus_SetState(DOOR_CLOSE);
		#endif
		IDL2W_AlarmTrigger_SetZonesOff(FDSD_ZONE);

		AnyDoorOpen = NO;
	}
	// Any Door Open
	else
	{
		if((Data[5]&0x80)==0x80)
		{
			// Start timer to only trigger on door open more then 1 sec.
			if(DoorTriggerDelay==0)
				Periodic_Enable(PERIODIC_TIMEOUT2_EVENT,120);

			if(Periodic_GetState(PERIODIC_TIMEOUT2_EVENT)==ON)
			{
				#if defined(HW_ALCA)
				DoorStatus_SetState(DOOR_OPEN);
				#endif

				IDL2W_AlarmTrigger_SetZonesOn(FDSD_ZONE);

				AnyDoorOpen = YES;

				//wait for a door open to activate idleMode
				if(idleModeReady)
					idleMode = ON;

				if(Input_GetState(GROUND_OUT_STATE)==ON)
				{
					//if the car is in idleMode, the door open will not shut the car
					// When the brake is press, the car will look for a key...or it will shut the car
					if(SecureTakeOver_CheckTimeout() == YES)
					{
						if(idleMode==OFF)
							ShutDown=ON;
					}
				}
				Periodic_Disable(PERIODIC_TIMEOUT2_EVENT);
			}
		}
		else
		{
			#if defined(HW_ALCA)
			DoorStatus_SetState(DOOR_OPEN);
			#endif

			AnyDoorOpen = YES;

			//wait for a door open to activate idleMode
			if(idleModeReady)
				idleMode = ON;

			if(Input_GetState(GROUND_OUT_STATE)==ON)
			{
				//if the car is in idleMode, the door open will not shut the car
				// When the brake is press, the car will look for a key...or it will shut the car
				if(SecureTakeOver_CheckTimeout() == YES)
				{
					if(idleMode==OFF)
						ShutDown=ON;
				}
			}
		}
		DoorTriggerDelay=1;
	}

	// Check Any Door open and send status in data
	if((Data[5]&0x20)==0x20)
		IDL2W_AlarmTrigger_SetZonesOn(FPSD_ZONE);
	else
		IDL2W_AlarmTrigger_SetZonesOff(FPSD_ZONE);

	if((Data[5]&0x08)==0x08)
		IDL2W_AlarmTrigger_SetZonesOn(RDSD_ZONE);
	else
		IDL2W_AlarmTrigger_SetZonesOff(RDSD_ZONE);

	if((Data[5]&0x02)==0x02)
		IDL2W_AlarmTrigger_SetZonesOn(RPSD_ZONE);
	else
		IDL2W_AlarmTrigger_SetZonesOff(RPSD_ZONE);

	// Trunk Close
	if((Data[6]&0x80)==0)
	{
		IDL2W_AlarmTrigger_SetZonesOff(TLG_ZONE);

		#if defined(HW_ALCA)
		TrunkStatus_SetState(TRUNK_CLOSE);
		#endif
	}
	// Trunk Open
	else
	{
		IDL2W_AlarmTrigger_SetZonesOn(TLG_ZONE);

		#if defined(HW_ALCA)
		TrunkStatus_SetState(TRUNK_OPEN);
		#endif

		if(Input_GetState(GROUND_OUT_STATE)==ON)
		{
			if(SecureTakeOver_CheckTimeout() == YES)
				ShutDown=ON;
		}
	}

	if(IgnoreBrake == OFF)
	{
		if((Data[6]&0x40) == 0x40)
		{
			if(Brake_Validated>4)
			{
				if((Input_GetState(GROUND_OUT_STATE) == ON) && (SecureTakeOver_CheckTimeout() == NO))
					ShutDownByBrake=YES;

				IDL2W_SetBrakeOn(BRAKE_PEDAL);
				NI7_SetBrakeOutput(HIGH);
			}
			else
			{
				Brake_Validated++;
			}
		}
		#if defined(PROGOPTION_ENABLE)
		else if((Input_GetState(GROUND_OUT_STATE)==ON)&&(ForceBrakeWhenDoorOpen==YES))
		{
			if(idleMode==OFF)
			{
				ShutDown = ON;
				SecureTakeOver_Lock();
			}
		}
		#endif
		else
		{
			Brake_Validated=0;
			IDL2W_SetBrakeOff(BRAKE_PEDAL);
			NI7_SetBrakeOutput(LOW);
		}
	}

	if(Input_GetState(IGNITION_STATE)==ON)
	{
		if((Data[7]&0x10) == 0x10)
		{
			IDL2W_SetBrakeOn(EBRAKE);

			#if defined(HW_ALCA)
			NI7_SetEbrakeState(ON);
			#endif

			EBrakeOff_Validated=0;
		}
		else
		{
			if(EBrakeOff_Validated>4)
			{
				IDL2W_SetBrakeOff(EBRAKE);

				#if defined(HW_ALCA)
				NI7_SetEbrakeState(OFF);
				#endif
			}
			else
			{
				EBrakeOff_Validated++;
			}
		}
	}
}

//*******************************************************************************/
// Rogue 2014			456			x6 xx xx (OEM cmds)
// Rogue 2014			456			xx xx 1x (Key IN Status)
// Rogue 2014			456			xx A8 xx (Doors unlocked)
//*******************************************************************************/
// OEM commands and FOB detection
//*******************************************************************************/
static void NI7_CAN_OEM_FOB_456(void)
{
	Uint8 Data[8];
	CAN_Get_Data(Data);

	if((Data[0]&0x02)==0x02)
	{
		SecureTakeOver_Lock();

		// Only send arm command if the timming between 2 keyless code is > 2sec or if the received command is different than before
		// Only send arm command if the timming between 2 keyless code is > 2sec or if the received command is different than before
		if(Periodic_GetState(PERIODIC_KEYLESS_TIMEOUT)||(LastKeylessCommand!=1))
			OEM_Alarm_SetState(OEM_ALARM_ARM); /*IDL2W_SendOEMAlarmState(OEM_ALARM_ARM);*/	// Arm
		Periodic_Enable(PERIODIC_KEYLESS_TIMEOUT,30);
		LastKeylessCommand=1;
	}
	else if((Data[0]&0x04)==0x04)
	{
		SecureTakeOver_Unlock();

		// Only send arm command if the timming between 2 keyless code is > 2sec or if the received command is different than before
		// Only send arm command if the timming between 2 keyless code is > 2sec or if the received command is different than before
		if(Periodic_GetState(PERIODIC_KEYLESS_TIMEOUT)||(LastKeylessCommand!=2))
			OEM_Alarm_SetState(OEM_ALARM_DISARM); /*IDL2W_SendOEMAlarmState(OEM_ALARM_DISARM);*/	// Disarm
		Periodic_Enable(PERIODIC_KEYLESS_TIMEOUT,30);
		LastKeylessCommand=2;
	}

	if((Data[2]&0x10)==0x10)
	{
		FOB_Detected = YES;
	}
	else
	{
		FOB_Detected = NO;
	}
}

#if defined(VEHICLEDEBUG_ENABLE)

//****************************************************/
//	Debug Parameter (We can add some if needed)
//****************************************************/
static void NI7_LoadDebugParameters(void)
{
	DebugParameters[0]=0; // NI7
	DebugParameters[1]=NissanPlatform;
	DebugParameterCount=2;
}
#endif

void NI7_BackDoor(void)
{
}

#if defined(IDATASTART)
void NI7_SetDebugInfo(void)
{
	debug_Parameters.count = 1;
	debug_Parameters.info [0] = NissanPlatform+1; // DL platform
}

static void NI7_IdataStart_Init(void)
{
	// Send function to execute for custom config mode
	IDL2W_IDM_AssignCustomAppDebug(NI7_BackDoor);
	IDL2W_IDM_AssignDebugAppDebug(NI7_SetDebugInfo);

	////////////////////////////////////////////////////////////////////////////////
	// Select ignition source for RS and bypass (Low power, high power or data)
	// Check in ignition.h for more source (Source can be updated further in the learn process)
	////////////////////////////////////////////////////////////////////////////////
		//Ignition_SetSource(IGNITION_SOURCE_ANALOG_LP);		// Get and control ignition on Low Power ignition
		Ignition_SetSource(IGNITION_SOURCE_ANALOG_HP);	// Get and control ignition on High Power ignition
		//Ignition_SetSource(IGNITION_SOURCE_CAN);			// Get and control ignition on CAN (GM7/8)
		//Ignition_SetSource(IGNITION_SOURCE_ANALOG_START); // Get and control ignition on start wire (GM10)

		// inform the RS MCU which circuit is use for (Acc/Ignition/Start output)
		//IDL2W_IDM_RsAccess_SelectAccOutput(ACCESSORY_OUTPUT_LOWPOWER);
		IDL2W_IDM_RsAccess_SelectAccOutput(ACCESSORY_OUTPUT_HIPOWER);
		IDL2W_IDM_RsAccess_SelectIgnitionOutput(IGNITION_OUTPUT_HIPOWER);
		IDL2W_IDM_RsAccess_SelectStartOutput(START_OUTPUT_HIPOWER);

	//*****************************************************************
	// These functions overide the RS output state in any source
	// selection (even if RS already control these output )
	//*****************************************************************
	// To control lo current acc output on RS MCU (0=OFF, 1=ON)
	//IDL2W_IDM_RsAccess_SetRsAccOutput(OFF);
	// To control low current ignition output on RS MCU (0=OFF, 1=ON)
	//IDL2W_IDM_RsAccess_SetRsIgnitionOutput(Uint8 state);
	// To control low current starter output on RS MCU (0=OFF, 1=ON)
	//IDL2W_IDM_RsAccess_SetRsStartOutput(Uint8 state);
	//*****************************************************************

		// To attribute a function to POC, to be able to control the output on bypass MCU, select "RS_POC_FUNCTION_OTHERS"
		// Check on
		IDL2W_IDM_RsAccess_SelectEpocFunction(1, RS_POC_FUNCTION_LOCK);		// Control by RS
		IDL2W_IDM_RsAccess_SelectEpocFunction(2, RS_POC_FUNCTION_UNLOCK);	// Control by RS
		IDL2W_IDM_RsAccess_SelectEpocFunction(3, RS_POC_FUNCTION_TRUNK);	// Control by RS
		IDL2W_IDM_RsAccess_SelectEpocFunction(4, RS_POC_FUNCTION_ARM);		// Control by RS
		IDL2W_IDM_RsAccess_SelectEpocFunction(5, RS_POC_FUNCTION_DISARM);	// Control by RS
		//IDL2W_IDM_RsAccess_SelectEpocFunction(5, RS_POC_FUNCTION_OTHERS);	// To be control by app
		// To control EPOC in the case of "control by app"
		//IDL2W_IDM_RsAccess_SetEpocOutput(5, OFF);

}
#endif


text:
package com.intellij.debugger.memory.component;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.components.*;
import com.intellij.openapi.project.Project;
import com.intellij.util.EventDispatcher;
import com.intellij.util.containers.HashMap;
import com.intellij.util.xmlb.annotations.AbstractCollection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import com.intellij.debugger.memory.event.InstancesTrackerListener;
import com.intellij.debugger.memory.tracking.TrackingType;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@State(name = "InstancesTracker", storages = @Storage(StoragePathMacros.WORKSPACE_FILE))
public class InstancesTracker extends AbstractProjectComponent
  implements PersistentStateComponent<InstancesTracker.MyState> {
  private final EventDispatcher<InstancesTrackerListener> myDispatcher =
    EventDispatcher.create(InstancesTrackerListener.class);
  private MyState myState = new MyState();

  public InstancesTracker(Project project) {
    super(project);
  }

  public static InstancesTracker getInstance(@NotNull Project project) {
    return project.getComponent(InstancesTracker.class);
  }

  public boolean isTracked(@NotNull String className) {
    return myState.classes.containsKey(className);
  }

  public boolean isBackgroundTrackingEnabled() {
    return myState.isBackgroundTrackingEnabled;
  }

  @Nullable
  public TrackingType getTrackingType(@NotNull String className) {
    return myState.classes.getOrDefault(className, null);
  }

  @NotNull
  public Map<String, TrackingType> getTrackedClasses() {
    return new HashMap<>(myState.classes);
  }

  public void add(@NotNull String name, @NotNull TrackingType type) {
    if (type.equals(myState.classes.getOrDefault(name, null))) {
      return;
    }

    myState.classes.put(name, type);
    myDispatcher.getMulticaster().classChanged(name, type);
  }

  public void remove(@NotNull String name) {
    TrackingType removed = myState.classes.remove(name);
    if (removed != null) {
      myDispatcher.getMulticaster().classRemoved(name);
    }
  }

  public void addTrackerListener(@NotNull InstancesTrackerListener listener) {
    myDispatcher.addListener(listener);
  }

  public void addTrackerListener(@NotNull InstancesTrackerListener listener, @NotNull Disposable parentDisposable) {
    myDispatcher.addListener(listener, parentDisposable);
  }

  public void removeTrackerListener(@NotNull InstancesTrackerListener listener) {
    myDispatcher.removeListener(listener);
  }

  public void setBackgroundTackingEnabled(boolean state) {
    boolean oldState = myState.isBackgroundTrackingEnabled;
    if (state != oldState) {
      myState.isBackgroundTrackingEnabled = state;
      myDispatcher.getMulticaster().backgroundTrackingValueChanged(state);
    }
  }

  @Nullable
  @Override
  public MyState getState() {
    return new MyState(myState);
  }

  @Override
  public void loadState(MyState state) {
    myState = new MyState(state);
  }

  static class MyState {
    boolean isBackgroundTrackingEnabled = false;

    @AbstractCollection(surroundWithTag = false, elementTypes = {Map.Entry.class}) final Map<String, TrackingType> classes =
      new ConcurrentHashMap<>();

    MyState() {
    }

    MyState(@NotNull MyState state) {
      isBackgroundTrackingEnabled = state.isBackgroundTrackingEnabled;
      for (Map.Entry<String, TrackingType> classState : state.classes.entrySet()) {
        classes.put(classState.getKey(), classState.getValue());
      }
    }
  }
}


text:
package com.hazelcast.core;

/**
 * Type of entry event.
 */
public enum EntryEventType {

    /**
     * Fired if an entry is added.
     */
    ADDED(TypeId.ADDED),

    /**
     * Fired if an entry is removed.
     */
    REMOVED(TypeId.REMOVED),

    /**
     * Fired if an entry is updated.
     */
    UPDATED(TypeId.UPDATED),

    /**
     * Fired if an entry is evicted.
     */
    EVICTED(TypeId.EVICTED),

    /**
     * Fired if an entry is expired.
     */
    EXPIRED(TypeId.EXPIRED),
    /**
     * Fired if all entries are evicted.
     */
    EVICT_ALL(TypeId.EVICT_ALL),

    /**
     * Fired if all entries are cleared.
     */
    CLEAR_ALL(TypeId.CLEAR_ALL),

    /**
     * Fired if an entry is merged after a network partition.
     */
    MERGED(TypeId.MERGED),

    /**
     * Fired if an entry is invalidated.
     */
    INVALIDATION(TypeId.INVALIDATION),

    /**
     * Fired if an entry is loaded.
     */
    LOADED(TypeId.LOADED);

    private int typeId;

    EntryEventType(final int typeId) {
        this.typeId = typeId;
    }

    /**
     * @return the event type ID
     */
    public int getType() {
        return typeId;
    }

    /**
     * @return the matching EntryEventType for the supplied {@code typeId}
     * or {@code null} if there is no match
     */
    @SuppressWarnings("checkstyle:returncount")
    public static EntryEventType getByType(final int typeId) {
        switch (typeId) {
            case TypeId.ADDED:
                return ADDED;
            case TypeId.REMOVED:
                return REMOVED;
            case TypeId.UPDATED:
                return UPDATED;
            case TypeId.EVICTED:
                return EVICTED;
            case TypeId.EVICT_ALL:
                return EVICT_ALL;
            case TypeId.CLEAR_ALL:
                return CLEAR_ALL;
            case TypeId.MERGED:
                return MERGED;
            case TypeId.EXPIRED:
                return EXPIRED;
            case TypeId.INVALIDATION:
                return INVALIDATION;
            case TypeId.LOADED:
                return LOADED;
            default:
                return null;
        }
    }

    /**
     * These constants represent event type ID and bit-mask of events.
     *
     * @see com.hazelcast.map.impl.MapListenerFlagOperator
     */
    @SuppressWarnings("checkstyle:magicnumber")
    private static class TypeId {
        private static final int ADDED = 1;
        private static final int REMOVED = 1 << 1;
        private static final int UPDATED = 1 << 2;
        private static final int EVICTED = 1 << 3;
        private static final int EXPIRED = 1 << 4;
        private static final int EVICT_ALL = 1 << 5;
        private static final int CLEAR_ALL = 1 << 6;
        private static final int MERGED = 1 << 7;
        private static final int INVALIDATION = 1 << 8;
        private static final int LOADED = 1 << 9;
    }
}


text:
package nl.us2.cloudpelican.stormprocessor;

import backtype.storm.Config;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Tuple;
import org.apache.commons.lang.NotImplementedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import storm.starter.util.TupleHelpers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Created by robin on 30/06/15.
 */
public class AbstractSinkBolt extends BaseRichBolt {

    protected HashMap<String, ArrayList<String>> resultAggregator;
    protected OutputCollector _collector;
    protected String sinkId;
    protected Settings settings;
    protected int batchSize;
    protected Executor executor;

    private static final Logger LOG = LoggerFactory.getLogger(AbstractSinkBolt.class);

    public AbstractSinkBolt(String sinkId, Settings settings) {
        this.sinkId = sinkId;
        this.settings = settings;
        this.batchSize = 500;
    }

    public void prepare(Map conf, TopologyContext context, OutputCollector collector) {
        _collector = collector;
        resultAggregator = new HashMap<String, ArrayList<String>>();
        prepareSink(conf, context, collector);
        executor = Executors.newFixedThreadPool(2);
    }

    public void execute(Tuple tuple) {
        if (TupleHelpers.isTickTuple(tuple)) {
            _collector.ack(tuple);
            executeTick();
        } else {
            executeTuple(tuple);
            _collector.ack(tuple);
        }
    }

    protected String _sinkVarPrefix(String k) {
        return "sinks." + sinkId + "." + k;
    }

    public String getSinkVar(String k) {
        return getSinkVarOrDefault(k, null);
    }

    public String getSinkVarOrDefault(String k, String d) {
        String pk = _sinkVarPrefix(k);
        String val = settings.getOrDefault(pk, d);
        LOG.info("Sink var: " + pk + "=" + val);
        return val;
    }

    public boolean isValid() {
        return false;
    }

    public void executeTick() {
        _flush();
    }

    protected void _flush() {
        throw new NotImplementedException();
    }

    public void executeTuple(Tuple tuple) {
        String filterId = tuple.getStringByField("filter_id");
        String msg = tuple.getStringByField("msg");

        // Append in-memory
        if (!resultAggregator.containsKey(filterId)) {
            resultAggregator.put(filterId, new ArrayList<String>());
        }
        resultAggregator.get(filterId).add(msg);

        // Flush auto
        if (resultAggregator.get(filterId).size() >= batchSize) {
            _flush();
        }

        // No ack, is handled in outer
    }

    public Map<String, Object> getComponentConfiguration() {
        Config conf = new Config();
        int tickFrequencyInSeconds = 10;
        conf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, tickFrequencyInSeconds);
        return conf;
    }

    public void prepareSink(Map conf, TopologyContext context, OutputCollector collector) {
    }

    public void declareOutputFields(OutputFieldsDeclarer declarer) {
    }
}


text:
const initData = {
  config: {},
  reports: []
}

const localStorage = global.localStorage
let storage = null

const getData = () => {
  if (!storage) {
    storage = JSON.parse(localStorage.getItem('weeport'))
  }
  const weeport = storage
  if (!weeport) {
    localStorage.setItem('weeport', JSON.stringify(initData))
    return initData
  } else {
    return storage
  }
}

export const save = (key, value) => {
  const data = getData()
  data[key] = Object.assign({}, data[key], value)
  localStorage.setItem('weeport', JSON.stringify(data))
}

export const load = (key, value) => getData()[key]


text:
/******/ (function(modules) { // webpackBootstrap
/******/ 	// install a JSONP callback for chunk loading
/******/ 	function webpackJsonpCallback(data) {
/******/ 		var chunkIds = data[0];
/******/ 		var moreModules = data[1];
/******/ 		var executeModules = data[2];
/******/
/******/ 		// add "moreModules" to the modules object,
/******/ 		// then flag all "chunkIds" as loaded and fire callback
/******/ 		var moduleId, chunkId, i = 0, resolves = [];
/******/ 		for(;i < chunkIds.length; i++) {
/******/ 			chunkId = chunkIds[i];
/******/ 			if(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ 				resolves.push(installedChunks[chunkId][0]);
/******/ 			}
/******/ 			installedChunks[chunkId] = 0;
/******/ 		}
/******/ 		for(moduleId in moreModules) {
/******/ 			if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
/******/ 				modules[moduleId] = moreModules[moduleId];
/******/ 			}
/******/ 		}
/******/ 		if(parentJsonpFunction) parentJsonpFunction(data);
/******/
/******/ 		while(resolves.length) {
/******/ 			resolves.shift()();
/******/ 		}
/******/
/******/ 		// add entry modules from loaded chunk to deferred list
/******/ 		deferredModules.push.apply(deferredModules, executeModules || []);
/******/
/******/ 		// run deferred modules when all chunks ready
/******/ 		return checkDeferredModules();
/******/ 	};
/******/ 	function checkDeferredModules() {
/******/ 		var result;
/******/ 		for(var i = 0; i < deferredModules.length; i++) {
/******/ 			var deferredModule = deferredModules[i];
/******/ 			var fulfilled = true;
/******/ 			for(var j = 1; j < deferredModule.length; j++) {
/******/ 				var depId = deferredModule[j];
/******/ 				if(installedChunks[depId] !== 0) fulfilled = false;
/******/ 			}
/******/ 			if(fulfilled) {
/******/ 				deferredModules.splice(i--, 1);
/******/ 				result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
/******/ 			}
/******/ 		}
/******/
/******/ 		return result;
/******/ 	}
/******/
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// object to store loaded and loading chunks
/******/ 	// undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/ 	// Promise = chunk loading, 0 = chunk loaded
/******/ 	var installedChunks = {
/******/ 		"runtime": 0
/******/ 	};
/******/
/******/ 	var deferredModules = [];
/******/
/******/ 	// script path function
/******/ 	function jsonpScriptSrc(chunkId) {
/******/ 		return __webpack_require__.p + "" + ({"setup-setup-module":"setup-setup-module","tweak-tweak-module":"tweak-tweak-module","firebase-auth":"firebase-auth"}[chunkId]||chunkId) +    "-es5.js"
/******/ 	}
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/ 	// This file contains only the entry chunk.
/******/ 	// The chunk loading function for additional chunks
/******/ 	__webpack_require__.e = function requireEnsure(chunkId) {
/******/ 		var promises = [];
/******/
/******/
/******/ 		// JSONP chunk loading for javascript
/******/
/******/ 		var installedChunkData = installedChunks[chunkId];
/******/ 		if(installedChunkData !== 0) { // 0 means "already installed".
/******/
/******/ 			// a Promise means "currently loading".
/******/ 			if(installedChunkData) {
/******/ 				promises.push(installedChunkData[2]);
/******/ 			} else {
/******/ 				// setup Promise in chunk cache
/******/ 				var promise = new Promise(function(resolve, reject) {
/******/ 					installedChunkData = installedChunks[chunkId] = [resolve, reject];
/******/ 				});
/******/ 				promises.push(installedChunkData[2] = promise);
/******/
/******/ 				// start chunk loading
/******/ 				var script = document.createElement('script');
/******/ 				var onScriptComplete;
/******/
/******/ 				script.charset = 'utf-8';
/******/ 				script.timeout = 120;
/******/ 				if (__webpack_require__.nc) {
/******/ 					script.setAttribute("nonce", __webpack_require__.nc);
/******/ 				}
/******/ 				script.src = jsonpScriptSrc(chunkId);
/******/
/******/ 				// create error before stack unwound to get useful stacktrace later
/******/ 				var error = new Error();
/******/ 				onScriptComplete = function (event) {
/******/ 					// avoid mem leaks in IE.
/******/ 					script.onerror = script.onload = null;
/******/ 					clearTimeout(timeout);
/******/ 					var chunk = installedChunks[chunkId];
/******/ 					if(chunk !== 0) {
/******/ 						if(chunk) {
/******/ 							var errorType = event && (event.type === 'load' ? 'missing' : event.type);
/******/ 							var realSrc = event && event.target && event.target.src;
/******/ 							error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')';
/******/ 							error.name = 'ChunkLoadError';
/******/ 							error.type = errorType;
/******/ 							error.request = realSrc;
/******/ 							chunk[1](error);
/******/ 						}
/******/ 						installedChunks[chunkId] = undefined;
/******/ 					}
/******/ 				};
/******/ 				var timeout = setTimeout(function(){
/******/ 					onScriptComplete({ type: 'timeout', target: script });
/******/ 				}, 120000);
/******/ 				script.onerror = script.onload = onScriptComplete;
/******/ 				document.head.appendChild(script);
/******/ 			}
/******/ 		}
/******/ 		return Promise.all(promises);
/******/ 	};
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "https://google.github.io/tweakr/easyserver/";
/******/
/******/ 	// on error function for async loading
/******/ 	__webpack_require__.oe = function(err) { console.error(err); throw err; };
/******/
/******/ 	var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || [];
/******/ 	var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);
/******/ 	jsonpArray.push = webpackJsonpCallback;
/******/ 	jsonpArray = jsonpArray.slice();
/******/ 	for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);
/******/ 	var parentJsonpFunction = oldJsonpFunction;
/******/
/******/
/******/ 	// run deferred modules from other chunks
/******/ 	checkDeferredModules();
/******/ })
/************************************************************************/
/******/ ([]);
//# sourceMappingURL=runtime-es5.js.map


text:
<?php

namespace app\models;

use dektrium\user\models\Profile as BaseProfile;
use Yii;
use phpDocumentor\Reflection\Types\String_;

class Profile extends BaseProfile
{
    /**
     * Se obtiene la ruta hacia el avatar del usuario, si no tiene se le
     * da un avatar por defecto
     * @return String_ ruta hacia el avatar
     */
    public function getAvatar()
    {
        $uploads = Yii::getAlias('@uploads');
        $ruta = "$uploads/{$this->user_id}.jpg";
        return file_exists($ruta) ? "/$ruta" : "/$uploads/default.jpg";
    }

    /**
     * Se obtiene la ruta hacia el avatar del usuario, si no tiene se le
     * da un avatar por defecto
     * @return String_ ruta hacia el avatar
     */
    public function getAvatarMini()
    {
        $uploads = Yii::getAlias('@uploads');
        $ruta = "$uploads/{$this->user_id}-mini.jpg";
        return file_exists($ruta) ? "/$ruta" : "/$uploads/default-mini.jpg";
    }
}


text:
package de.jungblut.online.stream;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import com.google.common.base.Preconditions;
import com.google.common.collect.AbstractIterator;

/**
 * A shuffled iterator. The implementation buffers a fixed amount of data by
 * consuming the stream, shuffles it and makes it available as a stream again.
 */
public final class ShuffledIterator<T> extends AbstractIterator<T> {

  private final Iterator<T> baseStreamIterator;
  private final int bufferedItems;
  private final List<T> buffer;
  private int currentIndex;

  ShuffledIterator(Stream<T> baseStream, int bufferedItems) {
    Preconditions.checkState(bufferedItems > 0, "bufferedItems > 0");
    Preconditions.checkNotNull(baseStream, "baseStream");

    this.bufferedItems = bufferedItems;
    this.baseStreamIterator = baseStream.iterator();
    this.buffer = new ArrayList<>(bufferedItems);

    bufferAndShuffle();
  }

  @Override
  protected T computeNext() {
    if (currentIndex >= buffer.size()) {
      bufferAndShuffle();
      if (buffer.isEmpty()) {
        return endOfData();
      }
    }

    return buffer.get(currentIndex++);
  }

  public Stream<T> asStream() {
    return StreamSupport.stream(
        Spliterators.spliteratorUnknownSize(this, Spliterator.NONNULL), false);
  }

  private void bufferAndShuffle() {
    buffer.clear();
    currentIndex = 0;
    for (int i = 0; i < bufferedItems; i++) {
      if (baseStreamIterator.hasNext()) {
        buffer.add(baseStreamIterator.next());
      } else {
        break;
      }
    }
    Collections.shuffle(buffer);
  }

  /**
   * Creates a new shuffled iterator to "proxy shuffle" a stream with the given
   * shuffle buffer.
   *
   * @param baseStream the base stream to load elements from.
   * @param bufferedItems the buffer size used to shuffle items.
   * @return a shuffled stream.
   */
  public static <T> Stream<T> fromStream(Stream<T> baseStream, int bufferedItems) {
    return new ShuffledIterator<>(baseStream, bufferedItems).asStream();
  }

}


text:
package org.apache.commons.jcs.jcache.cdi;

import java.io.Serializable;
import java.lang.reflect.Method;
import javax.annotation.Priority;
import javax.cache.Cache;
import javax.cache.annotation.CacheDefaults;
import javax.cache.annotation.CacheKeyInvocationContext;
import javax.cache.annotation.CacheRemove;
import javax.cache.annotation.GeneratedCacheKey;
import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;

@CacheRemove
@Interceptor
@Priority(/*LIBRARY_BEFORE*/1000)
public class CacheRemoveInterceptor implements Serializable
{
    @Inject
    private CDIJCacheHelper helper;

    @AroundInvoke
    public Object cache(final InvocationContext ic) throws Throwable
    {
        final CacheDefaults defaults = helper.findDefaults(ic);

        final Method method = ic.getMethod();
        final CacheRemove cacheRemove = method.getAnnotation(CacheRemove.class);
        final String cacheName = helper.defaultName(method, defaults, cacheRemove.cacheName());
        final boolean afterInvocation = cacheRemove.afterInvocation();

        final CacheKeyInvocationContext<CacheRemove> context =
                new CacheKeyInvocationContextImpl<CacheRemove>(ic, cacheRemove, cacheName, helper.keyParameterIndexes(method));

        if (!afterInvocation)
        {
            doRemove(context, defaults, cacheRemove);
        }

        final Object result;
        try
        {
            result = ic.proceed();
        }
        catch (final Throwable t)
        {
            if (afterInvocation)
            {
                if (helper.isIncluded(t.getClass(), cacheRemove.evictFor(), cacheRemove.noEvictFor()))
                {
                    doRemove(context, defaults, cacheRemove);
                }
            }

            throw t;
        }

        if (afterInvocation)
        {
            doRemove(context, defaults, cacheRemove);
        }

        return result;
    }

    private void doRemove(final CacheKeyInvocationContext<CacheRemove> context, final CacheDefaults defaults, final CacheRemove cacheRemove)
    {
        final Cache<Object, Object> cache = helper.cacheResolverFactoryFor(defaults, cacheRemove.cacheResolverFactory()).getCacheResolver(context).resolveCache(context);
        final GeneratedCacheKey key = helper.cacheKeyGeneratorFor(defaults, cacheRemove.cacheKeyGenerator()).generateCacheKey(context);
        cache.remove(key);
    }
}


text:
<?php

declare(strict_types=1);

namespace Povils\PHPMND\Extension;

use PhpParser\Node;
use Povils\PHPMND\Console\Option;

abstract class Extension
{
    protected Option $option;

    abstract public function extend(Node $node): bool;

    abstract public function getName(): string;

    public function setOption(Option $option)
    {
        $this->option = $option;
    }
}


text:
<?php

namespace Native5\Route\DeviceDetection;
use Symfony\Component\Yaml\Yaml;

/**
 * UA
 *
 * @category  DeviceDetection
 * @package   Native5\Route\DeviceDetection
 * @author    Barada Sahu <barry@native5.com>
 * @copyright 2012 Native5. All Rights Reserved
 * @license   See attached NOTICE.md for details
 * @version   Release: 1.0
 * @link      http://www.docs.native5.com
 * Created : 27-11-2012
 * Last Modified : Fri Dec 21 09:11:53 2012
 */
class UA
{

    private static $ua;

    private static $accept;

    private static $regexes;

    private static $debug    = false; // log requests

    public static $silent    = false; // no output when running UA::get()

    public static $nobackup  = false; // don't create a back-up when running UA::get()

    /**
     * Sets up some standard variables as well as starts the user agent parsing process
     *
     * @return {Object}       the result of the user agent parsing
     */
    public static function parse($ua = NULL) {

        self::$ua      = $ua ? $ua : strip_tags($_SERVER["HTTP_USER_AGENT"]);
        self::$accept  = empty($_SERVER["HTTP_ACCEPT"]) ? '' : strip_tags($_SERVER["HTTP_ACCEPT"]);
        if (empty(self::$regexes)) {
            if (file_exists(__DIR__."/resources/regexes.yaml")) {
                self::$regexes = Yaml::parse(__DIR__."/resources/regexes.yaml");
            } else {
                print "
Error

Please download the regexes.yaml file before using UAParser.php.

You can type the following at the command line to download the latest version:

                    %: cd /path/to/UAParser

                    %: php UAParser.php -get

";
                exit;
            }
        }

        // run the regexes to match things up
        $uaRegexes = self::$regexes['user_agent_parsers'];
        foreach ($uaRegexes as $uaRegex) {
            if ($result = self::uaParser($uaRegex)) {
                $result->uaOriginal = self::$ua;
                break;
            }
        }

        // if no browser was found check to see if it can be matched at least against a device (e.g. spider, generic feature phone or generic smartphone)
        if (!$result) {
            if (($result = self::deviceParser()) && ($result->device != 'Spider')) {
                $result->isMobile       = true;
                $result->isMobileDevice = true;
                $result->uaOriginal     = self::$ua;
            } else if (isset($result) && isset($result->device) && ($result->device == "Spider")) {
                $result->isMobile       = false;
                $result->isSpider       = true;
                $result->uaOriginal     = self::$ua;
            }
        }

        // still false?! see if it's a really dumb feature phone, if not just mark it as unknown
        if (!$result) {
            if ((strpos(self::$accept,'text/vnd.wap.wml') > 0) || (strpos(self::$accept,'application/vnd.wap.xhtml+xml') > 0) || isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE'])) {
                $result = new \stdClass();
                $result->device         = "Generic Feature Phone";
                $result->deviceFull     = "Generic Feature Phone";
                $result->isMobile       = true;
                $result->isMobileDevice = true;
                $result->uaOriginal     = self::$ua;
            } else {
                $result = new \stdClass();
                $result->device         = "Unknown";
                $result->deviceFull     = "Unknown";
                $result->isMobile       = false;
                $result->isMobileDevice = false;
                $result->isComputer     = true;
                $result->uaOriginal     = self::$ua;
            }
        }

        // log the results when testing
        if (self::$debug) {
            self::log($result);
        }

        return $result;
    }

    /**
     * Attemps to see if the user agent matches the regex for this test. If so it populates an obj
     * with properties based on the user agent. Will also try to fetch OS & device properties
     *
     * @param  {Array}        the regex to be tested as well as any extra variables that need to be swapped
     *
     * @return {Object}       the result of the user agent parsing
     */
    private static function uaParser($regex) {

        // tests the supplied regex against the user agent
        if (preg_match("/".str_replace("/","\/",$regex['regex'])."/",self::$ua,$matches)) {

            // Define safe parser defaults
            $defaults = array(
                'isMobileDevice' => false,
                'isMobile' => false,
                'isSpider' => false,
                'isTablet' => false,
                'isComputer' => true,
            );
            // build the obj that will be returned starting with defaults
            $obj = (object) $defaults;

            // build the version numbers for the browser
            if (isset($matches[2]) || isset($regex['v1_replacement'])) {
                $obj->major  = isset($regex['v1_replacement']) ? $regex['v1_replacement'] : $matches[2];
            } else {
                $obj->major = '';
            }
            if (isset($matches[3]) || isset($regex['v2_replacement'])) {
                $obj->minor = isset($regex['v2_replacement']) ? $regex['v2_replacement'] : $matches[3];
            }
            if (isset($matches[4])) {
                $obj->build = $matches[4];
                $obj->patch = $matches[4];
            }
            if (isset($matches[5])) {
                $obj->revision = $matches[5];
            }

            // pull out the browser family. replace the version number if necessary
            $obj->browser = isset($regex['family_replacement']) ? str_replace("$1",$obj->major,$regex['family_replacement']) : $matches[1];
            $obj->family  = isset($regex['family_replacement']) ? str_replace("$1",$obj->major,$regex['family_replacement']) : $matches[1];

            // set-up a clean version number
            $obj->version = isset($obj->major) ? $obj->major : "";
            $obj->version = isset($obj->minor) ? $obj->version.'.'.$obj->minor : $obj->version;
            $obj->version = isset($obj->build) ? $obj->version.'.'.$obj->build : $obj->version;
            $obj->version = isset($obj->revision) ? $obj->version.'.'.$obj->revision : $obj->version;

            // prettify
            $obj->browserFull = $obj->browser;
            if ($obj->version != '') {
                $obj->browserFull .= " ".$obj->version;
            }

            // detect if this is a uiwebview call on iOS
            $obj->isUIWebview = (($obj->browser == 'Mobile Safari') && !strstr(self::$ua,'Safari')) ? true : false;

            // check to see if this is a mobile browser
            $mobileBrowsers = array("Firefox Mobile","Opera Mobile","Opera Mini","Mobile Safari","webOS","IE Mobile","Playstation Portable",
                "Nokia","Blackberry","Palm","Silk","Android","Maemo","Obigo","Netfront","AvantGo","Teleca","SEMC-Browser",
                "Bolt","Iris","UP.Browser","Symphony","Minimo","Bunjaloo","Jasmine","Dolfin","Polaris","BREW","Chrome Mobile",
                "UC Browser","Tizen Browser");
            foreach($mobileBrowsers as $mobileBrowser) {
                if (stristr($obj->browser, $mobileBrowser)) {
                    $obj->isMobile = true;
                    break;
                }
            }

            // figure out the OS for the browser, if possible
            if ($osObj = self::osParser()) {
                $obj = (object) array_merge((array) $obj, (array) $osObj);
            }

            // create an attribute combinining browser and os
            if (isset($obj->osFull) && $obj->osFull) {
                $obj->full = $obj->browserFull."/".$obj->osFull;
            }

            // figure out the device name for the browser, if possible
            if ($deviceObj = self::deviceParser()) {
                $obj = (object) array_merge((array) $obj, (array) $deviceObj);
            }

            // if this is a mobile browser make sure mobile device is set to true
            if ($obj->isMobile) {
                $obj->isMobileDevice = true; // this is going to catch android devices
            } else if ($obj->isMobileDevice) {
                $obj->isMobile = true;       // this will catch some weird htc devices
            }

            // if OS is Android check to see if this is a tablet. won't work on UA strings less than Android 3.0
            // based on: http://googlewebmastercentral.blogspot.com/2011/03/mo-better-to-also-detect-mobile-user.html
            // opera doesn't follow this convention though...
            if ((isset($obj->os) && $obj->os == 'Android') && !strstr(self::$ua, 'Mobile') && !strstr(self::$ua, 'Opera')) {
                $obj->isTablet = true;
                $obj->isMobile = false;
            }

            // some select mobile OSs report a desktop browser. make sure we note they're mobile
            $mobileOSs = array('Windows Phone 6.5','Windows CE','Symbian OS');
            if (isset($obj->os) && in_array($obj->os,$mobileOSs)) {
                $obj->isMobile       = true;
                $obj->isMobileDevice = true;
            }

            if (stristr(self::$ua,"tablet")) {
                $obj->isTablet       = true;
                $obj->isMobileDevice = true;
                $obj->isMobile       = false;
            }

            // record if this is a spider
            $obj->isSpider = (isset($obj->device) && $obj->device == "Spider") ? true : false;

            // record if this is a computer
            $obj->isComputer = (!$obj->isMobile && !$obj->isSpider && !$obj->isMobileDevice) ? true : false;

            return $obj;

        } else {
            return false;
        }
    }

    /**
     * If the user agent is matched in uaParser() it also tries to check the OS and get properties
     *
     * @return {Object}       the result of the os parsing
     */
    private static function osParser() {

        // build the obj that will be returned
        $osObj = new \stdClass();

        // run the regexes to match things up
        $osRegexes = self::$regexes['os_parsers'];
        foreach ($osRegexes as $osRegex) {
            if (preg_match("/".str_replace("/","\/",$osRegex['regex'])."/",self::$ua,$matches)) {

                // Make sure matches 2 and 3 are at least set to null for setting
                // Major and Minor defaults
                if (!isset($matches[1])) { $matches[1] = null; }
                    if (!isset($matches[2])) { $matches[2] = null; }
                        if (!isset($matches[3])) { $matches[3] = null; }

                            // basic properties
                            $osObj->osMajor   = isset($osRegex['os_v1_replacement']) ? $osRegex['os_v1_replacement'] : $matches[2];
                $osObj->osMinor   = isset($osRegex['os_v2_replacement']) ? $osRegex['os_v2_replacement'] : $matches[3];
                if (isset($matches[4])) {
                    $osObj->osBuild = $matches[4];
                    $osObj->osPatch = $matches[4];
                }
                if (isset($matches[5])) {
                    $osObj->osRevision = $matches[5];
                }
                $osObj->os        = isset($osRegex['os_replacement'])    ? str_replace("$1",$osObj->osMajor,$osRegex['os_replacement'])  : $matches[1];
                $osObj->osFamily  = isset($osRegex['os_family'])    ? str_replace("$1",$osObj->osMajor,$osRegex['os_family'])  : $matches[1];

                // os version
                $osObj->osVersion = isset($osObj->osMajor) ? $osObj->osMajor : "";
                $osObj->osVersion = isset($osObj->osMinor) ? $osObj->osVersion.'.'.$osObj->osMinor : $osObj->osVersion;
                $osObj->osVersion = isset($osObj->osBuild) ? $osObj->osVersion.'.'.$osObj->osBuild : $osObj->osVersion;
                $osObj->osVersion = isset($osObj->osRevision) ? $osObj->osVersion.'.'.$osObj->osRevision : $osObj->osVersion;

                // prettify
                $osObj->osFull    = $osObj->os." ".$osObj->osVersion;

                return $osObj;
            }
        }
        return false;
    }

    /**
     * If the user agent is matched in uaParser() it also tries to check the device and get its properties
     *
     * @return {Object}       the result of the device parsing
     */
    private static function deviceParser() {

        // build the obj that will be returned
        $deviceObj = new \stdClass();

        // run the regexes to match things up
        $deviceRegexes = self::$regexes['device_parsers'];
        foreach ($deviceRegexes as $deviceRegex) {
            if (preg_match("/".str_replace("/","\/",$deviceRegex['regex'])."/i",self::$ua,$matches)) {

                // Make sure device matches are null
                // Device Name, Major and Minor defaults
                if (!isset($matches[1])) { $matches[1] = null; }
                    if (!isset($matches[2])) { $matches[2] = null; }
                        if (!isset($matches[3])) { $matches[3] = null; }

                            // basic properties
                            $deviceObj->deviceMajor  = isset($deviceRegex['device_v1_replacement']) ? $deviceRegex['device_v1_replacement'] : $matches[2];
                $deviceObj->deviceMinor  = isset($deviceRegex['device_v2_replacement']) ? $deviceRegex['device_v2_replacement'] : $matches[3];
                $deviceObj->device       = isset($deviceRegex['device_replacement']) ? str_replace("$1",$matches[1],$deviceRegex['device_replacement']) : str_replace("_"," ",$matches[1]);

                // device version?
                $deviceObj->deviceVersion = isset($deviceObj->deviceMajor) ? $deviceObj->deviceMajor : "";
                $deviceObj->deviceVersion = isset($deviceObj->deviceMinor) ? $deviceObj->deviceVersion.'.'.$deviceObj->deviceMinor : $deviceObj->deviceVersion;

                // prettify
                $deviceObj->deviceFull = $deviceObj->device." ".$deviceObj->deviceVersion;

                // check to see if this is a mobile device
                // this isn't really needed because if it matches a mobile browser it'll automatically mark it as a mobile device
                $deviceObj->isMobileDevice = false;
                $mobileDevices  = array("iPhone","iPod","iPad","HTC","Kindle","Lumia","Amoi","Asus","Bird","Dell","DoCoMo","Huawei","i-mate","Kyocera",
                    "Lenovo","LG","Kin","Motorola","Philips","Samsung","Softbank","Palm","HP ","Generic Feature Phone","Generic Smartphone",
                    "Nintendo DSi","Nintendo 3DS","PlayStation Vita");
                foreach($mobileDevices as $mobileDevice) {
                    if (stristr($deviceObj->device, $mobileDevice)) {
                        $deviceObj->isMobileDevice = true;
                        break;
                    }
                }

                // check to see if this is a tablet (not perfect)
                $deviceObj->isTablet = false;
                $tablets = array("Kindle","iPad","Playbook","TouchPad","Dell Streak","Galaxy Tab","Xoom");
                foreach($tablets as $tablet) {
                    if (stristr($deviceObj->device, $tablet)) {
                        $deviceObj->isTablet = true;
                        break;
                    }
                }

                return $deviceObj;
            }
        }
        return false;
    }

    /**
     * Logs the user agent info
     */
    private static function log($data) {
        if (!$data) {
            $data = new \stdClass();
            $data->ua = self::$ua;
        }
        $jsonData = json_encode($data);
        echo $jsonData."\r\n";
        //$fp = fopen(__DIR__."/log/user_agents.log", "a");
        //fwrite($fp, $jsonData."\r\n");
        //fclose($fp);
    }

    /**
     * Gets the latest user agent. Back-ups the old version first. it will fail silently if something is wrong...
     */
    public static function get() {
        if ($data = @file_get_contents("https://raw.github.com/tobie/ua-parser/master/regexes.yaml")) {
            if (file_exists(__DIR__."/resources/regexes.yaml")) {
                if (!self::$nobackup) {
                    if (!self::$silent) { print("backing up old YAML file...\n"); }
                        if (!copy(__DIR__."/resources/regexes.yaml", __DIR__."/resources/regexes.".date("Ymdhis").".yaml")) {
                            if (!self::$silent) { print("back-up failed...\n"); }
                                exit;
                        }
                }
            }
            $fp = fopen(__DIR__."/resources/regexes.yaml", "w");
            fwrite($fp, $data);
            fclose($fp);
            if (!self::$silent) { print("success...\n"); }
        } else {
            if (!self::$silent) { print("failed to get the file...\n"); }
        }
    }
}

if (defined('STDIN') && isset($argv) && isset($argv[1]) && ($argv[1] == '-get')) {
    UA::$silent   = ((isset($argv[2]) && ($argv[2] == '-silent')) || (isset($argv[3]) && ($argv[3] == '-silent'))) ? true : UA::$silent;
    UA::$nobackup = ((isset($argv[2]) && ($argv[2] == '-nobackup')) || (isset($argv[3]) && ($argv[3] == '-nobackup'))) ? true : UA::$nobackup;
    if (!UA::$silent) { print("getting the YAML file...\n"); }
    UA::get();
} else if (defined('STDIN')) {
    //print("You must use the -get flag to use UAParser.php from the command line.\n");
}

?>


text:
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Samples.Blog.Posts.Dtos;

namespace Abp.Samples.Blog.Posts
{
    public interface IPostAppService : IApplicationService
    {
        Task<PagedResultOutput<PostDto>> GetPosts(GetPostsInput input);

        Task CreatePost(CreatePostInput input);
    }
}


text:
<?php

namespace MushroomFramework\Routing;
use \Exception;

class Controller {
	function __construct() {

	}

	public static function make($name) {
		$className = ucfirst($name).'Controller';
		$fileName = "{$className}.php";
		if(is_file(MUSHROOM_DIR_APP_CONTROLLERS.'/'.$fileName)) {
			throw new Exception("file '$fileName' already exists");
		}
		$classString = "<?php\n\nclass $className extends Controller {\n\tpublic function index() {\n\t\t\n\t}\n}";
		file_put_contents(MUSHROOM_DIR_APP_CONTROLLERS.'/'.$fileName, $classString);
		return $fileName;
	}
}


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.sample.castcompanionlibrary"
    android:versionCode="5"
    android:versionName="1.4" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
    </application>

</manifest>


text:
use crate::{agent_error::ImlAgentError, rpm};

pub use rpm::Version;

pub async fn installed(package: String) -> Result<bool, ImlAgentError> {
    rpm::installed(&package).await
}

pub async fn version(package: String) -> Result<Option<Version>, ImlAgentError> {
    rpm::version(&package).await
}


text:
<link rel="import" href="chrome://resources/html/polymer.html">

<link rel="import" href="chrome://resources/cr_elements/chromeos/cr_picture/cr_picture_list.html">
<link rel="import" href="chrome://resources/cr_elements/chromeos/cr_picture/cr_picture_pane.html">
<link rel="import" href="chrome://resources/cr_elements/chromeos/cr_picture/cr_picture_types.html">
<link rel="import" href="chrome://resources/cr_elements/chromeos/cr_picture/png.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="../../i18n_setup.html">
<link rel="import" href="../os_route.html">
<link rel="import" href="../../settings_shared_css.html">
<link rel="import" href="change_picture_browser_proxy.html">
<link rel="import" href="../metrics_recorder.html">

<dom-module id="settings-change-picture">
  <template>

$i18n{changePicturePageDescription}

        <cr-picture-pane id="picturePane"
            camera-present="[[cameraPresent_]]",
            image-src="[[getImageSrc_(selectedItem_)]]"
            image-type="[[getImageType_(selectedItem_)]]"
            discard-image-label="$i18n{discardPhoto}"
            preview-alt-text="$i18n{previewAltText}"
            take-photo-label="$i18n{takePhoto}"
            capture-video-label="$i18n{captureVideo}"
            switch-mode-to-camera-label="$i18n{switchModeToCamera}"
            switch-mode-to-video-label="$i18n{switchModeToVideo}"
            camera-video-mode-enabled="[[cameraVideoModeEnabled_]]"
            on-keys-pressed="onCameraPaneKeysPressed_">
        </cr-picture-pane>

          [[getAuthorCredit_(selectedItem_, defaultImages_)]]

            [[getAuthorWebsite_(selectedItem_, defaultImages_)]]

      <cr-picture-list id="pictureList"
          hidden="[[!defaultImages_]]"
          camera-present="[[cameraPresent_]]"
          default-images="[[getDefaultImages_(defaultImages_,
              firstDefaultImageIndex_)]]"
          selected-item="{{selectedItem_}}"
          choose-file-label="$i18n{chooseFile}"
          old-image-label="[[oldImageLabel_]]"
          profile-image-label="$i18n{profilePhoto}"
          take-photo-label="$i18n{takePhoto}"
          capture-video-label="$i18n{captureVideo}">
      </cr-picture-list>

  </template>

</dom-module>


text:
var tools = require('./tools')
var deck = require('deck')

function chooseLeastBusy(servers, state){

	var counts = {}
	var serverMap = {}

	servers.forEach(function(server){
		serverMap[server.name] = server
		counts[server.name] = 0
	})

	Object.keys(state.run || {}).forEach(function(key){
		var hostname = state.run[key]
		counts[hostname] = counts[hostname] || 0
		counts[hostname]++
	})

	var objs = Object.keys(serverMap || {}).map(function(key){
		return {
			score:counts[key],
			id:key
		}
	})

	objs.sort(tools.sortCandidates)
	objs.reverse()

	var lowScore = null
	objs = objs.filter(function(obj){
		if(lowScore===null){
			lowScore = obj.score
		}
		return obj.score==lowScore
	})

	var obj = deck.pick(objs)
	return serverMap[obj.id]
}

module.exports = chooseLeastBusy


text:
package org.apache.felix.ipojo.handler.temporal.services;

import java.util.Properties;

public interface BarService {

	public boolean bar();

	public Properties getProps();

}


text:
@implementation PeopleAPI

- (void)fetchMeHandler:(INatAPIFetchCompletionCountHandler)done {
    [[Analytics sharedClient] debugLog:@"Network - fetch me from node"];
    NSString *path = @"/v1/users/me";
    [self fetch:path query:nil classMapping:ExploreUser.class handler:done];
}

- (void)setSiteId:(NSInteger)siteId forUserId:(NSInteger)userId handler:(INatAPIFetchCompletionCountHandler)done {
    [[Analytics sharedClient] debugLog:@"Network - set user site via node"];
    NSDictionary *params = @{
                             @"user": @{ @"site_id": @(siteId) },
                             };
    NSString *path = [NSString stringWithFormat:@"/v1/users/%ld", (long)userId];
    [self put:path query:nil params:params classMapping:nil handler:done];
}

- (void)createUserEmail:(NSString *)email login:(NSString *)login password:(NSString *)password siteId:(NSInteger)siteId license:(NSString *)license localeStr:(NSString *)localeStr handler:(INatAPIFetchCompletionCountHandler) done {

    NSDictionary *newUserDict = @{
        @"user": @{
                @"email": email,
                @"login": login,
                @"password": password,
                @"password_confirmation": password,
                @"site_id": @(siteId),
                @"preferred_observation_license": license,
                @"data_transfer_consent": @"true",
                @"pi_consent": @"true",
                @"preferred_photo_license": license,
                @"preferred_sound_license": license,
                @"locale": localeStr,

        },
    };

    NSURL *url = [NSURL URLWithString:@"/users.json" relativeToURL:[NSURL inat_baseURL]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";

    INaturalistAppDelegate *appDelegate = (INaturalistAppDelegate *)[[UIApplication sharedApplication] delegate];
    LoginController *loginController = appDelegate.loginController;
    [request addValue:[loginController anonymousJWT] forHTTPHeaderField:@"Authorization"];

    NSError *error = nil;
    NSData *JSONData = [NSJSONSerialization dataWithJSONObject:newUserDict options:0 error:nil];
    if (error) {
        done(nil, 0, error);
    } else {
        request.HTTPBody = JSONData;
        [request addValue:[[NSUserDefaults standardUserDefaults] stringForKey:INatTokenPrefKey]
       forHTTPHeaderField:@"Authorization"];
        [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {\
            if (error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    done(nil, 0, error);
                });
            } else {
                NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
                if (httpResponse.statusCode == 200) {

                    NSError *jsonError = nil;
                    id json = [NSJSONSerialization JSONObjectWithData:data
                                                              options:NSJSONReadingAllowFragments
                                                                error:&jsonError];

                    if (jsonError) {
                        // can't parse the json, so we can't get a userid
                        // and finish creating the new user, so bail.
                        dispatch_async(dispatch_get_main_queue(), ^{
                            done(nil, 0, jsonError);
                        });
                    } else {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            done(@[ json ], 1, nil);
                        });
                    }
                } else {
                    // some type of server error, check for JSON text in the response
                    NSError *jsonError = nil;
                    id json = [NSJSONSerialization JSONObjectWithData:data
                                                              options:NSJSONReadingAllowFragments
                                                                error:&jsonError];
                    if (jsonError) {
                        // can't parse the json response, but not 200, so we can't say we succeeded
                        NSError *error = [NSError errorWithDomain:@"org.inaturalist.api.http"
                                                             code:httpResponse.statusCode
                                                         userInfo:nil];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            done(nil, 0, error);
                        });
                    }
                    if ([json valueForKey:@"errors"]) {
                        NSArray *errors = [json valueForKey:@"errors"];
                        NSString *firstErrorText = [errors firstObject];
                        if (firstErrorText) {
                            NSDictionary *userInfo = @{
                                                       NSLocalizedDescriptionKey: firstErrorText,
                                                       };
                            NSError *error = [NSError errorWithDomain:@"org.inaturalist.api.http"
                                                                 code:httpResponse.statusCode
                                                             userInfo:userInfo];
                            dispatch_async(dispatch_get_main_queue(), ^{
                                done(nil, 0, error);
                            });
                        } else {
                            // error array was empty, but not 200, so we can't say we succeeded
                            NSError *error = [NSError errorWithDomain:@"org.inaturalist.api.http"
                                                                 code:httpResponse.statusCode
                                                             userInfo:nil];
                            dispatch_async(dispatch_get_main_queue(), ^{
                                done(nil, 0, error);
                            });
                        }
                    } else if ([json valueForKey:@"message"]) {
                        NSArray *message = [json valueForKey:@"message"];
                        NSDictionary *userInfo = @{
                                                   NSLocalizedDescriptionKey: message,
                                                   };
                        NSError *error = [NSError errorWithDomain:@"org.inaturalist.api.http"
                                                             code:httpResponse.statusCode
                                                         userInfo:userInfo];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            done(nil, 0, error);
                        });
                    } else {
                        // no error array, but not 200, so we can't say we succeeded
                        NSError *error = [NSError errorWithDomain:@"org.inaturalist.api.http"
                                                             code:httpResponse.statusCode
                                                         userInfo:nil];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            done(nil, 0, error);
                        });
                    }
                }
            }
        }] resume];
    }
}

- (void)removeProfilePhotoForUserId:(NSInteger)userId handler:(INatAPIFetchCompletionCountHandler)done {
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"/users/%ld.json", (long)userId]
                        relativeToURL:[NSURL inat_baseURL]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"PUT";

    NSDictionary *dictionary = @{ @"icon_delete" : @(YES) };
    NSError *error = nil;
    NSData *JSONData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:nil];
    if (error) {
        done(nil, 0, error);
    } else {
        request.HTTPBody = JSONData;
        [request addValue:[[NSUserDefaults standardUserDefaults] stringForKey:INatTokenPrefKey]
       forHTTPHeaderField:@"Authorization"];
        [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (error) {
                    done(nil, 0, error);
                } else {
                    done(@[], 0, nil);
                }
            });
        }] resume];
    }
}

- (void)uploadProfilePhoto:(UIImage *)image forUserId:(NSInteger)userId handler:(INatAPIFetchCompletionCountHandler)done {
    NSData *imageData = UIImageJPEGRepresentation(image, 0.8f);
    if (imageData) {
        // use afnetworking to deal with icky multi-part forms
        NSString *path = [NSString stringWithFormat:@"/users/%ld.json", (long)userId];
        NSString *urlString = [[NSURL URLWithString:path relativeToURL:[NSURL inat_baseURL]] absoluteString];

        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager.requestSerializer setValue:[[NSUserDefaults standardUserDefaults] stringForKey:INatTokenPrefKey]
                         forHTTPHeaderField:@"Authorization"];

        NSError *error = nil;
        NSURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:@"PUT" URLString:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            [formData appendPartWithFileData:imageData
                                        name:@"user[icon]"
                                    fileName:@"icon.jpg"
                                    mimeType:@"image/jpeg"];
        } error:&error];

        NSURLSessionDataTask *task = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
            if (error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    done(@[], 0, error);
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    done(@[], 0, nil);
                });
            }
        }];
        [task resume];
    }
}

- (void)setUsername:(NSString *)username forUserId:(NSInteger)userId handler:(INatAPIFetchCompletionCountHandler)done {
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"/users/%ld.json", (long)userId]
                        relativeToURL:[NSURL inat_baseURL]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"PUT";

    NSDictionary *dictionary = @{ @"login" : username };
    NSError *error = nil;
    NSData *JSONData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:nil];
    if (error) {
        done(nil, 0, error);
    } else {
        request.HTTPBody = JSONData;
        [request addValue:[[NSUserDefaults standardUserDefaults] stringForKey:INatTokenPrefKey]
       forHTTPHeaderField:@"Authorization"];
        [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

            // no response data, assume we couldn't change username
            if (!data) {
                done(@[], 0, nil);
            }

            if ([httpResponse statusCode] != 200) {
                NSError *jsonError;
                NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data
                                                                           options:NSJSONReadingAllowFragments
                                                                             error:&jsonError];
                if (!jsonError && [dictionary valueForKey:@"errors"]) {
                    // this error comes back as { errors: { key: ( valueError ) } }
                    NSDictionary *errors = [dictionary valueForKey:@"errors"];
                    NSString *errorKey = [[errors allKeys] firstObject];
                    NSArray *errorValues = (NSArray *)errors[errorKey];
                    NSString *errorString = [NSString stringWithFormat:@"%@ %@", errorKey, [errorValues firstObject]];
                    NSDictionary *info = @{NSLocalizedDescriptionKey: errorString };
                    NSError *error = [NSError errorWithDomain:@"org.inaturalist.ios"
                                                         code:[httpResponse statusCode]
                                                     userInfo:info];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        done(nil, 0, error);
                    });
                }
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (error) {
                        done(nil, 0, error);
                    } else {
                        done(@[], 0, nil);
                    }
                });
            }
        }] resume];
    }

}

- (void)setEmailAddress:(NSString *)email forUserId:(NSInteger)userId handler:(INatAPIFetchCompletionCountHandler)done {
    [[Analytics sharedClient] debugLog:@"Network - set email address via node"];
    NSDictionary *params = @{
                             @"user": @{ @"email": email },
                             };
    NSString *path = [NSString stringWithFormat:@"/v1/users/%ld", (long)userId];
    [self put:path query:nil params:params classMapping:nil handler:done];
}

- (void)setPrefersNoTracking:(BOOL)preference forUserId:(NSInteger)userId handler:(INatAPIFetchCompletionCountHandler)done {

    [[Analytics sharedClient] debugLog:@"Network - set tracking preference via node"];
    NSDictionary *params = @{
        @"user": @{ @"prefers_no_tracking": preference ? @"true" : @"false" }
    };
    NSString *path = [NSString stringWithFormat:@"/v1/users/%ld", (long)userId];
    [self put:path query:nil params:params classMapping:nil handler:done];
}

- (void)setPrefersShowCommonNames:(BOOL)preference forUserId:(NSInteger)userId handler:(INatAPIFetchCompletionCountHandler)done {

    [[Analytics sharedClient] debugLog:@"Network - set show common names preference via node"];
    NSDictionary *params = @{
        @"user": @{ @"prefers_common_names": preference ? @"true" : @"false" }
    };
    NSString *path = [NSString stringWithFormat:@"/v1/users/%ld", (long)userId];
    [self put:path query:nil params:params classMapping:nil handler:done];
}

- (void)setPrefersShowScientificNamesFirst:(BOOL)preference forUserId:(NSInteger)userId handler:(INatAPIFetchCompletionCountHandler)done {

    [[Analytics sharedClient] debugLog:@"Network - set show scientific names first preference via node"];
    NSDictionary *params = @{
        @"user": @{ @"prefers_scientific_name_first": preference ? @"true" : @"false" }
    };
    NSString *path = [NSString stringWithFormat:@"/v1/users/%ld", (long)userId];
    [self put:path query:nil params:params classMapping:nil handler:done];
}

- (void)setPiConsent:(BOOL)piConsent dtConsent:(BOOL)dtConsent forUserId:(NSInteger)userId handler:(INatAPIFetchCompletionCountHandler)done {
    [[Analytics sharedClient] debugLog:@"Network - set pi & dt consent via node"];
    NSDictionary *params = @{
        @"user": @{
            @"pi_consent": piConsent ? @"true" : @"false",
            @"data_transfer_consent": dtConsent ? @"true" : @"false",
        }
    };
    NSString *path = [NSString stringWithFormat:@"/v1/users/%ld", (long)userId];
    [self put:path query:nil params:params classMapping:nil handler:done];
}

@end


text:
using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace tdyctw.Server.Sandbox
{
    public class SandboxHub : Hub
    {
        public void JoinGame(string player)
        {
            var version = SandboxStorage.GetParameter("appversion");
            var message = string.Format("Player {0} joined server with version {1}", player, version);
            Clients.All.broadcastJoinGame(message);
        }
    }
}