text:
//================================================================
/**
 * @packageDocumentation
 * @module std.base
 */
//================================================================
import { IAssociativeContainer } from "../../internal/container/associative/IAssociativeContainer";
import { IContainer } from "./IContainer";
import { Container } from "./Container";

import { IForwardIterator } from "../../iterator/IForwardIterator";
import { ILinearContainerBase } from "../../internal/container/linear/ILinearContainerBase";
import { NativeArrayIterator } from "../../internal/iterator/disposable/NativeArrayIterator";
import { Pair } from "../../utility/Pair";

import { Temporary } from "../../internal/functional/Temporary";

/**
 * Basic set container.
 *
 * @template Key Key type
 * @template Unique Whether duplicated key is blocked or not
 * @template Source Derived type extending this {@link SetContainer}
 * @template IteratorT Iterator type
 * @template ReverseT Reverse iterator type
 *
 * @author Jeongho Nam - https://github.com/samchon
 */
export abstract class SetContainer<Key,
        Unique extends boolean,
        SourceT extends SetContainer<Key, Unique, SourceT, IteratorT, ReverseT>,
        IteratorT extends SetContainer.Iterator<Key, Unique, SourceT, IteratorT, ReverseT>,
        ReverseT extends SetContainer.ReverseIterator<Key, Unique, SourceT, IteratorT, ReverseT>>
    extends Container<Key, SourceT, IteratorT, ReverseT, Key>
    implements IAssociativeContainer<Key, Key, SourceT, IteratorT, ReverseT, Key>
{
    protected data_: ILinearContainerBase<Key, SourceT, IteratorT, ReverseT>;

    /* ---------------------------------------------------------
        CONSTURCTORS
    --------------------------------------------------------- */
    /**
     * Default Constructor.
     */
    protected constructor(factory: (thisArg: SourceT) => ILinearContainerBase<Key, SourceT, IteratorT, ReverseT>)
    {
        super();
        this.data_ = factory(<Temporary>this);
    }

    /**
     * @inheritDoc
     */
    public assign<InputIterator extends Readonly<IForwardIterator<Key, InputIterator>>>
        (first: InputIterator, last: InputIterator): void
    {
        // INSERT
        this.clear();
        this.insert(first, last);
    }

    /**
     * @inheritDoc
     */
    public clear(): void
    {
        // TO BE ABSTRACT
        this.data_.clear();
    }

    /* =========================================================
        ACCESSORS
            - ITERATORS
            - ELEMENTS
    ============================================================
        ITERATOR
    --------------------------------------------------------- */
    /**
     * @inheritDoc
     */
    public abstract find(key: Key): IteratorT;

    /**
     * @inheritDoc
     */
    public begin(): IteratorT
    {
        return this.data_.begin();
    }

    /**
     * @inheritDoc
     */
    public end(): IteratorT
    {
        return this.data_.end();
    }

    /* ---------------------------------------------------------
        ELEMENTS
    --------------------------------------------------------- */
    /**
     * @inheritDoc
     */
    public has(key: Key): boolean
    {
        return !this.find(key).equals(this.end());
    }

    /**
     * @inheritDoc
     */
    public abstract count(key: Key): number;

    /**
     * @inheritDoc
     */
    public size(): number
    {
        return this.data_.size();
    }

    /* =========================================================
        ELEMENTS I/O
            - INSERT
            - ERASE
            - UTILITY
            - POST-PROCESS
    ============================================================
        INSERT
    --------------------------------------------------------- */
    /**
     * @inheritDoc
     */
    public push(...items: Key[]): number
    {
        if (items.length === 0)
            return this.size();

        // INSERT BY RANGE
        const first: NativeArrayIterator<Key> = new NativeArrayIterator(items, 0);
        const last: NativeArrayIterator<Key> = new NativeArrayIterator(items, items.length);

        this._Insert_by_range(first, last);

        // RETURN SIZE
        return this.size();
    }

    public insert(key: Key): SetContainer.InsertRet<Key, Unique, SourceT, IteratorT, ReverseT>;
    public insert(hint: IteratorT, key: Key): IteratorT;
    public insert<InputIterator extends Readonly<IForwardIterator<Key, InputIterator>>>
        (first: InputIterator, last: InputIterator): void;

    public insert(...args: any[]): any
    {
        if (args.length === 1)
            return this._Insert_by_key(args[0]);
        else if (args[0].next instanceof Function && args[1].next instanceof Function)
            return this._Insert_by_range(args[0], args[1]);
        else
            return this._Insert_by_hint(args[0], args[1]);
    }

    protected abstract _Insert_by_key(key: Key): SetContainer.InsertRet<Key, Unique, SourceT, IteratorT, ReverseT>;
    protected abstract _Insert_by_hint(hint: IteratorT, key: Key): IteratorT;
    protected abstract _Insert_by_range<InputIterator extends Readonly<IForwardIterator<Key, InputIterator>>>
        (begin: InputIterator, end: InputIterator): void;

    /* ---------------------------------------------------------
        ERASE
    --------------------------------------------------------- */
    /**
     * @inheritDoc
     */
    public erase(key: Key): number;

    /**
     * @inheritDoc
     */
    public erase(pos: IteratorT): IteratorT;

    /**
     * @inheritDoc
     */
    public erase(first: IteratorT, last: IteratorT): IteratorT;

    public erase(...args: any[]): any
    {
        if (args.length === 1 && !(args[0] instanceof this.end().constructor && (args[0] as IteratorT).source() === <any>this))
            return this._Erase_by_val(args[0]);
        else if (args.length === 1)
            return this._Erase_by_range(args[0]);
        else
            return this._Erase_by_range(args[0], args[1]);
    }

    protected abstract _Erase_by_val(key: Key): number;

    protected _Erase_by_range(first: IteratorT, last: IteratorT = first.next()): IteratorT
    {
        // ERASE
        const it = this.data_.erase(first, last);

        // POST-PROCESS
        this._Handle_erase(first, last);

        return it;
    }

    /* ---------------------------------------------------------
        UTILITY
    --------------------------------------------------------- */
    /**
     * @inheritDoc
     */
    public abstract swap(obj: SourceT): void;

    /**
     * @inheritDoc
     */
    public abstract merge(source: SourceT): void;

    /* ---------------------------------------------------------
        POST-PROCESS
    --------------------------------------------------------- */
    protected abstract _Handle_insert(first: IteratorT, last: IteratorT): void;

    protected abstract _Handle_erase(first: IteratorT, last: IteratorT): void;
}

/**
 *
 */
export namespace SetContainer
{
    /**
     * Return type of {@link SetContainer.insert}
     */
    export type InsertRet<Key,
            Unique extends boolean,
            Source extends SetContainer<Key, Unique, Source, IteratorT, ReverseT>,
            IteratorT extends Iterator<Key, Unique, Source, IteratorT, ReverseT>,
            ReverseT extends ReverseIterator<Key, Unique, Source, IteratorT, ReverseT>>
        = Unique extends true
            ? Pair<IteratorT, boolean>
            : IteratorT;

    /**
     * Iterator of {@link SetContainer}
     *
     * @author Jenogho Nam <http://samchon.org>
     */
    export type Iterator<Key,
            Unique extends boolean,
            SourceT extends SetContainer<Key, Unique, SourceT, IteratorT, ReverseT>,
            IteratorT extends Iterator<Key, Unique, SourceT, IteratorT, ReverseT>,
            ReverseT extends ReverseIterator<Key, Unique, SourceT, IteratorT, ReverseT>>
        = Readonly<IContainer.Iterator<Key, SourceT, IteratorT, ReverseT, Key>>;

    /**
     * Reverse iterator of {@link SetContainer}
     *
     * @author Jenogho Nam <http://samchon.org>
     */
    export type ReverseIterator<Key,
            Unique extends boolean,
            SourceT extends SetContainer<Key, Unique, SourceT, IteratorT, ReverseT>,
            IteratorT extends Iterator<Key, Unique, SourceT, IteratorT, ReverseT>,
            ReverseT extends ReverseIterator<Key, Unique, SourceT, IteratorT, ReverseT>>
        = Readonly<IContainer.ReverseIterator<Key, SourceT, IteratorT, ReverseT, Key>>;
}


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

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

import docking.action.DockingAction;
import docking.action.MenuData;
import docking.tool.ToolConstants;
import generic.theme.GThemeDefaults.Colors.Messages;
import ghidra.app.CorePluginPackage;
import ghidra.app.context.NavigatableActionContext;
import ghidra.app.context.NavigatableContextAction;
import ghidra.app.plugin.PluginCategoryNames;
import ghidra.app.plugin.ProgramPlugin;
import ghidra.app.plugin.core.instructionsearch.ui.InstructionSearchDialog;
import ghidra.app.services.GoToService;
import ghidra.app.util.query.TableService;
import ghidra.framework.plugintool.PluginInfo;
import ghidra.framework.plugintool.PluginTool;
import ghidra.framework.plugintool.util.PluginStatus;
import ghidra.program.model.address.*;
import ghidra.program.model.listing.*;
import ghidra.program.model.mem.MemoryBlock;
import ghidra.program.util.ProgramSelection;
import ghidra.util.HelpLocation;
import ghidra.util.exception.InvalidInputException;
import ghidra.util.task.TaskMonitor;
import ghidra.util.task.TaskMonitorComponent;

/**
 * Plugin allowing users to construct search criteria based on a set of selected
 * instructions.
 *
 * Note: There's a bug here that is supposed to be fixed under JIRA ticket
 * #2024. When a user switches programs we need to clear out the current
 * instructions in the GUI; this works fine. However, if the user then hits the
 * refresh button to load any selected instructions in the new program, nothing
 * will be loaded because no selection event was generated on the program
 * activation. This problem will be resolved when that bug is fixed.
 */
//@formatter:off
@PluginInfo(
	status = PluginStatus.RELEASED,
	packageName = CorePluginPackage.NAME,
	category = PluginCategoryNames.SEARCH,
	shortDescription = "Allows users to construct instruction search patterns",
	description = "Provides a component for showing a selected set of instructions. " +
			"Users can mask any operands and/or mnemonics to produce a search" +
			" pattern, which can be used to find similar instruction sets" +
			" in the current program.",
	servicesRequired = { TableService.class, GoToService.class }
)
//@formatter:on
public class InstructionSearchPlugin extends ProgramPlugin {

	final static String SEARCH_ACTION_NAME = "Search Instruction Patterns";

	private TaskMonitor taskMonitor;

	private DockingAction searchAction;

	private final String DIALOG_TITLE = "Instruction Pattern Search";

	// Maximum number of instructions allowed in a selection. This is an arbitrary limit
	// but should be high enough to satisfy any reasonable requirement.
	private int MAX_SELECTION_SIZE = 500;

	private InstructionSearchDialog searchDialog;

	/**
	 * Constructor.
	 *
	 * @param tool the plugin tool
	 */
	public InstructionSearchPlugin(PluginTool tool) {
		super(tool);

		// Creates the menu actions used with this plugin.
		createActions();
	}

	public InstructionSearchDialog getSearchDialog() {
		return searchDialog;
	}

	/*********************************************************************************************
	 * PROTECTED METHODS
	 ********************************************************************************************/

	@Override
	protected void init() {
		taskMonitor = new TaskMonitorComponent();
	}

	/*********************************************************************************************
	 * PRIVATE METHODS
	 ********************************************************************************************/

	/**
	 * Checks the selection made by the user to make sure it is within
	 * acceptable bounds regarding size and number of ranges.
	 *
	 * @param selection the user selection
	 * @param dialog the parent dialog
	 * @return true if the selection is valid
	 */
	public boolean isSelectionValid(ProgramSelection selection, InstructionSearchDialog dialog) {

		// Users should not call this will a null selection but we need to check just in case.
		if (selection == null) {
			return false;
		}

		// First clear out the message panel if anything was being displayed there because of a
		// previous search.
		dialog.clearMessage();

		// Users can't select multiple regions or pick a region larger than MAX_SELECTION_SIZE, so
		// immediately return and display an error message if they do.
		if (selection.getNumAddresses() == 0) {
			dialog.displayMessage(
				"Select instructions from the listing (and hit reload) to populate the table.",
				Messages.NORMAL);
			return false;
		}
		if (!isSelectionSizeValid(selection)) {
			dialog.displayMessage("Invalid selection.  Cannot select more than " +
				MAX_SELECTION_SIZE + " instructions and/or data items.", Messages.ERROR);
			return false;
		}

		try {
			if (isSelectionRangeValid(selection)) {
				return true;
			}
		}
		catch (InvalidInputException e) {
			dialog.displayMessage(e.getMessage(), Messages.ERROR);
			return false;
		}

		return true;
	}

	/**
	 * Returns the number of instructions (and data) in the selection.
	 *
	 * @param program the current program
	 * @param selection the program selection
	 * @return number of instructions in the selection
	 */
	private int getNumInstructionsInSelection(Program program, ProgramSelection selection) {

		// First get the addresses in the selection;
		AddressRangeIterator addressRanges = selection.getAddressRanges();

		// Keep track of the number of instructions we find.
		int numInstructions = 0;

		// Loop over all the addresses, getting all code units and checking to see which ones
		// are instructions.  For those that are, increment our counter.
		while (addressRanges.hasNext()) {
			AddressRange range = addressRanges.next();
			AddressSet addrSet = new AddressSet(range);
			CodeUnitIterator cuIter = program.getListing().getCodeUnits(addrSet, true);

			while (cuIter.hasNext()) {
				CodeUnit cu = cuIter.next();
				if ((cu instanceof Instruction) || (cu instanceof Data)) {
					numInstructions++;
				}
			}
		}

		return numInstructions;
	}

	/**
	 * Returns true if the number of instructions selected is less or equal to
	 * MAX_SELECTION_SIZE.
	 *
	 * @param selection the program selection
	 * @return true if the selection size is valid
	 */
	private boolean isSelectionSizeValid(ProgramSelection selection) {
		int numInstructionsInSelection =
			getNumInstructionsInSelection(getCurrentProgram(), selection);

		return numInstructionsInSelection <= MAX_SELECTION_SIZE;
	}

	/**
	 * Returns true if the user has selected one and only one range of
	 * instructions.
	 *
	 * If there are multiple ranges, this could be for two reasons: 1) the user
	 * has (via the mouse) selected more than one set of address ranges, or 2)
	 * the user selects a single region but that region spans memory blocks;
	 * this would be interpreted by the program as being 2 distinct selection
	 * ranges. In both of these cases, we throw an exception with a message that
	 * the caller can log if desired.
	 *
	 * @param selection the program selection
	 * @return true if the selection range is valid
	 * @throws InvalidInputException
	 */
	private boolean isSelectionRangeValid(ProgramSelection selection) throws InvalidInputException {
		Set<String> blockNames = new HashSet<>();
		AddressRangeIterator iter = selection.getAddressRanges();
		while (iter.hasNext()) {
			AddressRange range = iter.next();
			Address addr = range.getMinAddress();
			MemoryBlock block = getCurrentProgram().getMemory().getBlock(addr);
			blockNames.add(block.getName());
		}
		if (blockNames.size() > 1) {
			throw new InvalidInputException("Selection range cannot span memory blocks");
		}

		if (selection.getNumAddressRanges() > 1) {
			throw new InvalidInputException("Selection cannot contain multiple address ranges");
		}
		return selection.getNumAddressRanges() == 1;
	}

	private void createActions() {
		searchAction = new NavigatableContextAction(SEARCH_ACTION_NAME, getName(), false) {
			@Override
			public void actionPerformed(NavigatableActionContext context) {
				showSearchDialog(context);
			}
		};
		searchAction.addToWindowWhen(NavigatableActionContext.class);
		searchAction.setHelpLocation(new HelpLocation("Search", "Instruction_Pattern_Search"));
		searchAction.setMenuBarData(
			new MenuData(new String[] { ToolConstants.MENU_SEARCH, "For Instruction Patterns" },
				null, "search for"));
		searchAction.setDescription("Construct searches using selected instructions");
		tool.addAction(searchAction);
	}

	/**
	 * Creates a new instruction search dialog and displays it, loading any
	 * instructions that have been selected.
	 *
	 * @param context the navigatable context
	 */
	private void showSearchDialog(NavigatableActionContext context) {
		searchDialog = new InstructionSearchDialog(this, DIALOG_TITLE, taskMonitor);
		searchDialog.showDialog(context.getComponentProvider());
	}

	@Override
	protected void programActivated(Program program) {
		if (searchDialog != null) {
			searchDialog.clear();
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rssdp;

namespace Test.RssdpPortable
{
	[TestClass]
	public class DeviceSerialisationTests
	{

		private const string UpnpDeviceXmlNamespace = "urn:schemas-upnp-org:device-1-0";

		[ExpectedException(typeof(System.InvalidOperationException))]
		[TestMethod]
		public void ToDescriptionDocument_ThrowsWithNullUuid()
		{
			var rootDevice = CreateSampleRootDevice();
			rootDevice.Uuid = null;

			var descriptionDocument = rootDevice.ToDescriptionDocument();
		}

		[ExpectedException(typeof(System.InvalidOperationException))]
		[TestMethod]
		public void ToDescriptionDocument_ThrowsWithEmptyUuid()
		{
			var rootDevice = CreateSampleRootDevice();
			rootDevice.Uuid = String.Empty;

			var descriptionDocument = rootDevice.ToDescriptionDocument();
		}

		[TestMethod]
		public void ToDescriptionDocument_CompletesWithNonEmptyResult()
		{
			var rootDevice = CreateSampleRootDevice();

			var descriptionDocument = rootDevice.ToDescriptionDocument();
			Assert.AreNotEqual(null, descriptionDocument);
			Assert.AreNotEqual(String.Empty, descriptionDocument);
		}

		[TestMethod]
		public void ToDescriptionDocument_StartsWithXmlDeclaration()
		{
			var rootDevice = CreateSampleRootDevice();

			var descriptionDocument = rootDevice.ToDescriptionDocument();

			Assert.AreEqual(true, descriptionDocument.StartsWith("<?xml version=\"1.0\" encoding=\"utf-8\"?>"));
		}

		[TestMethod]
		public void ToDescriptionDocument_RootNodeHasCorrectXmlns()
		{
			var rootDevice = CreateSampleRootDevice();

			var descriptionDocument = rootDevice.ToDescriptionDocument();

			var doc = XDocument.Parse(descriptionDocument);
			var rootNode = doc.Descendants(XName.Get("root", UpnpDeviceXmlNamespace));
			Assert.IsNotNull(rootNode);
		}

		[TestMethod]
		public void ToDescriptionDocument_ChilldlessRootDeviceContainsSingleDeviceNode()
		{
			var rootDevice = CreateSampleRootDevice();

			var descriptionDocument = rootDevice.ToDescriptionDocument();

			var doc = XDocument.Parse(descriptionDocument);
			var deviceNodes = doc.Descendants(XName.Get("device", UpnpDeviceXmlNamespace));
			Assert.AreEqual(1, deviceNodes.Count());
		}

		[TestMethod]
		public void ToDescriptionDocument_ContainsCorrectNumberOfIcons()
		{
			var rootDevice = CreateSampleRootDevice();

			var descriptionDocument = rootDevice.ToDescriptionDocument();

			var doc = XDocument.Parse(descriptionDocument);
			var deviceNodes = doc.Descendants(XName.Get("icon", UpnpDeviceXmlNamespace));
			Assert.AreEqual(2, deviceNodes.Count());
		}

		[TestMethod]
		public void ToDescriptionDocument_ContainsCorrectCustomProperties()
		{
			var rootDevice = CreateSampleRootDevice();

			var descriptionDocument = rootDevice.ToDescriptionDocument();

			var doc = XDocument.Parse(descriptionDocument);
			var customPropNode = doc.Descendants(XName.Get("TestProp1", UpnpDeviceXmlNamespace)).FirstOrDefault();
			Assert.IsNotNull(customPropNode);

			customPropNode = doc.Descendants(XName.Get("TestProp2", UpnpDeviceXmlNamespace)).FirstOrDefault();
			Assert.IsNotNull(customPropNode);
		}

		[TestMethod]
		public void ToDescriptionDocument_ContainsSpecVersion10()
		{
			var rootDevice = CreateSampleRootDevice();

			var descriptionDocument = rootDevice.ToDescriptionDocument();

			var doc = XDocument.Parse(descriptionDocument);
			var specVersionNodes = doc.Descendants(XName.Get("specVersion", UpnpDeviceXmlNamespace));
			Assert.AreEqual(1, specVersionNodes.Count());

			var specVersionNode = specVersionNodes.Single();
			var majorNode = specVersionNode.Elements(XName.Get("major", UpnpDeviceXmlNamespace)).Single();

			var minorNode = specVersionNode.Elements(XName.Get("minor", UpnpDeviceXmlNamespace)).Single();

			Assert.AreEqual("1", majorNode.Value);
			Assert.AreEqual("0", minorNode.Value);
		}

		[TestMethod]
		public void ToDescriptionDocument_ContainsSingleUrlBase()
		{
			var rootDevice = CreateSampleRootDevice();

			var descriptionDocument = rootDevice.ToDescriptionDocument();

			var doc = XDocument.Parse(descriptionDocument);
			doc.Descendants(XName.Get("URLBase", UpnpDeviceXmlNamespace)).Single();
		}

		[TestMethod]
		public void ToDescriptionDocument_BlankUrlBaseDoesNotSerialise()
		{
			var rootDevice = CreateSampleRootDevice();
			rootDevice.UrlBase = null;

			var descriptionDocument = rootDevice.ToDescriptionDocument();

			var doc = XDocument.Parse(descriptionDocument);
			Assert.AreEqual(0, doc.Descendants(XName.Get("URLBase", UpnpDeviceXmlNamespace)).Count());
		}

		[TestMethod]
		public void ToDescriptionDocument_ContainsEmbeddedDevices()
		{
			var rootDevice = CreateSampleRootDevice();
			rootDevice.AddDevice(CreateEmbeddedDevice(rootDevice));
			rootDevice.AddDevice(CreateEmbeddedDevice(rootDevice));

			var descriptionDocument = XDocument.Parse(rootDevice.ToDescriptionDocument());
			var deviceNodes = descriptionDocument.Descendants(XName.Get("device", UpnpDeviceXmlNamespace));

			Assert.AreEqual(3, deviceNodes.Count());
			Assert.IsTrue(deviceNodes.Where((n) => n.Elements(XName.Get("UDN", UpnpDeviceXmlNamespace)).First().Value == rootDevice.Udn).Any());
			Assert.IsTrue(deviceNodes.Where((n) => n.Elements(XName.Get("UDN", UpnpDeviceXmlNamespace)).First().Value == rootDevice.Devices.First().Udn).Any());
			Assert.IsTrue(deviceNodes.Where((n) => n.Elements(XName.Get("UDN", UpnpDeviceXmlNamespace)).First().Value == rootDevice.Devices.Last().Udn).Any());
		}

		[ExpectedException(typeof(System.ArgumentNullException))]
		[TestMethod]
		public void ToDescriptionDocument_WriteDeviceDescriptionXml_ThrowsIfWriterNull()
		{
			var device = new MockCustomDevice();
			device.DoInvalidWrite(null, CreateSampleRootDevice());
		}

		[ExpectedException(typeof(System.ArgumentNullException))]
		[TestMethod]
		public void ToDescriptionDocument_WriteDeviceDescriptionXml_ThrowsIfDeviceNull()
		{
			var device = new MockCustomDevice();
			using (var ms = new System.IO.MemoryStream())
			{
				using (var writer = XmlWriter.Create(ms))
				{
					device.DoInvalidWrite(writer, null);
				}
			}
		}

		private SsdpRootDevice CreateSampleRootDevice()
		{
			var retVal = new SsdpRootDevice()
			{
				CacheLifetime = TimeSpan.FromMinutes(30),
				DeviceType = "TestDeviceType",
				DeviceTypeNamespace = "test-device-ns",
				FriendlyName = "Test Device 1",
				Location = new Uri("http://testdevice:1700/xml"),
				Manufacturer = "Test Manufacturer",
				ManufacturerUrl = new Uri("http://testman.com"),
				ModelDescription = "A test device",
				ModelName = "Test Model",
				ModelNumber = "1234",
				ModelUrl = new Uri("http://testmodel.com"),
				PresentationUrl = new Uri("http://testmodel.com/presentation"),
				SerialNumber = "TM-12345",
				Upc = "123456789012",
				UrlBase = new Uri("http://testdevice:1700"),
				Uuid = Guid.NewGuid().ToString()
			};

			var customProp = new SsdpDeviceProperty() { Namespace = "custom-ns", Name = "TestProp1", Value = "Test" };
			retVal.CustomProperties.Add(customProp);
			customProp = new SsdpDeviceProperty() { Namespace = "custom-ns", Name = "TestProp2", Value = "Test" };
			retVal.CustomProperties.Add(customProp);

			var icon = new SsdpDeviceIcon() { ColorDepth = 32, Height = 48, Width = 48, MimeType = "image/png", Url = new Uri("icons/48", UriKind.Relative) };
			retVal.Icons.Add(icon);
			icon = new SsdpDeviceIcon() { ColorDepth = 32, Height = 120, Width = 120, MimeType = "image/png", Url = new Uri("icons/120", UriKind.Relative) };
			retVal.Icons.Add(icon);

			return retVal;
		}

		private SsdpEmbeddedDevice CreateEmbeddedDevice(SsdpRootDevice rootDevice)
		{
			var retVal = new SsdpEmbeddedDevice()
			{
				DeviceType = "TestEmbeddedDeviceType",
				DeviceTypeNamespace = "test-device-ns",
				FriendlyName = "Test Embedded Device 1",
				Manufacturer = "Test Manufacturer",
				ManufacturerUrl = new Uri("http://testman.com"),
				ModelDescription = "A test embeddeddevice",
				ModelName = "Test Model",
				ModelNumber = "1234",
				ModelUrl = new Uri("http://testmodel.com"),
				PresentationUrl = new Uri("http://testmodel.com/embedded/presentation"),
				SerialNumber = "TM-12345",
				Upc = "123456789012",
				Uuid = Guid.NewGuid().ToString()
			};
			rootDevice.AddDevice(retVal);

			return retVal;
		}

		private class MockCustomDevice : SsdpDevice
		{

			public void DoInvalidWrite(XmlWriter writer, SsdpDevice device)
			{
				this.WriteDeviceDescriptionXml(writer, device);
			}

			protected override void WriteDeviceDescriptionXml(System.Xml.XmlWriter writer, SsdpDevice device)
			{
				base.WriteDeviceDescriptionXml(writer, device);
			}

		}
	}
}


text:
package com.jlj.service.imp;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.jlj.dao.IValvedataDao;
import com.jlj.model.Valvedata;
import com.jlj.service.IValvedataService;
@Component("valvedataservice")
public class ValvedataServiceImp implements IValvedataService {
	private IValvedataDao valvedataDao;
	public IValvedataDao getValvedataDao() {
		return valvedataDao;
	}
	@Resource
	public void setValvedataDao(IValvedataDao valvedataDao) {
		this.valvedataDao = valvedataDao;
	}
	//添加对象

	/* (non-Javadoc)
	 * @see com.jlj.service.imp.IValvedataService#add(com.jlj.model.Valvedata)
	 */
	public void add(Valvedata valvedata) throws Exception {
		valvedataDao.save(valvedata);
	}
	//删除对象
	/* (non-Javadoc)
	 * @see com.jlj.service.imp.IValvedataService#delete(com.jlj.model.Valvedata)
	 */
	public void delete(Valvedata valvedata) {
		valvedataDao.delete(valvedata);
	}
	//删除某个id的对象
	/* (non-Javadoc)
	 * @see com.jlj.service.imp.IValvedataService#deleteById(int)
	 */
	public void deleteById(int id) {
		valvedataDao.deleteById(id);
	}
	//修改对象
	/* (non-Javadoc)
	 * @see com.jlj.service.imp.IValvedataService#update(com.jlj.model.Valvedata)
	 */
	public void update(Valvedata valvedata) {
		valvedataDao.update(valvedata);
	}
	//获取所有对象
	/* (non-Javadoc)
	 * @see com.jlj.service.imp.IValvedataService#getValvedatas()
	 */
	public List<Valvedata> getValvedatas() {
		return valvedataDao.getValvedatas();
	}
	//加载一个id的对象
	/* (non-Javadoc)
	 * @see com.jlj.service.imp.IValvedataService#loadById(int)
	 */
	public Valvedata loadById(int id) {
		return valvedataDao.loadById(id);
	}
	//后台管理-获取总记录数
	/* (non-Javadoc)
	 * @see com.jlj.service.imp.IValvedataService#getTotalCount(int, java.lang.String)
	 */
	public int getTotalCount(int con, String convalue) {
		String queryString = "select count(*) from Valvedata mo where 1=1 ";
		Object[] p = null;
		if(con!=0&&convalue!=null&&!convalue.equals("")){
			//线路名称
			if(con==1){
				queryString += "and mo.name like ? ";
			}
			p = new Object[]{'%'+convalue+'%'};
		}
		return valvedataDao.getUniqueResult(queryString,p);
	}
	//后台管理-获取符合条件的记录
	/* (non-Javadoc)
	 * @see com.jlj.service.imp.IValvedataService#queryList(int, java.lang.String, int, int)
	 */
	public List<Valvedata> queryList(int con, String convalue, int page, int size) {
		String queryString = "from Valvedata mo where 1=1 ";
		Object[] p = null;
		if(con!=0&&convalue!=null&&!convalue.equals("")){
			//线路名称
			if(con==1){
				queryString += "and mo.name like ? ";
			}
			p = new Object[]{'%'+convalue+'%'};
		}
		queryString += " order by mo.project.name asc,mo.name asc ";
		return valvedataDao.pageList(queryString,p,page,size);
	}

	//获取总页数
	/* (non-Javadoc)
	 * @see com.jlj.service.imp.IValvedataService#getPageCount(int, int)
	 */
	public int getPageCount(int totalCount, int size) {
		return totalCount%size==0?totalCount/size:(totalCount/size+1);
	}
	//根据外设id查询该外设的历史数据的总记录数
	public int getValveTotalCount(int con, String convalue, int valveid) {
		String queryString = "select count(*) from Valvedata mo where mo.valve.id=? ";
		Object[] p = null;
		if(con!=0&&convalue!=null&&!convalue.equals("")){
			//外设编号
			if(con==1){
				queryString += " and mo.valve.name like ? ";
			}
			p = new Object[]{valveid,'%'+convalue+'%'};
		}else{
			p = new Object[]{valveid};
		}
		return valvedataDao.getUniqueResult(queryString,p);
	}
	//根据外设id查询该外设的历史数据
	public List<Valvedata> queryValveList(int con, String convalue,
			int valveid, int page, int size) {
		String queryString = "from Valvedata mo where mo.valve.id=? ";
		Object[] p = null;
		if(con!=0&&convalue!=null&&!convalue.equals("")){
			//外设编号
			if(con==1){
				queryString += " and mo.valve.name like ? ";
			}
			p = new Object[]{valveid,'%'+convalue+'%'};
		}else{
			p = new Object[]{valveid};
		}
		queryString += " order by mo.id desc ";
		return valvedataDao.pageList(queryString,p,page,size);
	}

}


text:
title: "Quick-Start Guide"
permalink: /docs/quick-start-guide/
excerpt: "How to quickly install and setup Minimal Mistakes for use with GitHub Pages."
last_modified_at: 2020-07-27
redirect_from:
  - /theme-setup/
toc: true
---

Minimal Mistakes has been developed as a [Gem-based theme](http://jekyllrb.com/docs/themes/) for easier use, and 100% compatible with GitHub Pages when used as a remote theme.

**If you enjoy this theme, please consider [supporting me](https://www.paypal.me/mmistakes) for developing and maintaining it.**

[![Support via PayPal](https://cdn.jsdelivr.net/gh/twolfson/paypal-github-button@1.0.0/dist/button.svg)](https://www.paypal.me/mmistakes)

## Installing the theme

If you're running Jekyll v3.7+ and self-hosting you can quickly install the theme as a Ruby gem.

[^structure]: See [**Structure** page]({{ "/docs/structure/" | relative_url }}) for a list of theme files and what they do.

**ProTip:** Be sure to remove `/docs` and `/test` if you forked Minimal Mistakes. These folders contain documentation and test pages for the theme and you probably don't want them littering up your repo.
{: .notice--info}

**Note:** The theme uses the [jekyll-include-cache](https://github.com/benbalter/jekyll-include-cache) plugin which will need to be installed in your `Gemfile` and added to the `plugins` array of `_config.yml`. Otherwise you'll throw `Unknown tag 'include_cached'` errors at build.
{: .notice--warning}

### Gem-based method

With Gem-based themes, directories such as the `assets`, `_layouts`, `_includes`, and `_sass` are stored in the theme's gem, hidden from your immediate view. This allows for easier installation and updating as you don't have to manage any of the theme files.

To install as a Gem-based theme:

1. Add the following to your `Gemfile`:

   ```ruby
   gem "minimal-mistakes-jekyll"
   ```

2. Fetch and update bundled gems by running the following [Bundler](https://bundler.io/) command:

   ```bash
   bundle
   ```

3. Set the `theme` in your project's Jekyll `_config.yml` file:

   ```yaml
   theme: minimal-mistakes-jekyll
   ```

To update the theme run `bundle update`.

### Remote theme method

Remote themes are similar to Gem-based themes, but do not require `Gemfile` changes or whitelisting making them ideal for sites hosted with GitHub Pages.

To install as a remote theme:

1. Create/replace the contents of your `Gemfile` with the following:

   ```ruby
   source "https://rubygems.org"

   gem "github-pages", group: :jekyll_plugins
   ```

2. Add `jekyll-include-cache` to the `plugins` array of your `_config.yml`.

3. Fetch and update bundled gems by running the following [Bundler](https://bundler.io/) command:

   ```bash
   bundle
   ```

4. Add `remote_theme: "mmistakes/minimal-mistakes@4.20.1"` to your `_config.yml` file. Remove any other `theme:` or `remote_theme:` entry.

You may also optionally specify a branch, [tag](https://github.com/mmistakes/minimal-mistakes/tags), or commit to use by appending an @ and the Git ref (e.g., `mmistakes/minimal-mistakes@4.9.0` or `mmistakes/minimal-mistakes@bbf3cbc5fd64a3e1885f3f99eb90ba92af84063d`). This is useful when rolling back to older versions of the theme. If you don't specify a Git ref, the latest on `master` will be used.

**Looking for an example?** Use the [Minimal Mistakes remote theme starter](https://github.com/mmistakes/mm-github-pages-starter/generate) for the quickest method of getting a GitHub Pages hosted site up and running. Generate a new repository from the starter, replace sample content with your own, and configure as needed.
{: .notice--info}

---

**Note:** Your Jekyll site should be viewable immediately at <http://USERNAME.github.io>. If it's not, you can force a rebuild by **Customizing Your Site** (see below for more details).
{: .notice--warning}

If you're hosting several Jekyll based sites under the same GitHub username you will have to use Project Pages instead of User Pages. Essentially you rename the repo to something other than **USERNAME.github.io** and create a `gh-pages` branch off of `master`. For more details on how to set things up check [GitHub's documentation](https://help.github.com/articles/user-organization-and-project-pages/).

You can also install the theme by copying all of the theme files[^structure] into your project.

To do so fork the [Minimal Mistakes theme](https://github.com/mmistakes/minimal-mistakes/fork), then rename the repo to **USERNAME.github.io** --- replacing **USERNAME** with your GitHub username.

**GitHub Pages Alternatives:** Looking to host your site for free and install/update the theme painlessly? [Netlify][netlify-jekyll], [GitLab Pages][gitlab-jekyll], and [Continuous Integration (CI) services][ci-jekyll] have you covered. In most cases all you need to do is connect your repository to them, create a simple configuration file, and install the theme following the [Ruby Gem Method](#ruby-gem-method) above.
{: .notice--info}

[netlify-jekyll]: https://www.netlify.com/blog/2015/10/28/a-step-by-step-guide-jekyll-3.0-on-netlify/
[gitlab-jekyll]: https://about.gitlab.com/2016/04/07/gitlab-pages-setup/
[ci-jekyll]: https://jekyllrb.com/docs/continuous-integration/

### Remove the Unnecessary

If you forked or downloaded the `minimal-mistakes-jekyll` repo you can safely remove the following folders and files:

- `.editorconfig`
- `.gitattributes`
- `.github`
- `/docs`
- `/test`
- `CHANGELOG.md`
- `minimal-mistakes-jekyll.gemspec`
- `README.md`
- `screenshot-layouts.png`
- `screenshot.png`

**Note:** If forking the theme be sure to update `Gemfile` as well. The one found at the root of the project is for building the theme's Ruby gem and is missing dependencies. To properly setup a [`Gemfile`](https://github.com/mmistakes/minimal-mistakes/blob/master/docs/Gemfile) with the theme, consult the "[Install Dependencies](https://mmistakes.github.io/minimal-mistakes/docs/installation/#install-dependencies)" section.
{: .notice--warning}

## Setup Your Site

Depending on the path you took installing Minimal Mistakes you'll setup things a little differently.

**ProTip:** The source code and content files for this site can be found in the [`/docs` folder](https://github.com/mmistakes/minimal-mistakes/tree/master/docs) if you want to copy or learn from them.
{: .notice--info}

### Starting Fresh

Starting with an empty folder and `Gemfile` you'll need to copy or re-create this [default `_config.yml`](https://github.com/mmistakes/minimal-mistakes/blob/master/_config.yml) file. For a full explanation of every setting be sure to read the [**Configuration**]({{ "/docs/configuration/" | relative_url }}) section.

From `v4.5.0` onwards, Minimal Mistakes theme-gem comes bundled with the necessary data files for localization.
They will be picked up automatically if you have the [`jekyll-data`](https://github.com/ashmaroli/jekyll-data) plugin installed.
If you're hosting on GitHub Pages, you can copy the [`_data/ui-text.yml`][ui-text.yml] file into your repository for the localization feature to work.

You'll need to create and edit these data files to customize them:

- [`_data/ui-text.yml`][ui-text.yml] - UI text [documentation]({{ "/docs/ui-text/" | relative_url }})
- [`_data/navigation.yml`][navigation.yml] - navigation [documentation]({{ "/docs/navigation/" | relative_url }})

  [ui-text.yml]: https://github.com/mmistakes/minimal-mistakes/blob/master/_data/ui-text.yml
  [navigation.yml]: https://github.com/mmistakes/minimal-mistakes/blob/master/_data/navigation.yml

### Starting from `jekyll new`

Scaffolding out a site with the `jekyll new` command requires you to modify a few files that it creates.

Edit `_config.yml`. Then:

- Replace `<site root>/index.md` with a modified [Minimal Mistakes `index.html`](https://github.com/mmistakes/minimal-mistakes/blob/master/index.html). Be sure to enable pagination if using the [`home` layout]({{ "/docs/layouts/#home-page" | relative_url }}) by adding the necessary lines to **_config.yml**.
- Change `layout: post` in `_posts/0000-00-00-welcome-to-jekyll.markdown` to `layout: single`.
- Remove `about.md`, or at the very least change `layout: page` to `layout: single` and remove references to `icon-github.html` (or [copy to your `_includes`](https://github.com/jekyll/minima/tree/master/_includes) if using it).

### Migrating to Gem Version

If you're migrating a site already using Minimal Mistakes and haven't customized any of the theme files things upgrading will be easier for you.

Start by removing the following folders and any files within them:

```terminal
├── _includes
├── _layouts
├── _sass
├── assets
|  ├── css
|  ├── fonts
|  └── js
```

You won't need these anymore as they're bundled with the theme gem --- unless you intend to [override them](https://jekyllrb.com/docs/themes/#overriding-theme-defaults).

**Note:** When clearing out the `assets` folder be sure to leave any files you've added and need. This includes images, CSS, or JavaScript that aren't already [bundled in the theme](https://github.com/mmistakes/minimal-mistakes/tree/master/assets).
{: .notice--warning}

From `v4.5.0` onwards, the default language files are read-in automatically via the [`jekyll-data`](https://github.com/ashmaroli/jekyll-data) plugin if it's installed. For sites hosted with GitHub Pages, you still need to copy the [`_data/ui-text.yml`][ui-text.yml] file because the `jekyll-data` plugin [is unsupported on GitHub Pages](https://docs.github.com/en/github/working-with-github-pages/about-github-pages-and-jekyll#plugins).

If you customized any of these files leave them alone, and only remove the untouched ones. If done correctly your modified versions should [override](https://jekyllrb.com/docs/themes/#overriding-theme-defaults) the versions bundled with the theme and be used by Jekyll instead.

#### Update Gemfile

Replace `gem "github-pages` or `gem "jekyll"` with `gem "jekyll", "~> 3.5"`. You'll need the latest version of Jekyll[^update-jekyll] for Minimal Mistakes to work and load all of the theme's assets properly, this line forces Bundler to do that.

[^update-jekyll]: You could also run `bundle update jekyll` to update Jekyll.

Add the Minimal Mistakes theme gem:

```ruby
gem "minimal-mistakes-jekyll"
```

When finished your `Gemfile` should look something like this:

```ruby
source "https://rubygems.org"

gem "jekyll", "~> 3.7"
gem "minimal-mistakes-jekyll"
```

Then run `bundle update` and add `theme: minimal-mistakes-jekyll` to your `_config.yml`.

**v4 Breaking Change:** Paths for image headers, overlays, teasers, [galleries]({{ "/docs/helpers/#gallery" | relative_url }}), and [feature rows]({{ "/docs/helpers/#feature-row" | relative_url }}) have changed and now require a full path. Instead of just `image: filename.jpg` you'll need to use the full path eg: `image: /assets/images/filename.jpg`. The preferred location is now `/assets/images/` but can be placed elsewhere or externally hosted. This applies to image references in `_config.yml` and `author.yml` as well.
{: .notice--danger}

---

That's it! If all goes well running `bundle exec jekyll serve` should spin-up your site.


text:
(function(){

	var app = angular.module('store',[]);

	app.controller('StoreController', function(){
		this.products = gems;

	});

	app.controller('PanelController', function(){

		this.tab = 1;

		this.selectTab = function(setTab){
			this.tab = setTab;
		};

		this.isSelected = function(checkTab){
			//alert("CheckTab = " + checkTab + "Tab = " + this.tab);
			return this.tab === checkTab;
		};
	});

	var gems = [
		{
			name : "Dodecahedron",
			price : 2.95,
			description : ". . .",
			canPurchase : true,
			soldOut : false
		},
		{
			name: "Pentagonal Gem",
			price: 5.95,
			description: '. . .',
			canPurchase: false
		}
	];

})();


text:
(function(exports){

Layout.initialize({
	html: "/Craftyy/Playwright/layout/Calendar.html"
});

/***

CALENDAR
- A fullscreen layout with folding pages and tabs

*/
var Calendar = {

	// TODO: Should be defined in GameEditor
	tabConfigs: [
		{id:"publish"},
		{id:"preview"},
		{id:"draw"},
		{id:"home"},
		{id:"actionmaker"},
	],

	initialize: function(){

		this.tabs = {};
		this.pageStack = [];

		Layout.ready(this.init.bind(this));

		Layout.showModule = this.showModule.bind(this);
		Layout.addComponent = this.addComponent.bind(this);
		Layout.addIframe = this.addIframe.bind(this);

		// HACK: Before Unload
		Messenger.handleRequest("DisableExitPrompt",function(){
			window.onbeforeunload = null;
		});
		window.onbeforeunload = function(e) {
		    return "Wait, you have unsaved changes!";
		};

	},

	init: function(){

		// TABS
		for(var i=0; i<this.tabConfigs.length; i++){
			_addTab(this.tabConfigs[i]);
		}

	},

	addIframe: function(iframe){

		iframe.setAttribute("scrolling","no");

		if(this.pageStack.length==0){
			document.getElementById("first_module").appendChild(iframe);
		}else{
			document.getElementById("module").appendChild(iframe);
		}

	},

	showModule: function(module){

		var calendar_container = document.getElementById("calendar_container");
		var modules = document.getElementById("module").children;
		var footer = document.getElementById("footer");

		// Is it in the Stack?
		var idIndex = this.pageStack.indexOf(module);
		if(idIndex<0){

			// First one?
			if(this.pageStack.length!=0){
				module.iframe.style.zIndex = this.pageStack.length;
				calendar_container.style.display = 'block';
			}

			this.pageStack.push(module);
			setTimeout(function(){
				module.iframe.setAttribute("class","shown");
			},1);

		}else{

			// If so, pop everything on top & hide them.
			var popped = this.pageStack.splice(idIndex+1);
			popped.reverse();
			for(var i=0;i<popped.length;i++){
				(function(iframe,delay){
					setTimeout( function(){iframe.setAttribute("class","");}, delay );
				})(popped[i].iframe,i*200);
			}

		}

		// HACK: Navigation is right above the FIRST one.
		if(this.pageStack.length==1){
			setTimeout(function(){
				calendar_container.style.display = 'none';
			},500);
		}

		setTimeout(function(){
			Playwright.currentModule.iframe.focus();
		},100);

	},

	addComponent: function(dom){
		document.getElementById("playwright").appendChild(dom);
	}

};

////////////////
// HELPERS
var _addTab = function(tabConfig){
	var id = tabConfig.id;
	Calendar.tabs[id] = tabConfig;
	var dom = document.getElementById("nav_"+tabConfig.id);
	tabConfig.dom = dom;
};

////////////////
// SINGLETON
exports.Calendar = Calendar;
Calendar.initialize();

})(window);


text:
/* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.office;
import com.wilutions.com.*;

/**
 * GradientStop.
 *
 */
@CoInterface(guid="{000C03BF-0000-0000-C000-000000000046}")
public interface GradientStop extends IDispatch {
  static boolean __typelib__loaded = __TypeLib.load();
  @DeclDISPID(1610743808)  public IDispatch getApplication() throws ComException;
  @DeclDISPID(1610743809)  public Integer getCreator() throws ComException;
  @DeclDISPID(1)  public ColorFormat getColor() throws ComException;
  @DeclDISPID(2)  public Float getPosition() throws ComException;
  @DeclDISPID(2)  public void setPosition(final Float value) throws ComException;
  @DeclDISPID(3)  public Float getTransparency() throws ComException;
  @DeclDISPID(3)  public void setTransparency(final Float value) throws ComException;
}


text:
@implementation LayerBoundsTransition {
    CGRect _fromBounds;
    CGRect _toBounds;
}

- (instancetype)initWithView:(UIView *)view
                        from:(CGRect)from
                          to:(CGRect)to
                  startDelay:(NSTimeInterval)startDelay
                    duration:(NSTimeInterval)duration
                interpolator:(id<Interpolator>)interpolator {
    self = [super initWithView:view
                    startDelay:startDelay
                      duration:duration
                  interpolator:interpolator];
    _fromBounds = from;
    _toBounds = to;
    return self;
}

- (CATransform3D)animateWithProgress:(CGFloat)p {
    CGRect toBounds = [RNNInterpolator fromRect:_fromBounds
                                         toRect:_toBounds
                                        precent:p
                                   interpolator:self.interpolator];
    self.view.layer.bounds = toBounds;

    return CATransform3DIdentity;
}

@end


text:
require 'spec_helper'

RSpec.describe LocalSkiReport::Output do
  before(:all) do
    @input = LocalSkiReport::Input.new
    @region = LocalSkiReport::Region.new
    @scraper = LocalSkiReport::Scraper.new
    @output = LocalSkiReport::Output.new(
      input: @input,
      region: @region,
      scraper: @scraper
    )
  end
  after(:all) do
    # Not working find a way to close browser after test complete
    @scraper.browser.close
  end
  describe '#list_regions' do
    it 'outputs to terminal a numbered list of regions' do
      expect { @output.list_regions }.to output("1. MIDWEST\n2. NORTHEAST\n3. NORTHWEST\n4. ROCKIES\n5. SOUTHEAST\n6. WESTCOAST\n").to_stdout
    end
  end

  describe '#list_states' do
    it 'outputs to terminal a numbered list of states from a region' do
      expect { @output.list_states(0) }.to output("1. Illinois\n2. Indiana\n3. Iowa\n4. Kansas\n5. Michigan\n6. Minnesota\n7. Missouri\n8. Ohio\n9. Wisconsin\n").to_stdout
    end
  end

  describe '#select_region' do
    it 'lists regions, prompts user for input, and returns value as Fixnum' do
      allow(@output).to receive(:list_regions)
      allow($stdout).to receive(:puts)
      allow(@output.input).to receive(:gets).at_least(:once).and_return("1")

      expect(@output.select_region).to eq(0)
    end
  end

  describe '#select_state' do
    it 'lists states in regions, prompts user for input, and returns value as Fixnum' do
      allow(@output).to receive(:list_states)
      allow($stdout).to receive(:puts)
      allow(@output.input).to receive(:gets).at_least(:once).and_return("1")

      expect(@output.select_state(1)).to eq(0)
    end
  end
end

# allow($stdout).to receive(:puts)
# allow(@input).to receive(:gets).at_least(:once).and_return("1")
#
# expect(@input.user_selection('Make selection', ['Midwest', 'Northeast'])).to eq(1)


text:
from __future__ import absolute_import

import logging
from datetime import datetime, timedelta

# Adapted http://djangosnippets.org/snippets/2242/ by user s29 (October 25, 2010)

class _RateLimitFilter(object):
    last_error = datetime.min

    def filter(self, record):
        from django.conf import settings
        from django.core.cache import cache

        # Track duplicate errors
        duplicate = False
        rate = getattr(settings, '%s_LIMIT' %  self.__class__.__name__.upper(),
               600)  # seconds
        if rate > 0:
            # Test if the cache works
            try:
                cache.set('RLF_TEST_KEY', 1, 1)
                use_cache = cache.get('RLF_TEST_KEY') == 1
            except:
                use_cache = False

            if use_cache:
                key = self.__class__.__name__.upper()
                duplicate = cache.get(key) == 1
                cache.set(key, 1, rate)
            else:
                min_date = datetime.now() - timedelta(seconds=rate)
                duplicate = (self.last_error >= min_date)
                if not duplicate:
                    self.last_error = datetime.now()

        return not duplicate

class ZulipLimiter(_RateLimitFilter):
    pass

class EmailLimiter(_RateLimitFilter):
    pass

class ReturnTrue(logging.Filter):
    def filter(self, record):
        return True

class RequireReallyDeployed(logging.Filter):
    def filter(self, record):
        from django.conf import settings
        return settings.PRODUCTION


text:
import React from 'react';
import { getCart, setCart } from '../api/localstorage.js';
import Loading from 'react-loading-animation';
import currency from '../helpers/currency.js';
import total from '../helpers/total.js';
import CartItem from '../components/CartItem.js';

class Cart extends React.Component {
  constructor(props) {
    super(props);
    this.checkout = this.checkout.bind(this);
    this.state = {
      allcart: [],
      totalItem: 0,
      isLoading: true
    }
  }

  componentDidMount() {
    var cart = getCart();
    setTimeout(() => {
      this.setState({
        allcart: cart.all,
        totalItem: cart.totalItem,
        isLoading: false,
      });
    }, 1000);
  }

  checkout() {
    let cart = {
      all: [],
      totalItem: 0
    };
    setCart(cart);

    this.setState({
      allcart: [],
      totalItem: 0,
    });
  }

  render() {
    var { allcart, totalItem, isLoading } = this.state;

    if (isLoading) return
<Loading />
;

    return (

            {allcart.length === 0 ?
You have not bought something yet...
 :

Your Cart Items

                        No.
                        Name
                        Qty.
                        Price
                        Total

                      {allcart.map((item, index) => (
                        <CartItem key={index} item={item} index={index}/>
                      ))}

                        Total
                        {totalItem}

                        { currency(total(allcart)) }

                <button onClick={this.checkout} className="btn">Checkout</button>

}

    );
  }
};

export default Cart;


text:
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations
    Public Class AliasKeywordRecommenderTests
        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AliasAfterLibNameInSubTest()
            VerifyRecommendationsAreExactly(<ClassDeclaration>Declare Sub goo Lib "Goo" |</ClassDeclaration>, "Alias")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AliasAfterLibNameInFunctionTest()
            VerifyRecommendationsAreExactly(<ClassDeclaration>Declare Function goo Lib "Goo" |</ClassDeclaration>, "Alias")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AliasNotAfterLibKeywordTest()
            VerifyRecommendationsAreExactly(<ClassDeclaration>Declare Sub goo Lib |</ClassDeclaration>, Array.Empty(Of String)())
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub NothingAfterBrokenAliasTest()
            VerifyRecommendationsAreExactly(<ClassDeclaration>Declare Sub goo Lib "Goo" Alais |</ClassDeclaration>, Array.Empty(Of String)())
        End Sub

        <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")>
        <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub NoAliasAfterEolTest()
            VerifyRecommendationsMissing(
<ClassDeclaration>Declare Function goo Lib "Goo"
    |</ClassDeclaration>, "Alias")
        End Sub

        <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")>
        <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AliasAfterExplicitLineContinuationTest()
            VerifyRecommendationsAreExactly(
<ClassDeclaration>Declare Function goo Lib "Goo" _
|</ClassDeclaration>, "Alias")
        End Sub
        <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")>
        <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AliasAfterExplicitLineContinuationTestCommentsAfterLineContinuation()
            VerifyRecommendationsAreExactly(
<ClassDeclaration>Declare Function goo Lib "Goo" _ ' Test
|</ClassDeclaration>, "Alias")
        End Sub
    End Class
End Namespace


text:
packages="$(pwd)/packages"
scripts="$(pwd)/.scripts"

for letter in {a..z}
do
  cd "$packages/brittanica-$letter"
  cat <<EOF >> terms.js
module.exports = {
EOF
  cd ..
done

while IFS= read -r LINE; do
  letter=`echo "$LINE" | head -c 1`
  cat <<EOF >> "$packages/brittanica-$letter/terms.js"
    "$LINE": {
      page: $RANDOM,
      description: require('./fieri.js').guy
    },
EOF
  cd ..
done < "$scripts/words.txt"

for letter in {a..z}
do
  cd "$packages/brittanica-$letter"
  cat <<EOF >> terms.js
}

EOF
  cd ..
done


text:
function help {
    echo "Choose one of the following: {build|install|test|clean}"
    exit 1
}

RUN_DIR=`pwd`
TEST_DIR=$RUN_DIR/test
TEST_RESULT=1
TEST_BUILD_FAILED=1

# Temporary solution
if [ ! -x $RUN_DIR/gcovr ]
then
    chmod +x $RUN_DIR/gcovr
fi

function measure_coverage {
    echo "Collecting coverage metrics..."
    cd $RUN_DIR && ./gcovr -d -x -f "($RUN_DIR).*" -e ".*(test|kaa/gen).*" -o $RUN_DIR/gcovr-report.xml -v > $RUN_DIR/gcovr.log
}

function run_tests {
    cd build && make -j4 && TEST_BUILD_FAILED=0 && ./kaatest && TEST_RESULT=0 # --report_level=detailed --report_format=xml 2>$RUN_DIR/unittest_result.xml && TEST_RESULT=0
}

function test_cleanup {
    echo "Cleaning up..."
    cd $TEST_DIR/build && make clean
    echo "Cleanup done."
}

if [ $# -eq 0 ]
then
    help
fi

mkdir -p build; cd build; cmake -DKAA_WITH_SQLITE_LOG_STORAGE=1 ..; cd ..

for cmd in $@
do

case "$cmd" in
    build)
    cd build && make -j4 && cd ..
    ;;

    install)
    cd build && make install && cd ..
    ;;

    clean)
    cd build && make clean && cd ..
    test_cleanup
    ;;

    test)
    cd $TEST_DIR
    mkdir -p build; cd build; cmake ..; cd ..
    run_tests
    if [[ $TEST_BUILD_FAILED -eq 0 ]]
    then
        measure_coverage
    fi
    test_cleanup
    if [[ $TEST_RESULT -ne 0 ]]
    then
        echo "Kaa C++ SDK unittests have failed!"
        exit $TEST_RESULT
    else
        echo "Kaa C++ SDK unittests have successfully passed!"
    fi
    ;;

    *)
    help
    ;;
esac

done


text:
import React, { useRef } from 'react';
import { Text } from 'native-base';
import { View, Image, NativeSyntheticEvent, ScrollViewProps } from 'react-native';
import { HeaderComponent } from '../main/header_component';
import { colors, textStyles, themedStyles } from '../../application/styles';
import { BackButtonComponent } from '../header_button/back_button_component';
import { mbStartBackground, mbStartLogoSquare } from '../../application/images';
import { Trans } from '@lingui/react';
import { Link } from '../link/link_component';
import { ScrollView } from 'react-native-gesture-handler';
import { OffsetHook, useOffset } from '../use_offset';
import { useScrollViewToOffset } from '../use_scroll_view_to_offset';
import { useTheme } from '../main/context_component';

export const MBStartComponent = (): JSX.Element => {
    const scrollViewRef = useRef<ScrollView>();
    const { setOffset, offsetFromRouteLocation }: OffsetHook = useOffset();
    // tslint:disable-next-line: no-expression-statement
    useScrollViewToOffset(scrollViewRef, offsetFromRouteLocation);
    const theme = useTheme();
    const scrollViewThrottle = 8;
    const aspectRatio = 360 / 180;
    const mbStartUrl = 'https://manitobastart.com/';

    return (
        <View style={{ flex: 1 }}>
            <HeaderComponent
                backgroundColor={colors.lightGrey}
                statusBarColour={colors.lightGrey}
                leftButton={<BackButtonComponent textColor={colors.black} />}
                rightButtons={[]}
            />
            <ScrollView
                ref={scrollViewRef}
                onScroll={(e: NativeSyntheticEvent<ScrollViewProps>): void => setOffset(e.nativeEvent.contentOffset.y)}
                scrollEventThrottle={scrollViewThrottle}
            >
                <Image
                    source={mbStartBackground}
                    resizeMode='contain'
                    style={{height: undefined, width: '100%', aspectRatio}}
                />
                <View style={{ top: -60, marginHorizontal: 24 }}>
                    <Image
                        source={mbStartLogoSquare}
                        style={{height: 120, width: 120, borderColor: colors.lightGrey, borderRadius: 8, borderWidth: 4}}
                    />
                    <Text style={[textStyles.headlineH1StyleBlackLeft, { paddingTop: 24 }]}>Manitoba Start</Text>
                    <Text style={[textStyles.paragraphStyle, { paddingTop: 16 }]}>
                        <Trans>Manitoba Start provides central registration and needs assessment for all newcomers arriving to Winnipeg/Manitoba.
                            It is an important step to register through Manitoba Start then you will be connected to language services and other
                            settlement agencies in your area.Manitoba Start can help internationally educated and skilled newcomers
                            with credential recognition and employment preparation/opportunities.</Trans>
                    </Text>
                    <Link href={mbStartUrl} style={[themedStyles(theme).link, { paddingTop: 16 }]}>manitobastart.com</Link>
                </View>
            </ScrollView>
        </View>
    );
};


text:
game.IngredientEntity = me.Entity.extend({
    // extending the init function is not mandatory
    // unless you need to add some extra initialization
    init: function(x, y, settings) {
        // call the parent constructor
        this._super(me.Entity, 'init', [x, y , settings]);

    },

    // this function is called by the engine, when
    // an object is touched by something (here collected)
    onCollision : function (response, other) {
        // do something when collected

        // make sure it cannot be collected "again"
        this.body.setCollisionMask(me.collision.types.NO_OBJECT);

        // remove it
        me.game.world.removeChild(this);

        return false
    }
});


text:
package hu.marfoldi.example.javaee.model;

import java.io.Serializable;
import javax.persistence.*;

/**
 * @author marfoldi
 */

@MappedSuperclass
public abstract class BaseEntity implements Serializable {

	private static final long serialVersionUID = 891718856686139048L;

	@Id
	@GeneratedValue(generator = "ID_GEN", strategy = GenerationType.SEQUENCE)
	@SequenceGenerator(name = "ID_GEN", sequenceName = "ID_SEQ", allocationSize = 10)
	private Long id;

	@Version
	private Long version;

	/**
	 * @return the id
	 */
	public Long getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(Long id) {
		this.id = id;
	}

	/**
	 * @return the version
	 */
	public Long getVersion() {
		return version;
	}

	/**
	 * @param version
	 *            the version to set
	 */
	public void setVersion(Long version) {
		this.version = version;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + ((version == null) ? 0 : version.hashCode());
		return result;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof BaseEntity)) {
			return false;
		}
		BaseEntity other = (BaseEntity) obj;
		if (id == null) {
			if (other.id != null) {
				return false;
			}
		} else if (!id.equals(other.id)) {
			return false;
		}
		if (version == null) {
			if (other.version != null) {
				return false;
			}
		} else if (!version.equals(other.version)) {
			return false;
		}
		return true;
	}

}


text:
layout: default
description: >-
  In the ArangoDB shell, you can use the db._query() and db._createStatement()
  methods to execute AQL queries.
---
# Executing queries from _arangosh_

In the ArangoDB shell, you can use the `db._query()` and `db._createStatement()`
methods to execute AQL queries. This chapter also describes
how to use bind parameters, counting, statistics and cursors.

## With `db._query()`

You can execute queries with the `_query()` method of the `db` object.
This runs the specified query in the context of the currently
selected database and returns the query results in a cursor.
You can print the results of the cursor using its `toArray()` method:

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 01_workWithAQL_all
    @EXAMPLE_ARANGOSH_OUTPUT{01_workWithAQL_all}
    ~addIgnoreCollection("mycollection")
    db._create("mycollection")
    db.mycollection.save({ _key: "testKey", Hello : "World" })
    db._query('FOR my IN mycollection RETURN my._key').toArray()
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 01_workWithAQL_all
    {% endarangoshexample %}
    {% include arangoshexample.html id=examplevar script=script result=result %}

### `db._query()` bind parameters

To pass bind parameters into a query, you can specify a second argument when
calling the `_query()` method:

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 02_workWithAQL_bindValues
    @EXAMPLE_ARANGOSH_OUTPUT{02_workWithAQL_bindValues}
    | db._query('FOR c IN @@collection FILTER c._key == @key RETURN c._key', {
    |   '@collection': 'mycollection',
    |   'key': 'testKey'
      }).toArray();
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 02_workWithAQL_bindValues
    {% endarangoshexample %}
    {% include arangoshexample.html id=examplevar script=script result=result %}

### ES6 template strings

It is also possible to use ES6 template strings for generating AQL queries. There is
a template string generator function named `aql`.

The following example demonstrates what the template string function generates:

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 02_workWithAQL_aqlTemplateString
    @EXAMPLE_ARANGOSH_OUTPUT{02_workWithAQL_aqlTemplateString}
      var key = 'testKey';
      aql`FOR c IN mycollection FILTER c._key == ${key} RETURN c._key`
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 02_workWithAQL_aqlTemplateString
    {% endarangoshexample %}
    {% include arangoshexample.html id=examplevar script=script result=result %}

The next example directly uses the generated result to execute a query:

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 02_workWithAQL_aqlQuery
    @EXAMPLE_ARANGOSH_OUTPUT{02_workWithAQL_aqlQuery}
      var key = 'testKey';
    | db._query(
    |   aql`FOR c IN mycollection FILTER c._key == ${key} RETURN c._key`
      ).toArray();
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 02_workWithAQL_aqlQuery
    {% endarangoshexample %}
    {% include arangoshexample.html id=examplevar script=script result=result %}

Arbitrary JavaScript expressions can be used in queries that are generated with the
`aql` template string generator. Collection objects are handled automatically:

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 02_workWithAQL_aqlCollectionQuery
    @EXAMPLE_ARANGOSH_OUTPUT{02_workWithAQL_aqlCollectionQuery}
      var key = 'testKey';
      db._query(aql`FOR doc IN ${ db.mycollection } RETURN doc`).toArray();
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 02_workWithAQL_aqlCollectionQuery
    {% endarangoshexample %}
    {% include arangoshexample.html id=examplevar script=script result=result %}

Note: data-modification AQL queries normally do not return a result unless the
AQL query contains a `RETURN` operation at the top-level. Without a `RETURN`
operation, the `toArray()` method returns an empty array.

### Statistics and extra Information

It is always possible to retrieve statistics for a query with the `getExtra()` method:

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 03_workWithAQL_getExtra
    @EXAMPLE_ARANGOSH_OUTPUT{03_workWithAQL_getExtra}
    | db._query(`FOR i IN 1..100
    |   INSERT { _key: CONCAT('test', TO_STRING(i)) } INTO mycollection`
      ).getExtra();
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 03_workWithAQL_getExtra
{% endarangoshexample %}
{% include arangoshexample.html id=examplevar script=script result=result %}

The meaning of the statistics values is described in
[Query statistics](execution-and-performance-query-statistics.html).

Query warnings are also reported here. If you design queries on the shell,
be sure to check for warnings.

### Setting a memory limit

To set a memory limit for the query, pass `options` to the `_query()` method.
The memory limit specifies the maximum number of bytes that the query is
allowed to use. When a single AQL query reaches the specified limit value,
the query will be aborted with a *resource limit exceeded* exception. In a
cluster, the memory accounting is done per shard, so the limit value is
effectively a memory limit per query per shard.

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 02_workWithAQL_memoryLimit
    @EXAMPLE_ARANGOSH_OUTPUT{02_workWithAQL_memoryLimit}
    | db._query(
    |   'FOR i IN 1..100000 SORT i RETURN i',
    |   {},
    |   { memoryLimit: 100000 }
      ).toArray(); // xpError(ERROR_RESOURCE_LIMIT)
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 02_workWithAQL_memoryLimit
{% endarangoshexample %}
{% include arangoshexample.html id=examplevar script=script result=result %}

If no memory limit is specified, then the server default value (controlled by
the `--query.memory-limit` startup option) is used for restricting the maximum amount
of memory the query can use. A memory limit value of `0` means that the maximum
amount of memory for the query is not restricted.

### Setting options

There are further options that you can pass in the `options` attribute of the `_query()` method:

- `fullCount`: if set to `true` and if the query contains a `LIMIT` operation, then the
  result has an extra attribute with the sub-attributes `stats` and `fullCount`, like
  `{ ... , "extra": { "stats": { "fullCount": 123 } } }`. The `fullCount` attribute
  contains the number of documents in the result before the last top-level `LIMIT` in the
  query was applied. It can be used to count the number of documents that match certain
  filter criteria, but only return a subset of them, in one go. It is thus similar to
  MySQL's `SQL_CALC_FOUND_ROWS` hint. Note that setting the option disables a few
  `LIMIT` optimizations and may lead to more documents being processed, and thus make
  queries run longer. Note that the `fullCount` attribute may only be present in the
  result if the query has a top-level `LIMIT` operation and the `LIMIT` operation
  is actually used in the query.

- `failOnWarning`: when set to `true`, this makes the query throw an exception and
  abort in case a warning occurs. You should use this option in development to catch
  errors early. If set to `false`, warnings don't propagate to exceptions and are
  returned with the query results. There is also a `--query.fail-on-warning`
  startup options for setting the default value for `failOnWarning`, so that you
  don't need to set it on a per-query level.

- `cache`: if set to `true`, this puts the query result into the query result cache
  if the query result is eligible for caching and the query cache is running in demand
  mode. If set to `false`, the query result is not inserted into the query result
  cache. Note that query results are never inserted into the query result cache if
  the query result cache is disabled, and that they are automatically inserted into
  the query result cache if it is active in non-demand mode.

- `fillBlockCache`: if set to `true` or not specified, this makes the query store
  the data it reads via the RocksDB storage engine in the RocksDB block cache. This is
  usually the desired behavior. You can set the option to `false` for queries that are
  known to either read a lot of data that would thrash the block cache, or for queries
  that read data known to be outside of the hot set. By setting the option
  to `false`, data read by the query does not make it into the RocksDB block cache if
  it is not already in there, thus leaving more room for the actual hot set.

- `profile`: if set to `true` or `1`, returns extra timing information for the query.
  The timing information is accessible via the `getExtra()` method of the query
  result. If set to `2`, the query includes execution statistics per query plan
  execution node in `stats.nodes` sub-attribute of the `extra` return attribute.
  Additionally, the query plan is returned in the `extra.plan` sub-attribute.

- `maxWarningCount`: limits the number of warnings that are returned by the query if
  `failOnWarning` is not set to `true`. The default value is `10`.

- `maxNumberOfPlans`: limits the number of query execution plans the optimizer
  creates at most. Reducing the number of query execution plans may speed up query plan
  creation and optimization for complex queries, but normally there is no need to adjust
  this value.

- `optimizer`: Options related to the query optimizer.

  - `rules`: A list of to-be-included or to-be-excluded optimizer rules can be put into
  this attribute, telling the optimizer to include or exclude specific rules. To disable
  a rule, prefix its name with a `-`, to enable a rule, prefix it with a `+`. There is also
  a pseudo-rule `all`, which matches all optimizer rules. `-all` disables all rules.

- `stream`: Specify `true` and the query is executed in a **streaming** fashion. The query result is
  not stored on the server, but calculated on the fly. **Warning**: long-running queries
  need to hold the collection locks for as long as the query cursor exists. It is advisable
  to *only* use this option on short-running queries *or* without exclusive locks.
  When set to `false`, the query is executed right away in its entirety.
  In that case, the query results are either returned right away (if the result
  set is small enough), or stored on the arangod instance and can be accessed
  via the cursor API.

  Please note that the query options `cache`, `count` and `fullCount` don't work on streaming
  queries. Additionally, query statistics, warnings, and profiling data is only
  available after the query has finished. The default value is `false`.

- `maxRuntime`: The query has to be executed within the given runtime or it is killed.
  The value is specified in seconds. The default value is `0.0` (no timeout).

- `maxNodesPerCallstack`: The number of execution nodes in the query plan after
  that stack splitting is performed to avoid a potential stack overflow.
  Defaults to the configured value of the startup option
  `--query.max-nodes-per-callstack`.

  This option is only useful for testing and debugging and normally does not need
  any adjustment.

- `maxTransactionSize`: The transaction size limit in bytes.

- `intermediateCommitSize`: The maximum total size of operations after which an intermediate
  commit is performed automatically.

- `intermediateCommitCount`: The maximum number of operations after which an intermediate
  commit is performed automatically.

In the ArangoDB Enterprise Edition, there are additional parameters:

- `skipInaccessibleCollections`: Let AQL queries (especially graph traversals) treat
  collection to which a user has **no access** rights for as if these collections are empty.
  Instead of returning a *forbidden access* error, your queries execute normally.
  This is intended to help with certain use-cases: A graph contains several collections
  and different users execute AQL queries on that graph. You can naturally limit the
  accessible results by changing the access rights of users on collections.

- `satelliteSyncWait`: This Enterprise Edition parameter allows to configure how long
  a DB-Server has time to bring the SatelliteCollections involved in the query
  into sync. The default value is `60.0` seconds. When the maximal time is reached,
  the query is stopped.

## Additional parameters for spilling data from the query onto disk

Starting from ArangoDB 3.10, there are two additional parameters that allow spilling
intermediate data from a query onto a disk to decrease the memory usage.

{% hint 'info' %}
The option of spilling data from RAM onto disk is experimental and is turned off
by default. This parameter currently only has effect for sorting -
for a query that uses the `SORT` operation but without `LIMIT`.
Also, the query results are still built up entirely in RAM on Coordinators
and single servers for non-streaming queries. To avoid the buildup of
the entire query result in RAM, a streaming query should be used.
{% endhint %}

- `spillOverThresholdNumRows`: This parameter allows for input data and
  intermediate results to be spilled onto disk for a query execution
  after the number of rows reaches the specified value. This is
  used for decreasing the memory usage during the query execution. In a query
  that iterates over a collection that contains documents, each row is a
  document and, in a query that iterates over temporary values
  (i.e. `FOR i IN 1..100`), each row is one of such temporary values.
  This parameter is experimental and is only taken into account if a path for a
  directory to store the temporary data is provided with the
  [`--temp.intermediate-results-path` startup option](../programs-arangod-query.html#aql-query-with-spilling-input-data-to-disk).
  Default value: `5000000` rows.

- `spillOverThresholdMemoryUsage`: This parameter allows for input data and
  intermediate results to be spilled onto disk for a query execution
  after the memory usage reaches the specified value (in bytes). This
  is used for decreasing the memory usage during the query execution. This
  parameter is experimental and is only taken into account if a path for a
  directory to store the temporary data is provided with the
  [`--temp.intermediate-results-path` startup option](../programs-arangod-query.html#aql-query-with-spilling-input-data-to-disk).
  Default value: 128MB.

## With `db._createStatement()` (ArangoStatement)

The `_query()` method is a shorthand for creating an `ArangoStatement` object,
executing it and iterating over the resulting cursor. If more control over the
result set iteration is needed, it is recommended to first create an
`ArangoStatement` object as follows:

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 04_workWithAQL_statements1
    @EXAMPLE_ARANGOSH_OUTPUT{04_workWithAQL_statements1}
      stmt = db._createStatement( { "query": "FOR i IN [ 1, 2 ] RETURN i * 2" } );
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 04_workWithAQL_statements1
    {% endarangoshexample %}
    {% include arangoshexample.html id=examplevar script=script result=result %}

To execute the query, use the `execute()` method of the statement:

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 05_workWithAQL_statements2
    @EXAMPLE_ARANGOSH_OUTPUT{05_workWithAQL_statements2}
    ~ var stmt = db._createStatement( { "query": "FOR i IN [ 1, 2 ] RETURN i * 2" } );
      cursor = stmt.execute();
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 05_workWithAQL_statements2
    {% endarangoshexample %}
    {% include arangoshexample.html id=examplevar script=script result=result %}

### Cursors

Once the query executed the query results are available in a cursor.
The cursor can return all its results at once using the `toArray()` method.
This is a short-cut that you can use if you want to access the full result
set without iterating over it yourself.

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 05_workWithAQL_statements3
    @EXAMPLE_ARANGOSH_OUTPUT{05_workWithAQL_statements3}
    ~ var stmt = db._createStatement( { "query": "FOR i IN [ 1, 2 ] RETURN i * 2" } );
    ~ var cursor = stmt.execute();
      cursor.toArray();
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 05_workWithAQL_statements3
{% endarangoshexample %}
{% include arangoshexample.html id=examplevar script=script result=result %}

Cursors can also be used to iterate over the result set document-by-document.
To do so, use the `hasNext()` and `next()` methods of the cursor:

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 05_workWithAQL_statements4
    @EXAMPLE_ARANGOSH_OUTPUT{05_workWithAQL_statements4}
    ~ var stmt = db._createStatement( { "query": "FOR i IN [ 1, 2 ] RETURN i * 2" } );
    ~ var c = stmt.execute();
      while (c.hasNext()) { require("@arangodb").print(c.next()); }
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 05_workWithAQL_statements4
    {% endarangoshexample %}
    {% include arangoshexample.html id=examplevar script=script result=result %}

Please note that you can iterate over the results of a cursor only once, and that
the cursor will be empty when you have fully iterated over it. To iterate over
the results again, the query needs to be re-executed.

Additionally, the iteration can be done in a forward-only fashion. There is no
backwards iteration or random access to elements in a cursor.

### ArangoStatement parameters binding

To execute an AQL query using bind parameters, you need to create a statement first
and then bind the parameters to it before execution:

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 05_workWithAQL_statements5
    @EXAMPLE_ARANGOSH_OUTPUT{05_workWithAQL_statements5}
      var stmt = db._createStatement( { "query": "FOR i IN [ @one, @two ] RETURN i * 2" } );
      stmt.bind("one", 1);
      stmt.bind("two", 2);
      cursor = stmt.execute();
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 05_workWithAQL_statements5
    {% endarangoshexample %}
    {% include arangoshexample.html id=examplevar script=script result=result %}

The cursor results can then be dumped or iterated over as usual, e.g.:

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 05_workWithAQL_statements6
    @EXAMPLE_ARANGOSH_OUTPUT{05_workWithAQL_statements6}
    ~ var stmt = db._createStatement( { "query": "FOR i IN [ @one, @two ] RETURN i * 2" } );
    ~ stmt.bind("one", 1);
    ~ stmt.bind("two", 2);
    ~ var cursor = stmt.execute();
      cursor.toArray();
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 05_workWithAQL_statements6
    {% endarangoshexample %}
    {% include arangoshexample.html id=examplevar script=script result=result %}

or

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 05_workWithAQL_statements7
    @EXAMPLE_ARANGOSH_OUTPUT{05_workWithAQL_statements7}
    ~ var stmt = db._createStatement( { "query": "FOR i IN [ @one, @two ] RETURN i * 2" } );
    ~ stmt.bind("one", 1);
    ~ stmt.bind("two", 2);
    ~ var cursor = stmt.execute();
      while (cursor.hasNext()) { require("@arangodb").print(cursor.next()); }
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 05_workWithAQL_statements7
    {% endarangoshexample %}
    {% include arangoshexample.html id=examplevar script=script result=result %}

Please note that bind parameters can also be passed into the `_createStatement()`
method directly, making it a bit more convenient:

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 05_workWithAQL_statements8
    @EXAMPLE_ARANGOSH_OUTPUT{05_workWithAQL_statements8}
    | stmt = db._createStatement( {
    |   "query": "FOR i IN [ @one, @two ] RETURN i * 2",
    |   "bindVars": {
    |     "one": 1,
    |     "two": 2
    |   }
      });
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 05_workWithAQL_statements8
    {% endarangoshexample %}
    {% include arangoshexample.html id=examplevar script=script result=result %}

### Counting with a cursor

Cursors also optionally provide the total number of results. By default, they do not.
To make the server return the total number of results, you may set the `count` attribute to
`true` when creating a statement:

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 05_workWithAQL_statements9
    @EXAMPLE_ARANGOSH_OUTPUT{05_workWithAQL_statements9}
    | stmt = db._createStatement( {
    |   "query": "FOR i IN [ 1, 2, 3, 4 ] RETURN i",
        "count": true } );
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 05_workWithAQL_statements9
    {% endarangoshexample %}
    {% include arangoshexample.html id=examplevar script=script result=result %}

After executing this query, you can use the `count` method of the cursor to get the
number of total results from the result set:

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 05_workWithAQL_statements10
    @EXAMPLE_ARANGOSH_OUTPUT{05_workWithAQL_statements10}
    ~ var stmt = db._createStatement( { "query": "FOR i IN [ 1, 2, 3, 4 ] RETURN i", "count": true } );
      var cursor = stmt.execute();
      cursor.count();
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 05_workWithAQL_statements10
{% endarangoshexample %}
{% include arangoshexample.html id=examplevar script=script result=result %}

Please note that the `count` method returns nothing if you did not specify the `count`
attribute when creating the query.

This is intentional so that the server may apply optimizations when executing the query and
construct the result set incrementally. Incremental creation of the result sets
is no possible
if all of the results need to be shipped to the client anyway. Therefore, the client
has the choice to specify `count` and retrieve the total number of results for a query (and
disable potential incremental result set creation on the server), or to not retrieve the total
number of results and allow the server to apply optimizations.

Please note that at the moment the server will always create the full result set for each query so
specifying or omitting the `count` attribute currently does not have any impact on query execution.
This may change in the future. Future versions of ArangoDB may create result sets incrementally
on the server-side and may be able to apply optimizations if a result set is not fully fetched by
a client.

### Using cursors to obtain additional information on internal timings

Cursors can also optionally provide statistics of the internal execution phases. By default, they do not.
To get to know how long parsing, optimization, instantiation and execution took,
make the server return that by setting the `profile` attribute to
`true` when creating a statement:

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 06_workWithAQL_statements11
    @EXAMPLE_ARANGOSH_OUTPUT{06_workWithAQL_statements11}
    | stmt = db._createStatement( {
    |   "query": "FOR i IN [ 1, 2, 3, 4 ] RETURN i",
        options: {"profile": true}} );
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 06_workWithAQL_statements11
    {% endarangoshexample %}
    {% include arangoshexample.html id=examplevar script=script result=result %}

After executing this query, you can use the `getExtra()` method of the cursor to get the
produced statistics:

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 06_workWithAQL_statements12
    @EXAMPLE_ARANGOSH_OUTPUT{06_workWithAQL_statements12}
    ~ var stmt = db._createStatement( { "query": "FOR i IN [ 1, 2, 3, 4 ] RETURN i", options: {"profile": true}} );
      var cursor = stmt.execute();
      cursor.getExtra();
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 06_workWithAQL_statements12
{% endarangoshexample %}
{% include arangoshexample.html id=examplevar script=script result=result %}

## Query validation

The `_parse()` method of the `db` object can be used to parse and validate a
query syntactically, without actually executing it.

    {% arangoshexample examplevar="examplevar" script="script" result="result" %}
    @startDocuBlockInline 06_workWithAQL_statements13
    @EXAMPLE_ARANGOSH_OUTPUT{06_workWithAQL_statements13}
      db._parse( "FOR i IN [ 1, 2 ] RETURN i" );
    @END_EXAMPLE_ARANGOSH_OUTPUT
    @endDocuBlock 06_workWithAQL_statements13
    {% endarangoshexample %}
    {% include arangoshexample.html id=examplevar script=script result=result %}