text:
drop index ACT_IDX_HI_PROCVAR_NAME_TYPE;
drop index ACT_IDX_HI_VAR_SCOPE_ID_TYPE;
drop index ACT_IDX_HI_VAR_SUB_ID_TYPE;

drop table ACT_HI_VARINST;

redpajama_set_name: RedPajamaGithub


text:
package fi.csc.chipster.rest.websocket;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.glassfish.tyrus.client.ClientManager;
import org.glassfish.tyrus.core.HandshakeException;

import jakarta.websocket.CloseReason;
import jakarta.websocket.CloseReason.CloseCodes;
import jakarta.websocket.DeploymentException;

public class RetryHandler extends ClientManager.ReconnectHandler {

	private static final Logger logger = LogManager.getLogger();

	private int counter = 0;
	private int retries = -1;

	private String name;

	private volatile boolean close = false;

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

	@Override
	public boolean onDisconnect(CloseReason closeReason) {
		if (close) {
			// don't reconnect when we are trying to close the connection on purpose
			return false;
		}

		if (CloseCodes.VIOLATED_POLICY == closeReason.getCloseCode()) {
			logger.error("reconnection cancelled");
			throw new RuntimeException(new WebSocketClosedException(closeReason));
		}
		counter++;
		if (retries < 0 || counter <= retries) {
			logger.info("reconnecting... (" + counter + "/" + retries + ")");
			return true;
		} else {
			return false;
		}
	}

	@Override
	public boolean onConnectFailure(Exception exception) {
		logger.info("websocket client " + name + " connection failure", exception);

		// HTTP upgrade request errors
		if (exception instanceof DeploymentException && exception.getCause() instanceof HandshakeException) {
			logger.error("unrecoverable connection failure, reconnection cancelled");
			return false;
		}

		// VIOLATE_POLICY from onDisconnect(). Should we check the close reason also here?
		if (exception instanceof RuntimeException && exception.getCause() instanceof WebSocketClosedException) {
			logger.error("unrecoverable websocket close, reconnection cancelled");
			return false;
		}

		counter++;
		if (retries < 0 || counter <= retries) {
			logger.info("reconnecting... (" + counter + "/" + retries + ")");
			return true;
		} else {
			return false;
		}
	}

	@Override
	public long getDelay() {
		if (counter < 1) {
			return 0;
		} else if (counter < 15) {
			return 1;
		} else if (counter < 30) {
			return 10;
		} else {
			return 60;
		}
	}

	public void close() {
		this.close = true;
	}

	public void reset() {
		counter = 0;
	}
}


text:
/**
 *
 */
package com.hotf.client.action.result;

import java.util.ArrayList;
import java.util.List;

import net.customware.gwt.dispatch.shared.Result;

/**
 * @author Jeff
 *
 */
public class GamesResult implements Result {

	private List<GameResult> games = new ArrayList<GameResult>();

	public GamesResult() {
		super();
	}

	public List<GameResult> getGames() {
		return games;
	}

}


text:
package com.tomkasp.training.domain;

/**
 * @author Tomasz Kasprzycki
 */
public class MeasureSystem {

    MeasureType measureType;

    public MeasureSystem() {
        super();
    }

    public MeasureSystem(MeasureType measureType) {
        this.measureType = measureType;
    }

    public String getMassUnit() {
        if (measureType.equals(MeasureType.Metric)) {
            return "kg";
        } else {
            return "pound";
        }
    }

    public String getHeightUnit() {
        if (measureType.equals(MeasureType.Metric)) {
            return "cm";
        } else {
            return "foot";
        }
    }
}


text:
package com.founder.fix.fixflow.core.impl.cmd;

import com.founder.fix.fixflow.core.impl.bpmn.behavior.ProcessDefinitionBehavior;
import com.founder.fix.fixflow.core.impl.bpmn.behavior.UserTaskBehavior;
import com.founder.fix.fixflow.core.impl.expression.ExpressionMgmt;
import com.founder.fix.fixflow.core.impl.interceptor.Command;
import com.founder.fix.fixflow.core.impl.interceptor.CommandContext;
import com.founder.fix.fixflow.core.impl.persistence.ProcessDefinitionManager;

public class GetTaskFormByNodeId<T> implements Command<String> {

	protected String processDefinitionId;
	protected String nodeId;

	public GetTaskFormByNodeId(String processDefinitionId, String nodeId) {
		this.processDefinitionId = processDefinitionId;
		this.nodeId = nodeId;
	}

	public String execute(CommandContext commandContext) {

		ProcessDefinitionManager processDefinitionManager = commandContext.getProcessDefinitionManager();

		ProcessDefinitionBehavior processDefinition = processDefinitionManager
				.findLatestProcessDefinitionById(processDefinitionId);
		UserTaskBehavior userTask = (UserTaskBehavior) processDefinition.getDefinitions().getElement(nodeId);
		Object returnFormUri = null;
		if(userTask.getFormUri()!=null && !userTask.getFormUri().equals(""))
			returnFormUri=ExpressionMgmt.execute(userTask.getFormUri(),processDefinition);
		if(returnFormUri!=null && !returnFormUri.equals("")){
			return returnFormUri.toString();
		}
		else{
			String defaultFormUri=processDefinition.getDefaultFormUri();
			if(defaultFormUri != null && !defaultFormUri.equals("")){
					return defaultFormUri.toString();
			}

		}

		return null;
	}
}


text:
/*
** Author: DH	Date: October 2015
** Purpose: Write a Java application to input a single integer value and output the
**			 corresponding number of *'s
*/

public class Ex2q2
{

	public static void main(String args[])
	{
		int input=0;
		boolean exit = false;

		while(!exit){

			System.out.println("\n No of stars ? (-1 to quit): ");
			input = EasyIn.getInt();

			if(input==-1){
				exit=true;
				System.out.println("Goodbye!");
			}

			for(int i=0; i<input; i++){
				System.out.print("*");
			}

		}
	}
}


text:
package org.kalnee.trivor.nlp.domain;

import java.util.HashSet;
import java.util.Set;

import static java.util.stream.Collectors.toSet;

public class PhrasalVerbUsage {

    private String phrasalVerb;

    private Set<String> sentences = new HashSet<>();

    public PhrasalVerbUsage() {
    }

    public PhrasalVerbUsage(String phrasalVerb, Set<String> sentences) {
        this.phrasalVerb = phrasalVerb;
        this.sentences = sentences;
    }

    public String getPhrasalVerb() {
        return phrasalVerb;
    }

    public void setPhrasalVerb(String phrasalVerb) {
        this.phrasalVerb = phrasalVerb;
    }

    public Set<String> getSentences() {
        return sentences;
    }

    public void setSentences(Set<String> sentences) {
        this.sentences = sentences;
    }

    @Override
    public String toString() {
        return "PhrasalVerbUsage{" +
                "phrasalVerb='" + phrasalVerb + '\'' +
                ", sentences=" + sentences.stream().limit(2).collect(toSet()) +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        PhrasalVerbUsage that = (PhrasalVerbUsage) o;

        return phrasalVerb != null ? phrasalVerb.equals(that.phrasalVerb) : that.phrasalVerb == null;
    }

    @Override
    public int hashCode() {
        return phrasalVerb != null ? phrasalVerb.hashCode() : 0;
    }
}


text:
const VoiceResponse = require('twilio').twiml.VoiceResponse;

const response = new VoiceResponse();
const pay = response.pay({
    paymentMethod: 'ach-debit',
    chargeAmount: '13.22'
});
const prompt = pay.prompt({
    for: 'bank-account-number'
});
prompt.say('Thanks for using our service. Please enter your bank account number.');
const prompt2 = pay.prompt({
    for: 'bank-account-number',
    requireMatchingInputs: true
});
prompt2.say('Thank you. Please enter your bank account number again.');
const prompt3 = pay.prompt({
    for: 'bank-account-number',
    errorType: 'input-matching-failed'
});
prompt3.say('Sorry, your two bank account number inputs did not match. Please enter your bank account number again. We will then ask a second time again.');

console.log(response.toString());


text:
package matchers

import "gopkg.in/h2non/filetype.v1/types"

// Internal shortcut to NewType
var newType = types.NewType

// Matcher function interface as type alias
type Matcher func([]byte) bool

// Type interface to store pairs of type with its matcher function
type Map map[types.Type]Matcher

// Type specific matcher function interface
type TypeMatcher func([]byte) types.Type

// Store registered file type matchers
var Matchers = make(map[types.Type]TypeMatcher)

// Create and register a new type matcher function
func NewMatcher(kind types.Type, fn Matcher) TypeMatcher {
	matcher := func(buf []byte) types.Type {
		if fn(buf) {
			return kind
		}
		return types.Unknown
	}

	Matchers[kind] = matcher
	return matcher
}

func register(matchers ...Map) {
	for _, m := range matchers {
		for kind, matcher := range m {
			NewMatcher(kind, matcher)
		}
	}
}

func init() {
	// Arguments order is intentional
	register(Image, Video, Audio, Font, Document, Archive)
}


text:
<template>
	<require from="./breadcrumbs.css"></require>
	<require from="./instructionFilter"></require>

				<template repeat.for="instruction of router.currentInstruction.getAllInstructions() | instructionFilter">

						${instruction.config.title}

				</template>

</template>


text:
@interface SRShop : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *price;

@end


text:
id: 5900f5361000cf542c510048
challengeType: 5
isHidden: false
title: 'Problem 457: A polynomial modulo the square of a prime'
forumTopicId: 302131
---

## Description

Let f(n) = n2 - 3n - 1.
Let p be a prime.
Let R(p) be the smallest positive integer n such that f(n) mod p2 = 0 if such an integer n exists, otherwise R(p) = 0.

Let SR(L) be ∑R(p) for all primes not exceeding L.

Find SR(107).

## Instructions

## Tests

```yml
tests:
  - text: <code>euler457()</code> should return 2647787126797397000.
    testString: assert.strictEqual(euler457(), 2647787126797397000);

```

## Challenge Seed

```js
function euler457() {
  // Good luck!
  return true;
}

euler457();
```

## Solution

```js
// solution required
```


text:
/*	$OpenBSD: umass_quirks.c,v 1.6 2003/05/19 01:02:39 nate Exp $	*/
/*	$NetBSD: umass_quirks.c,v 1.39 2003/05/08 15:19:47 augustss Exp $	*/

/*
 * Copyright (c) 2001 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by MAEKAWA Masahide (gehenna@NetBSD.org).
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	  This product includes software developed by the NetBSD
 *	  Foundation, Inc. and its contributors.
 * 4. Neither the name of The NetBSD Foundation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/buf.h>

#if defined(__NetBSD__)
#include <dev/scsipi/scsipi_all.h> /* for scsiconf.h below */
#include <dev/scsipi/scsiconf.h> /* for quirks defines */
#elif defined(__OpenBSD__)
#include <scsi/scsi_all.h>
#include <scsi/scsiconf.h>
#endif

#include <dev/usb/usb.h>
#include <dev/usb/usbdi.h>
#include <dev/usb/usbdevs.h>

#include <dev/usb/umassvar.h>
#include <dev/usb/umass_quirks.h>

Static usbd_status umass_init_insystem(struct umass_softc *);
Static usbd_status umass_init_shuttle(struct umass_softc *);

Static void umass_fixup_sony(struct umass_softc *);
Static void umass_fixup_yedata(struct umass_softc *);

Static const struct umass_quirk umass_quirks[] = {
	{ { USB_VENDOR_ATI, USB_PRODUCT_ATI2_205 },
	  UMASS_WPROTO_BBB, UMASS_CPROTO_ISD_ATA,
	  0,
	  0,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_DMI, USB_PRODUCT_DMI_SA2_0 },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  PQUIRK_NOMODESENSE,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_EASYDISK, USB_PRODUCT_EASYDISK_EASYDISK },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  PQUIRK_NOMODESENSE,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_FUJIPHOTO, USB_PRODUCT_FUJIPHOTO_MASS0100 },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  UMASS_QUIRK_NO_START_STOP,
	  PQUIRK_NOTUR | PQUIRK_NOSENSE,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_GENESYS, USB_PRODUCT_GENESYS_GL641USB },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  UMASS_QUIRK_FORCE_SHORT_INQUIRY | UMASS_QUIRK_NO_START_STOP,
	  PQUIRK_NOMODESENSE,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_HP, USB_PRODUCT_HP_CDWRITERPLUS },
	  UMASS_WPROTO_CBI, UMASS_CPROTO_ATAPI,
	  0,
	  PQUIRK_NOSENSE | PQUIRK_NOMODESENSE,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_IMATION, USB_PRODUCT_IMATION_FLASHGO },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  PQUIRK_NODOORLOCK,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_INSYSTEM, USB_PRODUCT_INSYSTEM_ADAPTERV2 },
	  UMASS_WPROTO_BBB, UMASS_CPROTO_ISD_ATA,
	  0,
	  0,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_INSYSTEM, USB_PRODUCT_INSYSTEM_ATAPI },
	  UMASS_WPROTO_BBB, UMASS_CPROTO_ISD_ATA,
	  0,
	  0,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_INSYSTEM, USB_PRODUCT_INSYSTEM_DRIVEV2_5 },
	  UMASS_WPROTO_BBB, UMASS_CPROTO_ISD_ATA,
	  0,
	  0,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_INSYSTEM, USB_PRODUCT_INSYSTEM_IDEUSB2 },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  PQUIRK_NOMODESENSE,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_INSYSTEM, USB_PRODUCT_INSYSTEM_USBCABLE },
	  UMASS_WPROTO_CBI, UMASS_CPROTO_ATAPI,
	  UMASS_QUIRK_NO_START_STOP,
	  PQUIRK_NOTUR,
	  UMATCH_VENDOR_PRODUCT,
	  umass_init_insystem, NULL
	},

	{ { USB_VENDOR_IODATA2, USB_PRODUCT_IODATA2_USB2SC },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  0,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_IOMEGA, USB_PRODUCT_IOMEGA_ZIP100 },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  PQUIRK_NOTUR,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_IOMEGA, USB_PRODUCT_IOMEGA_ZIP250 },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  PQUIRK_NOTUR,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_IOMEGA, USB_PRODUCT_IOMEGA_ZIP250_2 },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  UMASS_QUIRK_NO_START_STOP,
	  PQUIRK_NOTUR,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_MELCO, USB_PRODUCT_MELCO_DUBPXXG },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  UMASS_QUIRK_FORCE_SHORT_INQUIRY | UMASS_QUIRK_NO_START_STOP,
	  PQUIRK_NOMODESENSE,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_MICROTECH, USB_PRODUCT_MICROTECH_DPCM },
	  UMASS_WPROTO_CBI, UMASS_CPROTO_ATAPI,
	  0,
	  PQUIRK_NOTUR,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_MINOLTA, USB_PRODUCT_MINOLTA_S304 },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  UMASS_QUIRK_NO_MAX_LUN | UMASS_QUIRK_NO_START_STOP,
	  0,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_MINOLTA, USB_PRODUCT_MINOLTA_X },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  UMASS_QUIRK_NO_MAX_LUN | UMASS_QUIRK_NO_START_STOP,
	  0,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_MSYSTEMS, USB_PRODUCT_MSYSTEMS_DISKONKEY },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  UMASS_QUIRK_NO_MAX_LUN,
	  PQUIRK_NOMODESENSE | PQUIRK_NODOORLOCK | PQUIRK_NOBIGMODESENSE,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_MSYSTEMS, USB_PRODUCT_MSYSTEMS_DISKONKEY2 },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  UMASS_QUIRK_NO_MAX_LUN,
	  PQUIRK_NOMODESENSE | PQUIRK_NODOORLOCK | PQUIRK_NOBIGMODESENSE,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_NEODIO, USB_PRODUCT_NEODIO_ND3050 },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  PQUIRK_NOMODESENSE | PQUIRK_FORCELUNS,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_NEODIO, USB_PRODUCT_NEODIO_ND5010 },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  PQUIRK_NOMODESENSE | PQUIRK_FORCELUNS,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_OLYMPUS, USB_PRODUCT_OLYMPUS_C1 },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  UMASS_QUIRK_WRONG_CSWSIG,
	  0,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_OLYMPUS, USB_PRODUCT_OLYMPUS_C700 },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  PQUIRK_ONLYBIG | SDEV_NOSYNCCACHE,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_ONSPEC, USB_PRODUCT_ONSPEC_MD1II },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  UMASS_QUIRK_NO_MAX_LUN | UMASS_QUIRK_NO_START_STOP,
	  PQUIRK_NOMODESENSE,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_ONSPEC, USB_PRODUCT_ONSPEC_MD2 },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  PQUIRK_NOMODESENSE,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_OTI, USB_PRODUCT_OTI_SOLID },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  PQUIRK_NOMODESENSE | PQUIRK_NOBIGMODESENSE,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_PEN, USB_PRODUCT_PEN_MOBILEDRIVE },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  PQUIRK_NOMODESENSE | PQUIRK_NODOORLOCK | PQUIRK_FORCELUNS,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_PEN, USB_PRODUCT_PEN_USBDISK },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  UMASS_QUIRK_NO_MAX_LUN | UMASS_QUIRK_NO_START_STOP,
	  0,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_PEN, USB_PRODUCT_PEN_USBREADER },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  PQUIRK_NOMODESENSE,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_PILOTECH, USB_PRODUCT_PILOTECH_CRW600 },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  PQUIRK_NOMODESENSE | PQUIRK_FORCELUNS,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_PQI, USB_PRODUCT_PQI_TRAVELFLASH },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  PQUIRK_NOMODESENSE | PQUIRK_NODOORLOCK,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_SCANLOGIC, USB_PRODUCT_SCANLOGIC_SL11R },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UFI,
	  UMASS_QUIRK_WRONG_CSWTAG,
	  0,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_SHUTTLE, USB_PRODUCT_SHUTTLE_EUSB },
	  UMASS_WPROTO_CBI_I, UMASS_CPROTO_ATAPI,
	  UMASS_QUIRK_NO_START_STOP,
	  PQUIRK_NOTUR,
	  UMATCH_VENDOR_PRODUCT,
	  umass_init_shuttle, NULL
	},

	{ { USB_VENDOR_SHUTTLE, USB_PRODUCT_SHUTTLE_ZIOMMC },
	  UMASS_WPROTO_CBI_I, UMASS_CPROTO_ATAPI,
	  UMASS_QUIRK_NO_START_STOP,
	  PQUIRK_NOTUR,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_SIIG, USB_PRODUCT_SIIG_MULTICARDREADER },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  UMASS_QUIRK_NO_START_STOP,
	  0,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL,NULL
	},

	{ { USB_VENDOR_SONY, USB_PRODUCT_SONY_DRIVEV2 },
	  UMASS_WPROTO_BBB, UMASS_CPROTO_ISD_ATA,
	  0,
	  0,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_SONY, USB_PRODUCT_SONY_DSC },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  0,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, umass_fixup_sony
	},

	{ { USB_VENDOR_SONY, USB_PRODUCT_SONY_MSC },
	  UMASS_WPROTO_CBI, UMASS_CPROTO_UFI,
	  UMASS_QUIRK_FORCE_SHORT_INQUIRY | UMASS_QUIRK_RS_NO_CLEAR_UA,
	  PQUIRK_NOMODESENSE,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_TEAC, USB_PRODUCT_TEAC_FD05PUB },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  PQUIRK_NOMODESENSE,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_TREK, USB_PRODUCT_TREK_THUMBDRIVE_8MB },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UNSPEC,
	  0,
	  PQUIRK_NODOORLOCK,
	  UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO,
	  NULL, NULL
	},

	{ { USB_VENDOR_TRUMPION, USB_PRODUCT_TRUMPION_XXX1100 },
	  UMASS_WPROTO_CBI, UMASS_CPROTO_ATAPI,
	  0,
	  0,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_YANO, USB_PRODUCT_YANO_U640MO },
	  UMASS_WPROTO_CBI_I, UMASS_CPROTO_ATAPI,
	  UMASS_QUIRK_FORCE_SHORT_INQUIRY,
	  0,
	  UMATCH_VENDOR_PRODUCT,
	  NULL, NULL
	},

	{ { USB_VENDOR_YEDATA, USB_PRODUCT_YEDATA_FLASHBUSTERU },
	  UMASS_WPROTO_UNSPEC, UMASS_CPROTO_UFI,
	  UMASS_QUIRK_RS_NO_CLEAR_UA,
	  PQUIRK_NOMODESENSE,
	  UMATCH_VENDOR_PRODUCT_REV,
	  NULL, umass_fixup_yedata
	},

};

const struct umass_quirk *
umass_lookup(u_int16_t vendor, u_int16_t product)
{
	return ((const struct umass_quirk *)
		usb_lookup(umass_quirks, vendor, product));
}

Static usbd_status
umass_init_insystem(struct umass_softc *sc)
{
	usbd_status err;

	err = usbd_set_interface(sc->sc_iface, 1);
	if (err) {
		DPRINTF(UDMASS_USB,
			("%s: could not switch to Alt Interface 1\n",
			USBDEVNAME(sc->sc_dev)));
		return (err);
	}

	return (USBD_NORMAL_COMPLETION);
}

Static usbd_status
umass_init_shuttle(struct umass_softc *sc)
{
	usb_device_request_t req;
	u_int8_t status[2];

	/* The Linux driver does this */
	req.bmRequestType = UT_READ_VENDOR_DEVICE;
	req.bRequest = 1;
	USETW(req.wValue, 0);
	USETW(req.wIndex, sc->sc_ifaceno);
	USETW(req.wLength, sizeof(status));

	return (usbd_do_request(sc->sc_udev, &req, &status));
}

Static void
umass_fixup_sony(struct umass_softc *sc)
{
	usb_interface_descriptor_t *id;

	id = usbd_get_interface_descriptor(sc->sc_iface);
	if (id->bInterfaceSubClass == 0xff) {
		sc->sc_cmd = UMASS_CPROTO_RBC;
	}
}

Static void
umass_fixup_yedata(struct umass_softc *sc)
{
	usb_device_descriptor_t *dd;

	dd = usbd_get_device_descriptor(sc->sc_udev);

	/*
	 * Revisions < 1.28 do not handle the interrupt endpoint very well.
	 */
	if (UGETW(dd->bcdDevice) < 0x128)
		sc->sc_wire = UMASS_WPROTO_CBI;
	else
		sc->sc_wire = UMASS_WPROTO_CBI_I;

	/*
	 * Revisions < 1.28 do not have the TEST UNIT READY command
	 * Revisions == 1.28 have a broken TEST UNIT READY
	 */
	if (UGETW(dd->bcdDevice) <= 0x128)
		sc->sc_busquirks |= PQUIRK_NOTUR;
}


text:
namespace blink {
class WebFrameWidget;
class WebLocalFrame;
class WebView;
class WebWidget;
struct WebContextMenuData;
}  // namespace blink

namespace gin {
class Arguments;
}  // namespace gin

namespace content {

class TestInterfaces;
class WebWidgetTestProxy;
class BlinkTestRunner;

// Key event location code introduced in DOM Level 3.
// See also: http://www.w3.org/TR/DOM-Level-3-Events/#events-keyboardevents
enum KeyLocationCode {
  DOMKeyLocationStandard = 0x00,
  DOMKeyLocationLeft = 0x01,
  DOMKeyLocationRight = 0x02,
  DOMKeyLocationNumpad = 0x03
};

class EventSender {
 public:
  explicit EventSender(WebWidgetTestProxy*);
  virtual ~EventSender();

  void Reset();
  void Install(blink::WebLocalFrame*);

  void SetContextMenuData(const blink::WebContextMenuData&);

  void DoDragDrop(const blink::WebDragData&, blink::WebDragOperationsMask);

 private:
  friend class EventSenderBindings;

  void MouseDown(int button_number, int modifiers);
  void MouseUp(int button_number, int modifiers);
  void PointerDown(int button_number,
                   int modifiers,
                   blink::WebPointerProperties::PointerType,
                   int pointerId,
                   float pressure,
                   int tiltX,
                   int tiltY);
  void PointerUp(int button_number,
                 int modifiers,
                 blink::WebPointerProperties::PointerType,
                 int pointerId,
                 float pressure,
                 int tiltX,
                 int tiltY);
  void SetMouseButtonState(int button_number, int modifiers);

  void KeyDown(const std::string& code_str,
               int modifiers,
               KeyLocationCode location);

  struct SavedEvent {
    enum SavedEventType {
      TYPE_UNSPECIFIED,
      TYPE_MOUSE_UP,
      TYPE_MOUSE_MOVE,
      TYPE_LEAP_FORWARD
    };

    SavedEvent();

    SavedEventType type;
    blink::WebMouseEvent::Button button_type;  // For MouseUp.
    gfx::PointF pos;                           // For MouseMove.
    int milliseconds;                          // For LeapForward.
    int modifiers;
  };

  enum class MouseScrollType { PIXEL, TICK };

  void EnableDOMUIEventLogging();
  void FireKeyboardEventsToElement();
  void ClearKillRing();

  std::vector<std::string> ContextClick();

  void TextZoomIn();
  void TextZoomOut();

  void ZoomPageIn();
  void ZoomPageOut();
  void SetPageZoomFactor(double zoom_factor);

  void ClearTouchPoints();
  void ReleaseTouchPoint(unsigned index);
  void UpdateTouchPoint(unsigned index, float x, float y, gin::Arguments* args);
  void CancelTouchPoint(unsigned index);
  void SetTouchModifier(const std::string& key_name, bool set_mask);
  void SetTouchCancelable(bool cancelable);
  void ThrowTouchPointError();

  void DumpFilenameBeingDragged();

  void GestureScrollFirstPoint(float x, float y);

  void TouchStart(gin::Arguments* args);
  void TouchMove(gin::Arguments* args);
  void TouchCancel(gin::Arguments* args);
  void TouchEnd(gin::Arguments* args);
  void NotifyStartOfTouchScroll();

  void LeapForward(int milliseconds);

  void BeginDragWithItems(
      const blink::WebVector<blink::WebDragData::Item>& items);
  void BeginDragWithFiles(const std::vector<std::string>& files);
  void BeginDragWithStringData(const std::string& data,
                               const std::string& mime_type);

  void AddTouchPoint(float x, float y, gin::Arguments* args);

  void GestureScrollBegin(blink::WebLocalFrame* frame, gin::Arguments* args);
  void GestureScrollEnd(blink::WebLocalFrame* frame, gin::Arguments* args);
  void GestureScrollUpdate(blink::WebLocalFrame* frame, gin::Arguments* args);
  void GestureTap(blink::WebLocalFrame* frame, gin::Arguments* args);
  void GestureTapDown(blink::WebLocalFrame* frame, gin::Arguments* args);
  void GestureShowPress(blink::WebLocalFrame* frame, gin::Arguments* args);
  void GestureTapCancel(blink::WebLocalFrame* frame, gin::Arguments* args);
  void GestureLongPress(blink::WebLocalFrame* frame, gin::Arguments* args);
  void GestureLongTap(blink::WebLocalFrame* frame, gin::Arguments* args);
  void GestureTwoFingerTap(blink::WebLocalFrame* frame, gin::Arguments* args);

  void MouseScrollBy(gin::Arguments* args, MouseScrollType scroll_type);
  void MouseMoveTo(blink::WebLocalFrame* frame, gin::Arguments* args);
  void MouseLeave(blink::WebPointerProperties::PointerType, int pointerId);
  void ScheduleAsynchronousClick(blink::WebLocalFrame* frame,
                                 int button_number,
                                 int modifiers);
  void ScheduleAsynchronousKeyDown(blink::WebLocalFrame* frame,
                                   const std::string& code_str,
                                   int modifiers,
                                   KeyLocationCode location);
  // Consumes the transient user activation state for follow-up tests that don't
  // expect it.
  void ConsumeUserActivation();

  base::TimeTicks GetCurrentEventTime() const;

  void DoLeapForward(int milliseconds);

  uint32_t GetUniqueTouchEventId(gin::Arguments* args);
  void SendCurrentTouchEvent(blink::WebInputEvent::Type, gin::Arguments* args);

  void GestureEvent(blink::WebInputEvent::Type,
                    blink::WebLocalFrame* frame,
                    gin::Arguments* args);

  void UpdateClickCountForButton(blink::WebMouseEvent::Button);

  blink::WebMouseWheelEvent GetMouseWheelEvent(gin::Arguments* args,
                                               MouseScrollType scroll_type,
                                               bool* send_gestures);
  void InitPointerProperties(gin::Arguments* args,
                             blink::WebPointerProperties* e,
                             float* radius_x,
                             float* radius_y);

  void FinishDragAndDrop(const blink::WebMouseEvent&, blink::WebDragOperation);

  int ModifiersForPointer(int pointer_id);
  void DoDragAfterMouseUp(const blink::WebMouseEvent&);
  void DoDragAfterMouseMove(const blink::WebMouseEvent&);
  void ReplaySavedEvents();
  blink::WebInputEventResult HandleInputEventOnViewOrPopup(
      const blink::WebInputEvent& event);

  void SendGesturesForMouseWheelEvent(
      const blink::WebMouseWheelEvent wheel_event);

  void UpdateLifecycleToPrePaint();

  base::TimeTicks last_event_timestamp() const { return last_event_timestamp_; }

  bool force_layout_on_events() const { return force_layout_on_events_; }
  void set_force_layout_on_events(bool force) {
    force_layout_on_events_ = force;
  }

  bool is_drag_mode() const { return is_drag_mode_; }
  void set_is_drag_mode(bool drag_mode) { is_drag_mode_ = drag_mode; }

#if defined(OS_WIN)
  int wm_key_down() const { return wm_key_down_; }
  void set_wm_key_down(int key_down) { wm_key_down_ = key_down; }

  int wm_key_up() const { return wm_key_up_; }
  void set_wm_key_up(int key_up) { wm_key_up_ = key_up; }

  int wm_char() const { return wm_char_; }
  void set_wm_char(int wm_char) { wm_char_ = wm_char; }

  int wm_dead_char() const { return wm_dead_char_; }
  void set_wm_dead_char(int dead_char) { wm_dead_char_ = dead_char; }

  int wm_sys_key_down() const { return wm_sys_key_down_; }
  void set_wm_sys_key_down(int key_down) { wm_sys_key_down_ = key_down; }

  int wm_sys_key_up() const { return wm_sys_key_up_; }
  void set_wm_sys_key_up(int key_up) { wm_sys_key_up_ = key_up; }

  int wm_sys_char() const { return wm_sys_char_; }
  void set_wm_sys_char(int sys_char) { wm_sys_char_ = sys_char; }

  int wm_sys_dead_char() const { return wm_sys_dead_char_; }
  void set_wm_sys_dead_char(int sys_dead_char) {
    wm_sys_dead_char_ = sys_dead_char;
  }

  int wm_key_down_;
  int wm_key_up_;
  int wm_char_;
  int wm_dead_char_;
  int wm_sys_key_down_;
  int wm_sys_key_up_;
  int wm_sys_char_;
  int wm_sys_dead_char_;
#endif

  WebWidgetTestProxy* web_widget_test_proxy_;
  TestInterfaces* interfaces();
  BlinkTestRunner* blink_test_runner();
  const blink::WebView* view() const;
  blink::WebView* view();
  blink::WebWidget* widget();
  blink::WebFrameWidget* MainFrameWidget();

  bool force_layout_on_events_;

  // When set to true (the default value), we batch mouse move and mouse up
  // events so we can simulate drag & drop.
  bool is_drag_mode_;

  int touch_modifiers_;
  bool touch_cancelable_;
  std::vector<blink::WebTouchPoint> touch_points_;

  std::unique_ptr<blink::WebContextMenuData> last_context_menu_data_;

  blink::WebDragData current_drag_data_;

  // Location of the touch point that initiated a gesture.
  gfx::PointF current_gesture_location_;

  // Mouse-like pointer properties.
  struct PointerState {
    // Last pressed button (Left/Right/Middle or None).
    blink::WebMouseEvent::Button pressed_button_;

    // A bitwise OR of the WebMouseEvent::*ButtonDown values corresponding to
    // currently pressed buttons of the pointer (e.g. pen or mouse).
    int current_buttons_;

    // Location of last mouseMoveTo event of this pointer.
    gfx::PointF last_pos_;

    int modifiers_;

    PointerState()
        : pressed_button_(blink::WebMouseEvent::Button::kNoButton),
          current_buttons_(0),
          modifiers_(0) {}
  };
  typedef std::unordered_map<int, PointerState> PointerStateMap;
  PointerStateMap current_pointer_state_;

  bool replaying_saved_events_;

  base::circular_deque<SavedEvent> mouse_event_queue_;

  blink::WebDragOperationsMask current_drag_effects_allowed_;

  // Time and place of the last mouse up event.
  base::TimeTicks last_click_time_;
  gfx::PointF last_click_pos_;

  // The last button number passed to mouseDown and mouseUp.
  // Used to determine whether the click count continues to increment or not.
  static blink::WebMouseEvent::Button last_button_type_;

  blink::WebDragOperation current_drag_effect_;

  base::TimeDelta time_offset_;
  int click_count_;
  // Timestamp of the last event that was dispatched
  base::TimeTicks last_event_timestamp_;

  base::WeakPtrFactory<EventSender> weak_factory_{this};

  DISALLOW_COPY_AND_ASSIGN(EventSender);
};

}  // namespace content

#endif  // CONTENT_SHELL_RENDERER_WEB_TEST_EVENT_SENDER_H_


text:
class CreateAnswers < ActiveRecord::Migration[5.0]
  def change
    create_table :answers do |t|
      t.belongs_to :question, index:true
      t.text :content

      t.timestamps
    end
  end
end


text:
namespace fengine
{
	class FEventsManager final : FSdlEventsDispatcher, private futils::FSingleton<FEventsManager>
	{
		friend class Engine;
		F_DISABLE_COPY(FEventsManager)
	public:
		FEventsManager();

		virtual ~FEventsManager();

		template<typename EventHandler>
		static int Register()
		{
			static_assert(std::is_base_of<FEventListener, EventHandler>::value, "Not a derived class from FEventListener");
			auto new_id = GetNewEventId();
			handlers_[new_id] = std::make_shared<EventHandler>();
			return new_id;
		}

		template<typename EventHandler>
		static int Register(const FShared<EventHandler>& handler)
		{
			auto new_id = GetNewEventId();
			handlers_[new_id] = handler;
			return new_id;
		}

		static int Deregister(int id);

		static void HandleEvents();

	private:

		static int GetNewEventId();

		template<typename EventListener, typename EventType>
		static void DelegateEvent(EventType&& event, fevents::EventSourceType source_type)
		{
			for (auto it = handlers_.begin(); it != handlers_.end() && !event.accepted(); ++it)
			{
				auto ptr = it->second.get();
				if (ptr->IsListenableSource(source_type))
				{
					// TODO: Avoid dynamic_cast!
					dynamic_cast<EventListener*>(it->second.get())->CallEvent(event);
				}
			}
		}

	private:
		static std::atomic_int last_id_;
		static FMap<int, FShared<FEventListener>> handlers_;

		constexpr static int kMaxLastId = 1024;
	};
}

#endif // _3FENGINE_SRC_FCOMPONENTS_F_EVENTS_MANAGER_HPP_


text:
var socket = io.connect('http://131.160.13.18:2014');

var localStream;
var localPeerConnection;
var remotePeerConnection;
var offerData;
var isReceiver;
var receiverIdentifier;

var constraints = {
  video: {
    mandatory: {
      minHeight: 720,
      minWidth: 1280
    }
  },
  audio: false
};

var videoElement = document.getElementById("videoElement");

var startButton = document.getElementById("startButton");
var stopButton = document.getElementById("stopButton");
var infoButton = document.getElementById("infoButton");

startButton.onclick = startStreaming;
stopButton.onclick = stopStreaming;
infoButton.onclick = refreshPage;

startButton.disabled = true;
stopButton.disabled = true;

function startStreaming() {
  startButton.disabled = true;
  stopButton.disabled = false;
  getLocalStream();

  socket.emit('updateStreamingStatus', true);
  trace("Started streaming.");
}

function stopStreaming() {
  startButton.disabled = false;
  stopButton.disabled = true;
  socket.emit('updateStreamingStatus', false);
}

socket.on('streamingStatus', function (isStreaming) {
  if (!isStreaming) {
    isReceiver = false;
    startButton.disabled = false;
    infoButton.style.visibility = 'hidden';
    trace("I will be streaming.");
  } else {
    isReceiver = true;
    startButton.style.visibility = 'hidden';
    stopButton.style.visibility = 'hidden';
    infoButton.style.visibility = 'visible';
    infoButton.innerHTML = " This live feed auto-closes after 20 seconds.";
    receiverIdentifier = getRandomInt(0, 100000);
    socket.emit('sendRequestOffer', receiverIdentifier);
    trace("I will be receiving." + receiverIdentifier);
  }

});

socket.on('requestOffer', function(data) {
  if(!isReceiver) {
    receiverIdentifier = data;
    call();
  }
});

function trace(text) {
  console.log((performance.now() / 1000).toFixed(3) + ": " + text);
}

function gotLocalPeerLocalStream(stream){
  trace("Got Local Media Stream.");
  videoElement.src = URL.createObjectURL(stream);
  localStream = stream;
}

function getLocalStream() {
   navigator.webkitGetUserMedia(constraints, gotLocalPeerLocalStream,
     errorCallback);
}

function call() {
  trace("Starting call");

  var servers = null;

  localPeerConnection = new webkitRTCPeerConnection(servers);

  localPeerConnection.addStream(localStream);
  trace("Added localStream to localPeerConnection");

  // createOffer triggers the ICE candidate gathering process at the local side.
  localPeerConnection.createOffer(gotLocalDescription);
  localPeerConnection.onicecandidate = gotLocalIceCandidate;
}

function gotLocalDescription(description){
  // The Generated SDP does not contain ICE candidates.
  localPeerConnection.setLocalDescription(description);
  trace("Local Description Set.");
}

function gotLocalIceCandidate(event) {
  if (event.target.iceGatheringState == "complete") {
    trace("Local ICE candidates gathering complete.");

    // Once the ICE gathering state is completed, create an SDP updated with
    // the ICE candidates.
    localPeerConnection.createOffer(sendOffer);
  }
}

function sendOffer(description) {
  trace("Sending offer to the other peer.");
  socket.emit('sendOfferToPeer', { id: receiverIdentifier,
    data: description });
}

socket.on('sendingOffer', function (offer) {
  if (isReceiver && offer.id == receiverIdentifier) {
    trace('Incoming Call: ' + offer.id);
    offerData = new RTCSessionDescription(offer.data);
    acceptCall();
  }
});

function acceptCall() {
  var servers = null;

  remotePeerConnection = new webkitRTCPeerConnection(servers);
  remotePeerConnection.onicecandidate = gotRemoteIceCandidate;
  remotePeerConnection.onaddstream = gotRemoteStream;

  remotePeerConnection.setRemoteDescription(offerData);
  trace("Remote description of Remote peer set.");

  //Create Answer triggers the ICE gathering process at the remote peer.
  remotePeerConnection.createAnswer(gotRemoteDescription);
}

function gotRemoteDescription(description){
  // The remote peer also sets its local description without the ICE candidates.
  remotePeerConnection.setLocalDescription(description);
  trace("Local description of the remote peer set.");
}

function gotRemoteIceCandidate(event){
  if (event.target.iceGatheringState == "complete") {
    trace("Remote ICE candidates gathering complete.");

    // Once the ICE gathering state is completed, create an SDP updated with
    // the ICE candidates.
    remotePeerConnection.createAnswer(sendAnswer);
  }
}

function sendAnswer(description) {
  trace("Sending Answer to the other peer.");
  socket.emit('sendAnswerToPeer', description);
}

socket.on('sendingAnswer', function (AnswerData) {
  if (!isReceiver) {
    trace("Answer received from receiver.");
    // For some reason, socket.io doesn't preserve the object type.
    AnswerData = new RTCSessionDescription(AnswerData);

    localPeerConnection.setRemoteDescription(AnswerData);
    trace("Remote description of the local peer set.");
  }
});

function gotRemoteStream(event){
  videoElement.src = URL.createObjectURL(event.stream);
  trace("Received remote stream.");
  setTimeout(closeRemotePeerConnection, 20000);
}

socket.on('closeCall', function (data) {
  if (isReceiver) {
    closeRemotePeerConnection();
  } else {
    closeLocalPeerConnection();
  }
});

function errorCallback() {
  trace("Failed to get User Media!");
  socket.emit('hangUpCall', null);
}

function closeRemotePeerConnection() {
  console.log("Closing Remote Peer Connection.");
  remotePeerConnection.close();
  remotePeerConnection = null;
  videoElement.src = null;
  infoButton.innerHTML = "Refresh the page to CThaQ again.";
}

function closeLocalPeerConnection() {
  localPeerConnection.close();
  localPeerConnection = null;
  localStream = null;
  offerData = null;
  isReceiver = null;
  startButton.disabled = false;
  videoElement.src = null;
  startButton.style.visibility = 'visible';
  stopButton.style.visibility = 'visible';
}

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function refreshPage() {
  if(remotePeerConnection == null) {
    location.reload(true);
  }
}


text:
CircularBuffer::CircularBuffer() {
}

CircularBuffer::~CircularBuffer() {
}

void CircularBuffer::CreateBuffer(HANDLE fileMap, size_t size) {
    if (isCreated)
        return;

    buff = (char*)MapViewOfFile(
        fileMap,
        FILE_MAP_ALL_ACCESS,
        0,
        0,
        size
    );

    this->size = size;

    head = tail = 0;
    usableSize = size - 1000000;
    freemem = usableSize;
    // Send over init values of head and tail.
    mutex.Lock(); {
        memcpy(buff + size - sizeof(size_t), reinterpret_cast<char *>(&head), sizeof(size_t));
        memcpy(buff + size - (sizeof(size_t) * 2), reinterpret_cast<char *>(&tail), sizeof(size_t));
        memcpy(buff + size - (sizeof(size_t) * 3), reinterpret_cast<char *>(&freemem), sizeof(size_t));
    }
    mutex.Unlock();

    isCreated = true;
}

void CircularBuffer::SaveData(char* data, size_t size) {
    mutex.Lock(); {
        memcpy(buff + head, data, size);
    }
    mutex.Unlock();

    head += size;
    freemem -= size;
    SaveHead();
}

void CircularBuffer::LoadData(char* data, size_t size) {
    mutex.Lock(); {
        memcpy(data, buff + tail, size);
    }
    mutex.Unlock();

    tail += size;
    freemem += size;
    SaveTail();
}

bool CircularBuffer::IsEmpty() {
    UpdateTail();
    UpdateHead();

    if (head == tail)
        return true;

    return false;
}

bool CircularBuffer::IsFull() {
    UpdateTail();
    UpdateHead();
    UpdateFreemem();

    if (freemem <= 1000000)
        return true;

    return false;
}

bool CircularBuffer::GetUsableSize() {
    return usableSize;
}

bool CircularBuffer::HeadIsAtEnd() {
    if (head >= usableSize)
        return true;

    return false;
}

bool CircularBuffer::TailIsAtEnd() {
    if (tail >= usableSize)
        return true;

    return false;
}

void CircularBuffer::ResetHead() {
    UpdateHead();
    freemem -= usableSize - head;
    head = 0;
    SaveHead();
}

void CircularBuffer::ResetTail() {
    UpdateTail();
    freemem += usableSize - tail;
    tail = 0;
    SaveTail();
}

void CircularBuffer::UpdateHead() {
    mutex.Lock(); {
        memcpy(reinterpret_cast<char *>(&head), buff + size - sizeof(size_t), sizeof(size_t));
    }
    mutex.Unlock();
}

void CircularBuffer::UpdateTail() {
    mutex.Lock(); {
        memcpy(reinterpret_cast<char *>(&tail), buff + size - (sizeof(size_t) * 2), sizeof(size_t));
    }
    mutex.Unlock();
}

void CircularBuffer::UpdateFreemem() {
    mutex.Lock(); {
        memcpy(reinterpret_cast<char *>(&freemem), buff + size - (sizeof(size_t) * 3), sizeof(size_t));
    }
    mutex.Unlock();
}

void CircularBuffer::SaveHead() {
    mutex.Lock(); {
        memcpy(buff + size - sizeof(size_t), reinterpret_cast<char *>(&head), sizeof(size_t));
    }
    mutex.Unlock();
}

void CircularBuffer::SaveTail() {
    mutex.Lock(); {
        memcpy(buff + size - (sizeof(size_t) * 2), reinterpret_cast<char *>(&tail), sizeof(size_t));
    }
    mutex.Unlock();
}

void CircularBuffer::SaveFreemem() {
    mutex.Lock(); {
        memcpy(buff + size - (sizeof(size_t) * 3), reinterpret_cast<char *>(&freemem), sizeof(size_t));
    }
    mutex.Unlock();
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Institusi_model extends CI_Model {

	public $table = 'institusi';

	public function read_all_institusi() {
		$this->db->where('is_deleted',0);
		$query = $this->db->get($this->table);
		return $query;
	}

	public function read_institusi($key, $val) {
		$this->db->where($key, $val);
		$query = $this->db->get($this->table, 1);
		return $query;
	}

	public function read_institusi_id($key, $val) {
		$this->db->where('nama_institusi', $institusi);
		$query = $this->db->get($this->table, 1);
		return $query;
	}

	public function is_exist($institusi) {
		$this->db->where('nama_institusi', $institusi);
		$this->db->get($this->table, 1);
		if($this->db->affected_rows() == 1) { return true; }
		else { return false; }
	}

	public function insert_institusi($institusi, $jumlah=0) {
		$data = array(
			'nama_institusi' => $institusi,
			'jumlah' => $jumlah
		);
		$this->db->insert($this->table, $data);
		return $this->db->affected_rows();
	}

	public function update_jumlah($key, $val, $inc=true) {
		$this->db->where($key, $val);
		if($inc == true) {
			$this->db->set('jumlah','`jumlah`+1', FALSE);
		} else {
			$this->db->set('jumlah','`jumlah`-1', FALSE);
		}
		$query = $this->db->update($this->table);
		return ($this->db->affected_rows() != 1) ? False : True;
	}

}

?>


text:
<!DOCTYPE html>

 Twitter


text:
package com.salesmanager.core.business.services.reference.loader;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.salesmanager.core.business.exception.ServiceException;
import com.salesmanager.core.business.services.reference.country.CountryService;
import com.salesmanager.core.business.services.reference.language.LanguageService;
import com.salesmanager.core.model.reference.country.Country;
import com.salesmanager.core.model.reference.language.Language;
import com.salesmanager.core.model.reference.zone.Zone;
import com.salesmanager.core.model.reference.zone.ZoneDescription;

/**
 * Drop files in reference/zones with following format
 *
 * <country code>_<language code>.json All lower cases
 *
 * @author carlsamson
 *
 */
@Component
public class ZonesLoader {

	private static final Logger LOGGER = LoggerFactory.getLogger(ZonesLoader.class);

	@Inject
	private LanguageService languageService;

	@Inject
	private CountryService countryService;

	@Autowired
	private ResourcePatternResolver resourceResolver;

	private static final String PATH = "classpath:/reference/zones/*.json";

	private static final String ALL_REGIONS = "*";

	//
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Map<String, Zone>> loadIndividualZones() throws Exception {

		List<Map<String, Zone>> loadedZones = new ArrayList<Map<String, Zone>>();
		try {

			List<Resource> files = geZoneFiles(PATH);
			List<Language> languages = languageService.list();

			ObjectMapper mapper = new ObjectMapper();

			List<Country> countries = countryService.list();
			Map<String, Country> countriesMap = new HashMap<String, Country>();
			for (Country country : countries) {
				countriesMap.put(country.getIsoCode(), country);
			}

			Map<String, Zone> zonesMap = new LinkedHashMap<String, Zone>();
			Map<String, List<ZoneDescription>> zonesDescriptionsMap = new LinkedHashMap<String, List<ZoneDescription>>();
			Map<String, String> zonesMark = new LinkedHashMap<String, String>();

			// load files individually
			for (Resource resource : files) {
				InputStream in = resource.getInputStream();
				if(in == null) {
					continue;
				}
				Map<String, Object> data = mapper.readValue(in, Map.class);

				if(resource.getFilename().contains("_")) {
					for (Language l : languages) {
						if (resource.getFilename().contains("_" + l.getCode())) {// lead for this
							// language
							List langList = (List) data.get(l.getCode());
							if (langList != null) {
								/**
								 * submethod
								 */
								for (Object z : langList) {
									Map<String, String> e = (Map<String, String>) z;
									mapZone(l, zonesDescriptionsMap, countriesMap, zonesMap, zonesMark, e);
								}
							}
						}
					}
				} else {
					List langList = (List) data.get(ALL_REGIONS);
					if (langList != null) {
						/**
						 * submethod
						 */
						for (Language l : languages) {
							for (Object z : langList) {
								Map<String, String> e = (Map<String, String>) z;
								mapZone(l, zonesDescriptionsMap, countriesMap, zonesMap, zonesMark, e);
							}
						}
					}
				}

				for (Map.Entry<String, Zone> entry : zonesMap.entrySet()) {
					String key = entry.getKey();
					Zone value = entry.getValue();

					// get descriptions
					List<ZoneDescription> descriptions = zonesDescriptionsMap.get(key);
					if (descriptions != null) {
						value.setDescriptons(descriptions);
					}
				}

				loadedZones.add(zonesMap);
			}
			return loadedZones;

		} catch (Exception e) {
			throw new ServiceException(e);
		}

	}

	private InputStream loadFileContent(String fileName) throws Exception {
		return this.getClass().getClassLoader().getResourceAsStream("classpath:/reference/zones/" + fileName);
	}

	public Map<String, Zone> loadZones(String jsonFilePath) throws Exception {

		List<Language> languages = languageService.list();

		List<Country> countries = countryService.list();
		Map<String, Country> countriesMap = new HashMap<String, Country>();
		for (Country country : countries) {

			countriesMap.put(country.getIsoCode(), country);

		}

		ObjectMapper mapper = new ObjectMapper();

		try {

			InputStream in = this.getClass().getClassLoader().getResourceAsStream(jsonFilePath);

			@SuppressWarnings("unchecked")
			Map<String, Object> data = mapper.readValue(in, Map.class);

			Map<String, Zone> zonesMap = new HashMap<String, Zone>();
			Map<String, List<ZoneDescription>> zonesDescriptionsMap = new HashMap<String, List<ZoneDescription>>();
			Map<String, String> zonesMark = new HashMap<String, String>();

			for (Language l : languages) {
				@SuppressWarnings("rawtypes")
				List langList = (List) data.get(l.getCode());
				if (langList != null) {
					/**
					 * submethod
					 */
					for (Object z : langList) {
						@SuppressWarnings("unchecked")
						Map<String, String> e = (Map<String, String>) z;
						this.mapZone(l, zonesDescriptionsMap, countriesMap, zonesMap, zonesMark, e);

						/**
						 * String zoneCode = e.get("zoneCode"); ZoneDescription
						 * zoneDescription = new ZoneDescription();
						 * zoneDescription.setLanguage(l);
						 * zoneDescription.setName(e.get("zoneName")); Zone zone
						 * = null; List<ZoneDescription> descriptions = null; if
						 * (!zonesMap.containsKey(zoneCode)) { zone = new
						 * Zone(); Country country =
						 * countriesMap.get(e.get("countryCode")); if (country
						 * == null) { LOGGER.warn("Country is null for " +
						 * zoneCode + " and country code " +
						 * e.get("countryCode")); continue; }
						 * zone.setCountry(country); zonesMap.put(zoneCode,
						 * zone); zone.setCode(zoneCode);
						 *
						 * }
						 *
						 * if (zonesMark.containsKey(l.getCode() + "_" +
						 * zoneCode)) { LOGGER.warn("This zone seems to be a
						 * duplicate ! " + zoneCode + " and language code " +
						 * l.getCode()); continue; }
						 *
						 * zonesMark.put(l.getCode() + "_" + zoneCode,
						 * l.getCode() + "_" + zoneCode);
						 *
						 * if (zonesDescriptionsMap.containsKey(zoneCode)) {
						 * descriptions = zonesDescriptionsMap.get(zoneCode); }
						 * else { descriptions = new
						 * ArrayList<ZoneDescription>();
						 * zonesDescriptionsMap.put(zoneCode, descriptions); }
						 *
						 * descriptions.add(zoneDescription);
						 **/

					}
				}

			}

			for (Map.Entry<String, Zone> entry : zonesMap.entrySet()) {
				String key = entry.getKey();
				Zone value = entry.getValue();

				// get descriptions
				List<ZoneDescription> descriptions = zonesDescriptionsMap.get(key);
				if (descriptions != null) {
					value.setDescriptons(descriptions);
				}
			}

			return zonesMap;

		} catch (Exception e) {
			throw new ServiceException(e);
		}

	}

	// internal complex mapping stuff, don't try this at home ...
	private void mapZone(Language l, Map<String, List<ZoneDescription>> zonesDescriptionsMap,
			Map<String, Country> countriesMap, Map<String, Zone> zonesMap, Map<String, String> zonesMark,
			Map<String, String> list) {

		String zoneCode = list.get("zoneCode");
		ZoneDescription zoneDescription = new ZoneDescription();
		zoneDescription.setLanguage(l);
		zoneDescription.setName(list.get("zoneName"));
		Zone zone = null;
		List<ZoneDescription> descriptions = null;
		if (!zonesMap.containsKey(zoneCode)) {
			zone = new Zone();
			Country country = countriesMap.get(list.get("countryCode"));
			if (country == null) {
				LOGGER.warn("Country is null for " + zoneCode + " and country code " + list.get("countryCode"));
				return;
			}
			zone.setCountry(country);
			zone.setCode(zoneCode);
			zonesMap.put(zoneCode, zone);

		}

		if (zonesMark.containsKey(l.getCode() + "_" + zoneCode)) {
			LOGGER.warn("This zone seems to be a duplicate !  " + zoneCode + " and language code " + l.getCode());
			return;
		}

		zonesMark.put(l.getCode() + "_" + zoneCode, l.getCode() + "_" + zoneCode);

		if (zonesDescriptionsMap.containsKey(zoneCode)) {
			descriptions = zonesDescriptionsMap.get(zoneCode);
		} else {
			descriptions = new ArrayList<ZoneDescription>();
			zonesDescriptionsMap.put(zoneCode, descriptions);
		}

		descriptions.add(zoneDescription);

	}

	private List<Resource> geZoneFiles(String path) throws IOException {
		Resource[] resources =resourceResolver.getResources(PATH);

		List<Resource> files = new ArrayList<>();
		Collections.addAll(files, resources);
		return files;

	}

}


text:
<?php

use Codeception\Util\Stub;
require_once 'tests/data/app/data.php';
require_once __DIR__ . '/TestsForBrowsers.php';

class PhpBrowserTest extends TestsForBrowsers
{
    /**
     * @var \Codeception\Module\PhpBrowser
     */
    protected $module;

    /**
     * @var \GuzzleHttp\Subscriber\History
     */
    protected $history;

    protected function setUp() {
        $this->module = new \Codeception\Module\PhpBrowser();
        $url = 'http://localhost:8000';
        $this->module->_setConfig(array('url' => $url));
        $this->module->_initialize();
        $this->module->_cleanup();
        $this->module->_before($this->makeTest());
        $this->history = new \GuzzleHttp\Subscriber\History();
        $this->module->guzzle->getEmitter()->attach($this->history);
    }

    protected function tearDown() {
        if ($this->module) {
            $this->module->_after($this->makeTest());
        }
        data::clean();
    }

    protected function makeTest()
    {
        return Stub::makeEmpty('\Codeception\TestCase\Cept', array('dispatcher' => Stub::makeEmpty('Symfony\Component\EventDispatcher\EventDispatcher')));
    }

    public function testAjax() {
        $this->module->amOnPage('/');
        $this->module->sendAjaxGetRequest('/info');
        $this->assertNotNull(data::get('ajax'));

        $this->module->sendAjaxPostRequest('/form/complex', array('show' => 'author'));
        $this->assertNotNull(data::get('ajax'));
        $post = data::get('form');
        $this->assertEquals('author', $post['show']);
    }

    public function testLinksWithNonLatin() {
        $this->module->amOnPage('/info');
        $this->module->seeLink('Ссылочка');
        $this->module->click('Ссылочка');
    }

	public function testSetMultipleCookies() {
        $cookie_name_1  = 'test_cookie';
        $cookie_value_1 = 'this is a test';
        $this->module->setCookie($cookie_name_1, $cookie_value_1);

        $cookie_name_2  = '2_test_cookie';
        $cookie_value_2 = '2 this is a test';
        $this->module->setCookie($cookie_name_2, $cookie_value_2);

        $this->module->seeCookie($cookie_name_1);
        $this->module->seeCookie($cookie_name_2);
        $this->module->dontSeeCookie('evil_cookie');

        $cookie1 = $this->module->grabCookie($cookie_name_1);
        $this->assertEquals($cookie_value_1, $cookie1);

        $cookie2 = $this->module->grabCookie($cookie_name_2);
        $this->assertEquals($cookie_value_2, $cookie2);

        $this->module->resetCookie($cookie_name_1);
        $this->module->dontSeeCookie($cookie_name_1);
        $this->module->seeCookie($cookie_name_2);
        $this->module->resetCookie($cookie_name_2);
        $this->module->dontSeeCookie($cookie_name_2);
    }

    public function testSubmitFormGet()
    {
        $I = $this->module;
        $I->amOnPage('/search');
        $I->submitForm('form', array('searchQuery' => 'test'));
        $I->see('Success');
    }

    public function testHtmlRedirect()
    {
        $this->module->amOnPage('/redirect2');
        $this->module->seeResponseCodeIs(200);
        $this->module->seeCurrentUrlEquals('/info');

        $this->module->amOnPage('/redirect_interval');
        $this->module->seeCurrentUrlEquals('/redirect_interval');
    }

    public function testMetaRefresh()
    {
        $this->module->amOnPage('/redirect_self');
        $this->module->see('Redirecting to myself');
    }

    public function testRefreshRedirect()
    {
        $this->module->amOnPage('/redirect3');
        $this->module->seeResponseCodeIs(200);
        $this->module->seeCurrentUrlEquals('/info');

        $this->module->amOnPage('/redirect_header_interval');
        $this->module->seeCurrentUrlEquals('/redirect_header_interval');
        $this->module->see('Welcome to test app!');
    }

    public function testRedirectWithGetParams()
    {
        $this->module->amOnPage('/redirect4');
        $this->module->seeInCurrentUrl('/search?ln=test@gmail.com&sn=testnumber');
        $params = data::get('params');
        $this->assertContains('test@gmail.com', $params);
    }

    public function testSetCookieByHeader()
    {
        $this->module->amOnPage('/cookies2');
        $this->module->seeResponseCodeIs(200);
        $this->module->seeCookie('a');
        $this->assertEquals('b', $this->module->grabCookie('a'));
    }

    public function testUrlSlashesFormatting()
    {
        $this->module->amOnPage('somepage.php');
        $this->module->seeCurrentUrlEquals('/somepage.php');
        $this->module->amOnPage('///somepage.php');
        $this->module->seeCurrentUrlEquals('/somepage.php');
    }

    /**
     * @Issue https://github.com/Codeception/Codeception/issues/933
     */
    public function testSubmitFormWithQueries()
    {
        $this->module->amOnPage('/form/example3');
        $this->module->seeElement('form');
        $this->module->submitForm('form', array(
                'name' => 'jon',
        ));
        $form = data::get('form');
        $this->assertEquals('jon', $form['name']);
        $this->module->seeCurrentUrlEquals('/form/example3?validate=yes');
    }

    public function testChangeDomains()
    {
        $this->mockResponse();
        $this->module->amOnSubdomain('user');
        $this->module->amOnPage('/form1');
        $this->assertEquals('http://user.localhost:8000/form1', $this->module->client->getHistory()->current()->getUri());
    }

    public function testHeadersByConfig()
    {
        $this->mockResponse();
        $this->module->_setConfig(['headers' => ['xxx' => 'yyyy']]);
        $this->module->_initialize();
        $this->module->amOnPage('/form1');
        $this->assertArrayHasKey('xxx', $this->module->guzzle->getDefaultOption('headers'));
        $this->assertEquals('yyyy', $this->module->guzzle->getDefaultOption('headers/xxx'));
    }

    public function testHeadersBySetHeader()
    {
        $this->module->setHeader('xxx', 'yyyy');
        $this->module->amOnPage('/');
        $this->assertTrue($this->history->getLastRequest()->hasHeader('xxx'));
    }

    public function testDeleteHeaders()
    {
        $this->module->setHeader('xxx', 'yyyy');
        $this->module->deleteHeader('xxx');
        $this->module->amOnPage('/');
        $this->assertFalse($this->history->getLastRequest()->hasHeader('xxx'));
    }

    public function testDeleteHeadersByEmptyValue()
    {
        $this->module->setHeader('xxx', 'yyyy');
        $this->module->setHeader('xxx', '');
        $this->module->amOnPage('/');
        $this->assertFalse($this->history->getLastRequest()->hasHeader('xxx'));
    }

    public function testCurlOptions()
    {
        $this->module->_setConfig(array('url' => 'http://google.com', 'curl' => array('CURLOPT_NOBODY' => true)));
        $this->module->_initialize();
        $this->assertTrue($this->module->guzzle->getDefaultOption('config/curl/'.CURLOPT_NOBODY));
    }

    public function testHttpAuth()
    {
        $this->module->amOnPage('/auth');
        $this->module->seeResponseCodeIs(401);
        $this->module->see('Unauthorized');
        $this->module->amHttpAuthenticated('davert', 'password');
        $this->module->amOnPage('/auth');
        $this->module->dontSee('Unauthorized');
        $this->module->see("Welcome, davert");
        $this->module->amHttpAuthenticated('davert', '123456');
        $this->module->amOnPage('/auth');
        $this->module->see('Forbidden');
    }

    public function testRawGuzzle()
    {
        $code = $this->module->executeInGuzzle(function(\GuzzleHttp\Client $client) {
            $res = $client->get('/info');
            return $res->getStatusCode();
        });
        $this->assertEquals(200, $code);
    }

    protected function mockResponse($body = "hello", $code = 200)
    {
        $mock = new \GuzzleHttp\Subscriber\Mock([
            new \GuzzleHttp\Message\Response($code, [], \GuzzleHttp\Stream\Stream::factory($body))
        ]);
        $this->module->guzzle->getEmitter()->attach($mock);
    }

    /**
     * If we have a form with fields like
     * ```
     * <input type="file" name="foo" />
     * <input type="file" name="foo[bar]" />
     * ```
     * then only array variable will be used while simple variable will be ignored in php $_FILES
     * (eg $_FILES = [
     *                 foo => [
     *                     tmp_name => [
     *                         'bar' => 'asdf'
     *                     ],
     *                     //...
     *                ]
     *              ]
     * )
     * (notice there is no entry for file "foo", only for file "foo[bar]"
     * this will check if current element contains inner arrays within it's keys
     * so we can ignore element itself and only process inner files
     */
    public function testFormWithFilesInOnlyArray()
    {
        $this->shouldFail();
        $this->module->amOnPage('/form/example13');
        $this->module->attachFile('foo', 'app/avatar.jpg');
        $this->module->attachFile('foo[bar]', 'app/avatar.jpg');
        $this->module->click('Submit');
    }

    public function testDoubleSlash()
    {
        $I = $this->module;
        $I->amOnPage('/register');
        $I->submitForm('form', array('test' => 'test'));
        $formUrl = $this->module->client->getHistory()->current()->getUri();
        $formPath = parse_url($formUrl)['path'];
        $this->assertEquals($formPath, '/register');
    }

    public function testFillFieldWithoutPage()
    {
        $this->setExpectedException("\\Codeception\\Exception\\TestRuntime");
        $this->module->fillField('#name', 'Nothing special');
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

  <title></title>
  <meta http-equiv="content-type" content="text/html; charset=latin1">

/*
 * CPArray.j
 * Foundation
 *
 * Created by Francisco Tolmasky.
 * Copyright 2008, 280 North, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

@import "CPObject.j"
@import "CPRange.j"
@import "CPEnumerator.j"
@import "CPSortDescriptor.j"
@import "CPException.j"

/* @ignore */
@implementation _CPArrayEnumerator : CPEnumerator
{
    CPArray _array;
    int     _index;
}

- (id)initWithArray:(CPArray)anArray
{
    self = [super init];

    if (self)
    {
        _array = anArray;
        _index = -1;
    }

    return self;
}

- (id)nextObject
{
    if (++_index >= [_array count])
        return nil;

    return [_array objectAtIndex:_index];
}

@end

/* @ignore */
@implementation _CPReverseArrayEnumerator : CPEnumerator
{
    CPArray _array;
    int     _index;
}

- (id)initWithArray:(CPArray)anArray
{
    self = [super init];

    if (self)
    {
        _array = anArray;
        _index = [_array count];
    }

    return self;
}

- (id)nextObject
{
    if (--_index < 0)
        return nil;

    return [_array objectAtIndex:_index];
}

@end

/*!
    @class CPArray
    @brief A mutable array backed by a JavaScript Array.
    @ingroup foundation

    A mutable array class backed by a JavaScript Array.
    There is also a CPMutableArray class,
    but it is just a child class of this class with an
    empty implementation. All mutable functionality is
    implemented directly in CPArray.
*/
@implementation CPArray : CPObject

/*!
    Returns a new uninitialized CPArray.
*/
+ (id)alloc
{
    return [];
}

/*!
    Returns a new initialized CPArray.
*/
+ (id)array
{
    return [[self alloc] init];
}

/*!
    Creates a new array containing the objects in \c anArray.
    @param anArray Objects in this array will be added to the new array
    @return a new CPArray of the provided objects
*/
+ (id)arrayWithArray:(CPArray)anArray
{
    return [[self alloc] initWithArray:anArray];
}

/*!
    Creates a new array with \c anObject in it.
    @param anObject the object to be added to the array
    @return a new CPArray containing a single object
*/
+ (id)arrayWithObject:(id)anObject
{
    return [[self alloc] initWithObjects:anObject];
}

/*!
    Creates a new CPArray containing all the objects passed as arguments to the method.
    @param anObject the objects that will be added to the new array
    @return a new CPArray containing the argument objects
*/
+ (id)arrayWithObjects:(id)anObject, ...
{
    var i = 2,
        array = [[self alloc] init],
        argument;

    for(; i < arguments.length && (argument = arguments[i]) != nil; ++i)
        array.push(argument);

    return array;
}

/*!
    Creates a CPArray from a JavaScript array of objects.
    @param objects the JavaScript Array
    @param aCount the number of objects in the JS Array
    @return a new CPArray containing the specified objects
*/
+ (id)arrayWithObjects:(id)objects count:(unsigned)aCount
{
    return [[self alloc] initWithObjects:objects count:aCount];
}

/*!
    Initializes the CPArray.
    @return the initialized array
*/
- (id)init
{
    return self;
}

// Creating an Array
/*!
    Creates a new CPArray from \c anArray.
    @param anArray objects in this array will be added to the new array
    @return a new CPArray containing the objects of \c anArray
*/
- (id)initWithArray:(CPArray)anArray
{
    self = [super init];

    if (self)
        [self setArray:anArray];

    return self;
}

/*!
    Initializes a the array with the contents of \c anArray
    and optionally performs a deep copy of the objects based on \c copyItems.
    @param anArray the array to copy the data from
    @param copyItems if \c YES, each object will be copied by having a \c -copy message sent to it, and the
    returned object will be added to the receiver. Otherwise, no copying will be performed.
    @return the initialized array of objects
*/
- (id)initWithArray:(CPArray)anArray copyItems:(BOOL)copyItems
{
    if (!copyItems)
        return [self initWithArray:anArray];

    self = [super init];

    if (self)
    {
        var index = 0,
            count = [anArray count];

        for(; index < count; ++i)
        {
            if (anArray[i].isa)
                self[i] = [anArray copy];
            // Do a deep/shallow copy?
            else
                self[i] = anArray;
        }
    }

    return self;
}

/*!
    initializes an array with the contents of anArray
*/
- (id)initWithObjects:(Array)anArray, ...
{
    // The arguments array contains self and _cmd, so the first object is at position 2.
    var i = 2,
        argument;

    for(; i < arguments.length && (argument = arguments[i]) != nil; ++i)
        push(argument);

    return self;
}

/*!
    Initializes the array with a JavaScript array of objects.
    @param objects the array of objects to add to the receiver
    @param aCount the number of objects in \c objects
    @return the initialized CPArray
*/
- (id)initWithObjects:(id)objects count:(unsigned)aCount
{
    self = [super init];

    if (self)
    {
        var index = 0;

        for(; index < aCount; ++index)
            push(objects[index]);
    }

    return self;
}

// Querying an array
/*!
    Returns \c YES if the array contains \c anObject. Otherwise, it returns \c NO.
    @param anObject the method checks if this object is already in the array
*/
- (BOOL)containsObject:(id)anObject
{
    return [self indexOfObject:anObject] != CPNotFound;
}

/*!
    Returns the number of elements in the array
*/
- (int)count
{
    return length;
}

/*!
    Returns the index of \c anObject in this array.
    If the object is \c nil or not in the array,
    returns \c CPNotFound. It first attempts to find
    a match using \c -isEqual:, then \c ==.
    @param anObject the object to search for
*/
- (int)indexOfObject:(id)anObject
{
    if (anObject === nil)
        return CPNotFound;

    var i = 0,
        count = length;

    // Only use -isEqual: if our object is a CPObject.
    if (anObject.isa)
    {
        for(; i < count; ++i)
            if([self[i] isEqual:anObject])
                return i;
    }
    // If indexOf exists, use it since it's probably
    // faster than anything we can implement.
    else if (self.indexOf)
        return indexOf(anObject);
    // Last resort, do a straight forward linear O(N) search.
    else
        for(; i < count; ++i)
            if(self[i] == anObject)
                return i;

    return CPNotFound;
}

/*!
    Returns the index of \c anObject in the array
    within \c aRange. It first attempts to find
    a match using \c -isEqual:, then \c ==.
    @param anObject the object to search for
    @param aRange the range to search within
    @return the index of the object, or \c CPNotFound if it was not found.
*/
- (int)indexOfObject:(id)anObject inRange:(CPRange)aRange
{
    if (anObject === nil)
        return CPNotFound;

    var i = aRange.location,
        count = MIN(CPMaxRange(aRange), length);

    // Only use isEqual: if our object is a CPObject.
    if (anObject.isa)
    {
        for(; i < count; ++i)
            if([self[i] isEqual:anObject])
                return i;
    }
    // Last resort, do a straight forward linear O(N) search.
    else
        for(; i < count; ++i)
            if(self[i] == anObject)
                return i;

    return CPNotFound;
}

/*!
    Returns the index of \c anObject in the array. The test for equality is done using only \c ==.
    @param anObject the object to search for
    @return the index of the object in the array. \c CPNotFound if the object is not in the array.
*/
- (int)indexOfObjectIdenticalTo:(id)anObject
{
    if (anObject === nil)
        return CPNotFound;

    // If indexOf exists, use it since it's probably
    // faster than anything we can implement.
    if (self.indexOf)
        return indexOf(anObject);

    // Last resort, do a straight forward linear O(N) search.
    else
    {
        var index = 0,
            count = length;

        for(; index < count; ++index)
            if(self[index] === anObject)
                return index;
    }

    return CPNotFound;
}

/*!
    Returns the index of \c anObject in the array
    within \c aRange. The test for equality is
    done using only \c ==.
    @param anObject the object to search for
    @param aRange the range to search within
    @return the index of the object, or \c CPNotFound if it was not found.
*/
- (int)indexOfObjectIdenticalTo:(id)anObject inRange:(CPRange)aRange
{
    if (anObject === nil)
        return CPNotFound;

    // If indexOf exists, use it since it's probably
    // faster than anything we can implement.
    if (self.indexOf)
    {
        var index = indexOf(anObject, aRange.location);

        if (CPLocationInRange(index, aRange))
            return index;
    }

    // Last resort, do a straight forward linear O(N) search.
    else
    {
        var index = aRange.location,
            count = MIN(CPMaxRange(aRange), length);

        for(; index < count; ++index)
            if(self[index] == anObject)
                return index;
    }

    return CPNotFound;
}

/*!
    Returns the index of \c anObject in the array, which must be sorted in the same order as
    calling sortUsingSelector: with the selector passed to this method would result in.
    @param anObject the object to search for
    @param aSelector the comparison selector to call on each item in the list, the same
    selector should have been used to sort the array (or to maintain its sorted order).
    @return the index of the object, or \c CPNotFound if it was not found.
*/
- (unsigned)indexOfObject:(id)anObject sortedBySelector:(SEL)aSelector
{
    return [self indexOfObject:anObject sortedByFunction: function(lhs, rhs) { objj_msgSend(lhs, aSelector, rhs); }];
}

/*!
    Returns the index of \c anObject in the array, which must be sorted in the same order as
    calling sortUsingFunction: with the selector passed to this method would result in.
    The function will be called like so:
    <pre>
    aFunction(anObject, currentObjectInArrayForComparison)
    </pre>
    @param anObject the object to search for
    @param aFunction the comparison function to call on each item in the array that we search. the same
    selector should have been used to sort the array (or to maintain its sorted order).
    @return the index of the object, or \c CPNotFound if it was not found.
*/
- (unsigned)indexOfObject:(id)anObject sortedByFunction:(Function)aFunction
{
    return [self indexOfObject:anObject sortedByFunction:aFunction context:nil];
}

/*!
    Returns the index of \c anObject in the array, which must be sorted in the same order as
    calling sortUsingFunction: with the selector passed to this method would result in.
    The function will be called like so:
    <pre>
    aFunction(anObject, currentObjectInArrayForComparison, context)
    </pre>
    @param anObject the object to search for
    @param aFunction the comparison function to call on each item in the array that we search. the same
    function should have been used to sort the array (or to maintain its sorted order).
    @param aContext a context object that will be passed to the sort function
    @return the index of the object, or \c CPNotFound if it was not found.
*/
- (unsigned)indexOfObject:(id)anObject sortedByFunction:(Function)aFunction context:(id)aContext
{
    if (!aFunction || anObject === undefined)
        return CPNotFound;

    var mid, c, first = 0, last = length - 1;
    while (first <= last)
    {
        mid = FLOOR((first + last) / 2);
          c = aFunction(anObject, self[mid], aContext);

        if (c > 0)
            first = mid + 1;
        else if (c < 0)
            last = mid - 1;
        else
        {
            while (mid < length - 1 && aFunction(anObject, self[mid+1], aContext) == CPOrderedSame)
                mid++;

            return mid;
        }
    }

    return CPNotFound;
}

/*!
    Returns the index of \c anObject in the array, which must be sorted in the same order as
    calling sortUsingDescriptors: with the descriptors passed to this method would result in.
    @param anObject the object to search for
    @param descriptors the array of descriptors to use to compare each item in the array that we search. the same
    descriptors should have been used to sort the array (or to maintain its sorted order).
    @return the index of the object, or \c CPNotFound if it was not found.
*/
- (unsigned)indexOfObject:(id)anObject sortedByDescriptors:(CPArray)descriptors
{
    return [self indexOfObject:anObject sortedByFunction:function(lhs, rhs)
    {
        var i = 0,
            count = [descriptors count],
            result = CPOrderedSame;

        while (i < count)
            if((result = [descriptors[i++] compareObject:lhs withObject:rhs]) != CPOrderedSame)
                return result;

        return result;
    }];
}

/*!
    Returns the last object in the array. If the array is empty, returns \c nil/
*/
- (id)lastObject
{
    var count = [self count];

    if (!count) return nil;

    return self[count - 1];
}

/*!
    Returns the object at index \c anIndex.
    @throws CPRangeException if \c anIndex is out of bounds
*/
- (id)objectAtIndex:(int)anIndex
{
    if (anIndex >= length || anIndex < 0)
        [CPException raise:CPRangeException reason:@"index (" + anIndex + @") beyond bounds (" + length + @")"];

    return self[anIndex];
}

/*!
    Returns the objects at \c indexes in a new CPArray.
    @param indexes the set of indices
    @throws CPRangeException if any of the indices is greater than or equal to the length of the array
*/
- (CPArray)objectsAtIndexes:(CPIndexSet)indexes
{
    var index = CPNotFound,
        objects = [];

    while((index = [indexes indexGreaterThanIndex:index]) !== CPNotFound)
        [objects addObject:[self objectAtIndex:index]];

    return objects;
}

/*!
    Returns an enumerator describing the array sequentially
    from the first to the last element. You should not modify
    the array during enumeration.
*/
- (CPEnumerator)objectEnumerator
{
    return [[_CPArrayEnumerator alloc] initWithArray:self];
}

/*!
    Returns an enumerator describing the array sequentially
    from the last to the first element. You should not modify
    the array during enumeration.
*/
- (CPEnumerator)reverseObjectEnumerator
{
    return [[_CPReverseArrayEnumerator alloc] initWithArray:self];
}

// Sending messages to elements
/*!
    Sends each element in the array a message.
    @param aSelector the selector of the message to send
    @throws CPInvalidArgumentException if \c aSelector is \c nil
*/
- (void)makeObjectsPerformSelector:(SEL)aSelector
{
    if (!aSelector)
        [CPException raise:CPInvalidArgumentException reason:"makeObjectsPerformSelector: 'aSelector' can't be nil"];

    var index = 0,
        count = length;

    for(; index < count; ++index)
        objj_msgSend(self[index], aSelector);
}

/*!
    Sends each element in the array a message with an argument.
    @param aSelector the selector of the message to send
    @param anObject the first argument of the message
    @throws CPInvalidArgumentException if \c aSelector is \c nil
*/
- (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)anObject
{
    if (!aSelector)
        [CPException raise:CPInvalidArgumentException reason:"makeObjectsPerformSelector:withObject 'aSelector' can't be nil"];

    var index = 0,
        count = length;

    for(; index < count; ++index)
        objj_msgSend(self[index], aSelector, anObject);
}

- (void)makeObjectsPerformSelector:(SEL)aSelector withObjects:(CPArray)objects
{
    if (!aSelector)
        [CPException raise:CPInvalidArgumentException reason:"makeObjectsPerformSelector:withObjects: 'aSelector' can't be nil"];

    var index = 0,
        count = length,
        argumentsArray = [nil, aSelector].concat(objects || []);

    for(; index < count; ++index)
    {
        argumentsArray[0] = self[index];
        objj_msgSend.apply(this, argumentsArray);
    }
}

// Comparing arrays
/*!
    Returns the first object found in the receiver (starting at index 0) which is present in the
    \c otherArray as determined by using the \c -containsObject: method.
    @return the first object found, or \c nil if no common object was found.
*/
- (id)firstObjectCommonWithArray:(CPArray)anArray
{
    if (![anArray count] || ![self count])
        return nil;

    var i = 0,
        count = [self count];

    for(; i < count; ++i)
        if([anArray containsObject:self[i]])
            return self[i];

    return nil;
}

/*!
    Returns true if anArray contains exactly the same objects as the reciever.
*/
- (BOOL)isEqualToArray:(id)anArray
{
    if (self === anArray)
        return YES;

    if(length != anArray.length)
        return NO;

    var index = 0,
        count = [self count];

    for(; index < count; ++index)
    {
        var lhs = self[index],
            rhs = anArray[index];

        // If they're not equal, and either doesn't have an isa, or they're !isEqual (not isEqual)
        if (lhs !== rhs && (!lhs.isa || !rhs.isa || ![lhs isEqual:rhs]))
            return NO;
    }

    return YES;
}

- (BOOL)isEqual:(id)anObject
{
    if (self === anObject)
        return YES;

    if(![anObject isKindOfClass:[CPArray class]])
        return NO;

    return [self isEqualToArray:anObject];
}

// Deriving new arrays
/*!
    Returns a copy of this array plus \c anObject inside the copy.
    @param anObject the object to be added to the array copy
    @throws CPInvalidArgumentException if \c anObject is \c nil
    @return a new array that should be n+1 in size compared to the receiver.
*/
- (CPArray)arrayByAddingObject:(id)anObject
{
    if (anObject === nil || anObject === undefined)
        [CPException raise:CPInvalidArgumentException
                    reason:"arrayByAddingObject: object can't be nil"];

    var array = [self copy];

    array.push(anObject);

    return array;
}

/*!
    Returns a new array which is the concatenation of \c self and otherArray (in this precise order).
    @param anArray the array that will be concatenated to the receiver's copy
*/
- (CPArray)arrayByAddingObjectsFromArray:(CPArray)anArray
{
    return slice(0).concat(anArray);
}

/*
- (CPArray)filteredArrayUsingPredicate:(CPPredicate)aPredicate
{
    var i= 0,
        count = [self count],
        array = [CPArray array];

    for(; i<count; ++i)
        if(aPredicate.evaluateWithObject(self[i]))
            array.push(self[i]);

    return array;
}
*/

/*!
    Returns a subarray of the receiver containing the objects found in the specified range \c aRange.
    @param aRange the range of objects to be copied into the subarray
    @throws CPRangeException if the specified range exceeds the bounds of the array
*/
- (CPArray)subarrayWithRange:(CPRange)aRange
{
    if (aRange.location < 0 || CPMaxRange(aRange) > length)
        [CPException raise:CPRangeException reason:"subarrayWithRange: aRange out of bounds"];

    return slice(aRange.location, CPMaxRange(aRange));
}

// Sorting arrays
/*
    Not yet described.
*/
- (CPArray)sortedArrayUsingDescriptors:(CPArray)descriptors
{
    var sorted = [self copy];

    [sorted sortUsingDescriptors:descriptors];

    return sorted;
}

/*!
    Return a copy of the receiver sorted using the function passed into the first parameter.
*/
- (CPArray)sortedArrayUsingFunction:(Function)aFunction
{
    return [self sortedArrayUsingFunction:aFunction context:nil];
}

/*!
    Returns an array in which the objects are ordered according
    to a sort with \c aFunction. This invokes
    \c -sortUsingFunction:context.
    @param aFunction a JavaScript 'Function' type that compares objects
    @param aContext context information
    @return a new sorted array
*/
- (CPArray)sortedArrayUsingFunction:(Function)aFunction context:(id)aContext
{
    var sorted = [self copy];

    [sorted sortUsingFunction:aFunction context:aContext];

    return sorted;
}

/*!
    Returns a new array in which the objects are ordered according to a sort with \c aSelector.
    @param aSelector the selector that will perform object comparisons
*/
- (CPArray)sortedArrayUsingSelector:(SEL)aSelector
{
    var sorted = [self copy]

    [sorted sortUsingSelector:aSelector];

    return sorted;
}

// Working with string elements

/*!
    Returns a string formed by concatenating the objects in the
    receiver, with the specified separator string inserted between each part.
    If the element is a Objective-J object, then the \c -description
    of that object will be used, otherwise the default JavaScript representation will be used.
    @param aString the separator that will separate each object string
    @return the string representation of the array
*/
- (CPString)componentsJoinedByString:(CPString)aString
{
    // Objective-J objects get "description" called on them automatically when coerced to strings
    // (see "objj_object.prototype.toString" at bottom of CPObject.j)
    return join(aString);
}

// Creating a description of the array

/*!
    Returns a human readable description of this array and it's elements.
*/
- (CPString)description
{
    var index = 0,
        count = [self count],
        description = '(';

    for(; index < count; ++index)
    {
        if (index === 0)
            description += '\n';

        var object = self[index],
            objectDescription = object && object.isa ? [object description] : object + "";

        description += "\t" + objectDescription.split('\n').join("\n\t");

        if (index !== count - 1)
            description += ", ";

        description += '\n';
    }

    return description + ')';
}

// Collecting paths
/*!
    Returns a new array subset formed by selecting the elements that have
    filename extensions from \c filterTypes. Only elements
    that are of type CPString are candidates for inclusion in the returned array.
    @param filterTypes an array of CPString objects that contain file extensions (without the '.')
    @return a new array with matching paths
*/
- (CPArray)pathsMatchingExtensions:(CPArray)filterTypes
{
    var index = 0,
        count = [self count],
        array = [];

    for(; index < count; ++index)
        if (self[index].isa && [self[index] isKindOfClass:[CPString class]] && [filterTypes containsObject:[self[index] pathExtension]])
            array.push(self[index]);

    return array;
}

// Key value coding
/*!
    Sets the key-value for each element in the array.
    @param aValue the value for the coding
    @param aKey the key for the coding
*/
- (void)setValue:(id)aValue forKey:(CPString)aKey
{
    var i = 0,
        count = [self count];

    for(; i < count; ++i)
        [self[i] setValue:aValue forKey:aKey];
}

/*!
    Returns the value for \c aKey from each element in the array.
    @param aKey the key to return the value for
    @return an array of containing a value for each element in the array
*/
- (CPArray)valueForKey:(CPString)aKey
{
    var i = 0,
        count = [self count],
        array = [];

    for(; i < count; ++i)
        array.push([self[i] valueForKey:aKey]);

    return array;
}

// Copying arrays

/*!
    Makes a copy of the receiver.
    @return a new CPArray copy
*/
- (id)copy
{
    return slice(0);
}

@end

@implementation CPArray(CPMutableArray)

// Creating arrays
/*!
    Creates an array able to store at least  \c aCapacity
    items. Because CPArray is backed by JavaScript arrays,
    this method ends up simply returning a regular array.
*/
+ (CPArray)arrayWithCapacity:(unsigned)aCapacity
{
    return [[self alloc] initWithCapacity:aCapacity];
}

/*!
    Initializes an array able to store at least \c aCapacity items. Because CPArray
    is backed by JavaScript arrays, this method ends up simply returning a regular array.
*/
- (id)initWithCapacity:(unsigned)aCapacity
{
    return self;
}

// Adding and replacing objects
/*!
    Adds \c anObject to the end of the array.
    @param anObject the object to add to the array
*/
- (void)addObject:(id)anObject
{
    push(anObject);
}

/*!
    Adds the objects in \c anArray to the receiver array.
    @param anArray the array of objects to add to the end of the receiver
*/
- (void)addObjectsFromArray:(CPArray)anArray
{
    splice.apply(self, [length, 0].concat(anArray));
}

/*!
    Inserts an object into the receiver at the specified location.
    @param anObject the object to insert into the array
    @param anIndex the location to insert \c anObject at
*/
- (void)insertObject:(id)anObject atIndex:(int)anIndex
{
    splice(anIndex, 0, anObject);
}

/*!
    Inserts the objects in the provided array into the receiver at the indexes specified.
    @param objects the objects to add to this array
    @param anIndexSet the indices for the objects
*/
- (void)insertObjects:(CPArray)objects atIndexes:(CPIndexSet)indexes
{
    var indexesCount = [indexes count],
        objectsCount = [objects count];

    if(indexesCount !== objectsCount)
        [CPException raise:CPRangeException reason:"the counts of the passed-in array (" + objectsCount + ") and index set (" + indexesCount + ") must be identical."];

    var lastIndex = [indexes lastIndex];

    if(lastIndex >= [self count] + indexesCount)
        [CPException raise:CPRangeException reason:"the last index (" + lastIndex + ") must be less than the sum of the original count (" + [self count] + ") and the insertion count (" + indexesCount + ")."];

    var index = 0,
        currentIndex = [indexes firstIndex];

    for (; index < objectsCount; ++index, currentIndex = [indexes indexGreaterThanIndex:currentIndex])
        [self insertObject:objects[index] atIndex:currentIndex];
}

/*!
    Replaces the element at \c anIndex with \c anObject.
    The current element at position \c anIndex will be removed from the array.
    @param anIndex the position in the array to place \c anObject
*/
- (void)replaceObjectAtIndex:(int)anIndex withObject:(id)anObject
{
    self[anIndex] = anObject;
}

/*!
    Replace the elements at the indices specified by \c anIndexSet with
    the objects in \c objects.
    @param anIndexSet the set of indices to array positions that will be replaced
    @param objects the array of objects to place in the specified indices
*/
- (void)replaceObjectsAtIndexes:(CPIndexSet)anIndexSet withObjects:(CPArray)objects
{
    var i = 0,
        index = [anIndexSet firstIndex];

    while(index != CPNotFound)
    {
        [self replaceObjectAtIndex:index withObject:objects[i++]];
        index = [anIndexSet indexGreaterThanIndex:index];
    }
}

/*!
    Replaces some of the receiver's objects with objects from \c anArray. Specifically, the elements of the
    receiver in the range specified by \c aRange,
    with the elements of \c anArray in the range specified by \c otherRange.
    @param aRange the range of elements to be replaced in the receiver
    @param anArray the array to retrieve objects for placement into the receiver
    @param otherRange the range of objects in \c anArray to pull from for placement into the receiver
*/
- (void)replaceObjectsInRange:(CPRange)aRange withObjectsFromArray:(CPArray)anArray range:(CPRange)otherRange
{
    if (!otherRange.location && otherRange.length == [anArray count])
        [self replaceObjectsInRange:aRange withObjectsFromArray:anArray];
    else
        splice.apply(self, [aRange.location, aRange.length].concat([anArray subarrayWithRange:otherRange]));
}

/*!
    Replaces some of the receiver's objects with the objects from
    \c anArray. Specifically, the elements of the
    receiver in the range specified by \c aRange.
    @param aRange the range of elements to be replaced in the receiver
    @param anArray the array to retrieve objects for placement into the receiver
*/
- (void)replaceObjectsInRange:(CPRange)aRange withObjectsFromArray:(CPArray)anArray
{
    splice.apply(self, [aRange.location, aRange.length].concat(anArray));
}

/*!
    Sets the contents of the receiver to be identical to the contents of \c anArray.
    @param anArray the array of objects used to replace the receiver's objects
*/
- (void)setArray:(CPArray)anArray
{
    if(self == anArray) return;

    splice.apply(self, [0, length].concat(anArray));
}

// Removing Objects
/*!
    Removes all objects from this array.
*/
- (void)removeAllObjects
{
    splice(0, length);
}

/*!
    Removes the last object from the array.
*/
- (void)removeLastObject
{
    pop();
}

/*!
    Removes all entries of \c anObject from the array.
    @param anObject the object whose entries are to be removed
*/
- (void)removeObject:(id)anObject
{
    [self removeObject:anObject inRange:CPMakeRange(0, length)];
}

/*!
    Removes all entries of \c anObject from the array, in the range specified by \c aRange.
    @param anObject the object to remove
    @param aRange the range to search in the receiver for the object
*/
- (void)removeObject:(id)anObject inRange:(CPRange)aRange
{
    var index;

    while ((index = [self indexOfObject:anObject inRange:aRange]) != CPNotFound)
    {
        [self removeObjectAtIndex:index];
        aRange = CPIntersectionRange(CPMakeRange(index, length - index), aRange);
    }
}

/*!
    Removes the object at \c anIndex.
    @param anIndex the location of the element to be removed
*/
- (void)removeObjectAtIndex:(int)anIndex
{
    splice(anIndex, 1);
}

/*!
    Removes the objects at the indices specified by \c CPIndexSet.
    @param anIndexSet the indices of the elements to be removed from the array
*/
- (void)removeObjectsAtIndexes:(CPIndexSet)anIndexSet
{
    var index = [anIndexSet lastIndex];

    while (index != CPNotFound)
    {
        [self removeObjectAtIndex:index];
        index = [anIndexSet indexLessThanIndex:index];
    }
}

/*!
    Remove the first instance of \c anObject from the array.
    The search for the object is done using \c ==.
    @param anObject the object to remove
*/
- (void)removeObjectIdenticalTo:(id)anObject
{
    [self removeObjectIdenticalTo:anObject inRange:CPMakeRange(0, [self count])];
}

/*!
    Remove the first instance of \c anObject from the array,
    within the range specified by \c aRange.
    The search for the object is done using \c ==.
    @param anObject the object to remove
    @param aRange the range in the array to search for the object
*/
- (void)removeObjectIdenticalTo:(id)anObject inRange:(CPRange)aRange
{
    var index,
        count = [self count];

    while ((index = [self indexOfObjectIdenticalTo:anObject inRange:aRange]) !== CPNotFound)
    {
        [self removeObjectAtIndex:index];
        aRange = CPIntersectionRange(CPMakeRange(index, (--count) - index), aRange);
    }
}

/*!
    Remove the objects in \c anArray from the receiver array.
    @param anArray the array of objects to remove from the receiver
*/
- (void)removeObjectsInArray:(CPArray)anArray
{
    var index = 0,
        count = [anArray count];

    for (; index < count; ++index)
        [self removeObject:anArray[index]];
}

/*!
    Removes all the objects in the specified range from the receiver.
    @param aRange the range of objects to remove
*/
- (void)removeObjectsInRange:(CPRange)aRange
{
    splice(aRange.location, aRange.length);
}

// Rearranging objects
/*!
    Swaps the elements at the two specified indices.
    @param anIndex the first index to swap from
    @param otherIndex the second index to swap from
*/
- (void)exchangeObjectAtIndex:(unsigned)anIndex withObjectAtIndex:(unsigned)otherIndex
{
    var temporary = self[anIndex];
    self[anIndex] = self[otherIndex];
    self[otherIndex] = temporary;
}

- (CPArray)sortUsingDescriptors:(CPArray)descriptors
{
    sort(function(lhs, rhs)
    {
        var i = 0,
            count = [descriptors count],
            result = CPOrderedSame;

        while(i < count)
            if((result = [descriptors[i++] compareObject:lhs withObject:rhs]) != CPOrderedSame)
                return result;

        return result;
    });
}

/*!
    Sorts the receiver array using a JavaScript function as a comparator, and a specified context.
    @param aFunction a JavaScript function that will be called to compare objects
    @param aContext an object that will be passed to \c aFunction with comparison
*/
- (void)sortUsingFunction:(Function)aFunction context:(id)aContext
{
    sort(function(lhs, rhs) { return aFunction(lhs, rhs, aContext); });
}

/*!
    Sorts the receiver array using an Objective-J method as a comparator.
    @param aSelector the selector for the method to call for comparison
*/
- (void)sortUsingSelector:(SEL)aSelector
{
    sort(function(lhs, rhs) { return objj_msgSend(lhs, aSelector, rhs); });
}

@end

@implementation CPArray (CPCoding)

- (id)initWithCoder:(CPCoder)aCoder
{
    return [aCoder decodeObjectForKey:@"CP.objects"];
}

- (void)encodeWithCoder:(CPCoder)aCoder
{
    [aCoder _encodeArrayOfObjects:self forKey:@"CP.objects"];
}

@end

/*!
    @class CPMutableArray
    @ingroup compatability

    This class is just an empty subclass of CPArray.
    CPArray already implements mutable methods and
    this class only exists for source compatability.
*/
@implementation CPMutableArray : CPArray

@end

Array.prototype.isa = CPArray;
[CPArray initialize];