text:
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "Ethereal.h"
#include "Widgets/Tutorial.h"
#include "UndeadWarrior.h"

#define LOCTEXT_NAMESPACE "EtherealText"

// Sets default values
AUndeadWarrior::AUndeadWarrior(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
	static ConstructorHelpers::FObjectFinder<USkeletalMesh> EnemyMesh(TEXT("SkeletalMesh'/Game/EtherealParty/Skeleton/mSkeleton.mSkeleton'"));
	static ConstructorHelpers::FObjectFinder<UClass> AnimBP(TEXT("AnimBlueprint'/Game/EtherealParty/Skeleton/Skeleton_AnimBP.Skeleton_AnimBP_C'"));
	static ConstructorHelpers::FObjectFinder<USoundCue> DeathAudioObject(TEXT("SoundCue'/Game/Audio/Party/SoulEater_Death_Cue.SoulEater_Death_Cue'"));

	S_DeathAudio = DeathAudioObject.Object;

	// Default Config
	Name = EEnemyNames::EN_UndeadWarrior;
	NameText = LOCTEXT("UndeadWarriorText", "Undead Warrior");
	Realm = ERealms::R_Arcadia;
	BattleType = EBattleTypes::BT_Standard;
	CommonDrop = EMasterGearList::GL_None;
	UncommonDrop = EMasterGearList::GL_Potion;
	RareDrop = EMasterGearList::GL_Ether;
	AttackDelay = 3.0f;
	BaseEyeHeight = 16;
	GetCapsuleComponent()->SetRelativeScale3D(FVector(0.2f, 0.2f, 0.2f));
	GetCharacterMovement()->MaxAcceleration = 30;
	GetCharacterMovement()->RotationRate = FRotator(0, 5, 0);  // seems to do nothing?

	// Pawn A.I. config
	PawnSensing->HearingThreshold = 400;
	PawnSensing->LOSHearingThreshold = 500;
	PawnSensing->SightRadius = 500;
	PawnSensing->SetPeripheralVisionAngle(40.0f);
	AcceptanceRadius = 50.0f;
	RunAI = false;

	// Mesh Config
	GetMesh()->SkeletalMesh = EnemyMesh.Object;
	GetMesh()->SetAnimInstanceClass(AnimBP.Object);
	GetMesh()->SetRelativeScale3D(FVector(1, 1, 1));
	GetMesh()->SetRelativeLocation(FVector(0, 0, -90));
	GetMesh()->SetRelativeRotation(FRotator(0, -90, 0));

	// Melee Radius Config
	MeleeRadius->SetSphereRadius(100);
	MeleeRadius->SetRelativeLocation(FVector(50, 0, 0));

	// Targeting Reticle config
	TargetingReticle->SetRelativeLocation(FVector(0, 0, 215));
	TargetingReticle->SetRelativeRotation(FRotator(0, 0, 180));
	TargetingReticle->SetRelativeScale3D(FVector(0.2f, 0.2f, 0.2f));

	// Death FX Config
	DeathFX->SetRelativeLocation(FVector(0, 0, -90));
	DeathFX->SetRelativeScale3D(FVector(0.8f, 0.8f, 0.8f));
	HitFX->SetRelativeLocation(FVector(0, 0, 40));
	DisappearFX->SetRelativeLocation(FVector(0, 0, -20));

	// Enemy-Specific Object Config
	DeathAudio = ObjectInitializer.CreateDefaultSubobject<UAudioComponent>(this, TEXT("DeathAudio"));
	DeathAudio->Sound = S_DeathAudio;
	DeathAudio->bAutoActivate = false;
	DeathAudio->SetupAttachment(RootComponent);
}

// Called when the game starts or when spawned
void AUndeadWarrior::BeginPlay()
{
	Super::BeginPlay();

	PawnSensing->OnHearNoise.AddDynamic(this, &AUndeadWarrior::OnHearNoise);  // bind the OnHearNoise event
	PawnSensing->OnSeePawn.AddDynamic(this, &AUndeadWarrior::OnSeePawn);  // bind the OnSeePawn event
	OnDeath.AddDynamic(this, &AUndeadWarrior::CustomDeath); // bind the death fuction to the OnDeath event
	OnReachedTarget.AddDynamic(this, &AUndeadWarrior::MeleeAttack);  // bind the attack function to the OnReachedTarget event

	// Get the Gatekeeper actor, so this enemy has a reference to it for tutorial progression
	for (TActorIterator<AGatekeeper> ActorItr(GetWorld()); ActorItr; ++ActorItr)
	{
		Gatekeeper = *ActorItr; // get the instance of the Gatekeeper actor
	}
}

// Called every frame
void AUndeadWarrior::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
}

void AUndeadWarrior::MeleeAttack()
{
	EnemyDealDamage(10);
	Attack = true;
}

void AUndeadWarrior::CustomDeath()
{
	DeathAudio->Play();  // Play death audio
	//Target->EtherealPlayerState->EnemyKillReward(Level, CommonDrop, UncommonDrop, RareDrop);  // reward the player for killing this enemy

	if (!Target->EtherealPlayerState->HasCompletedTutorial)  // don't bother running this code if the player has completed the tutorial
	{
		if (Gatekeeper)  // be sure Gatekeeper reference isn't NULL
		{
			if (Gatekeeper->Tutorial)  // be sure the Tutorial widget isn't NULL
			{
				if (Target->AggroList.Num() == 0)  // only progress with this function if the aggro list is empty
				{
					if (Gatekeeper->Tutorial->TutorialIndex == 2)  // you killed this enemy while on the proper TutorialIndex, so we progress the Tutorial
					{
						FTimerHandle ConvoTimer;
						GetWorldTimerManager().SetTimer(ConvoTimer, this, &AUndeadWarrior::ShowTutorialConvo, 2.5f, false);
					}
				}
			}
		}
	}
}

void AUndeadWarrior::ShowTutorialConvo()
{
	Gatekeeper->Tutorial->ShowConversation_05();  // show the Consumable Item tutorial panel
}

void AUndeadWarrior::OnHearNoise(APawn* PawnInstigator, const FVector& Location, float Volume)
{
	if (!IsDead)
	{
		if (!IsAggroed)
		{
			//Aggro(PawnInstigator);

			IsAggroed = true;

			// Delay Aggro so the skeleton can get up from the ground
			FTimerDelegate DelegateAggro;
			DelegateAggro.BindUFunction(this, FName("Aggro"), PawnInstigator);
			FTimerHandle AggroTimer;
			GetWorldTimerManager().SetTimer(AggroTimer, DelegateAggro, 2.5f, false);
		}
	}
}

void AUndeadWarrior::OnSeePawn(APawn* Pawn)
{
	if (!IsDead)
	{
		if (!IsAggroed)
		{
			//Aggro(Pawn);

			IsAggroed = true;

			// Delay Aggro so the skeleton can get up from the ground
			FTimerDelegate DelegateAggro;
			DelegateAggro.BindUFunction(this, FName("Aggro"), Pawn);
			FTimerHandle AggroTimer;
			GetWorldTimerManager().SetTimer(AggroTimer, DelegateAggro, 2.5f, false);
		}
	}
}

#undef LOCTEXT_NAMESPACE


text:
'use strict';

function stringToRegex(string) {

  string = string.replace(/[àáâäãåā]/gi, "[àáâäãåāa]");
  string = string.replace(/[èéêëēėę]/gi, "[èéêëēėęe]");
  string = string.replace(/[îïíīįì]/gi, "[îïíīįìi]");
  string = string.replace(/[ôöòóøōõ]/gi, "[ôöòóøōõo]");
  string = string.replace(/[ûüùúū]/gi, "[ûüùúūu]");

  var re = new RegExp(string, "gi");

  return re;
}

exports.stringsToRegexes = function (strings) {
  var regexes = [];

  strings.forEach(function (string) {
    regexes.push(stringToRegex(string));
  });

  return (regexes);
}

exports.getMessage = function (messages, default_message) {
  if (messages !== undefined && messages != null) {
    if (Object.prototype.toString.call(messages) === '[object Array]')
      return messages[Math.floor(Math.random()*messages.length)];
    else if (typeof messages == "string")
      return messages;
  }
  return default_message; // Default message
}

redpajama_set_name: RedPajamaGithub


text:
namespace content {

void InitializeMojo() {
  mojo::embedder::Init();
  mojo::ApplicationManager::GetInstance();
}

}  // namespace content


text:
import type {ReactElement, ReactNode} from 'react';
import type {Size} from './types';

import React, {useMemo} from 'react';
import {isUndefined} from './helpers';

export type GradientProps = {
    id?: string;
    idPrefix?: string;
    type?: 'linear' | 'radial';
    spreadMethod?: 'pad' | 'repeat' | 'reflect';
    gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
    gradientTransform?: string;
    /**
     * For type=linear
     */
    from?: [Size, Size];
    /**
     * For type=linear
     */
    to?: [Size, Size];
    x1?: Size;
    y1?: Size;
    x2?: Size;
    y2?: Size;
    /**
     * For type=radial
     */
    center?: [Size, Size];
    /**
     * For type=radial
     */
    focalPoint?: [Size, Size];
    cx?: Size;
    cy?: Size;
    fx?: Size;
    fy?: Size;
    r?: Size;
    radius?: Size;
    children?: ReactNode;
}

let counter = 0;

/**
 * Wrapper around standard svg linearGradient and radialGradient.
 */
export function Gradient(
    {
        type = 'linear',
        idPrefix = 'chartGradient',
        gradientUnits = 'objectBoundingBox',
        spreadMethod = 'pad',
        // for linear gradient
        from = ['0%', '0%'],
        to = ['100%', '0%'],
        // for radial gradient
        center = ['50%', '50%'],
        ...props
    }: GradientProps
): ReactElement {
    const id = useMemo(() => {
        if (props.id) {
            return props.id;
        }
        counter++;
        return idPrefix + counter;
    }, [props.id, idPrefix]);

    if (type === 'radial') {
        const {
            focalPoint, radius, gradientTransform, cx, cy, fx, fy, r
        } = props;

        const _cx = isUndefined(cx) ? (center && center[0]) : cx;
        const _cy = isUndefined(cy) ? (center && center[1]) : cy;
        const _fx = isUndefined(fx) ? (focalPoint && focalPoint[0]) : fx;
        const _fy = isUndefined(fy) ? (focalPoint && focalPoint[1]) : fy;
        const _r = isUndefined(r) ? radius : r;

        return <radialGradient
            id={id}
            gradientUnits={gradientUnits} gradientTransform={gradientTransform} spreadMethod={spreadMethod}
            cx={_cx} cy={_cy} fx={_fx} fy={_fy} r={_r}>
            {props.children}
        </radialGradient>;

    } else {

        const {gradientTransform, x1, y1, x2, y2} = props;

        const _x1 = isUndefined(x1) ? (from && from[0]) : x1;
        const _y1 = isUndefined(y1) ? (from && from[1]) : y1;
        const _x2 = isUndefined(x2) ? (to && to[0]) : x2;
        const _y2 = isUndefined(y2) ? (to && to[1]) : y2;

        return <linearGradient
            id={id}
            gradientUnits={gradientUnits} gradientTransform={gradientTransform} spreadMethod={spreadMethod}
            x1={_x1} y1={_y1} x2={_x2} y2={_y2}>
            {props.children}
        </linearGradient>;
    }
}


text:
function Module() {
    isReadDataArrived = true;
    isConnected = true;
    isTemp = true; // add by kjs 20170824 // is address 21 value 8?
    this.addressToRead = [];
    this.varTimeout = null;

    this.prevInstruction = 0;
    this.prevAddress = [];
    this.prevLength = [];
    this.prevValue = [];

    this.servoPrevAddres = []; // add by kjs 20170627
    this.servoPrevLength = []; // add by kjs 20170627
    this.servoPrevValue = []; // add by kjs 20170627
    this.servoPrevAddres2 = []; // add by kjs 20170627
    this.servoPrevLength2 = []; // add by kjs 20170627
    this.servoPrevValue2 = []; // add by kjs 20170627
    this.servoPrevAddres3 = []; // add by kjs 20170627
    this.servoPrevLength3 = []; // add by kjs 20170627
    this.servoPrevValue3 = []; // add by kjs 20170627
    this.servoPrevAddres4 = []; // add by kjs 20170627
    this.servoPrevLength4 = []; // add by kjs 20170627
    this.servoPrevValue4 = []; // add by kjs 20170627

    this.receiveBuffer = []; // buffer to receive from H/W
    this.dataBuffer = []; // saved sensor value buffer
    this.robotisBuffer = []; // buffer to save 'ROBOTIS_DATA'
    this.receiveAddress = -1; // to check read packet
    this.receiveLength = -1; // to check read packet
    this.defaultLength = -1; // to check read packet

    this.isFront = 32; // add by kjs 170511
    this.prevRightValue = 0;
    this.prevLeftValue = 0;
    this.isRight = false;

    //this.touchSensor = 0;
    this.humidity = [];
    this.temperature = [];
    this.colorSensor = [];
    this.touchSensor = [];
    this.irSensor = [];
    this.lightSensor = [];
    this.detectedSound = 0;
    this.detectringSound = 0;
    this.userButtonState = 0;
    this.isUpdate = []; // add by kjs 170623
    this.prevState = []; // add by kjs 170623
}

Module.prototype.init = function(handler, config) {
    //console.log("######### init");

};

Module.prototype.lostController = function(self, callback) {
    self.timer = setInterval(function() {
        if (self.connected) {
            if (self.received == false) {
                if (isConnected == false) {
                    self.connected = false;
                    if (callback) {
                        callback('lost');
                    }
                }
                isConnected = false;
            }
            self.received = false;
        }
    }, 1000);
};

Module.prototype.requestInitialData = function() {
    //console.log("######### requestInitialData");
    isReadDataArrived = true;
    isConnected = true;
    isTemp = true; // add by kjs 20170824
    this.addressToRead = [];
    this.varTimeout = null;

    this.prevInstruction = 0;
    this.prevAddress = [];
    this.prevLength = [];
    this.prevValue = [];

    this.servoPrevAddres = [];
    this.servoPrevLength = [];
    this.servoPrevValue = [];

    this.receiveBuffer = [];
    this.dataBuffer = [];
    this.robotisBuffer = [];
    this.receiveAddress = -1;
    this.receiveLength = -1;
    this.defaultLength = -1;

    var sendbuffer = null;

    //this.touchSensor = 0;
    this.colorSensor = [];
    this.temperature = [];
    this.humidity = [];
    this.touchSensor = [];
    this.irSensor = [];
    this.lightSensor = [];
    this.detectedSound = 0;
    this.detectringSound = 0;
    this.userButtonState = 0;

    this.servoPrevAddres = []; // add by kjs 20170627
    this.servoPrevLength = []; // add by kjs 20170627
    this.servoPrevValue = [];  // add by kjs 20170627
    this.servoPrevAddres2 = []; // add by kjs 20170627
    this.servoPrevLength2 = []; // add by kjs 20170627
    this.servoPrevValue2 = [];  // add by kjs 20170627
    this.servoPrevAddres3 = []; // add by kjs 20170627
    this.servoPrevLength3 = []; // add by kjs 20170627
    this.servoPrevValue3 = [];  // add by kjs 20170627
    this.servoPrevAddres4 = []; // add by kjs 20170627
    this.servoPrevLength4 = []; // add by kjs 20170627
    this.servoPrevValue4 = [];  // add by kjs 20170627

    this.robotisBuffer.push([INST_WRITE, 21, 2, 20]);
    this.robotisBuffer.push([INST_WRITE, 20, 1, 1]);

    return this.readPacket(200, 0, 2);
};

Module.prototype.checkInitialData = function(data, config) {
    console.log("######### checkInitialData");

    return true;
};

Module.prototype.validateLocalData = function(data) {
    return true;
};

Module.prototype.requestRemoteData = function(handler) {

    for (var indexA = 0; indexA < this.dataBuffer.length; indexA++) { // 일반형
        if (this.dataBuffer[indexA] != undefined) {
            handler.write(indexA, this.dataBuffer[indexA]);
        }
    }
    //실과형
    //console.log("###### value : " + this.detectedSound);
    for (var i = 0; i < 4; i++) {
        handler.write('TOUCH' + i, this.touchSensor[i]); // 접촉 센서
        handler.write('IR' + i, this.irSensor[i]); // 적외선 센서
        handler.write('LIGHT' + i, this.lightSensor[i]); // 조도 센서
        handler.write('COLOR' + i, this.colorSensor[i]); // 칼라 센서
        handler.write('HUMIDTY' + i, this.humidity[i]); // 습도 센서
        handler.write('TEMPERATURE' + i, this.temperature[i]); // 온도 센서
    }
    handler.write('DETECTEDSOUNDE', this.detectedSound); // 최종 소리 감지 횟수
    handler.write('DETECTINGSOUNDE1', this.detectringSound); // 실시간 소리 감지 횟수
    handler.write('USERBUTTONSTATE', this.userButtonState);

};

Module.prototype.handleRemoteData = function(handler) {
    var data = handler.read('ROBOTIS_DATA');

    var setZero = handler.read('setZero');
    if (setZero[0] == 1) {
        this.robotisBuffer = [];

        this.servoPrevAddres = []; // add by kjs 20170627
        this.servoPrevLength = []; // add by kjs 20170627
        this.servoPrevValue = [];  // add by kjs 20170627
        this.servoPrevAddres2 = []; // add by kjs 20170627
        this.servoPrevLength2 = []; // add by kjs 20170627
        this.servoPrevValue2 = [];  // add by kjs 20170627
        this.servoPrevAddres3 = []; // add by kjs 20170627
        this.servoPrevLength3 = []; // add by kjs 20170627
        this.servoPrevValue3 = [];  // add by kjs 20170627
        this.servoPrevAddres4 = []; // add by kjs 20170627
        this.servoPrevLength4 = []; // add by kjs 20170627
        this.servoPrevValue4 = [];  // add by kjs 20170627

    }
    for (var index = 0; index < data.length; index++) {
        var instruction = data[index][0];
        var address = data[index][1];
        var length = data[index][2];
        var value = data[index][3];
        var doSend = false;
        //console.log("###2 : " + address + " and : " + value + " instruction : " + instruction + " length : " + length);
        if (instruction == INST_NONE) {
            doSend = false;
        } else if (instruction == INST_READ) {
            if (isReadDataArrived == false &&
                this.prevInstruction == INST_READ &&
                this.prevAddress == address &&
                this.prevLength == length &&
                this.prevValue == value) {
                doSend = false;
            } else {
                doSend = true;
            }
        } else if (instruction == INST_WRITE) {
            if (this.prevInstruction == INST_WRITE &&
                this.prevAddress == address &&
                this.prevLength == length &&
                this.prevValue == value && address != 86) {
                doSend = false;
            } else {
                if (this.prevServoCompare(address, value, length)) {

                } else {
                    doSend = true;
                }
            }
        }
        //console.log("dosend : " + doSend);
        if (doSend) {
            for (var indexA = 0; indexA < this.robotisBuffer.length; indexA++) {
                if (data[index][0] == this.robotisBuffer[indexA][0] &&
                    data[index][1] == this.robotisBuffer[indexA][1] &&
                    data[index][2] == this.robotisBuffer[indexA][2] &&
                    data[index][3] == this.robotisBuffer[indexA][3]) {
                    doSend = false;
                    break;
                }
            }
        }
        if(instruction == 4 || instruction == 5 || instruction == 6) {
			doSend = true;
		}
        if (!doSend) {
            continue;
        }

        if (setZero[0] == 1) {
            this.prevInstruction = 0;
            this.prevAddress = [];
            this.prevLength = [];
            this.prevValue = [];

            this.servoPrevAddres = []; // add by kjs 20170627
            this.servoPrevLength = []; // add by kjs 20170627
            this.servoPrevValue = [];  // add by kjs 20170627
            this.servoPrevAddres2 = []; // add by kjs 20170627
            this.servoPrevLength2 = []; // add by kjs 20170627
            this.servoPrevValue2 = [];  // add by kjs 20170627
            this.servoPrevAddres3 = []; // add by kjs 20170627
            this.servoPrevLength3 = []; // add by kjs 20170627
            this.servoPrevValue3 = [];  // add by kjs 20170627
            this.servoPrevAddres4 = []; // add by kjs 20170627
            this.servoPrevLength4 = []; // add by kjs 20170627
            this.servoPrevValue4 = [];  // add by kjs 20170627
        } else {
            this.prevInstruction = instruction;
            this.prevAddress = address;
            this.prevLength = length;
            this.prevValue = value;
            this.prevServoSet(address, value, length);
        }

        if (instruction == INST_WRITE || instruction == INST_DXL_SYNCWRITE || instruction == INST_DXL_REGWRITE || instruction == INST_DXL_ACTION) {
            this.robotisBuffer.push(data[index]);
        } else if (instruction == INST_READ) {
            if (this.addressToRead[address] == undefined || this.addressToRead[address] == 0) {
                this.addressToRead[address] = 1;
                this.robotisBuffer.push(data[index]);
            } else {
                // 10번 이상 읽지 못한다면 에러이므로 강제로 읽을 수 있도록 처리
                this.addressToRead[address] += 1;
                if (this.addressToRead[address] >= 10) {
                    this.addressToRead[address] = 0;
                }
            }
        }
    }
};

Module.prototype.requestLocalData = function() {
    var sendBuffer = null;
    var dataLength = 0;
    if (isReadDataArrived == false) {
        //console.log("######## 1");
        return sendBuffer;
    }
    /////////////////
    isConnected  = true;
    if (!isConnected) {
        this.receiveAddress = -1;
        return this.readPacket(200, 0, 2);
    }

        if (!isTemp) { // add by kjs 20170824
            sendBuffer = this.writeBytePacket(200, 21, 8);

        dataLength = this.makeWord(sendBuffer[5], sendBuffer[6]);
        if (sendBuffer[7] == 0x02) {
            this.receiveAddress = 21;
            this.receiveLength = 1;
            this.defaultLength = 1;
            isReadDataArrived = false;

            if (this.varTimeout != null) {
                clearTimeout(this.varTimeout);
            }

            this.varTimeout = setTimeout(function() {
                isReadDataArrived = true;
            }, 100);
        }
        isTemp = true;
    } else {

            var data = this.robotisBuffer.shift();
        if (data == null) {
            return sendBuffer;
        }
        var instruction = data[0];
        var address = data[1];
        var length = data[2];
        var value = data[3];
        //console.log('send address : ' + address + ', ' + value + ", " + length); // add by kjs 170426
        if (instruction == INST_WRITE) {
            if (length == 1) {
                sendBuffer = this.writeBytePacket(200, address, value);
            } else if (length == 2) {
                sendBuffer = this.writeWordPacket(200, address, value);
            } else if (length == 4 && address == 136) {
                var value2;
                if (value < 1024)
                    value2 = value + 1024;
                else
                    value2 = value - 1024;
                sendBuffer = this.writeDWordPacket2(200, address, value, value2);
            } else {
                sendBuffer = this.writeDWordPacket(200, address, value);
            }

        } else if (instruction == INST_READ) {
            this.addressToRead[address] = 0;
            sendBuffer = this.readPacket(200, address, length);
        } else if (instruction == INST_DXL_SYNCWRITE) { //function(ids, address, rLength, values)
            //isReadDataArrived = true;
            var ids = data[4];
            value = data[5];
            var tmpSendBuffer = this.dxlSyncWritePacket(ids, address, length, value);
            var tmp = [];
            for(let j = 0; j < tmpSendBuffer / 20; j++){
                for(let i = j*20; i < j*20+20; i++) {
                    tmp.push(tmpSendBuffer[i]);
                }
                sendBuffer.push(tmp);
            }

            sendBuffer = this.dxlSyncWritePacket(ids, address, length, value);
        } else if(instruction == INST_DXL_REGWRITE) {
            var ids = data[4];

            sendBuffer = this.dxlRegWritePacket(ids[0], address, length, value);
        } else if(instruction == INST_DXL_ACTION) {
            sendBuffer = this.dxlActionWrite();
        }

        console.log("send buffer : " + sendBuffer)
        if (sendBuffer[0] == 0xFF &&
            sendBuffer[1] == 0xFF &&
            sendBuffer[2] == 0xFD &&
            sendBuffer[3] == 0x00 &&
            sendBuffer[4] == 0xC8) {
            dataLength = this.makeWord(sendBuffer[5], sendBuffer[6]);

            if (sendBuffer[7] == 0x02) {
                this.receiveAddress = address;
                this.receiveLength = length;
                this.defaultLength = data[2];
                isReadDataArrived = false;
                if (this.varTimeout != null) {
                    clearTimeout(this.varTimeout);
                }

                this.varTimeout = setTimeout(function () {
                    isReadDataArrived = true;
                }, 100);
            }
        }
    }
    return sendBuffer;
};
Module.prototype.packetChecker = function (data) {
    if(data[0] == 0xFF && data[1] == 0xFF  && data[2] == 0xFD)
    {
        return true;
    }else
    {
        return false;
    }
};

Module.prototype.handleLocalData = function(data) { // data: Native Buffer
	for (var i = 0; i < data.length; i++) {
		this.receiveBuffer.push(data[i]);
	}

	if (this.receiveBuffer.length >= 11 + this.receiveLength) {
		isConnected = true;
		// console.log('<< 1 : ' + this.receiveLength + ' : ' + this.receiveBuffer);

		// while (this.receiveBuffer.length > 0) {
		while (this.receiveBuffer.length >= 11 + this.receiveLength) {
			if (this.receiveBuffer.shift() == 0xFF) {
				if (this.receiveBuffer.shift() == 0xFF) {
					if (this.receiveBuffer.shift() == 0xFD) {
						if (this.receiveBuffer.shift() == 0x00) {
							if (this.receiveBuffer.shift() == 0xC8) {
								var packetLength = this.makeWord(this.receiveBuffer.shift(), this.receiveBuffer.shift());
								// if (packetLength > 4) {
								// console.log("?? : " + this.receiveLength + ' / ' + (packetLength - 4));
								if (this.receiveLength == (packetLength - 4)) {
									this.receiveBuffer.shift(); // take 0x55 - status check byte
									this.receiveBuffer.shift(); // take 0x00 - error check byte

									var valueLength = packetLength - 4;
									var returnValue = [];
                                    var tmpValue = 0;
									for (var index = 0; index < valueLength / this.defaultLength; index++) {
										if (this.defaultLength == 1) {
                                            tmpValue = this.receiveBuffer.shift()
                                            returnValue.push(tmpValue);
											// returnValue.push(this.receiveBuffer.shift());
										} else if (this.defaultLength == 2) {
                                            tmpValue = this.receiveBuffer.shift() | (this.receiveBuffer.shift() << 8);
                                            if(tmpValue > 60000) {
                                                tmpValue = tmpValue - 65536;
                                            }
                                            returnValue.push(tmpValue);
                                            //returnValue.push(this.receiveBuffer.shift() | (this.receiveBuffer.shift() << 8));
										} else if (this.defaultLength == 4) {
                                            tmpValue = this.receiveBuffer.shift() | (this.receiveBuffer.shift() << 8) | (this.receiveBuffer.shift() << 16) | (this.receiveBuffer.shift() << 24);

                                            returnValue.push(tmpValue);
											// returnValue.push(this.receiveBuffer.shift() | (this.receiveBuffer.shift() << 8) | (this.receiveBuffer.shift() << 16) | (this.receiveBuffer.shift() << 24));
										}
									}

									if (this.receiveAddress != -1) {
										if (this.varTimeout != null) {
											clearTimeout(this.varTimeout);
										}

										for (var index = 0; index < returnValue.length; index++) {
											this.dataBuffer[this.receiveAddress + index * this.defaultLength] = returnValue[index];
										}

										isReadDataArrived = true;
										// console.log('<- ' + new Date().getHours() + ':' + new Date().getMinutes() + ':' + new Date().getMilliseconds() + '\n'
										 // + this.receiveAddress + ' : ' + returnValue);
									} else {
										// console.log('<- ' + new Date().getHours() + ':' + new Date().getMinutes() + ':' + new Date().getMilliseconds() + '\n' + '-1');
									}

									this.receiveBuffer.shift(); // take crc check byte
									this.receiveBuffer.shift(); // take crc check byte

									// break because this packet has no error.
									break;
								} else {
									for (var i = 0; i < packetLength; i++) {
										this.receiveBuffer.shift(); // take bytes of write status
									}
								}
							}
						}
					}
				}
			}

			// if (this.receiveBuffer.length > 0) {
				// this.receiveBuffer.shift();
			// }
		}

		// console.log('data check 2 : ' + data.length + ' / ' + this.receiveBuffer.length);
		// console.log('<< 2 : ' + this.receiveBuffer);
	}
};

Module.prototype.reset = function() {

    this.addressToRead = [];
    this.varTimeout = null;

    this.prevInstruction = 0;
    this.prevAddress = [];
    this.prevLength = [];
    this.prevValue = [];

    this.receiveBuffer = [];
    this.dataBuffer = [];
    this.robotisBuffer = [];
    this.receiveAddress = -1;
    this.receiveLength = -1;
    this.defaultLength = -1;

    this.servoPrevAddres = []; // add by kjs 20170731
    this.servoPrevLength = []; // add by kjs 20170627
    this.servoPrevValue = [];  // add by kjs 20170627
    this.servoPrevAddres2 = []; // add by kjs 20170627
    this.servoPrevLength2 = []; // add by kjs 20170627
    this.servoPrevValue2 = [];  // add by kjs 20170627
    this.servoPrevAddres3 = []; // add by kjs 20170627
    this.servoPrevLength3 = []; // add by kjs 20170627
    this.servoPrevValue3 = [];  // add by kjs 20170627
    this.servoPrevAddres4 = []; // add by kjs 20170627
    this.servoPrevLength4 = []; // add by kjs 20170627
    this.servoPrevValue4 = [];  // add by kjs 20170731
};

module.exports = new Module();

var INST_NONE = 0;
var INST_READ = 2;
var INST_WRITE = 3;
var INST_DXL_SYNCWRITE = 4;
var INST_DXL_REGWRITE = 5;
var INST_DXL_ACTION = 6;

var isReadDataArrived = true;
var isConnected = true;

Module.prototype.writeBytePacket = function(id, address, value) {
    console.log("######### writeBytepacket");
    var packet = [];
    packet.push(0xff);
    packet.push(0xff);
    packet.push(0xfd);
    packet.push(0x00);
    packet.push(id);
    packet.push(0x06);
    packet.push(0x00);
    packet.push(INST_WRITE);
    packet.push(this.getLowByte(address));
    packet.push(this.getHighByte(address));
    packet.push(value);
    var crc = this.updateCRC(0, packet, packet.length);
    packet.push(this.getLowByte(crc));
    packet.push(this.getHighByte(crc));
    return packet;
};

Module.prototype.writeWordPacket = function(id, address, value) {
    console.log("######### writeWordPacket");
    var packet = [];
    packet.push(0xff);
    packet.push(0xff);
    packet.push(0xfd);
    packet.push(0x00);
    packet.push(id);
    packet.push(0x07);
    packet.push(0x00);
    packet.push(INST_WRITE);
    packet.push(this.getLowByte(address));
    packet.push(this.getHighByte(address));
    packet.push(this.getLowByte(value));
    packet.push(this.getHighByte(value));
    var crc = this.updateCRC(0, packet, packet.length);
    packet.push(this.getLowByte(crc));
    packet.push(this.getHighByte(crc));
    return packet;
};

Module.prototype.writeDWordPacket = function(id, address, value) {
    console.log("######### writeDWordPacket");
    var packet = [];
    packet.push(0xff);
    packet.push(0xff);
    packet.push(0xfd);
    packet.push(0x00);
    packet.push(id);
    packet.push(0x09);
    packet.push(0x00);
    packet.push(INST_WRITE);
    packet.push(this.getLowByte(address));
    packet.push(this.getHighByte(address));
    packet.push(this.getLowByte(this.getLowWord(value)));
    packet.push(this.getHighByte(this.getLowWord(value)));
    packet.push(this.getLowByte(this.getHighWord(value)));
    packet.push(this.getHighByte(this.getHighWord(value)));
    console.log("packet : " + packet);
    var crc = this.updateCRC(0, packet, packet.length);
    packet.push(this.getLowByte(crc));
    packet.push(this.getHighByte(crc));
    return packet;
};

Module.prototype.writeDWordPacket2 = function(id, address, value, value2) {
    //console.log("######### writeDWordPacket2");
    var packet = [];
    packet.push(0xff);
    packet.push(0xff);
    packet.push(0xfd);
    packet.push(0x00);
    packet.push(id);
    packet.push(0x09);
    packet.push(0x00);
    packet.push(INST_WRITE);
    packet.push(this.getLowByte(address));
    packet.push(this.getHighByte(address));
    packet.push(this.getLowByte(this.getLowWord(value)));
    packet.push(this.getHighByte(this.getLowWord(value)));
    packet.push(this.getLowByte(this.getLowWord(value2)));
    packet.push(this.getHighByte(this.getLowWord(value2)));
    //console.log("packet : " + packet);
    var crc = this.updateCRC(0, packet, packet.length);
    packet.push(this.getLowByte(crc));
    packet.push(this.getHighByte(crc));
    return packet;
};

Module.prototype.dxlRegWritePacket = function(id, address, length, value) {
    var packet = [];
    var paramLength = length + 5;

    packet.push(0xff);
	packet.push(0xff);
	packet.push(0xfd);
    packet.push(0x00);

    packet.push(this.getLowByte(id));
    packet.push(this.getLowByte(paramLength));
    packet.push(this.getHighByte(paramLength));

    packet.push(0x04);

    packet.push(this.getLowByte(address));
    packet.push(this.getHighByte(address));

    switch(length) {
        case 1:
            packet.push(this.getLowByte(value));
            break;
        case 2:
            break;
        case 4:
            packet.push(this.getLowByte(this.getLowWord(value)));
            packet.push(this.getHighByte(this.getLowWord(value)));
            packet.push(this.getLowByte(this.getHighWord(value)));
            packet.push(this.getHighByte(this.getHighWord(value)));
            break;
        case 8:
            var tmpV_1 = value / 4294967296;
            var tmpV_2 = value % 4294967296;

            packet.push(this.getLowByte(this.getLowWord(tmpV_1)));
            packet.push(this.getHighByte(this.getLowWord(tmpV_1)));
            packet.push(this.getLowByte(this.getHighWord(tmpV_1)));
            packet.push(this.getHighByte(this.getHighWord(tmpV_1)));

            packet.push(this.getLowByte(this.getLowWord(tmpV_2)));
            packet.push(this.getHighByte(this.getLowWord(tmpV_2)));
            packet.push(this.getLowByte(this.getHighWord(tmpV_2)));
            packet.push(this.getHighByte(this.getHighWord(tmpV_2)));
            break;
    }

    var crc = this.updateCRC(0, packet, packet.length);
    packet.push(this.getLowByte(crc));
    packet.push(this.getHighByte(crc));
	return packet;
}

Module.prototype.dxlActionWrite = function() {
    var packet = [];
    packet.push(0xff);
    packet.push(0xff);
    packet.push(0xfd);
    packet.push(0x00);

    packet.push(0xfe);

    packet.push(0x03);
    packet.push(0x00);

    packet.push(0x05);

    var crc = this.updateCRC(0, packet, packet.length);
    packet.push(this.getLowByte(crc));
    packet.push(this.getHighByte(crc));
	return packet;
}

Module.prototype.dxlSyncWritePacket = function(ids, address, rLength, values) {
	var packet = [];
	var paramLength = 7 + ids.length * (rLength + 1);

	packet.push(0xff);
	packet.push(0xff);
	packet.push(0xfd);
	packet.push(0x00);
	packet.push(0xfe);

	packet.push(this.getLowByte(paramLength));
	packet.push(this.getHighByte(paramLength));

	packet.push(0x83);

	packet.push(this.getLowByte(address));
	packet.push(this.getHighByte(address));

	packet.push(this.getLowByte(rLength));
	packet.push(this.getHighByte(rLength));

	for(let i = 0; i < ids.length; i++) {
        packet.push(this.getLowByte(ids[i]));
        switch(rLength) {
            case 1:
                packet.push(this.getLowByte(values[i]));
                break;
            case 2:
                break;
            case 4:
                packet.push(this.getLowByte(this.getLowWord(values[i])));
                packet.push(this.getHighByte(this.getLowWord(values[i])));
                packet.push(this.getLowByte(this.getHighWord(values[i])));
                packet.push(this.getHighByte(this.getHighWord(values[i])));
                break;
        }

	}

	var crc = this.updateCRC(0, packet, packet.length);
    packet.push(this.getLowByte(crc));
    packet.push(this.getHighByte(crc));
	return packet;
}

Module.prototype.prevServoCompare = function(address, value, length) {
    if ((address >= 108 && address <= 111) && value == 7) { //Module
        if (this.prevInstruction == INST_WRITE &&
            this.servoPrevAddres == address &&
            this.servoPrevLength == length &&
            this.servoPrevValue == value) {
            doSend = false;
            return true;
        }
    }

    if (address >= 128 && address <= 131) { //Mode
        if (this.prevInstruction == INST_WRITE &&
            this.servoPrevAddres2 == address &&
            this.servoPrevLength2 == length &&
            this.servoPrevValue2 == value) {
            doSend = false;
            return true;
        }
    }

    if (address >= 140 && address <= 146) { //Speed
        if (this.prevInstruction == INST_WRITE &&
            this.servoPrevAddres3 == address &&
            this.servoPrevLength3 == length &&
            this.servoPrevValue3 == value) {
            doSend = false;
            return true;
        }
    }

    if (address >= 156 && address <= 162) { //Position
        if (this.prevInstruction4 == INST_WRITE &&
            this.servoPrevAddres4 == address &&
            this.servoPrevLength4 == length &&
            this.servoPrevValue4 == value) {
            doSend = false;
            return true;
        }
    }

}

Module.prototype.prevServoSet = function(address, value, length) {
    if ((address >= 108 && address <= 111) && value == 7) { //Module
        this.servoPrevAddres = address;
        this.servoPrevLength = length;
        this.servoPrevValue = value;
    }

    if (address >= 128 && address <= 131) { //Mode
        this.servoPrevAddres2 = address;
        this.servoPrevLength2 = length;
        this.servoPrevValue2 = value;
    }

    if (address >= 140 && address <= 146) { //Speed
        this.servoPrevAddres3 = address;
        this.servoPrevLength3 = length;
        this.servoPrevValue3 = value;
    }

    if (address >= 156 && address <= 162) { //Position
        this.servoPrevAddres4 = address;
        this.servoPrevLength4 = length;
        this.servoPrevValue4 = value;
    }

}

Module.prototype.readPacket = function(id, address, lengthToRead) {
    //console.log("######### readPacket");
    var packet = [];
    packet.push(0xff);
    packet.push(0xff);
    packet.push(0xfd);
    packet.push(0x00);
    packet.push(id);
    packet.push(0x07);
    packet.push(0x00);
    packet.push(INST_READ);
    packet.push(this.getLowByte(address));
    packet.push(this.getHighByte(address));
    packet.push(this.getLowByte(lengthToRead));
    packet.push(this.getHighByte(lengthToRead));
    var crc = this.updateCRC(0, packet, packet.length);
    packet.push(this.getLowByte(crc));
    packet.push(this.getHighByte(crc));
    return packet;
};

var crc_table = [0x0000,
    0x8005, 0x800F, 0x000A, 0x801B, 0x001E, 0x0014, 0x8011,
    0x8033, 0x0036, 0x003C, 0x8039, 0x0028, 0x802D, 0x8027,
    0x0022, 0x8063, 0x0066, 0x006C, 0x8069, 0x0078, 0x807D,
    0x8077, 0x0072, 0x0050, 0x8055, 0x805F, 0x005A, 0x804B,
    0x004E, 0x0044, 0x8041, 0x80C3, 0x00C6, 0x00CC, 0x80C9,
    0x00D8, 0x80DD, 0x80D7, 0x00D2, 0x00F0, 0x80F5, 0x80FF,
    0x00FA, 0x80EB, 0x00EE, 0x00E4, 0x80E1, 0x00A0, 0x80A5,
    0x80AF, 0x00AA, 0x80BB, 0x00BE, 0x00B4, 0x80B1, 0x8093,
    0x0096, 0x009C, 0x8099, 0x0088, 0x808D, 0x8087, 0x0082,
    0x8183, 0x0186, 0x018C, 0x8189, 0x0198, 0x819D, 0x8197,
    0x0192, 0x01B0, 0x81B5, 0x81BF, 0x01BA, 0x81AB, 0x01AE,
    0x01A4, 0x81A1, 0x01E0, 0x81E5, 0x81EF, 0x01EA, 0x81FB,
    0x01FE, 0x01F4, 0x81F1, 0x81D3, 0x01D6, 0x01DC, 0x81D9,
    0x01C8, 0x81CD, 0x81C7, 0x01C2, 0x0140, 0x8145, 0x814F,
    0x014A, 0x815B, 0x015E, 0x0154, 0x8151, 0x8173, 0x0176,
    0x017C, 0x8179, 0x0168, 0x816D, 0x8167, 0x0162, 0x8123,
    0x0126, 0x012C, 0x8129, 0x0138, 0x813D, 0x8137, 0x0132,
    0x0110, 0x8115, 0x811F, 0x011A, 0x810B, 0x010E, 0x0104,
    0x8101, 0x8303, 0x0306, 0x030C, 0x8309, 0x0318, 0x831D,
    0x8317, 0x0312, 0x0330, 0x8335, 0x833F, 0x033A, 0x832B,
    0x032E, 0x0324, 0x8321, 0x0360, 0x8365, 0x836F, 0x036A,
    0x837B, 0x037E, 0x0374, 0x8371, 0x8353, 0x0356, 0x035C,
    0x8359, 0x0348, 0x834D, 0x8347, 0x0342, 0x03C0, 0x83C5,
    0x83CF, 0x03CA, 0x83DB, 0x03DE, 0x03D4, 0x83D1, 0x83F3,
    0x03F6, 0x03FC, 0x83F9, 0x03E8, 0x83ED, 0x83E7, 0x03E2,
    0x83A3, 0x03A6, 0x03AC, 0x83A9, 0x03B8, 0x83BD, 0x83B7,
    0x03B2, 0x0390, 0x8395, 0x839F, 0x039A, 0x838B, 0x038E,
    0x0384, 0x8381, 0x0280, 0x8285, 0x828F, 0x028A, 0x829B,
    0x029E, 0x0294, 0x8291, 0x82B3, 0x02B6, 0x02BC, 0x82B9,
    0x02A8, 0x82AD, 0x82A7, 0x02A2, 0x82E3, 0x02E6, 0x02EC,
    0x82E9, 0x02F8, 0x82FD, 0x82F7, 0x02F2, 0x02D0, 0x82D5,
    0x82DF, 0x02DA, 0x82CB, 0x02CE, 0x02C4, 0x82C1, 0x8243,
    0x0246, 0x024C, 0x8249, 0x0258, 0x825D, 0x8257, 0x0252,
    0x0270, 0x8275, 0x827F, 0x027A, 0x826B, 0x026E, 0x0264,
    0x8261, 0x0220, 0x8225, 0x822F, 0x022A, 0x823B, 0x023E,
    0x0234, 0x8231, 0x8213, 0x0216, 0x021C, 0x8219, 0x0208,
    0x820D, 0x8207, 0x0202
];

Module.prototype.makeWord = function(a, b) {
    return ((a & 0xff) | ((b & 0xff) << 8));
};

Module.prototype.getLowByte = function(a) {
    return (a & 0xff);
};

Module.prototype.getHighByte = function(a) {
    return ((a >> 8) & 0xff);
};

Module.prototype.getLowWord = function(a) {
    return (a & 0xffff);
};

Module.prototype.getHighWord = function(a) {
    return ((a >> 16) & 0xffff);
};

Module.prototype.updateCRC = function(crc_accum, data_blk_ptr, data_blk_size) {
    var i, j;

    for (j = 0; j < data_blk_size; j++) {
        i = ((crc_accum >> 8) ^ data_blk_ptr[j]) & 0xff;
        crc_accum = (crc_accum << 8) ^ crc_table[i];
    }

    return crc_accum;
};


text:
layout: post
title: "BackboneJS: Getting Started"
description: Learn how to quickly build apps with BackboneJS.
date: 2017-08-29 8:30
category: Technical Guide, Frontend, BackboneJS
author:
  name: Prosper Otemuyiwa
  url: https://twitter.com/unicodeveloper?lang=en
  avatar: https://en.gravatar.com/avatar/1097492785caf9ffeebffeb624202d8f?s=200
  mail: prosper.otemuyiwa@auth0.com
design:
  bg_color: "#002A41"
  image: https://cdn.auth0.com/blog/backbone/gettingstarted.png
tags:
- backbonejs
- backbone
- javascript
- authentication
- web-app
- auth0
- framework
related:
- 2017-04-18-vuejs2-authentication-tutorial
- 2017-05-11-emberjs-authentication-tutorial
- 2016-09-29-angular-2-authentication
---

---

**TL;DR:** BackboneJS is a JavaScript library that provides models with key-value bindings and custom events, views with declarative event handling, and collections with an abundant API of enumerable functions. Currently, BackboneJS has over 25,000 stars on [GitHub](https://github.com/jashkenas/backbone). BackboneJS gives your web applications structure. In this tutorial, I'll show you how to build a web application with BackboneJS and add authentication to it. Check out the [repo](https://github.com/auth0-blog/employee-app) to get the code.

---

**BackboneJS** is a JavaScript library, built by [Jeremy Ashkenas](https://github.com/jashkenas) and maintained by a team of contributors. It is an open source component of [DocumentCloud](http://documentcloud.org). It was initially released in 2010. Since then, it has undergone tremendous growth and adoption in the developer community. Over the past 2 years, the use of Backbone have declined due to new libraries and framework like ReactJS, Vue.js and Angular. The latest stable release is 1.3.3 and it was tagged on April 5, 2016. Actively used open source projects and libraries tag releases very often, which signifies growth. However, **BackboneJS** has been stagnant for over a year now!

Furthermore, there are many web platforms that use BackboneJS to build their frontends. Such platforms include *Trello*, *Bitbucket*, *Foursquare*, *SeatGeek* and more. The [documentation](http://backbonejs.org) is very comrehensive.

## Understanding Key Concepts in BackboneJS

**BackboneJS** has a philosophy: `Keep Business logic separate from User Interface`. When the two are entangled, change is hard. The key concepts needed to understand how BackboneJS works are:

* **Models**
* **Views**
* **Collections**
* **Events**

I'll give a basic overview of these concepts to nourish your understanding of **BackboneJS**.

### Models

A Model is a layer that transforms and syncs data with a persistence layer (mostly RESTful API interacting with a database). They contain all the helpful functions needed to manipulate some piece of data from the persistence layer. When any of its data is modified, Models trigger `change` events.

Consider a Model as a sort of manipulator. Instead of directly interacting with the data from your API, it serves as a layer that allows you easily manipulate every tiny piece of data in a very friendly and fantastic way.

Here's a simple case study: Imagine we are in charge of a gift shop and we need to build a database of the gifts that we sell. We need to keep track of the stock of those gifts. Details like the price, brand, stock and type.

```js

var Shop = Backbone.Model.extend({

});

```

Now, we can create an instance of the Shop model and populate it like so:

```js
var Shop = Backbone.Model.extend({
  brand: 'Rolex',
  type: 'Wrist Watch',
  price: 900
  stock: 8
});
```

We can also add `default attributes` to the Model like below:

```js
var Shop = Backbone.Model.extend({
  defaults: {
    brand: '',
    type: '',
    price: 900
    stock: 0
  }
});
```

Now, we can call `get` and `set` methods on an instance of the Shop model. If we want to fetch the brand of the gift, we will retrieve it with this:

```js

var firstShop = new Shop({
  brand: 'Rolex',
  type: 'Wrist Watch',
  price: 900
  stock: 8
});

var secondShop = new Shop({
  brand: 'Michael Korrs',
  type: 'Wrist Watch',
  price: 400
  stock: 16
});

firstShop.get('brand');
// Rolex
secondShop.get('brand');
// Michael Korrs
```

Let's look at another practical case. If we need to create a new user on the backend, we can instantiate a new User Model and call the `save` method.

```js
var UserModel = Backbone.Model.extend({
    urlRoot: '/user',
    defaults: {
      name: '',
      email: ''
    }
});

var user = new UserModel();
// Notice that we haven't set an `id`
var userDetails = {
    name: 'Prosper',
    email: 'unicodeveloper@gmail.com'
};

// Because we have not set a `id` the server will call
// POST /user with a payload of { name:'Prosper', email: 'unicodeveloper@gmail.com'}
// The server should save the data and return a response containing the new `id`
user.save(userDetails, {
    success: function (user) {
        alert(JSON.stringify(user));
    }
});
```

We can fetch the details of a user that has been created with an id with the code below:

```js
var user = new UserModel({id: 1});

// The fetch below will perform GET /user/1
// The server should return the id, name and email from the database
user.fetch({
    success: function (user) {
        alert(JSON.stringify(user));
    }
});
```

Updating the User Model will look like this:

```js
...
...
user.save({name: 'Goodness'}, {
  success: function (model) {
    alert(JSON.stringify(user));
  }
});
```

### Collections

Collections are ordered sets of models. You can bind some events to be notified when any model in the collection has been modified. Events such as `change`, `add`, `remove`.

Let's create a Backbone collection and add models to it.

```js
var ShopCollection = Backbone.Collection.extend({

});
```

Now, we can set the `Shop` model to our collection like this:

```js
var ShopCollection = Backbone.Collection.extend({
  model: Shop
});
```

The next thing will be to instantiate the Collection and the instances of our models like this:

```js
var ShopCollection = new ShopCollection;
ShopCollection.add(firstShop);
ShopCollection.add(secondShop);
```

To access the models in the collection, you can use `each`, one of the Underscore methods available to loop over the collection and present the data to the screen. During the iteration, you can perform model methods like `get/set` on each model.

```js
ShopCollection.each((shop) => {
   ...
   shop.get('brand');
   shop.get('stock');
   ...
});
```

Other popular methods you can use on a collection are [toJSON](http://backbonejs.org/#Collection-toJSON), and [sync](http://backbonejs.org/#Collection-sync).

### Views

Backbone views can be used with any JavaScript templating library. It is unopinionated about the process used to render View objects and their subviews into UI. The views handle user input and interactivity, renders data from the model and also sends captureed input back to the model.

The views listen to the model "change" events, and react or re-render themselves appropriately.

**Note:** Templates allow us to render the User Interface as an alternative to direct DOM manipulation.

```js
var PersonView = Backbone.View.extend({

   tagName: 'li',

   initialize: function(){
     this.render();
   },

   render: function(){
     this.$el.html( this.model.get('name') + ' (' + this.model.get('age') + ') - ' + this.model.get('occupation') );
  }
});
```

Now, let's use a template

```
var Person = Backbone.Model.extend({
    defaults: {
        name: 'Prosper Otemuyiwa',
        age: 23,
        occupation: 'Evangelist'
    }
});

var PersonView = Backbone.View.extend({
    tagName: 'li',

    my_template: _.template("<strong><%= name %></strong> (<%= age %>) - <%= occupation %>"),

    initialize: function(){
        this.render();
    },

    render: function(){
        this.$el.html( this.my_template(this.model.toJSON()));
    }
});
```

### Events

Events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events.

```js
var object = {};
_.extend(object, Backbone.Events);
object.on("alert", function(msg) { alert("Triggered " + msg); });
object.trigger("alert", "an event");
```

In the code above, we copied all of Backbone's events to a JavaScript object using the extend functionality of underscore. So we listen on `alert` Backbone event and then trigger the event.

Let's try something more practical. Say we have a UserModel,

```js
var UserModel = Backbone.Model.extend({

    initialize: function(){
        this.on('change',this.someChange,this);
    },

    defaults : {
      name : '',
      email : ''
    },

    someChange: function(model,options) {
      alert('something has changed');
    }

});

```

```js
var newUser = new UserModel({ name:'Raymond Igoladebayi', email: 'raymond@waya.com'});
newUser.set('email', 'ppp@ppp.com'); // this will trigger the `change` event
```

In the code above, the user model will now listen to change events on itself. Once you set the name to another value, it triggers the change event that calls the `someChange` function.

In Backbone, you can also listen to just a specific attribute change. For example, we can listen to only `title` attribute change. How? We simply chain it with a colon like so: `change:title`.

```js
...
this.on('change:title', this.someChange, this);
...
```

The `change` event is only triggered whenever the title changes. And then calls the `someChange` function.

We also have built-in events that occur on collections. Check out the [catalog](http://backbonejs.org/#Events-catalog) of built-in Backbone events.

## Our app: Address Book

The app we will build today is an Address Book. This app simply manages the address of employees in an organization. We won't make use of any back-end, but will take advantage of Backbone Collections. I'll leave you to persist it to a backend or use local Storage.

## Build The App With BackBoneJS

We'll need three main dependencies, backbone.js, underscore and jquery. Go ahead and create your app directory.

In the root directory, create an `index.html` file. Also create `css`, and `js` folders within the directory.

Inside the `js` directory, go ahead and create the `collections`, `models` and `views` directories.

Populate the `index.html` file with the following code:

```js
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Address Book</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="app/css/main.css" rel="stylesheet">
  </head>
  <body>
    <header class="bs-header">
      <div class="container">
        <h1>Address Book</h1>
      </div>
    </header>
    <div class="container">
      <div class="row">
        <div class="col-xs-12 main-container">
        </div>
      </div>
    </div>

    <script type="text/template" id="tpl-contacts">
      <h2 class="page-header text-center">List of Employees</h2>
      <p class="text-center">
        <a href="#employees/new" class="btn btn-lg btn-outline">Add Employee</a>
      </p>
      <ul class="media-list row contacts-container"></ul>
    </script>

    <script type="text/template" id="tpl-contact">
      <div class="thumbnail">
        <img class="media-object" src="http://svgavatars.com/style/svg/<%- avatar %>">
      </div>
      <div class="media-heading">
        <h3>
          <%- name %>
          <small>
            <a href="#employees/edit/<%- id %>"><span class="glyphicon glyphicon-pencil"></span></a>
            <a href="#employees/delete/<%- id %>" class="delete-employee">
              <span class="glyphicon glyphicon-trash"></span>
            </a>
          </small>
        </h3>
      </div>
      <div class="media-body">
        <dl>
          <dt>Phone Number:</dt>
          <dd><%- tel %></dd>
          <dt>Email:</dt>
          <dd><%- email %></dd>
        </dl>
      </div>
      <hr>
    </script>

    <script type="text/template" id="tpl-new-contact">
      <h2 class="page-header text-center"><%= isNew ? 'Create' : 'Edit' %> Employee </h2>
      <form role="form" class="form-horizontal employee-form">
        <div class="form-group">
          <label class="col-sm-4 control-label">Full name:</label>
          <div class="col-sm-6">
            <input type="text" class="form-control employee-name-input" value="<%- name %>" required>
          </div>
        </div>
        <div class="form-group">
          <label class="col-sm-4 control-label">Email address:</label>
          <div class="col-sm-6">
            <input type="email" class="form-control employee-email-input" value="<%- email %>" required>
          </div>
        </div>
        <div class="form-group">
          <label class="col-sm-4 control-label">Telephone number:</label>
          <div class="col-sm-6">
            <input type="tel" class="form-control employee-tel-input" value="<%- tel %>" required>
          </div>
        </div>
        <div class="form-group">
          <div class="col-sm-offset-4 col-sm-3">
            <button type="submit" class="btn btn-outline btn-lg btn-block">Submit</button>
          </div>
          <div class="col-sm-3">
            <a href="#employees" class="btn btn-outline btn-lg btn-block">Cancel</a>
          </div>
        </div>
      </form>
    </script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
    <script src="https://cdn.auth0.com/js/auth0/8.8/auth0.min.js"></script>

    <script src="app/js/app.js"></script>
    <script src="app/js/models/employee.js"></script>
    <script src="app/js/collections/employees.js"></script>
    <script src="app/js/views/employee.js"></script>
    <script src="app/js/views/employees.js"></script>
    <script src="app/js/views/employeeForm.js"></script>
    <script src="app/js/router.js"></script>

    <script>
      $(function() {
        EmployeeManager.start({
          employees: [
            {
              id: 1,
              name : 'Christian Nwamba',
              avatar: '11.svg',
              tel: '651-603-1723',
              email: 'chris@scotch.io'
            },
            {
              id: 2,
              name : 'Bukola Ayodeji',
              avatar: '20.svg',
              tel: '513-307-5859',
              email: 'bukolayodeji@nairabet.com'
            },
            {
              id: 3,
              name : 'Rick Ross',
              avatar: '17.svg',
              tel: '918-774-0199',
              email: 'ross@auth0.com'
            },
            {
              id: 4,
              name : 'Godson Ukpere',
              avatar: '19.svg',
              tel: '702-989-5145',
              email: 'g.ukpe@gigstar.co'
            },
            {
              id: 5,
              name : 'John I. Wilson',
              avatar: '01.svg',
              tel: '318-292-6700',
              email: 'JohnIWilson@dayrep.com'
            },
            {
              id: 6,
              name : 'Goodnes Tejufona',
              avatar: '05.svg',
              tel: '803-557-9815',
              email: 'goodness.teju@kudiai.com'
            }
          ]
        });
      });
    </script>
  </body>
</html>
```

Let's analyze the code above. We have three template-type scripts. One for displaying the list of employees, another for editing and creating new employees and one for displaying the link for creating new employees.

Furthermore, we referenced jquery, underscore and backbone libraries. We also linked some views and script files that do not exist yet. We'll create them soon.

Finally, there is a startup function, `EmployeeManager.start()`, that takes in an array of employees for display when the app is started. You'll understand how this works in a couple of minutes.

Next, open up the models directory and create an `employee.js` file.

_employee.js_

```js
EmployeeManager.Models.Employee = Backbone.Model.extend({
  defaults: {
    name: null,
    tel: null,
    email: null,
    avatar: null
  }
});
```

We just set the defaults of our model attributes to null. In our app, we are not persisting anything so our model will be very simple.

Next, create an `employees.js` file in the `collections` directory and add the following code to it:

_collections/employees.js_

```js
EmployeeManager.Collections.Employees = Backbone.Collection.extend({
  model: EmployeeManager.Models.Employee
});
``

Earlier I mentioned that collections work with models.

## Create The Views

We'll have three views. One view for handling the list of employees, one view for the details of each employee and one view for adding employees.

Let's get started. Go ahead and open up the `js/views` directory. Create a file, `employee.js`.

_js/views/employee.js_

```js
EmployeeManager.Views.Employee = Backbone.View.extend({
  tagName: 'li',
  className: 'media col-md-6 col-lg-4',
  template: _.template($('#tpl-contact').html()),

  events: {
    'click .delete-employee': 'onClickDelete'
  },

  initialize: function() {
    this.listenTo(this.model, 'remove', this.remove);
  },

  render: function() {
    var html = this.template(this.model.toJSON());
    this.$el.append(html);
    return this;
  },

  onClickDelete: function(e) {
    e.preventDefault();
    this.model.collection.remove(this.model);
  }
});
```

This is the view that handles the details of each employee. In the code above, we have the html tag, `<li>` that is assigned a class. This is the element that houses the employee detail. The render function ensures that the right data is appended to the template and displays on the page. The `onClickDelete` function is for removing the data from the model and collection.

The events object simply maps the `onClickDelete` function to the click event of the `delete-employee` button.

Next, create the `add employee form` view. Create a file, `employeeForm.js` in the `js/views` directory.

_js/views/employeeForm.js_

```js
EmployeeManager.Views.EmployeeForm = Backbone.View.extend({
  template: _.template($('#tpl-new-contact').html()),

  events: {
    'submit .employee-form': 'onFormSubmit'
  },

  render: function() {
    var html = this.template(_.extend(this.model.toJSON(), {
      isNew: this.model.isNew()
    }));
    this.$el.append(html);
    return this;
  },

  onFormSubmit: function(e) {
    e.preventDefault();

    this.trigger('form:submitted', {
      name: this.$('.employee-name-input').val(),
      tel: this.$('.employee-tel-input').val(),
      email: this.$('.employee-email-input').val(),
      avatar: '13.svg'
    });
  }
});
```

In the code above, the `onFormSubmit` function is called when we submit the form. And this function is called whenever the submit event is fired. The render function assigns the model to the template.

Finally, create a file, `employees.js` in the `js/views` directory.

_js/views/employees.js_

```js
EmployeeManager.Views.Employees = Backbone.View.extend({
  template: _.template($('#tpl-contacts').html()),

  renderOne: function(employee) {
    var itemView = new EmployeeManager.Views.Employee({model: employee});
    this.$('.contacts-container').append(itemView.render().$el);
  },

  render: function() {
    var html = this.template();
    this.$el.html(html);

    this.collection.each(this.renderOne, this);

    return this;
  }
});
```

This view is responsible for the list of employees on the page.

## Create The Router

This is a single page application, we need to make use of some routing capabilities. In the `js` directory, create a `router.js` file and add the code below:

_js/router.js_

```js
EmployeeManager.Router = Backbone.Router.extend({
  routes: {
    '': 'home',
    'employees': 'showEmployees',
    'employees/new': 'newEmployee',
    'employees/edit/:id': 'editEmployee',
  }
});
```

In the code above, whenever each of the routes on the left are visited, the name of the actions on the right are fired as events, so the router can listen on it like:

```js
router.on('route:showEmployees', function() {
  ...
});
```

## Create The App Logic

Let's go ahead and create the `js/app.js` file. This is the file that houses the functionalities that happens whenever each route is visited. Add the code below to it:

```js
window.EmployeeManager = {
  Models: {},
  Collections: {},
  Views: {},

  start: function(data) {
    var employees = new EmployeeManager.Collections.Employees(data.employees),
        router = new EmployeeManager.Router();

    router.on('route:home', function() {
      router.navigate('employees', {
        trigger: true,
        replace: true
      });
    });

    router.on('route:showEmployees', function() {
      var employeesView = new EmployeeManager.Views.Employees({
        collection: employees
      });

      $('.main-container').html(employeesView.render().$el);
    });

    router.on('route:newEmployee', function() {
      var newEmployeeForm = new EmployeeManager.Views.EmployeeForm({
        model: new EmployeeManager.Models.Employee()
      });

      newEmployeeForm.on('form:submitted', function(attrs) {
        attrs.id = employees.isEmpty() ? 1 : (_.max(employees.pluck('id')) + 1);
        employees.add(attrs);
        router.navigate('employees', true);
      });

      $('.main-container').html(newEmployeeForm.render().$el);
    });

    router.on('route:editEmployee', function(id) {
      var employee = employees.get(id),
          editEmployeeForm;

      if (employee) {
        editEmployeeForm = new EmployeeManager.Views.EmployeeForm({
            model: employee
        });

        editEmployeeForm.on('form:submitted', function(attrs) {
          employee.set(attrs);
          router.navigate('employees', true);
        });

        $('.main-container').html(editEmployeeForm.render().$el);
      } else {
        router.navigate('employees', true);
      }
    });

    Backbone.history.start();
  }
};
```

Remember the `EmployeeManager.start()` function that was called in the `index.html` file? The function houses the events that the router listens on.

* Whenever the user launches the app, the router listens on the `home` event, and triggers a redirect to the `employees` route.
* Whenever the user hits the `#employees` route, it listens on the `showEmployees` event and renders the list of employees.
* Whenever the user hits the `#employee/new` route, it listens on the `newEmployee` event, renders the form for adding new employees and handles the form submission.
* Whenever the user hits the `#employees/edit/:id` route, it listens on the `editEmployee` event, and renders the edit form.

`Backbone.history.start()` is used to allow the use of hashbangs for the routes.

## Run Your App

Now, launch your app. It should start up like so:

![Show list of employees](https://cdn.auth0.com/blog/addressbook/list.png)
_Launching the app_

![Create new employee](https://cdn.auth0.com/blog/addressbook/create.png)
_Creating a new employee_

![Editing an employee details](https://cdn.auth0.com/blog/addressbook/edit.png)
_Editing an employee details_

## Adding Authentication to Your BackboneJS App

The majority of the apps we use on a daily basis have a means of authenticating users. Adding authentication to your BackboneJS apps is as easy as using [Auth0](https://auth0.com/) in your JQuery apps.

Auth0 allows us to issue [JSON Web Tokens (JWTs)](https://jwt.io). If you don't already have an Auth0 account, [sign up](javascript:signup\(\)) for a free one now.

Login to your Auth0 [management dashboard](https://manage.auth0.com) and create a new client. Select `Single Page Application` during creation.

BackboneJS relies heavily on JQuery. So, go ahead and follow this [amazing quickstart](https://auth0.com/docs/quickstart/spa/jquery/01-login) to add authentication to the app.

## Conclusion

**BackboneJS** is a library that can be used to build your user interfaces. Right now, it has not undergone updates in over a year. And many web applications that initially used it heavily have either moved away to new JS libraries or are currently rewriting their frontend to make use of another tool.

In addition, Auth0 can help secure your apps with more than just username-password authentication. It provides features like [multifactor auth](https://auth0.com/docs/multifactor-authentication), [anomaly detection](https://auth0.com/docs/anomaly-detection), [enterprise federation](https://auth0.com/docs/identityproviders), [single sign on (SSO)](https://auth0.com/docs/sso), and more. [Sign up](javascript:signup\(\)) today so you can focus on building features unique to your app.


text:
require 'uglifier'

File.open("static/application.min.js", "w") {|file| file.truncate(0) }

libs = [
  "javascripts/libs/jquery-1.10.2.min.js",
  "javascripts/libs/handlebars-1.3.0.min.js",
  "javascripts/libs/ember.min.js",
  "javascripts/libs/ember-validations.min.js",
  "javascripts/libs/list-view.min.js",
  "javascripts/libs/classie.js",
  "javascripts/libs/notificationFx.js",
]

app = [
  "javascripts/app/router.js",
  "javascripts/app/models.js",
  "javascripts/app/routes.js",
  "javascripts/app/controllers.js",
  "javascripts/app/views.js",
  "javascripts/app/helpers.js",
]

libs.each do |js_file|
  File.open("static/application.min.js", "a") do |f|
    puts "cat #{js_file}"
    f << File.read(js_file)
  end
end

app.each do |js_file|
  File.open("static/application.min.js", "a") do |f|
    puts "compile #{js_file}"
    f << Uglifier.compile(File.read(js_file))
  end
end


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

package com.google.gerrit.server.git;

import com.google.gerrit.reviewdb.Project;
import com.google.inject.Singleton;

import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Repository;

import java.io.IOException;

/**
 * Manages Git repositories for the Gerrit server process.
 *

 * Implementations of this interface should be a {@link Singleton} and
 * registered in Guice so they are globally available within the server
 * environment.
 */
public interface GitRepositoryManager {
  /** Note tree listing commits we refuse {@code refs/meta/reject-commits} */
  public static final String REF_REJECT_COMMITS = "refs/meta/reject-commits";

  /**
   * Get (or open) a repository by name.
   *
   * @param name the repository name, relative to the base directory.
   * @return the cached Repository instance. Caller must call {@code close()}
   *         when done to decrement the resource handle.
   * @throws RepositoryNotFoundException the name does not denote an existing
   *         repository, or the name cannot be read as a repository.
   */
  public abstract Repository openRepository(Project.NameKey name)
      throws RepositoryNotFoundException;

  /**
   * Create (and open) a repository by name.
   *
   * @param name the repository name, relative to the base directory.
   * @return the cached Repository instance. Caller must call {@code close()}
   *         when done to decrement the resource handle.
   * @throws RepositoryNotFoundException the name does not denote an existing
   *         repository, or the name cannot be read as a repository.
   */
  public abstract Repository createRepository(Project.NameKey name)
      throws RepositoryNotFoundException;

  /**
   * Read the {@code GIT_DIR/description} file for gitweb.
   *

   * NB: This code should really be in JGit, as a member of the Repository
   * object. Until it moves there, its here.
   *
   * @param name the repository name, relative to the base directory.
   * @return description text; null if no description has been configured.
   * @throws RepositoryNotFoundException the named repository does not exist.
   * @throws IOException the description file exists, but is not readable by
   *         this process.
   */
  public abstract String getProjectDescription(Project.NameKey name)
      throws RepositoryNotFoundException, IOException;

  /**
   * Set the {@code GIT_DIR/description} file for gitweb.
   *

   * NB: This code should really be in JGit, as a member of the Repository
   * object. Until it moves there, its here.
   *
   * @param name the repository name, relative to the base directory.
   * @param description new description text for the repository.
   */
  public abstract void setProjectDescription(Project.NameKey name,
      final String description);
}


text:
<?php
/**
 * QueuedTask Fixture.
 *
 */
class QueuedTaskFixture extends CakeTestFixture {

/**
 * Fields.
 *
 * @var array
 */
	public $fields = [
		'id' => ['type' => 'integer', 'null' => false, 'default' => null, 'length' => 10, 'unsigned' => true, 'key' => 'primary'],
		'task' => ['type' => 'string', 'null' => false, 'default' => null, 'key' => 'index', 'collate' => 'utf8_general_ci', 'charset' => 'utf8'],
		'data' => ['type' => 'text', 'null' => true, 'default' => null, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'],
		'not_before' => ['type' => 'timestamp', 'null' => true, 'default' => null],
		'fetched' => ['type' => 'timestamp', 'null' => true, 'default' => null],
		'completed' => ['type' => 'timestamp', 'null' => true, 'default' => null, 'key' => 'index'],
		'failed_count' => ['type' => 'integer', 'null' => false, 'default' => '0', 'length' => 10, 'unsigned' => true],
		'failure_message' => ['type' => 'text', 'null' => true, 'default' => null, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'],
		'worker_key' => ['type' => 'string', 'null' => true, 'default' => null, 'length' => 40, 'key' => 'index', 'collate' => 'utf8_general_ci', 'charset' => 'utf8'],
		'created' => ['type' => 'timestamp', 'null' => true, 'default' => null],
		'indexes' => [
			'PRIMARY' => ['column' => 'id', 'unique' => 1],
			'completed' => ['column' => 'completed', 'unique' => 0],
			'worker_key' => ['column' => 'worker_key', 'unique' => 0],
			'task' => ['column' => 'task', 'unique' => 0]
		],
		'tableParameters' => ['charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB']
	];

/**
 * Records.
 *
 * @var array
 */
	public $records = [
		[
			'id' => 1,
			'task' => 'Example',
			'data' => 'Lorem ipsum dolor sit amet, aliquet feugiat. Convallis morbi fringilla gravida, phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla vestibulum massa neque ut et, id hendrerit sit, feugiat in taciti enim proin nibh, tempor dignissim, rhoncus duis vestibulum nunc mattis convallis.',
			'not_before' => '2014-12-19 17:12:30',
			'fetched' => '2014-12-19 17:12:30',
			'completed' => '2014-12-19 17:12:30',
			'failed_count' => 1,
			'failure_message' => 'Lorem ipsum dolor sit amet, aliquet feugiat. Convallis morbi fringilla gravida, phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla vestibulum massa neque ut et, id hendrerit sit, feugiat in taciti enim proin nibh, tempor dignissim, rhoncus duis vestibulum nunc mattis convallis.',
			'worker_key' => 'Lorem ipsum dolor sit amet',
			'created' => '2014-12-19 17:12:30'
		],
	];

/**
 * Constructor.
 *
 *  Generates dynamic records.
 *
 * @return void
 */
	public function __construct() {
		$this->records[] = [
			'id' => 2,
			'task' => 'Example',
			'data' => 'Lorem ipsum dolor sit amet, aliquet feugiat. Convallis morbi fringilla gravida, phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla vestibulum massa neque ut et, id hendrerit sit, feugiat in taciti enim proin nibh, tempor dignissim, rhoncus duis vestibulum nunc mattis convallis.',
			'not_before' => '2014-12-19 17:12:30',
			'fetched' => '2014-12-19 17:12:30',
			'completed' => date('Y-m-d H:i:s', strtotime('+1 minute')),
			'failed_count' => 1,
			'failure_message' => 'Lorem ipsum dolor sit amet, aliquet feugiat. Convallis morbi fringilla gravida, phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla vestibulum massa neque ut et, id hendrerit sit, feugiat in taciti enim proin nibh, tempor dignissim, rhoncus duis vestibulum nunc mattis convallis.',
			'worker_key' => 'Lorem ipsum dolor sit amet',
			'created' => '2014-12-19 17:12:30'
		];
		$this->records[] = [
				'id' => 3,
				'task' => 'Example',
				'data' => 'Lorem ipsum dolor sit amet, aliquet feugiat. Convallis morbi fringilla gravida, phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla vestibulum massa neque ut et, id hendrerit sit, feugiat in taciti enim proin nibh, tempor dignissim, rhoncus duis vestibulum nunc mattis convallis.',
				'not_before' => '2014-12-19 17:12:30',
				'fetched' => '2014-12-19 17:12:30',
				'completed' => date('Y-m-d H:i:s', strtotime('-15 minute')),
				'failed_count' => 1,
				'failure_message' => 'Lorem ipsum dolor sit amet, aliquet feugiat. Convallis morbi fringilla gravida, phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla vestibulum massa neque ut et, id hendrerit sit, feugiat in taciti enim proin nibh, tempor dignissim, rhoncus duis vestibulum nunc mattis convallis.',
				'worker_key' => 'Lorem ipsum dolor sit amet',
				'created' => '2014-12-19 17:12:30'
		];
		$this->records[] = [
				'id' => 4,
				'task' => 'Example',
				'data' => 'Lorem ipsum dolor sit amet, aliquet feugiat. Convallis morbi fringilla gravida, phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla vestibulum massa neque ut et, id hendrerit sit, feugiat in taciti enim proin nibh, tempor dignissim, rhoncus duis vestibulum nunc mattis convallis.',
				'not_before' => '2014-12-19 17:12:30',
				'fetched' => '2014-12-19 17:12:30',
				'completed' => date('Y-m-d H:i:s', strtotime('-5 minute')),
				'failed_count' => 1,
				'failure_message' => 'Lorem ipsum dolor sit amet, aliquet feugiat. Convallis morbi fringilla gravida, phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla vestibulum massa neque ut et, id hendrerit sit, feugiat in taciti enim proin nibh, tempor dignissim, rhoncus duis vestibulum nunc mattis convallis.',
				'worker_key' => 'Lorem ipsum dolor sit amet',
				'created' => '2014-12-19 17:12:30'
		];

		parent::__construct();
	}

}


text:
package com.bxtel.model.model;
import com.bxtel.model.*;
import java.util.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

@Document(indexName = "database", type = ".Sms?lower_case", shards = 1, replicas = 0, refreshInterval = "-1")
public class .Sms
{

		 @Id
		 private String indexid;

		 public long .Sms;//.Sms
		 public java.lang.String .Sms;//.Sms
		 public java.lang.String .Sms;//.Sms
		 public java.lang.String .Sms;//.Sms
		 public java.lang.String .Sms;//.Sms

		 public void set.Sms(long .Sms)
		 {
		 	this..Sms=.Sms;
		 }
		 public long get.Sms()
		 {
		 	return this..Sms;
		 }
		 public void set.Sms(java.lang.String .Sms)
		 {
		 	this..Sms=.Sms;
		 }
		 public java.lang.String get.Sms()
		 {
		 	return this..Sms;
		 }
		 public void set.Sms(java.lang.String .Sms)
		 {
		 	this..Sms=.Sms;
		 }
		 public java.lang.String get.Sms()
		 {
		 	return this..Sms;
		 }
		 public void set.Sms(java.lang.String .Sms)
		 {
		 	this..Sms=.Sms;
		 }
		 public java.lang.String get.Sms()
		 {
		 	return this..Sms;
		 }
		 public void set.Sms(java.lang.String .Sms)
		 {
		 	this..Sms=.Sms;
		 }
		 public java.lang.String get.Sms()
		 {
		 	return this..Sms;
		 }

	/*
		 model.set.Sms(".Smsvalue");
		 model.set.Sms(".Smsvalue");
		 model.set.Sms(".Smsvalue");
		 model.set.Sms(".Smsvalue");
		 model.set.Sms(".Smsvalue");
		 model.get.Sms();
		 model.get.Sms();
		 model.get.Sms();
		 model.get.Sms();
		 model.get.Sms();
	*/
}


text:
from . import models

from core.custom_filters import BaseFilterSet

class QAFilter(BaseFilterSet):
    class Meta:
        model = models.QualityAssuranceCheck
        fields = {
            'source__name': ('icontains',),
            'checked_by': ('exact',),
            'content_changed': ('exact',),
            'technical_quality_changed': ('exact',),
            'source_action': ('exact',),
        }


text:
package org.wso2.carbon.esb.mediator.test.aggregate;

import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.esb.integration.common.utils.ESBIntegrationTest;

import java.io.IOException;

public class AggregateWithinTimeoutTestCase extends ESBIntegrationTest {

    private AggregatedRequestClient aggregatedRequestClient;
    private final int no_of_requests = 200;

    @BeforeClass(alwaysRun = true)
    public void setEnvironment() throws Exception {
        super.init();
        verifyProxyServiceExistence("aggregateMediatorTimeoutTestProxy");
        aggregatedRequestClient = new AggregatedRequestClient();
        aggregatedRequestClient.setProxyServiceUrl(getProxyServiceURLHttp("aggregateMediatorTimeoutTestProxy"));
        aggregatedRequestClient.setSymbol("IBM");
        aggregatedRequestClient.setNoOfIterations(no_of_requests);

    }

    @Test(groups = {"wso2.esb"}, description = "replacing a property by using an enrich mediator", enabled = false)
    public void test() throws IOException {
        int companyCount = 0, responseTagCount = 0, SoapEnvCount = 0;

        String Response = aggregatedRequestClient.getResponse();
        String[] response = getTagArray(Response);

        for (int i = 0; i < response.length; i++) {
            if (response[i].contains("soapenv")) {
                SoapEnvCount++;
            } else if (response[i].contains("WSO2 Company")) {
                companyCount++;
            } else if (response[i].contains("getQuoteResponse")) {
                responseTagCount++;
            }
        }

        Assert.assertTrue(Response.contains("WSO2 Company"));
        Assert.assertTrue(Response.contains("getQuoteResponse"));
        Assert.assertTrue(2 * no_of_requests > responseTagCount);
        Assert.assertTrue((no_of_requests > companyCount));
    }

    @AfterClass(alwaysRun = true)
    public void destroy() throws Exception {
        aggregatedRequestClient = null;
        super.cleanup();
    }

    public String[] getTagArray(String xml) {
        return xml.split("<");
    }

}


text:
package org.springframework.beans.factory.support;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.MethodParameter;
import org.springframework.util.ClassUtils;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * @author Mark Fisher
 * @author Juergen Hoeller
 */
public class QualifierAnnotationAutowireBeanFactoryTests {

	private static final String JUERGEN = "juergen";

	private static final String MARK = "mark";

	@Test
	public void testAutowireCandidateDefaultWithIrrelevantDescriptor() throws Exception {
		DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
		ConstructorArgumentValues cavs = new ConstructorArgumentValues();
		cavs.addGenericArgumentValue(JUERGEN);
		RootBeanDefinition rbd = new RootBeanDefinition(Person.class, cavs, null);
		lbf.registerBeanDefinition(JUERGEN, rbd);
		assertThat(lbf.isAutowireCandidate(JUERGEN, null)).isTrue();
		assertThat(lbf.isAutowireCandidate(JUERGEN,
				new DependencyDescriptor(Person.class.getDeclaredField("name"), false))).isTrue();
		assertThat(lbf.isAutowireCandidate(JUERGEN,
				new DependencyDescriptor(Person.class.getDeclaredField("name"), true))).isTrue();
	}

	@Test
	public void testAutowireCandidateExplicitlyFalseWithIrrelevantDescriptor() throws Exception {
		DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
		ConstructorArgumentValues cavs = new ConstructorArgumentValues();
		cavs.addGenericArgumentValue(JUERGEN);
		RootBeanDefinition rbd = new RootBeanDefinition(Person.class, cavs, null);
		rbd.setAutowireCandidate(false);
		lbf.registerBeanDefinition(JUERGEN, rbd);
		assertThat(lbf.isAutowireCandidate(JUERGEN, null)).isFalse();
		assertThat(lbf.isAutowireCandidate(JUERGEN,
				new DependencyDescriptor(Person.class.getDeclaredField("name"), false))).isFalse();
		assertThat(lbf.isAutowireCandidate(JUERGEN,
				new DependencyDescriptor(Person.class.getDeclaredField("name"), true))).isFalse();
	}

	@Disabled
	@Test
	public void testAutowireCandidateWithFieldDescriptor() throws Exception {
		DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
		ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
		cavs1.addGenericArgumentValue(JUERGEN);
		RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
		person1.addQualifier(new AutowireCandidateQualifier(TestQualifier.class));
		lbf.registerBeanDefinition(JUERGEN, person1);
		ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
		cavs2.addGenericArgumentValue(MARK);
		RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
		lbf.registerBeanDefinition(MARK, person2);
		DependencyDescriptor qualifiedDescriptor = new DependencyDescriptor(
				QualifiedTestBean.class.getDeclaredField("qualified"), false);
		DependencyDescriptor nonqualifiedDescriptor = new DependencyDescriptor(
				QualifiedTestBean.class.getDeclaredField("nonqualified"), false);
		assertThat(lbf.isAutowireCandidate(JUERGEN, null)).isTrue();
		assertThat(lbf.isAutowireCandidate(JUERGEN, nonqualifiedDescriptor)).isTrue();
		assertThat(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor)).isTrue();
		assertThat(lbf.isAutowireCandidate(MARK, null)).isTrue();
		assertThat(lbf.isAutowireCandidate(MARK, nonqualifiedDescriptor)).isTrue();
		assertThat(lbf.isAutowireCandidate(MARK, qualifiedDescriptor)).isFalse();
	}

	@Test
	public void testAutowireCandidateExplicitlyFalseWithFieldDescriptor() throws Exception {
		DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
		ConstructorArgumentValues cavs = new ConstructorArgumentValues();
		cavs.addGenericArgumentValue(JUERGEN);
		RootBeanDefinition person = new RootBeanDefinition(Person.class, cavs, null);
		person.setAutowireCandidate(false);
		person.addQualifier(new AutowireCandidateQualifier(TestQualifier.class));
		lbf.registerBeanDefinition(JUERGEN, person);
		DependencyDescriptor qualifiedDescriptor = new DependencyDescriptor(
				QualifiedTestBean.class.getDeclaredField("qualified"), false);
		DependencyDescriptor nonqualifiedDescriptor = new DependencyDescriptor(
				QualifiedTestBean.class.getDeclaredField("nonqualified"), false);
		assertThat(lbf.isAutowireCandidate(JUERGEN, null)).isFalse();
		assertThat(lbf.isAutowireCandidate(JUERGEN, nonqualifiedDescriptor)).isFalse();
		assertThat(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor)).isFalse();
	}

	@Test
	public void testAutowireCandidateWithShortClassName() throws Exception {
		DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
		ConstructorArgumentValues cavs = new ConstructorArgumentValues();
		cavs.addGenericArgumentValue(JUERGEN);
		RootBeanDefinition person = new RootBeanDefinition(Person.class, cavs, null);
		person.addQualifier(new AutowireCandidateQualifier(ClassUtils.getShortName(TestQualifier.class)));
		lbf.registerBeanDefinition(JUERGEN, person);
		DependencyDescriptor qualifiedDescriptor = new DependencyDescriptor(
				QualifiedTestBean.class.getDeclaredField("qualified"), false);
		DependencyDescriptor nonqualifiedDescriptor = new DependencyDescriptor(
				QualifiedTestBean.class.getDeclaredField("nonqualified"), false);
		assertThat(lbf.isAutowireCandidate(JUERGEN, null)).isTrue();
		assertThat(lbf.isAutowireCandidate(JUERGEN, nonqualifiedDescriptor)).isTrue();
		assertThat(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor)).isTrue();
	}

	@Disabled
	@Test
	public void testAutowireCandidateWithConstructorDescriptor() throws Exception {
		DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
		ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
		cavs1.addGenericArgumentValue(JUERGEN);
		RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
		person1.addQualifier(new AutowireCandidateQualifier(TestQualifier.class));
		lbf.registerBeanDefinition(JUERGEN, person1);
		ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
		cavs2.addGenericArgumentValue(MARK);
		RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
		lbf.registerBeanDefinition(MARK, person2);
		MethodParameter param = new MethodParameter(QualifiedTestBean.class.getDeclaredConstructor(Person.class), 0);
		DependencyDescriptor qualifiedDescriptor = new DependencyDescriptor(param, false);
		param.initParameterNameDiscovery(new DefaultParameterNameDiscoverer());
		assertThat(param.getParameterName()).isEqualTo("tpb");
		assertThat(lbf.isAutowireCandidate(JUERGEN, null)).isTrue();
		assertThat(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor)).isTrue();
		assertThat(lbf.isAutowireCandidate(MARK, qualifiedDescriptor)).isFalse();
	}

	@Disabled
	@Test
	public void testAutowireCandidateWithMethodDescriptor() throws Exception {
		DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
		ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
		cavs1.addGenericArgumentValue(JUERGEN);
		RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
		person1.addQualifier(new AutowireCandidateQualifier(TestQualifier.class));
		lbf.registerBeanDefinition(JUERGEN, person1);
		ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
		cavs2.addGenericArgumentValue(MARK);
		RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
		lbf.registerBeanDefinition(MARK, person2);
		MethodParameter qualifiedParam =
				new MethodParameter(QualifiedTestBean.class.getDeclaredMethod("autowireQualified", Person.class), 0);
		MethodParameter nonqualifiedParam =
				new MethodParameter(QualifiedTestBean.class.getDeclaredMethod("autowireNonqualified", Person.class), 0);
		DependencyDescriptor qualifiedDescriptor = new DependencyDescriptor(qualifiedParam, false);
		DependencyDescriptor nonqualifiedDescriptor = new DependencyDescriptor(nonqualifiedParam, false);
		qualifiedParam.initParameterNameDiscovery(new DefaultParameterNameDiscoverer());
		assertThat(qualifiedParam.getParameterName()).isEqualTo("tpb");
		nonqualifiedParam.initParameterNameDiscovery(new DefaultParameterNameDiscoverer());
		assertThat(nonqualifiedParam.getParameterName()).isEqualTo("tpb");
		assertThat(lbf.isAutowireCandidate(JUERGEN, null)).isTrue();
		assertThat(lbf.isAutowireCandidate(JUERGEN, nonqualifiedDescriptor)).isTrue();
		assertThat(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor)).isTrue();
		assertThat(lbf.isAutowireCandidate(MARK, null)).isTrue();
		assertThat(lbf.isAutowireCandidate(MARK, nonqualifiedDescriptor)).isTrue();
		assertThat(lbf.isAutowireCandidate(MARK, qualifiedDescriptor)).isFalse();
	}

	@Test
	public void testAutowireCandidateWithMultipleCandidatesDescriptor() throws Exception {
		DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
		ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
		cavs1.addGenericArgumentValue(JUERGEN);
		RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
		person1.addQualifier(new AutowireCandidateQualifier(TestQualifier.class));
		lbf.registerBeanDefinition(JUERGEN, person1);
		ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
		cavs2.addGenericArgumentValue(MARK);
		RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
		person2.addQualifier(new AutowireCandidateQualifier(TestQualifier.class));
		lbf.registerBeanDefinition(MARK, person2);
		DependencyDescriptor qualifiedDescriptor = new DependencyDescriptor(
				new MethodParameter(QualifiedTestBean.class.getDeclaredConstructor(Person.class), 0),
				false);
		assertThat(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor)).isTrue();
		assertThat(lbf.isAutowireCandidate(MARK, qualifiedDescriptor)).isTrue();
	}

	@SuppressWarnings("unused")
	private static class QualifiedTestBean {

		@TestQualifier
		private Person qualified;

		private Person nonqualified;

		public QualifiedTestBean(@TestQualifier Person tpb) {
		}

		public void autowireQualified(@TestQualifier Person tpb) {
		}

		public void autowireNonqualified(Person tpb) {
		}
	}

	@SuppressWarnings("unused")
	private static class Person {

		private String name;

		public Person(String name) {
			this.name = name;
		}

		public String getName() {
			return this.name;
		}
	}

	@Target({ElementType.FIELD, ElementType.PARAMETER})
	@Retention(RetentionPolicy.RUNTIME)
	@Qualifier
	private @interface TestQualifier {
	}

}


text:
// A set implemented using vectors.  Slow, but works on non-Comparables.
// (c) 1998, 2001 duane a. bailey

package io.datalayer.data.structure5;
import java.util.Iterator;

/**
 * Implementation of a set of elements using a vector as the underlying
 * storage mechanism.
 * As with the mathematical object, the elements of the set are
 * not duplicated.  No order is implied or enforced in this structure, but
 * simple set operations such as intersection, union, difference, and subset
 * are provided.
 *

 * Example Usage:
 * Given a list of students who completed a computer science thesis in the
 * 2001-2002 academic year at Williams College and a list of graduating
 * computer science majors who are continuing on to graduate school, we could
 * determine which thesis students are planning to attend graduate school
 * as follows:
 *

 *

 * public static void main(String... argv){
 *      //thesis students in the class of '02
 *      String[] thesis = new String[]{"Doug", "Evan", "Feng"};
 *
 *      //students continuing on to grad school
 *      String[] grad = new String[]{"Doug", "Feng", "Lida"};
 *
 *      //instantiate our sets
 *      Set thesisSet = new {@link #SetVector()},
 *          gradSet = new {@link #SetVector()};
 *
 *      //build sets up
 *      for(int i = 0; i < thesis.length; i++) thesisSet.{@link #add(Object) add(thesis[i])};
 *      for(int i = 0; i < grad.length; i++) gradSet.{@link #add(Object) add(grad[i])};
 *
 *      //calculate the intersection of the two sets
 *      thesisSet.{@link #retainAll(Structure) retainAll(gradSet)};
 *      System.out.println(thesisSet);
 * }
 *

 * @version $Id: SetVector.java 22 2006-08-21 19:27:26Z bailey $
 * @author, 2001 duane a. bailey
 */
public class SetVector<E> extends AbstractSet<E>
{
    /**
     * The underlying structure --- a vector.
     */
    protected Vector<E> data; // the underlying vector

    /**
     * Construct a new set.
     *
     * @post constructs a new, empty set
     */
    public SetVector()
    {
        data = new Vector<E>();
    }

    /**
     * Construct a new set from another structure.
     * @post constructs a new set with elements from other
     */
    public SetVector(Structure<E> other)
    {
        this();
        addAll(other);
    }

    /**
     * Remove all the elements from the set.
     *
     * @post elements of set are removed
     */
    public void clear()
    {
        data.clear();
    }

    /**
     * Determine if the set is empty.
     *
     * @post returns true iff set is empty
     *
     * @return True iff there are no elements in set.
     */
    public boolean isEmpty()
    {
        return data.isEmpty();
    }

    /**
     * Add an element to set, if not already present.
     *
     * @pre e is non-null object
     * @post adds element e to set
     *
     * @param e The new value to be added to set.
     */
    public void add(E e)
    {
        if (!data.contains(e)) data.add(e);
    }

    /**
     * Remove an element from the set.
     *
     * @pre e is non-null object
     * @post e is removed from set, value returned
     *
     * @param e The element of the set to be removed.
     * @return The value actually removed.
     */
    public E remove(E e)
    {
        return data.remove(e);
    }

    /**
     * Returns true if value is an element of the set.
     *
     * @pre e is non-null
     * @post returns true iff e is in set
     *
     * @param e The element sought in set.
     * @return True iff the element is in the set.
     */
    public boolean contains(E e)
    {
        return data.contains(e);
    }

    /**
     * Determine if this set is a subset of other.
     *
     * @pre other is non-null reference to set
     * @post returns true iff this set is subset of other
     *
     * @param other The potential superset.
     */
    public boolean containsAll(Structure<E> other)
    {
        Iterator<E> myElements = data.iterator();
        while (myElements.hasNext())
        {
            if (!other.contains(myElements.next())) return false;
        }
        return true;
    }

    /**
     * Returns a shallow clone of this set.
     *
     * @post returns a copy of set
     *
     * @return A new set with same values.
     */
    public Object clone()
    {
        Set<E> result = new SetVector<E>();
        Iterator<E> myElements = iterator();
        while (myElements.hasNext()) {
            result.add(myElements.next());
        }
        return result;
    }

    /**
     * Compute the union of this set with other.
     *
     * @pre other is a non-null structure
     * @post add all elements of other to set, if needed
     * @param other The set to be unioned with this.
     */
    public void addAll(Structure<E> other)
    {
        Iterator<E> yourElements = other.iterator();
        while (yourElements.hasNext())
        {
            add(yourElements.next());
        }
    }

    /**
     * Compute the intersection of this set and other.
     * Members of result are in both this and other.
     *
     * @pre other is non-null reference to set
     * @post returns set containing intersection of this and other
     *
     * @param other The other set to be intersected with this.
     * @return Intersection of this and other.
     */
    public void retainAll(Structure<E> other)
    {
        Set<E> temp = new SetVector<E>();
        //error! temp should have been data FIXED
        Iterator<E> myElements = data.iterator();
        while (myElements.hasNext())
        {
            E v = myElements.next();
            if (other.contains(v))
            {
                temp.add(v);
            }
        }
        clear();
        addAll(temp);
    }

    /**
     * Compute the difference between two sets.
     * Values of the result are members of this, but not other.
     * @pre other is non-null reference to set
     * @post returns set containing difference of this and other
     *
     * @param other The set whose values are to be eliminated from this.
     * @return Difference between this and other.
     */
    public void removeAll(Structure<E> other)
    {
        Iterator<E> yourElements = other.iterator();
        while (yourElements.hasNext())
        {
            remove(yourElements.next());
        }
    }

    /**
     * Construct an traversal to traverse the elements of the set.
     * Elements will not appear in any particular order.
     *
     * @post returns traversal to traverse the elements of set
     *
     * @return An traversal for inspecting members of the set.
     */
    public Iterator<E> iterator()
    {
        return data.iterator();
    }

    /**
     * Determine the number of elements in the set.
     *
     * @post returns number of elements in set
     *
     * @return The number of elements in the set.
     */
    public int size()
    {
        return data.size();
    }

    /**
     * Construct a string representation of the set.
     *
     * @post returns a string representation of set
     *
     * @return A string representing the set.
     */
    public String toString()
    {
        return "<SetVector: "+data+">";
    }

    public static void main(String... argv){
        //thesis students in the class of '02
        String[] thesis = new String[]{"Doug", "Evan", "Feng"};

        //students continuing on to grad school
        String[] grad = new String[]{"Doug", "Feng", "Lida"};

        //instantiate our sets
        Set<String> thesisSet = new SetVector<String>(),
            gradSet = new SetVector<String>();

        //build sets up
        for(int i = 0; i < thesis.length; i++) thesisSet.add(thesis[i]);
        for(int i = 0; i < grad.length; i++) gradSet.add(grad[i]);

        //calculate the intersection of the two sets
        thesisSet.retainAll(gradSet);
        System.out.println(thesisSet);
    }
}