text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
using System.IO;
using System.Linq;
using EnvDTE80;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudioTools.TestUtilities.UI;
using FluentAssertions;
using System.Diagnostics;

namespace Microsoft.VSIntegrationTests {
	[TestClass]
	public class Tests {
		[TestMethod, Priority(1)]
		[HostType("VSTestHost"), TestCategory("Installed")]
		public void CreateNewScript() {
			using (var app = new VisualStudioApp()) {
				var project = app.CreateProject(
					RConstants.TemplateLanguageName, RConstants.ProjectTemplate_EmptyProject,
					System.IO.Path.GetTempPath(), "RTestProject");
				app.OpenSolutionExplorer().SelectProject(project);
				using (var newItem = NewItemDialog.FromDte(app)) {
					AutomationWrapper.Select(newItem.ProjectTypes.FindItem("R Script"));
					newItem.FileName = "my-script.r";
					newItem.OK();
				}

				var document = app.GetDocument("my-script.r");
				document.SetFocus();
				document.Type("2 -> a");
				document.Text.Should().Be("2 -> a# R Script");
			}
		}

		[TestMethod, Priority(1)]
		[HostType("VSTestHost"), TestCategory("Installed")]
		public void VerifyTemplateDirectories() {
			var languageName = RConstants.TemplateLanguageName;
			using (var app = new VisualStudioApp()) {
				var sln = (Solution2)app.Dte.Solution;
				var paths = (new[] { RConstants.ProjectTemplate_EmptyProject })
					.Select(n => sln.GetProjectTemplate(n, languageName));
				var existingPaths = paths.Where(templatePath => File.Exists(templatePath) || Directory.Exists(templatePath));
				existingPaths.Should().BeEquivalentTo(paths);
			}
		}
	}
}


text:
VERSION="2.0.43"
# create fsurfer lib rpms
work_dir=`mktemp -d`
cur_dir=$PWD
echo "Scratch dir: $work_dir"
cp -a * $work_dir
cp -a ../bash $work_dir
echo "Generating package"
cd $work_dir
rm MANIFEST
sed -i'' "s/PKG_VERSION/$VERSION/" setup_fsurfer.py
sed -i'' "s/PKG_VERSION/$VERSION/" fsurfer/__init__.py
python setup_fsurfer.py bdist_rpm
cp dist/*.rpm $cur_dir
rm -fr $work_dir

# create fsurfer script rpms
cd $cur_dir
work_dir=`mktemp -d`
echo "Scratch dir: $work_dir"
cp -a * $work_dir
cp -a ../bash $work_dir
echo "Generating package"
cd $work_dir
rm MANIFEST
mv fsurf-osgconnect fsurf
sed -i'' "s/PKG_VERSION/$VERSION/" setup_osgconnect.py
sed -i'' "s/PKG_VERSION/$VERSION/" fsurfer/__init__.py
python setup_osgconnect.py bdist_rpm
cp dist/*.rpm $cur_dir
rm -fr $work_dir

# create fsurfer script rpms
cd $cur_dir
work_dir=`mktemp -d`
echo "Scratch dir: $work_dir"
cp -a * $work_dir
cp -a ../bash $work_dir
echo "Generating package"
cd $work_dir
rm MANIFEST
mv fsurf-osgconnect fsurf
sed -i'' "s/PKG_VERSION/$VERSION/" setup_fsurfer_backend.py
sed -i'' "s/PKG_VERSION/$VERSION/" fsurfer/__init__.py
python setup_fsurfer_backend.py bdist_rpm
cp dist/*.rpm $cur_dir
rm -fr $work_dir

redpajama_set_name: RedPajamaGithub


text:
/**
 * Is the given variable an array-like object?
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.2.1
 * @version  0.2.1
 *
 * @param    {Mixed}   variable
 *
 * @return   {Boolean}
 */
Blast.defineStatic('Array', function likeArray(variable) {

	// Return the variable unmodified if it's already an array
	if (Array.isArray(variable)) {
		return true;
	}

	// Convert array-like objects to regular arrays
	if (variable && typeof variable == 'object') {

		// If the variable has a 'length' property, it could be array-like
		if (typeof variable.length == 'number') {
			return true;
		}
	}

	return false;
});

/**
 * Cast a variable to an array.
 * Also turns array-like objects into real arrays, except String objects.
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  0.1.10
 *
 * @param    {Mixed}   variable
 *
 * @return   {Array}
 */
Blast.defineStatic('Array', function cast(variable) {

	var type;

	// Return the variable unmodified if it's already an array
	if (Array.isArray(variable)) {
		return variable;
	}

	type = typeof variable;

	// Convert array-like objects to regular arrays
	if (variable && type == 'object') {

		// If the variable has a 'length' property, it could be array-like
		if (typeof variable.length == 'number') {

			// Skip it if it's a String object (not a string primitive)
			// or an HTML element (SELECTs also have a length)
			if (variable.constructor.name !== 'String' && variable.nodeType == null) {
				return Array.prototype.slice.call(variable, 0);
			}
		}
	} else if (type == 'undefined') {
		return [];
	}

	// Return the variable wrapped in an array otherwise
	return [variable];
});

/**
 * Create an array containing arithmetic progressions,
 * an implementation of Python's range function
 *
 * @author   Tomasz Jaskowski <http://www.jaskowski.info/>
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.1.2
 * @version  0.1.2
 *
 * @param    {Number}   start   The first value, defaults to 0
 * @param    {Number}   stop    The last value, is required
 * @param    {Number}   step    The step value, defaults to 1
 *
 * @return   {Array}
 */
Blast.defineStatic('Array', function range(start, stop, step) {

	var result = [],
	    i;

	// If only 1 argument is given, interpret it as the stop parameter
	if (typeof stop == 'undefined') {
		stop = start;
		start = 0;
	} else {

		// Make sure start is a valid number
		if (typeof start != 'number') {
			start = Number(start) || 0;
		}

		// Make sure stop is a valid number
		if (typeof stop != 'number') {
			stop = Number(stop);
		}
	}

	// If no valid step is given, just use a step of 1
	if (typeof step == 'undefined') {
		step = 1;
	} else if (typeof step != 'number') {
		step = Number(step) || 1;
	}

	if (!((step>0 && start>=stop) || (step<0 && start<=stop))) {
		for (i = start; step > 0 ? i < stop : i > stop; i += step) {
			result.push(i);
		}
	}

	return result;
});

/**
 * Fill all the elements of the array from a start index
 * to an end index with a static value
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.1.3
 * @version  0.1.3
 *
 * @param    {Mixed}   value    Value to fill an array with
 * @param    {Number}  start    Start index (0)
 * @param    {Number}  end      End index (this.length)
 */
Blast.definePrototype('Array', function fill(value, start, end) {

	var length = this.length,
	    rStart,
	    rEnd;

	if (typeof start === 'undefined') {
		rStart = 0;
	} else {
		rStart = ~~start || 0;
	}

	if (typeof end === 'undefined') {
		rEnd = length;
	} else {
		rEnd = ~~end || 0;
	}

	// Normalize the start index
	if (rStart < 0) {
		rStart = Math.max(length + rStart, 0);
	} else {
		rStart = rStart < length ? rStart : length;
	}

	// Normalize the end index
	if (rEnd < 0) {
		rEnd = Math.max(length + rEnd, 0);
	} else {
		rEnd = rEnd < length? rEnd : length;
	}

	// Do the actual filling
	for (; rStart < rEnd; rStart++) {
		this[rStart] = value;
	}

	return this;
}, true);

/**
 * Move an array element from one array position to another
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.1.4
 * @version  0.1.4
 *
 * @param    {Number}  oldIndex
 * @param    {Number}  newIndex
 */
Blast.definePrototype('Array', function move(oldIndex, newIndex) {

	var length = this.length,
	    k;

	if (typeof oldIndex == 'number') {
		while (oldIndex < 0) oldIndex += length;
	} else {
		oldIndex = this.indexOf(oldIndex);
	}

	if (typeof newIndex == 'number') {
		while (newIndex < 0) newIndex += length;
	} else {
		newIndex = this.indexOf(newIndex);
	}

	// Move nothing if certain elements were not found
	if (oldIndex == -1 || newIndex == -1) {
		return this;
	}

	if (newIndex >= length) {
		k = newIndex - length;
		while ((k--) + 1) {
			this.push(undefined);
		}
	}

	this.splice(newIndex, 0, this.splice(oldIndex, 1)[0]);

	return this;
});

/**
 * Get the first value of an array,
 * or the first nr of wanted values
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.1.0
 * @version  0.1.2
 *
 * @param    {Number}   nr   Return the first nr of values in a new array
 *
 * @return   {Mixed}
 */
Blast.definePrototype('Array', function first(nr, page) {

	if (typeof nr === 'number') {

		if (typeof page === 'number') {
			page = nr * page;
			nr = nr + page;
		} else {
			page = 0;
		}

		return this.slice(page, nr);
	}

	return this[0];
});

/**
 * Get the last value of an array
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.1.0
 * @version  0.1.2
 *
 * @param    {Number}   nr   Return the first nr of values in a new array
 *
 * @return   {Mixed}
 */
Blast.definePrototype('Array', function last(nr, page) {

	if (typeof nr === 'number') {

		nr = 0-nr;

		if (typeof page === 'number' && page) {
			page = nr * page;
			nr = nr + page;
		} else {
			page = undefined;
		}

		return this.slice(nr, page);
	}

	return this[this.length-1];
});

/**
 * Create the sum of all the values inside the array
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.1.3
 * @version  0.1.3
 *
 * @param    {String}     property   The property name to use of all the values
 * @param    {Function}   map        The map function to use
 *
 * @return   {Number|String}
 */
Blast.definePrototype('Array', function sum(property, map) {

	var sumResult,
	    propType,
	    mapType,
	    temp,
	    i;

	// If no map parameter is given, just sum everything as numbers
	if (!property && !map) {

		sumResult = this[0];

		for (i = 1; i < this.length; i++) {
			sumResult += this[i];
		}

		return sumResult;
	}

	// Get the parameter types
	propType = typeof property;

	if (propType == 'function') {
		propType = 'undefined';
		mapType = 'function';
		map = property;
	} else {
		mapType = typeof map;
	}

	// A property name has been given, we'll need to sum that property
	// of all the values
	if (propType == 'string') {

		if (mapType == 'function') {
			// When a map function is given, the property needs to use it
			sumResult = map(this[0][property]);

			for (i = 1; i < this.length; i++) {
				sumResult += map(this[i][property]);
			}
		} else {
			// No map function is given, just sum the property
			sumResult = this[0][property];

			for (i = 1; i < this.length; i++) {
				sumResult += this[i][property];
			}
		}

		return sumResult;
	}

	// Only a map function is given, we'll just map all the values
	if (mapType == 'function') {

		sumResult = map(this[0]);

		for (i = 1; i < this.length; i++) {
			sumResult += map(this[i]);
		}
	} else {
		throw new TypeError('Invalid arguments');
	}

	return sumResult;
});

/**
 * Clip the values inside the array.
 * Invalid values will be clipped to `lowest`
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.1.3
 * @version  0.3.0
 *
 * @param    {Number}   lowest    The lowest allowed value
 * @param    {Number}   highest   The highest allowed value
 *
 * @return   {Number}
 */
Blast.definePrototype('Array', function clip(lowest, highest) {

	var length = this.length,
	    i;

	// If no lowest is given, infinity is allowed
	if (lowest == null) {
		lowest = -Infinity;
	}

	// If no highest is given, infinity is allowed
	if (highest == null) {
		highest = +Infinity;
	}

	// Iterate over all the elements in the array
	for (i = 0; i < length; i++) {
		if (!(lowest < this[i])) {
			// Value is too low
			this[i] = lowest;
		} else if (!(highest > this[i])) {
			// Value is too high
			this[i] = highest;
		}
	}

	return this;
});

/**
 * Get the closest numeric value inside an array
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.1.2
 * @version  0.1.2
 *
 * @param    {Number}   goal   The goal we want to get the closest value to
 *
 * @return   {Number}
 */
Blast.definePrototype('Array', function closest(goal) {

	var closestVal = null,
	    i;

	for (i = 0; i < this.length; i++) {
		if (closestVal === null || Math.abs(this[i] - goal) < Math.abs(closestVal - goal)) {
			closestVal = this[i];
		}
	}

	return closestVal;
});

/**
 * Get the highest value inside the array
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.1.2
 * @version  0.4.1
 *
 * @param    {String}   path
 *
 * @return   {Number}
 */
Blast.definePrototype('Array', function max(path) {

	if (path) {
		return Bound.Array.sortByPath(this.slice(0), -1, path)[0];
	}

	return Math.max.apply(Math, this);
});

/**
 * Get the lowest value inside the array
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.1.2
 * @version  0.4.1
 *
 * @param    {String}   path
 *
 * @return   {Number}
 */
Blast.definePrototype('Array', function min(path) {

	if (path) {
		return Bound.Array.sortByPath(this.slice(0), 1, path)[0];
	}

	return Math.min.apply(Math, this);
});

/**
 * Insert item at the given index,
 * modifies the array in-place
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.1.2
 * @version  0.1.2
 *
 * @param    {Number}   index   Where to insert the values
 * @param    {Mixed}    value
 *
 * @return   {Array}    The same array
 */
Blast.definePrototype('Array', function insert(index, value) {

	var args,
	    i;

	// Make sure the array is at least as long up to the wanted index
	if (this.length < (index-1)) {
		this.length = index-1;
	}

	// Keep function optimized by not leaking the `arguments` object
	args = new Array(arguments.length-1);
	for (i = 0; i < args.length; i++) args[i] = arguments[i+1];

	this.splice.apply(this, [index, 0].concat(args));

	return this;
});

/**
 * Include an array (or multiple arrays) at the given index.
 * Impure function.
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.1.4
 * @version  0.1.11
 *
 * @param    {Number}   index   Where to insert the contents of the array
 * @param    {Array}    values  The array of values
 *
 * @return   {Array}
 */
Blast.definePrototype('Array', function include(_index, values) {

	var allValues,
	    index,
	    i;

	if (arguments.length == 1 || _index == null || typeof _index != 'number') {
		index = this.length;
		i = 1;
	} else {
		index = _index;
		i = 2;
	}

	if (this.length < index-1) {
		this.length = index;
	}

	// Start with all the values of the first array
	if (Array.isArray(arguments[i-1])) {
		allValues = arguments[i-1].slice();
	} else {
		allValues = [arguments[i-1]];
	}

	// Now add all the other arrays
	for (; i < arguments.length; i++) {
		allValues = allValues.concat(arguments[i]);
	}

	// And finally: splice them in
	this.splice.apply(this, [index, 0].concat(allValues));

	return this;
});

/**
 * Flatten the array by returning a single-dimensional copy.
 * Pure function.
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.1.4
 * @version  0.1.4
 *
 * @param    {Number}   limit   Recursive limit
 *
 * @return   {Array}
 */
Blast.definePrototype('Array', function flatten(limit) {

	var result,
	    temp,
	    i;

	if (typeof limit !== 'number') {
		limit = Infinity;
	}

	result = [];

	for (i = 0; i < this.length; i++) {

		if (Array.isArray(this[i]) && limit && limit > 0) {

			// Clone the array
			temp = this[i].slice();

			// Add the array
			Collection.Array.prototype.include.call(result, result.length, flatten.call(temp, limit-1));
		} else {
			result.push(this[i]);
		}
	}

	return result;
});

/**
 * Get all the unique values and return them as a new array.
 * Object contents will NOT be take into account.
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.1.2
 * @version  0.6.4
 *
 * @param    {String}   path   Path to use to check for uniqueness
 * @param    {Function} cast   Function used to cast values
 *
 * @return   {Array}    A new array with only unique values
 */
Blast.definePrototype('Array', function unique(path, cast) {

	var result = [],
	    check = [],
	    entry,
	    i;

	if (typeof path == 'function') {
		cast = path;
		path = null;
	}

	// Create an array to check cast values
	check = [];

	for (i = 0; i < this.length; i++) {

		if (path == null) {
			entry = this[i];
		} else {
			entry = Obj.path(this[i], path);
		}

		if (cast) {
			entry = cast(entry);
		}

		if (check.indexOf(entry) === -1) {
			result.push(this[i]);
			check.push(entry);
		}
	}

	return result;
});

/**
 * Get the shared value between the 2 arrays
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  0.1.4
 *
 * @param    {Array}     arr            The array to test against
 * @param    {Function}  cast_function  Function to use to cast values
 *
 * @return   {Array}
 */
Blast.definePrototype('Array', function shared(arr, cast_function) {

	// Make sure the given value to match against is an array
	arr = Collection.Array.cast(arr);

	// Go over every item in the array, and return the ones they have in common
	return this.filter(function(value) {

		var test, i;

		// Cast the value if a cast function is given
		value = cast_function ? cast_function(value) : value;

		// Go over every item in the second array
		for (i = 0; i < arr.length; i++) {

			// Also cast that value
			test = cast_function ? cast_function(arr[i]) : arr[i];

			// If the values match, add this value to the array
			if (value == test) {
				return true;
			}
		}

		return false;
	});
});

/**
 * Get the values from the first array that are not in the second array,
 * basically: remove all the values in the second array from the first one
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Array}     arr            The array to test agains
 * @param    {Function}  cast_function  Function to use to cast values
 *
 * @return   {Array}
 */
Blast.definePrototype('Array', function subtract(arr, cast_function) {

	// Make sure the given value to match against is an array
	if (!Array.isArray(arr)) {
		arr = [arr];
	}

	// Go over every item in the array,
	// and return the ones that are not in the second array
	return this.filter(function(value, index) {

		var test, i;

		// Cast the value if a cast function is given
		value = cast_function ? cast_function(value) : value;

		// Go over every item in the second array
		for (i = 0; i < arr.length; i++) {

			// Also cast that value
			test = cast_function ? cast_function(arr[i]) : arr[i];

			// If the values match, we should NOT add this
			if (value == test) {
				return false;
			}
		}

		return true;
	});
});

/**
 * Get all the values that are either in the first or in the second array,
 * but not in both
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  0.1.10
 *
 * @param    {Array}     arr            The array to test against
 * @param    {Function}  cast_function  Function to use to cast values
 *
 * @return   {Array}
 */
Blast.definePrototype('Array', function exclusive(arr, cast_function) {

	// Get all the shared values
	var shared = Collection.Array.prototype.shared.call(this, arr);

	// Return the merged differences between the 2
	return Collection.Array.prototype.subtract.call(this, shared).concat(Collection.Array.prototype.subtract.call(arr, shared));
});

/**
 * Remove certain elements from an array
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.0.1
 * @version  0.1.0
 *
 * @param    {Mixed}   delete_value   The value to remove from the array
 */
Blast.definePrototype('Array', function clean(delete_value) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] === delete_value) {
			this.splice(i, 1);
			i--;
		}
	}
	return this;
});

// Sort type symbols
Blast.arrayPath = Symbol('array_path');

/**
 * Sort by given paths.
 * Modifies the array in-place.
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.1.5
 * @version  0.6.3
 *
 * @param    {Symbol}   _flag    Use certain sort flag?
 * @param    {Number}   _order   Sort order: 1 for ascending, -1 for descending
 * @param    {String}   _paths   One path, an array of paths, of multiple arguments
 *
 * @return   {Array}
 */
Blast.definePrototype('Array', function sortByPath(_flag, _order, _paths) {

	var paths,
	    path,
	    flag,
	    len,
	    i = 0;

	paths = [];

	if (typeof _flag == 'symbol') {
		flag = _flag;
		i = 1;
	}

	for (; i < arguments.length; i++) {
		if (Array.isArray(arguments[i])) {
			paths = paths.concat(arguments[i]);
		} else {
			paths.push(arguments[i]);
		}
	}

	len = paths.length;

	this.sort(function doSort(a, b) {

		var alpha,
		    beta,
		    ord;

		ord = -1;

		for (i = 0; i < len; i++) {
			path = paths[i];

			// Allow changing of direction
			if (typeof path == 'number') {
				ord = path;
				continue;
			}

			if (flag) {
				alpha = Obj.path(flag, a, path);
				beta = Obj.path(flag, b, path);

				if (Array.isArray(alpha)) {
					alpha = alpha[alpha.length - 1];
				}

				if (Array.isArray(beta)) {
					beta = beta[beta.length - 1];
				}

			} else {
				alpha = Obj.path(a, path);
				beta = Obj.path(b, path);
			}

			if (alpha < beta) {
				return 0 - ord;
			} else if (alpha > beta) {
				return ord;
			} else if (alpha === beta) {
				// Ignore
			} else {
				if (alpha == null) {
					return 0 - ord;
				} else if (beta == null) {
					return ord;
				}
			}
		}

		return 0;
	});

	return this;
});

/**
 * Search the array
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.3.8
 * @version  0.6.0
 *
 * @param    {String}   path
 * @param    {Mixed}    value
 *
 * @return   {Mixed}
 */
Blast.definePrototype('Array', function findByPath(path, value) {

	var entries,
	    results,
	    length,
	    entry,
	    key,
	    i;

	length = this.length;

	if (path && typeof path == 'object') {

		// Do all keys in the path
		for (key in path) {
			entries = [];

			// Iterate over all entries
			for (i = 0; i < length; i++) {
				entry = Obj.path(this[i], key);

				// If it matches, add it to the entries array
				if (entry == path[key]) {
					entries.push(this[i]);
				}
			}

			// If nothing was found, return early
			if (!entries.length) {
				return;
			}

			if (results) {
				results = Bound.Array.shared(results, entries);
			} else {
				results = entries;
			}

			// If the results still is empty we can return already
			if (!results.length) {
				return;
			}
		}

		if (!results || !results.length) {
			return;
		} else {
			return results[0];
		}
	}

	for (i = 0; i < length; i++) {
		entry = Obj.path(this[i], path);

		if (entry == value) {
			return this[i];
		}
	}
});

/**
 * Modify the path in place
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.4.1
 * @version  0.4.1
 *
 * @param    {Number}   path   The path to modify
 * @param    {String}   fnc    The modifier function
 *
 * @return   {Array}
 */
Blast.definePrototype('Array', function modifyByPath(path, fnc) {

	var pieces,
	    entry,
	    end,
	    val,
	    i;

	pieces = Obj.parseDotNotationPath(path);

	if (!pieces) {
		return;
	}

	end = pieces.pop();

	for (i = 0; i < this.length; i++) {
		// Get the object that contains the entry
		entry = Obj.path(this[i], pieces);

		// Skip undefined values
		if (!entry || entry[end] == null) {
			continue;
		}

		val = fnc.call(entry, entry[end], i);

		if (val !== undefined) {
			entry[end] = val;
		}
	}

	return this;
});

/**
 * Shuffle the array
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.3.7
 * @version  0.3.7
 *
 * @param    {Object}   rng   An object that has a `random` method
 *
 * @return   {Array}
 */
Blast.definePrototype('Array', function shuffle(rng) {

	var counter = this.length,
	    index,
	    temp;

	if (rng == null) {
		rng = Math;
	}

	// While there are elements in the array
	while (counter > 0) {

		// Pick a random index
		index = Math.floor(rng.random() * counter);

		// Decrease counter by 1
		counter--;

		// And swap the last element with it
		temp = this[counter];
		this[counter] = this[index];
		this[index] = temp;
	}

	return this;
});

/**
 * Get all elements after the given needle
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.5.5
 * @version  0.5.5
 *
 * @param    {Mixed}   needle
 *
 * @return   {Array}
 */
Blast.definePrototype('Array', function after(needle) {

	var index = this.indexOf(needle);

	if (index == -1) {
		return [];
	}

	return this.slice(index + 1);
});


text:
static NSString *const RefBranchReferenceNamePrefix = @"refs/heads/";
static NSString *const RefTagReferenceNamePrefix = @"refs/tags/";

@implementation OCTRef (Additions)

NSString *DefaultReferenceName() {
    return [RefBranchReferenceNamePrefix stringByAppendingString:@"master"];
}

NSString *ReferenceNameWithBranchName(NSString *branchName) {
    NSCParameterAssert(branchName.length > 0);
    return [NSString stringWithFormat:@"%@%@", RefBranchReferenceNamePrefix, branchName];
}

NSString *ReferenceNameWithTagName(NSString *tagName) {
    NSCParameterAssert(tagName.length > 0);
    return [NSString stringWithFormat:@"%@%@", RefTagReferenceNamePrefix, tagName];
}

@end


text:
id: version-1.7.0-simple
title: Simple Queries
sidebar_label: Simple Queries
original_id: simple
---

To support the extraction of values from a JSON structure, a location path syntax is defined. In common with XPath, this will select all possible values in the document that match the specified location path.  The two structural constructs of JSON are objects and arrays.

## Navigating JSON Objects

A JSON object is an associative array (a.k.a map or hash). The location path syntax to navigate into an arbitrarily deeply nested structure of JSON objects comprises the field names separated by dot '.' delimiters. The expression returns the JSON value referenced after navigating to the last step in the location path.  If during the navigation of the location path, a field is not found, then the expression returns nothing (represented by Javascript _undefined_).  No errors are thrown as a result of non-existing data in the input document.

The following sample JSON document is used by examples throughout this guide, unless otherwise indicated:

```json
{
  "FirstName": "Fred",
  "Surname": "Smith",
  "Age": 28,
  "Address": {
    "Street": "Hursley Park",
    "City": "Winchester",
    "Postcode": "SO21 2JN"
  },
  "Phone": [
    {
      "type": "home",
      "number": "0203 544 1234"
    },
    {
      "type": "office",
      "number": "01962 001234"
    },
    {
      "type": "office",
      "number": "01962 001235"
    },
    {
      "type": "mobile",
      "number": "077 7700 1234"
    }
  ],
  "Email": [
    {
      "type": "work",
      "address": ["fred.smith@my-work.com", "fsmith@my-work.com"]
    },
    {
      "type": "home",
      "address": ["freddy@my-social.com", "frederic.smith@very-serious.com"]
    }
  ],
  "Other": {
    "Over 18 ?": true,
    "Misc": null,
    "Alternative.Address": {
      "Street": "Brick Lane",
      "City": "London",
      "Postcode": "E1 6RF"
    }
  }
}
```

#### Examples

Here are some example expressions and their results when applied to the above JSON document:

- Returns a JSON string ("double quoted")

Surname

"Smith"

- Returns a JSON number

Age

28

- Field references are separated by '.'

Address.City

"Winchester"

- Matched the path and returns the null value

Other.Misc

null

- Path not found.  Returns nothing (i.e. Javascript _undefined_)

Other.Nothing

- Field references containing whitespace or reserved tokens can be enclosed in backticks

Other.`Over 18 ?`

true

## Navigating JSON Arrays

JSON arrays are used when an ordered collection of values is required.  Each value in the array is associated with an index (position) rather than a name, so in order to address individual values in an array, extra syntax is required to specify the index.  This is done using square brackets after the field name of the array.  If the square brackets contains a number, or an expression that evaluates to a number, then the number represents the index of the value to select.  Indexes are zero offset, i.e. the first value in an array `arr` is `arr[0]`.  If the number is not an integer, then it is rounded _down_ to an integer.  If the expression in square brackets is non-numeric, or is an expression that doesn't evaluate to a number, then it is treated as a [predicate](predicate#predicates).

Negative indexes count from the end of the array, for example, `arr[-1]` will select the last value, `arr[-2]` the second to last, etc. If an index is specified that exceeds the size of the array, then nothing is selected.

If no index is specified for an array (i.e. no square brackets after the field reference), then the whole array is selected. If the array contains objects, and the location path selects fields within these objects, then each object within the array will be queried for selection.

#### Examples

- Returns the first item (an object)

Phone[0]

{ "type": "home", "number": "0203 544 1234" }

- Returns the second item

Phone[1]

{ "type": "office", "number": "01962 001234" }

- Returns the last item

Phone[-1]

{ "type": "mobile", "number": "077 7700 1234" }

- Negative indexed count from the end

Phone[-2]

{ "type": "office", "number": "01962 001235" }

- Doesn't exist - returns nothing

Phone[8]

- Selects the `number` field in the first item

Phone[0].number

"0203 544 1234"

- No index is given to `Phone` so it selects all of them (the whole array), then it selects all the `number` fields for each of them

Phone.number

[ "0203 544 1234", "01962 001234", "01962 001235", "077 7700 1234" ]

- Might expect it to just return the first number, but it returns the first number of each of the items selected by `Phone`

Phone.number[0]

[ "0203 544 1234", "01962 001234", "01962 001235", "077 7700 1234" ]

- Applies the index to the array returned by `Phone.number`. One use of [parentheses](composition.md#parenthesized-expressions-and-blocks).

(Phone.number)[0]

"0203 544 1234"

- Returns a range of items by creating an array of indexes

Phone[[0..1]]

[
  { "type": "home", "number": "0203 544 1234" },
  { "type": "office", "number": "01962 001234" }
]

## Result sequences

## Sequence flattening

## Empty sequences and singleton sequences

### Top level arrays, nested arrays and array flattening

Consider the JSON document:

    [
      { "ref": [ 1,2 ] },
      { "ref": [ 3,4 ] }
    ]

At the top level, we have an array rather than an object.  If we want to select the first object in this top level array, we don't have a field name to append the `[0]` to.  We can't use `[0]` on its own because that clashes with the [array constructor](construction.md#array-constructors) syntax.  However, we can use the _context_ reference `$` to refer to the start of the document as follows:

- `$` at the start of an expression refers to the entire input document

$[0]

{ "ref": [ 1,2 ] }

- `.ref` here returns the entire internal array

$[0].ref

[ 1,2 ]

- returns element on first position of the internal array

$[0].ref[0]

1

- Despite the structure of the nested array, the resultant selection is flattened into a single flat array.  The original nested structure of the input arrays is lost. See [Array constructors](construction.md#array-constructors) for how to maintain the original structure in the results.

$.ref

[ 1, 2, 3, 4 ]


text:
.formError {
	display: none;
}

#user-signup-page form.form-stacked div.clearfix{
	padding-bottom: 5px;
	padding-top: 5px;
}


text:
namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DETAIL

namespace detail
{

#ifndef BOOST_GEOMETRY_ROBUST_TYPE_USE_MULTIPRECISION

typedef boost::long_long_type robust_signed_integral_type;

#else

typedef boost::multiprecision::number
    <
        boost::multiprecision::cpp_int_backend
            <
                64, 256,
                boost::multiprecision::signed_magnitude,
                boost::multiprecision::unchecked,
                void
            >
    > robust_signed_integral_type;

#endif

}

namespace detail_dispatch
{

template <typename CoordinateType, typename IsFloatingPoint>
struct robust_type
{
};

template <typename CoordinateType>
struct robust_type<CoordinateType, boost::false_type>
{
    typedef CoordinateType type;
};

template <typename CoordinateType>
struct robust_type<CoordinateType, boost::true_type>
{
    typedef geometry::detail::robust_signed_integral_type type;
};

} // namespace detail_dispatch

namespace detail
{

template <typename CoordinateType>
struct robust_type
{
    typedef typename detail_dispatch::robust_type
        <
            CoordinateType,
            typename boost::is_floating_point<CoordinateType>::type
        >::type type;
};

} // namespace detail
#endif // DOXYGEN_NO_DETAIL

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_POLICIES_ROBUSTNESS_ROBUST_TYPE_HPP


text:
using System.Collections.Generic;
using FizzWare.NBuilder.Tests.TestClasses;
using NSubstitute;

using Shouldly;
using Xunit;

namespace FizzWare.NBuilder.Tests.Unit
{

    public class PersistenceServiceTests
    {
        public PersistenceServiceTests()
        {
            repository = Substitute.For<IMyClassRepository>();
            repository2 = Substitute.For<IMyClassRepository>();
        }

        private IMyClassRepository repository;
        private IMyClassRepository repository2;

        [Fact]
        public void ShouldBeAbleToPersistAList_Create()
        {
            IList<MyClass> list = new List<MyClass>();

            var persistenceService = new PersistenceService();
            persistenceService.SetPersistenceCreateMethod<IList<MyClass>>(x => repository.SaveAll(x));

            {
                repository.SaveAll(list);
            }

            {
                persistenceService.Create(list);
            }
        }

        [Fact]
        public void ShouldBeAbleToPersistAList_Update()
        {
            IList<MyClass> list = new List<MyClass>();

            var persistenceService = new PersistenceService();
            persistenceService.SetPersistenceUpdateMethod<IList<MyClass>>(x => repository.SaveAll(x));
            repository.SaveAll(list);
            persistenceService.Update(list);
        }

        [Fact]
        public void ShouldBeAbleToPersistAnObject_Create()
        {
            var obj = new MyClass();

            var persistenceService = new PersistenceService();
            persistenceService.SetPersistenceCreateMethod<MyClass>(x => repository.Save(x));

            {
                repository.Save(obj);
            }

            {
                persistenceService.Create(obj);
            }
        }

        [Fact]
        public void ShouldBeAbleToPersistAnObject_Update()
        {
            var obj = new MyClass();

            var persistenceService = new PersistenceService();
            persistenceService.SetPersistenceUpdateMethod<MyClass>(x => repository.Save(x));

            {
                repository.Save(obj);
            }

            {
                persistenceService.Update(obj);
            }
        }

        [Fact]
        public void ShouldComplainIfNoCreatePersistenceServiceFound()
        {

            {
                var persistenceService = new PersistenceService();

                Should.Throw<PersistenceMethodNotFoundException>(() => { persistenceService.Create(new MyClass()); });
            }
        }

        [Fact]
        public void ShouldComplainIfNoCreatePersistenceServiceFoundForList()
        {

            {
                var persistenceService = new PersistenceService();
                Should.Throw<PersistenceMethodNotFoundException>(
                    () => { persistenceService.Create((IList<MyClass>) new List<MyClass>()); });
            }
        }

        [Fact]
        public void ShouldComplainIfNoUpdatePersistenceServiceFound()
        {

            {
                var persistenceService = new PersistenceService();
                Should.Throw<PersistenceMethodNotFoundException>(() => { persistenceService.Update(new MyClass()); });
            }
        }

        [Fact]
        public void ShouldComplainIfNoUpdatePersistenceServiceFoundForList()
        {

            {
                var persistenceService = new PersistenceService();
                Should.Throw<PersistenceMethodNotFoundException>(
                    () => { persistenceService.Update((IList<MyClass>) new List<MyClass>()); });
            }
        }

        [Fact]
        public void ShouldReplaceExistingCreatePersister()
        {
            var obj = new MyClass();

            var persistenceService = new PersistenceService();
            persistenceService.SetPersistenceCreateMethod<MyClass>(x => repository.Save(x));
            persistenceService.SetPersistenceCreateMethod<MyClass>(x => repository2.Save(x));
            repository2.Save(obj);
            persistenceService.Create(obj);
        }

        [Fact]
        public void ShouldReplaceExistingUpdatePersister()
        {
            var obj = new MyClass();

            var persistenceService = new PersistenceService();
            persistenceService.SetPersistenceUpdateMethod<MyClass>(x => repository.Save(x));
            persistenceService.SetPersistenceUpdateMethod<MyClass>(x => repository2.Save(x));
            repository2.Save(obj);
            persistenceService.Update(obj);
        }
    }
}


text:
Select Order file

  <input type="file" nv-file-select="" uploader="uploader"/>

      Name
      Size
      Progress
      Actions

      {{ item.file.name }}
      {{ item.file.size/1024/1024|number:2 }} MB

        <button type="button" ng-click="item.upload()" ng-disabled="item.isReady || item.isUploading || item.isSuccess" class="btn btn-success btn-xs"> Upload</button>
        <button type="button" ng-click="item.remove()" class="btn btn-danger btn-xs"> Remove</button>

  <svg ng-if="uploader.progress === 100 && !json" width="65px" height="65px" viewBox="0 0 66 66" xmlns="http://www.w3.org/2000/svg" class="spinner">
    <circle fill="none" stroke-width="6" stroke-linecap="round" cx="33" cy="33" r="30" class="path"></circle>
  </svg>

    <button ng-if="json" ng-csv="json" filename="TNT_Express_AllTrackingInfo_{{date}}.csv" csv-header="['Consignment', 'Status', 'Date', 'Time', 'Depot']" class="btn btn-lg btn-success col-xs-4">Generate Excel</button>


text:
package org.properssl.sslcertx.mariadb.jdbc.internal.mysql.packet.commands;

import java.io.IOException;
import java.io.OutputStream;

import org.properssl.sslcertx.mariadb.jdbc.internal.common.packet.CommandPacket;
import org.properssl.sslcertx.mariadb.jdbc.internal.common.packet.PacketOutputStream;

public class MySQLPingPacket implements CommandPacket {
    public MySQLPingPacket() {
    }
    public int send(final OutputStream os) throws IOException {
        PacketOutputStream pos=(PacketOutputStream)os;
        pos.startPacket(0);
        pos.write(0x0e);
        pos.finishPacket();
        return 0;
    }
}


text:
#ifndef __ASM_AU1000_PCMCIA_H
#define __ASM_AU1000_PCMCIA_H

#define AU1000_PCMCIA_POLL_PERIOD    (2*HZ)
#define AU1000_PCMCIA_IO_SPEED       (255)
#define AU1000_PCMCIA_MEM_SPEED      (300)

#define AU1X_SOCK0_IO        0xF00000000
#define AU1X_SOCK0_PHYS_ATTR 0xF40000000
#define AU1X_SOCK0_PHYS_MEM  0xF80000000

/* pcmcia socket 1 needs external glue logic so the memory map
 * differs from board to board. the general rule is that
 * static bus address bit 26 should be used to decode socket 0
 * from socket 1. alas, some boards dont follow this...
 * These really belong in a board-specific header file...
 */
#ifdef CONFIG_MIPS_PB1000
#define SOCK1_DECODE (1<<27)
#endif
#ifdef CONFIG_MIPS_DB1000
#define SOCK1_DECODE (1<<26)
#endif
#ifdef CONFIG_MIPS_DB1500
#define SOCK1_DECODE (1<<26)
#endif
#ifdef CONFIG_MIPS_DB1100
#define SOCK1_DECODE (1<<26)
#endif
#ifdef CONFIG_MIPS_DB1550
#define SOCK1_DECODE (1<<26)
#endif
#ifdef CONFIG_MIPS_DB1200
#define SOCK1_DECODE (1<<26)
#endif
#ifdef CONFIG_MIPS_PB1550
#define SOCK1_DECODE (1<<26)
#endif
#ifdef CONFIG_MIPS_PB1200
#define SOCK1_DECODE (1<<26)
#endif

/* The board has a second PCMCIA socket */
#ifdef SOCK1_DECODE
#define AU1X_SOCK1_IO        (0xF00000000|SOCK1_DECODE)
#define AU1X_SOCK1_PHYS_ATTR (0xF40000000|SOCK1_DECODE)
#define AU1X_SOCK1_PHYS_MEM  (0xF80000000|SOCK1_DECODE)
#endif

struct pcmcia_state {
  unsigned detect: 1,
            ready: 1,
           wrprot: 1,
	     bvd1: 1,
	     bvd2: 1,
            vs_3v: 1,
            vs_Xv: 1;
};

struct pcmcia_configure {
  unsigned sock: 8,
            vcc: 8,
            vpp: 8,
         output: 1,
        speaker: 1,
          reset: 1;
};

struct pcmcia_irq_info {
	unsigned int sock;
	unsigned int irq;
};

struct au1000_pcmcia_socket {
	socket_state_t        cs_state;
	struct pcmcia_state   k_state;
	unsigned int          irq;
	void                  (*handler)(void *, unsigned int);
	void                  *handler_info;
	pccard_io_map         io_map[MAX_IO_WIN];
	pccard_mem_map        mem_map[MAX_WIN];
	u32                   virt_io;
	ioaddr_t              phys_attr, phys_mem;
	unsigned short        speed_io, speed_attr, speed_mem;
};

struct pcmcia_init {
	void (*handler)(int irq, void *dev, struct pt_regs *regs);
};

struct pcmcia_low_level {
	int (*init)(struct pcmcia_init *);
	int (*shutdown)(void);
	int (*socket_state)(unsigned sock, struct pcmcia_state *);
	int (*get_irq_info)(struct pcmcia_irq_info *);
	int (*configure_socket)(const struct pcmcia_configure *);
};

extern struct pcmcia_low_level au1x00_pcmcia_ops;
#endif /* __ASM_AU1000_PCMCIA_H */


text:
package com.microsoft.azure.management.appservice.v2016_08_01.implementation;

import com.microsoft.azure.management.appservice.v2016_08_01.SiteCloneability;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import java.util.List;
import com.microsoft.azure.management.appservice.v2016_08_01.SiteCloneabilityCriterion;
import com.microsoft.azure.management.appservice.v2016_08_01.CloneAbilityResult;

class SiteCloneabilityImpl extends WrapperImpl<SiteCloneabilityInner> implements SiteCloneability {
    private final AppServiceManager manager;
    SiteCloneabilityImpl(SiteCloneabilityInner inner, AppServiceManager manager) {
        super(inner);
        this.manager = manager;
    }

    @Override
    public AppServiceManager manager() {
        return this.manager;
    }

    @Override
    public List<SiteCloneabilityCriterion> blockingCharacteristics() {
        return this.inner().blockingCharacteristics();
    }

    @Override
    public List<SiteCloneabilityCriterion> blockingFeatures() {
        return this.inner().blockingFeatures();
    }

    @Override
    public CloneAbilityResult result() {
        return this.inner().result();
    }

    @Override
    public List<SiteCloneabilityCriterion> unsupportedFeatures() {
        return this.inner().unsupportedFeatures();
    }

}


text:
'use strict'

// Each method operate on either a presentaion (P) or a stream (S)
//
// Check RFC 2326 section 10 for details:
// https://tools.ietf.org/html/rfc2326#page-29

module.exports = [ // RFC implementation guide:
  'ANNOUNCE',      // optional (P,S)
  'GET_PARAMETER', // optional (P,S)
  'OPTIONS',       // optional (P,S)
  'REDIRECT',      // optional (P,S)
  'SET_PARAMETER'  // optional (P,S)
]


text:
package org.apache.druid.query.groupby.epinephelinae.vector;

import com.google.common.base.Suppliers;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.guava.BaseSequence;
import org.apache.druid.java.util.common.guava.Sequence;
import org.apache.druid.java.util.common.parsers.CloseableIterator;
import org.apache.druid.query.QueryConfig;
import org.apache.druid.query.aggregation.AggregatorAdapters;
import org.apache.druid.query.dimension.DimensionSpec;
import org.apache.druid.query.filter.Filter;
import org.apache.druid.query.groupby.GroupByQuery;
import org.apache.druid.query.groupby.GroupByQueryConfig;
import org.apache.druid.query.groupby.ResultRow;
import org.apache.druid.query.groupby.epinephelinae.AggregateResult;
import org.apache.druid.query.groupby.epinephelinae.BufferArrayGrouper;
import org.apache.druid.query.groupby.epinephelinae.CloseableGrouperIterator;
import org.apache.druid.query.groupby.epinephelinae.GroupByQueryEngineV2;
import org.apache.druid.query.groupby.epinephelinae.HashVectorGrouper;
import org.apache.druid.query.groupby.epinephelinae.VectorGrouper;
import org.apache.druid.query.vector.VectorCursorGranularizer;
import org.apache.druid.segment.DimensionHandlerUtils;
import org.apache.druid.segment.StorageAdapter;
import org.apache.druid.segment.filter.Filters;
import org.apache.druid.segment.vector.VectorColumnSelectorFactory;
import org.apache.druid.segment.vector.VectorCursor;
import org.joda.time.DateTime;
import org.joda.time.Interval;

import javax.annotation.Nullable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;

public class VectorGroupByEngine
{
  private VectorGroupByEngine()
  {
    // No instantiation.
  }

  public static boolean canVectorize(
      final GroupByQuery query,
      final StorageAdapter adapter,
      @Nullable final Filter filter
  )
  {
    // Multi-value dimensions are not yet supported.
    //
    // Two notes here about how we're handling this check:
    //   1) After multi-value dimensions are supported, we could alter "GroupByQueryEngineV2.isAllSingleValueDims"
    //      to accept a ColumnSelectorFactory, which makes more sense than using a StorageAdapter (see #8013).
    //   2) Technically using StorageAdapter here is bad since it only looks at real columns, but they might
    //      be shadowed by virtual columns (again, see #8013). But it's fine for now since adapter.canVectorize
    //      always returns false if there are any virtual columns.
    //
    // This situation should sort itself out pretty well once this engine supports multi-valued columns. Then we
    // won't have to worry about having this all-single-value-dims check here.

    return GroupByQueryEngineV2.isAllSingleValueDims(adapter::getColumnCapabilities, query.getDimensions(), true)
           && query.getDimensions().stream().allMatch(DimensionSpec::canVectorize)
           && query.getAggregatorSpecs().stream().allMatch(aggregatorFactory -> aggregatorFactory.canVectorize(adapter))
           && adapter.canVectorize(filter, query.getVirtualColumns(), false);
  }

  public static Sequence<ResultRow> process(
      final GroupByQuery query,
      final StorageAdapter storageAdapter,
      final ByteBuffer processingBuffer,
      @Nullable final DateTime fudgeTimestamp,
      @Nullable final Filter filter,
      final Interval interval,
      final GroupByQueryConfig config,
      final QueryConfig queryConfig
  )
  {
    if (!canVectorize(query, storageAdapter, filter)) {
      throw new ISE("Cannot vectorize");
    }

    return new BaseSequence<>(
        new BaseSequence.IteratorMaker<ResultRow, CloseableIterator<ResultRow>>()
        {
          @Override
          public CloseableIterator<ResultRow> make()
          {
            final VectorCursor cursor = storageAdapter.makeVectorCursor(
                Filters.toFilter(query.getDimFilter()),
                interval,
                query.getVirtualColumns(),
                false,
                queryConfig.getVectorSize(),
                null
            );

            if (cursor == null) {
              // Return empty iterator.
              return new CloseableIterator<ResultRow>()
              {
                @Override
                public boolean hasNext()
                {
                  return false;
                }

                @Override
                public ResultRow next()
                {
                  throw new NoSuchElementException();
                }

                @Override
                public void close()
                {
                  // Nothing to do.
                }
              };
            }

            try {
              final VectorColumnSelectorFactory columnSelectorFactory = cursor.getColumnSelectorFactory();
              final List<GroupByVectorColumnSelector> dimensions = query.getDimensions().stream().map(
                  dimensionSpec ->
                      DimensionHandlerUtils.makeVectorProcessor(
                          dimensionSpec,
                          GroupByVectorColumnProcessorFactory.instance(),
                          columnSelectorFactory
                      )
              ).collect(Collectors.toList());

              return new VectorGroupByEngineIterator(
                  query,
                  config,
                  storageAdapter,
                  cursor,
                  interval,
                  dimensions,
                  processingBuffer,
                  fudgeTimestamp
              );
            }
            catch (Throwable e) {
              try {
                cursor.close();
              }
              catch (Throwable e2) {
                e.addSuppressed(e2);
              }
              throw e;
            }
          }

          @Override
          public void cleanup(CloseableIterator<ResultRow> iterFromMake)
          {
            try {
              iterFromMake.close();
            }
            catch (IOException e) {
              throw new RuntimeException(e);
            }
          }
        }
    );
  }

  private static class VectorGroupByEngineIterator implements CloseableIterator<ResultRow>
  {
    private final GroupByQuery query;
    private final GroupByQueryConfig querySpecificConfig;
    private final StorageAdapter storageAdapter;
    private final VectorCursor cursor;
    private final List<GroupByVectorColumnSelector> selectors;
    private final ByteBuffer processingBuffer;
    private final DateTime fudgeTimestamp;
    private final int keySize;
    private final WritableMemory keySpace;
    private final VectorGrouper vectorGrouper;

    @Nullable
    private final VectorCursorGranularizer granulizer;

    // Granularity-bucket iterator and current bucket.
    private final Iterator<Interval> bucketIterator;

    @Nullable
    private Interval bucketInterval;

    private int partiallyAggregatedRows = -1;

    @Nullable
    private CloseableGrouperIterator<Memory, ResultRow> delegate = null;

    VectorGroupByEngineIterator(
        final GroupByQuery query,
        final GroupByQueryConfig config,
        final StorageAdapter storageAdapter,
        final VectorCursor cursor,
        final Interval queryInterval,
        final List<GroupByVectorColumnSelector> selectors,
        final ByteBuffer processingBuffer,
        @Nullable final DateTime fudgeTimestamp
    )
    {
      this.query = query;
      this.querySpecificConfig = config;
      this.storageAdapter = storageAdapter;
      this.cursor = cursor;
      this.selectors = selectors;
      this.processingBuffer = processingBuffer;
      this.fudgeTimestamp = fudgeTimestamp;
      this.keySize = selectors.stream().mapToInt(GroupByVectorColumnSelector::getGroupingKeySize).sum();
      this.keySpace = WritableMemory.allocate(keySize * cursor.getMaxVectorSize());
      this.vectorGrouper = makeGrouper();
      this.granulizer = VectorCursorGranularizer.create(storageAdapter, cursor, query.getGranularity(), queryInterval);

      if (granulizer != null) {
        this.bucketIterator = granulizer.getBucketIterable().iterator();
      } else {
        this.bucketIterator = Collections.emptyIterator();
      }

      this.bucketInterval = this.bucketIterator.hasNext() ? this.bucketIterator.next() : null;
    }

    @Override
    public ResultRow next()
    {
      if (delegate == null || !delegate.hasNext()) {
        throw new NoSuchElementException();
      }

      return delegate.next();
    }

    @Override
    public boolean hasNext()
    {
      if (delegate != null && delegate.hasNext()) {
        return true;
      } else {
        final boolean moreToRead = !cursor.isDone() || partiallyAggregatedRows >= 0;

        if (bucketInterval != null && moreToRead) {
          while (delegate == null || !delegate.hasNext()) {
            if (delegate != null) {
              delegate.close();
              vectorGrouper.reset();
            }

            delegate = initNewDelegate();
          }
          return true;
        } else {
          return false;
        }
      }
    }

    @Override
    public void remove()
    {
      throw new UnsupportedOperationException();
    }

    @Override
    public void close()
    {
      cursor.close();

      if (delegate != null) {
        delegate.close();
      }
    }

    private VectorGrouper makeGrouper()
    {
      final VectorGrouper grouper;

      final int cardinalityForArrayAggregation = GroupByQueryEngineV2.getCardinalityForArrayAggregation(
          querySpecificConfig,
          query,
          storageAdapter,
          processingBuffer
      );

      if (cardinalityForArrayAggregation >= 0) {
        grouper = new BufferArrayGrouper(
            Suppliers.ofInstance(processingBuffer),
            AggregatorAdapters.factorizeVector(
                cursor.getColumnSelectorFactory(),
                query.getAggregatorSpecs()
            ),
            cardinalityForArrayAggregation
        );
      } else {
        grouper = new HashVectorGrouper(
            Suppliers.ofInstance(processingBuffer),
            keySize,
            AggregatorAdapters.factorizeVector(
                cursor.getColumnSelectorFactory(),
                query.getAggregatorSpecs()
            ),
            querySpecificConfig.getBufferGrouperMaxSize(),
            querySpecificConfig.getBufferGrouperMaxLoadFactor(),
            querySpecificConfig.getBufferGrouperInitialBuckets()
        );
      }

      grouper.initVectorized(cursor.getMaxVectorSize());

      return grouper;
    }

    private CloseableGrouperIterator<Memory, ResultRow> initNewDelegate()
    {
      // Method must not be called unless there's a current bucketInterval.
      assert bucketInterval != null;

      final DateTime timestamp = fudgeTimestamp != null
                                 ? fudgeTimestamp
                                 : query.getGranularity().toDateTime(bucketInterval.getStartMillis());

      while (!cursor.isDone()) {
        final int startOffset;

        if (partiallyAggregatedRows < 0) {
          granulizer.setCurrentOffsets(bucketInterval);
          startOffset = granulizer.getStartOffset();
        } else {
          startOffset = granulizer.getStartOffset() + partiallyAggregatedRows;
        }

        if (granulizer.getEndOffset() > startOffset) {
          // Write keys to the keySpace.
          int keyOffset = 0;
          for (final GroupByVectorColumnSelector selector : selectors) {
            selector.writeKeys(keySpace, keySize, keyOffset, startOffset, granulizer.getEndOffset());
            keyOffset += selector.getGroupingKeySize();
          }

          // Aggregate this vector.
          final AggregateResult result = vectorGrouper.aggregateVector(
              keySpace,
              startOffset,
              granulizer.getEndOffset()
          );

          if (result.isOk()) {
            partiallyAggregatedRows = -1;
          } else {
            if (partiallyAggregatedRows < 0) {
              partiallyAggregatedRows = result.getCount();
            } else {
              partiallyAggregatedRows += result.getCount();
            }
          }
        } else {
          partiallyAggregatedRows = -1;
        }

        if (partiallyAggregatedRows >= 0) {
          break;
        } else if (!granulizer.advanceCursorWithinBucket()) {
          // Advance bucketInterval.
          bucketInterval = bucketIterator.hasNext() ? bucketIterator.next() : null;
          break;
        }
      }

      final boolean resultRowHasTimestamp = query.getResultRowHasTimestamp();
      final int resultRowDimensionStart = query.getResultRowDimensionStart();
      final int resultRowAggregatorStart = query.getResultRowAggregatorStart();

      return new CloseableGrouperIterator<>(
          vectorGrouper.iterator(),
          entry -> {
            final ResultRow resultRow = ResultRow.create(query.getResultRowSizeWithoutPostAggregators());

            // Add timestamp, if necessary.
            if (resultRowHasTimestamp) {
              resultRow.set(0, timestamp.getMillis());
            }

            // Add dimensions.
            int keyOffset = 0;
            for (int i = 0; i < selectors.size(); i++) {
              final GroupByVectorColumnSelector selector = selectors.get(i);

              selector.writeKeyToResultRow(
                  entry.getKey(),
                  keyOffset,
                  resultRow,
                  resultRowDimensionStart + i
              );

              keyOffset += selector.getGroupingKeySize();
            }

            // Convert dimension values to desired output types, possibly.
            GroupByQueryEngineV2.convertRowTypesToOutputTypes(
                query.getDimensions(),
                resultRow,
                resultRowDimensionStart
            );

            // Add aggregations.
            for (int i = 0; i < entry.getValues().length; i++) {
              resultRow.set(resultRowAggregatorStart + i, entry.getValues()[i]);
            }

            return resultRow;
          },
          vectorGrouper
      );
    }
  }
}


text:
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html

#include "unicode/utypes.h"

#if U_PLATFORM_USES_ONLY_WIN32_API

#if !UCONFIG_NO_FORMATTING

#include "winnmfmt.h"

#include "unicode/format.h"
#include "unicode/numfmt.h"
#include "unicode/locid.h"
#include "unicode/ustring.h"

#include "cmemory.h"
#include "uassert.h"
#include "locmap.h"

#ifndef WIN32_LEAN_AND_MEAN
#   define WIN32_LEAN_AND_MEAN
#endif
#   define VC_EXTRALEAN
#   define NOUSER
#   define NOSERVICE
#   define NOIME
#   define NOMCX
#include <windows.h>
#include <stdio.h>

U_NAMESPACE_BEGIN

union FormatInfo
{
    NUMBERFMTW   number;
    CURRENCYFMTW currency;
};

UOBJECT_DEFINE_RTTI_IMPLEMENTATION(Win32NumberFormat)

#define NEW_ARRAY(type,count) (type *) uprv_malloc((count) * sizeof(type))
#define DELETE_ARRAY(array) uprv_free((void *) (array))

#define STACK_BUFFER_SIZE 32

/*
 * Turns a string of the form "3;2;0" into the grouping UINT
 * needed for NUMBERFMT and CURRENCYFMT. If the string does not
 * end in ";0" then the return value should be multiplied by 10.
 * (e.g. "3" => 30, "3;2" => 320)
 */
static UINT getGrouping(const wchar_t *grouping)
{
    UINT g = 0;
    const wchar_t *s;

    for (s = grouping; *s != L'\0'; s += 1) {
        if (*s > L'0' && *s < L'9') {
            g = g * 10 + (*s - L'0');
        } else if (*s != L';') {
            break;
        }
    }

    if (*s != L'0') {
        g *= 10;
    }

    return g;
}

static void getNumberFormat(NUMBERFMTW *fmt, const wchar_t *windowsLocaleName)
{
    wchar_t buf[10];

    GetLocaleInfoEx(windowsLocaleName, LOCALE_RETURN_NUMBER|LOCALE_IDIGITS, (LPWSTR) &fmt->NumDigits, sizeof(UINT));
    GetLocaleInfoEx(windowsLocaleName, LOCALE_RETURN_NUMBER|LOCALE_ILZERO,  (LPWSTR) &fmt->LeadingZero, sizeof(UINT));

    GetLocaleInfoEx(windowsLocaleName, LOCALE_SGROUPING, (LPWSTR)buf, 10);
    fmt->Grouping = getGrouping(buf);

    fmt->lpDecimalSep = NEW_ARRAY(wchar_t, 6);
    GetLocaleInfoEx(windowsLocaleName, LOCALE_SDECIMAL,  fmt->lpDecimalSep,  6);

    fmt->lpThousandSep = NEW_ARRAY(wchar_t, 6);
    GetLocaleInfoEx(windowsLocaleName, LOCALE_STHOUSAND, fmt->lpThousandSep, 6);

    GetLocaleInfoEx(windowsLocaleName, LOCALE_RETURN_NUMBER|LOCALE_INEGNUMBER, (LPWSTR) &fmt->NegativeOrder, sizeof(UINT));
}

static void freeNumberFormat(NUMBERFMTW *fmt)
{
    if (fmt != NULL) {
        DELETE_ARRAY(fmt->lpThousandSep);
        DELETE_ARRAY(fmt->lpDecimalSep);
    }
}

static void getCurrencyFormat(CURRENCYFMTW *fmt, const wchar_t *windowsLocaleName)
{
    wchar_t buf[10];

    GetLocaleInfoEx(windowsLocaleName, LOCALE_RETURN_NUMBER|LOCALE_ICURRDIGITS, (LPWSTR) &fmt->NumDigits, sizeof(UINT));
    GetLocaleInfoEx(windowsLocaleName, LOCALE_RETURN_NUMBER|LOCALE_ILZERO, (LPWSTR) &fmt->LeadingZero, sizeof(UINT));

    GetLocaleInfoEx(windowsLocaleName, LOCALE_SMONGROUPING, (LPWSTR)buf, sizeof(buf));
    fmt->Grouping = getGrouping(buf);

    fmt->lpDecimalSep = NEW_ARRAY(wchar_t, 6);
    GetLocaleInfoEx(windowsLocaleName, LOCALE_SMONDECIMALSEP,  fmt->lpDecimalSep,  6);

    fmt->lpThousandSep = NEW_ARRAY(wchar_t, 6);
    GetLocaleInfoEx(windowsLocaleName, LOCALE_SMONTHOUSANDSEP, fmt->lpThousandSep, 6);

    GetLocaleInfoEx(windowsLocaleName, LOCALE_RETURN_NUMBER|LOCALE_INEGCURR,  (LPWSTR) &fmt->NegativeOrder, sizeof(UINT));
    GetLocaleInfoEx(windowsLocaleName, LOCALE_RETURN_NUMBER|LOCALE_ICURRENCY, (LPWSTR) &fmt->PositiveOrder, sizeof(UINT));

    fmt->lpCurrencySymbol = NEW_ARRAY(wchar_t, 8);
    GetLocaleInfoEx(windowsLocaleName, LOCALE_SCURRENCY, (LPWSTR) fmt->lpCurrencySymbol, 8);
}

static void freeCurrencyFormat(CURRENCYFMTW *fmt)
{
    if (fmt != NULL) {
        DELETE_ARRAY(fmt->lpCurrencySymbol);
        DELETE_ARRAY(fmt->lpThousandSep);
        DELETE_ARRAY(fmt->lpDecimalSep);
    }
}

// TODO: This is copied in both winnmfmt.cpp and windtfmt.cpp, but really should
// be factored out into a common helper for both.
static UErrorCode GetEquivalentWindowsLocaleName(const Locale& locale, UnicodeString** buffer)
{
    UErrorCode status = U_ZERO_ERROR;
    char asciiBCP47Tag[LOCALE_NAME_MAX_LENGTH] = {};

    // Convert from names like "en_CA" and "de_DE@collation=phonebook" to "en-CA" and "de-DE-u-co-phonebk".
    (void) uloc_toLanguageTag(locale.getName(), asciiBCP47Tag, UPRV_LENGTHOF(asciiBCP47Tag), FALSE, &status);

    if (U_SUCCESS(status))
    {
        // Need it to be UTF-16, not 8-bit
        // TODO: This seems like a good thing for a helper
        wchar_t bcp47Tag[LOCALE_NAME_MAX_LENGTH] = {};
        int32_t i;
        for (i = 0; i < UPRV_LENGTHOF(bcp47Tag); i++)
        {
            if (asciiBCP47Tag[i] == '\0')
            {
                break;
            }
            else
            {
                // normally just copy the character
                bcp47Tag[i] = static_cast<wchar_t>(asciiBCP47Tag[i]);
            }
        }

        // Ensure it's null terminated
        if (i < (UPRV_LENGTHOF(bcp47Tag) - 1))
        {
            bcp47Tag[i] = L'\0';
        }
        else
        {
            // Ran out of room.
            bcp47Tag[UPRV_LENGTHOF(bcp47Tag) - 1] = L'\0';
        }

        wchar_t windowsLocaleName[LOCALE_NAME_MAX_LENGTH] = {};

        // Note: On Windows versions below 10, there is no support for locale name aliases.
        // This means that it will fail for locales where ICU has a completely different
        // name (like ku vs ckb), and it will also not work for alternate sort locale
        // names like "de-DE-u-co-phonebk".

        // TODO: We could add some sort of exception table for cases like ku vs ckb.

        int length = ResolveLocaleName(bcp47Tag, windowsLocaleName, UPRV_LENGTHOF(windowsLocaleName));

        if (length > 0)
        {
            *buffer = new UnicodeString(windowsLocaleName);
        }
        else
        {
            status = U_UNSUPPORTED_ERROR;
        }
    }
    return status;
}

Win32NumberFormat::Win32NumberFormat(const Locale &locale, UBool currency, UErrorCode &status)
  : NumberFormat(), fCurrency(currency), fFormatInfo(NULL), fFractionDigitsSet(FALSE), fWindowsLocaleName(nullptr)
{
    if (!U_FAILURE(status)) {
        fLCID = locale.getLCID();

        GetEquivalentWindowsLocaleName(locale, &fWindowsLocaleName);
        // Note: In the previous code, it would look up the LCID for the locale, and if
        // the locale was not recognized then it would get an LCID of 0, which is a
        // synonym for LOCALE_USER_DEFAULT on Windows.
        // If the above method fails, then fWindowsLocaleName will remain as nullptr, and
        // then we will pass nullptr to API GetLocaleInfoEx, which is the same as passing
        // LOCALE_USER_DEFAULT.

        // Resolve actual locale to be used later
        UErrorCode tmpsts = U_ZERO_ERROR;
        char tmpLocID[ULOC_FULLNAME_CAPACITY];
        int32_t len = uloc_getLocaleForLCID(fLCID, tmpLocID, UPRV_LENGTHOF(tmpLocID) - 1, &tmpsts);
        if (U_SUCCESS(tmpsts)) {
            tmpLocID[len] = 0;
            fLocale = Locale((const char*)tmpLocID);
        }

        const wchar_t *localeName = nullptr;

        if (fWindowsLocaleName != nullptr)
        {
            localeName = reinterpret_cast<const wchar_t*>(toOldUCharPtr(fWindowsLocaleName->getTerminatedBuffer()));
        }

        fFormatInfo = (FormatInfo*)uprv_malloc(sizeof(FormatInfo));

        if (fCurrency) {
            getCurrencyFormat(&fFormatInfo->currency, localeName);
        } else {
            getNumberFormat(&fFormatInfo->number, localeName);
        }
    }
}

Win32NumberFormat::Win32NumberFormat(const Win32NumberFormat &other)
  : NumberFormat(other), fFormatInfo((FormatInfo*)uprv_malloc(sizeof(FormatInfo)))
{
    if (fFormatInfo != NULL) {
        uprv_memset(fFormatInfo, 0, sizeof(*fFormatInfo));
    }
    *this = other;
}

Win32NumberFormat::~Win32NumberFormat()
{
    if (fFormatInfo != NULL) {
        if (fCurrency) {
            freeCurrencyFormat(&fFormatInfo->currency);
        } else {
            freeNumberFormat(&fFormatInfo->number);
        }

        uprv_free(fFormatInfo);
    }
    delete fWindowsLocaleName;
}

Win32NumberFormat &Win32NumberFormat::operator=(const Win32NumberFormat &other)
{
    NumberFormat::operator=(other);

    this->fCurrency          = other.fCurrency;
    this->fLocale            = other.fLocale;
    this->fLCID              = other.fLCID;
    this->fFractionDigitsSet = other.fFractionDigitsSet;
    this->fWindowsLocaleName = other.fWindowsLocaleName == NULL ? NULL : new UnicodeString(*other.fWindowsLocaleName);

    const wchar_t *localeName = nullptr;

    if (fWindowsLocaleName != nullptr)
    {
        localeName = reinterpret_cast<const wchar_t*>(toOldUCharPtr(fWindowsLocaleName->getTerminatedBuffer()));
    }

    if (fCurrency) {
        freeCurrencyFormat(&fFormatInfo->currency);
        getCurrencyFormat(&fFormatInfo->currency, localeName);
    } else {
        freeNumberFormat(&fFormatInfo->number);
        getNumberFormat(&fFormatInfo->number, localeName);
    }

    return *this;
}

Format *Win32NumberFormat::clone(void) const
{
    return new Win32NumberFormat(*this);
}

UnicodeString& Win32NumberFormat::format(double number, UnicodeString& appendTo, FieldPosition& /* pos */) const
{
    return format(getMaximumFractionDigits(), appendTo, L"%.16f", number);
}

UnicodeString& Win32NumberFormat::format(int32_t number, UnicodeString& appendTo, FieldPosition& /* pos */) const
{
    return format(getMinimumFractionDigits(), appendTo, L"%I32d", number);
}

UnicodeString& Win32NumberFormat::format(int64_t number, UnicodeString& appendTo, FieldPosition& /* pos */) const
{
    return format(getMinimumFractionDigits(), appendTo, L"%I64d", number);
}

void Win32NumberFormat::parse(const UnicodeString& text, Formattable& result, ParsePosition& parsePosition) const
{
    UErrorCode status = U_ZERO_ERROR;
    NumberFormat *nf = fCurrency? NumberFormat::createCurrencyInstance(fLocale, status) : NumberFormat::createInstance(fLocale, status);

    nf->parse(text, result, parsePosition);
    delete nf;
}
void Win32NumberFormat::setMaximumFractionDigits(int32_t newValue)
{
    fFractionDigitsSet = TRUE;
    NumberFormat::setMaximumFractionDigits(newValue);
}

void Win32NumberFormat::setMinimumFractionDigits(int32_t newValue)
{
    fFractionDigitsSet = TRUE;
    NumberFormat::setMinimumFractionDigits(newValue);
}

UnicodeString &Win32NumberFormat::format(int32_t numDigits, UnicodeString &appendTo, const wchar_t *fmt, ...) const
{
    wchar_t nStackBuffer[STACK_BUFFER_SIZE];
    wchar_t *nBuffer = nStackBuffer;
    va_list args;
    int result;

    nBuffer[0] = 0x0000;

    /* Due to the arguments causing a result to be <= 23 characters (+2 for NULL and minus),
    we don't need to reallocate the buffer. */
    va_start(args, fmt);
    result = _vsnwprintf(nBuffer, STACK_BUFFER_SIZE, fmt, args);
    va_end(args);

    /* Just to make sure of the above statement, we add this assert */
    U_ASSERT(result >=0);
    // The following code is not used because _vscwprintf isn't available on MinGW at the moment.
    /*if (result < 0) {
        int newLength;

        va_start(args, fmt);
        newLength = _vscwprintf(fmt, args);
        va_end(args);

        nBuffer = NEW_ARRAY(UChar, newLength + 1);

        va_start(args, fmt);
        result = _vsnwprintf(nBuffer, newLength + 1, fmt, args);
        va_end(args);
    }*/

    // vswprintf is sensitive to the locale set by setlocale. For some locales
    // it doesn't use "." as the decimal separator, which is what GetNumberFormatW
    // and GetCurrencyFormatW both expect to see.
    //
    // To fix this, we scan over the string and replace the first non-digits, except
    // for a leading "-", with a "."
    //
    // Note: (nBuffer[0] == L'-') will evaluate to 1 if there is a leading '-' in the
    // number, and 0 otherwise.
    for (wchar_t *p = &nBuffer[nBuffer[0] == L'-']; *p != L'\0'; p += 1) {
        if (*p < L'0' || *p > L'9') {
            *p = L'.';
            break;
        }
    }

    wchar_t stackBuffer[STACK_BUFFER_SIZE];
    wchar_t *buffer = stackBuffer;
    FormatInfo formatInfo;

    formatInfo = *fFormatInfo;
    buffer[0] = 0x0000;

    const wchar_t *localeName = nullptr;

    if (fWindowsLocaleName != nullptr)
    {
        localeName = reinterpret_cast<const wchar_t*>(toOldUCharPtr(fWindowsLocaleName->getTerminatedBuffer()));
    }

    if (fCurrency) {
        if (fFractionDigitsSet) {
            formatInfo.currency.NumDigits = (UINT) numDigits;
        }

        if (!isGroupingUsed()) {
            formatInfo.currency.Grouping = 0;
        }

        result = GetCurrencyFormatEx(localeName, 0, nBuffer, &formatInfo.currency, buffer, STACK_BUFFER_SIZE);

        if (result == 0) {
            DWORD lastError = GetLastError();

            if (lastError == ERROR_INSUFFICIENT_BUFFER) {
                int newLength = GetCurrencyFormatEx(localeName, 0, nBuffer, &formatInfo.currency, NULL, 0);

                buffer = NEW_ARRAY(wchar_t, newLength);
                buffer[0] = 0x0000;
                GetCurrencyFormatEx(localeName, 0, nBuffer,  &formatInfo.currency, buffer, newLength);
            }
        }
    } else {
        if (fFractionDigitsSet) {
            formatInfo.number.NumDigits = (UINT) numDigits;
        }

        if (!isGroupingUsed()) {
            formatInfo.number.Grouping = 0;
        }

        result = GetNumberFormatEx(localeName, 0, nBuffer, &formatInfo.number, buffer, STACK_BUFFER_SIZE);

        if (result == 0) {
            if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
                int newLength = GetNumberFormatEx(localeName, 0, nBuffer, &formatInfo.number, NULL, 0);

                buffer = NEW_ARRAY(wchar_t, newLength);
                buffer[0] = 0x0000;
                GetNumberFormatEx(localeName, 0, nBuffer, &formatInfo.number, buffer, newLength);
            }
        }
    }

    appendTo.append((UChar *)buffer, (int32_t) wcslen(buffer));

    if (buffer != stackBuffer) {
        DELETE_ARRAY(buffer);
    }

    /*if (nBuffer != nStackBuffer) {
        DELETE_ARRAY(nBuffer);
    }*/

    return appendTo;
}

U_NAMESPACE_END

#endif /* #if !UCONFIG_NO_FORMATTING */

#endif // U_PLATFORM_USES_ONLY_WIN32_API


text:
// $Id$
package mkl.testarea.pdfbox1.merge;

import static org.junit.Assert.fail;

import java.io.File;
import java.io.IOException;

import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageNode;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * @author mkl
 *
 */
public class InsertPages
{
    final static File RESULT_FOLDER = new File("target/test-outputs", "merge");

    @BeforeClass
    public static void setUpBeforeClass() throws Exception
    {
        RESULT_FOLDER.mkdirs();
    }

    /**
     *
     * PDFBox Split into 3 at specified page numbers (to insert pdf)
     *
     *

     * This test shows how to insert the same single page into another document multiple times.
     *

     *

     * Beware, this code assumes a flat page tree. In case of deeper page trees one has to
     * walk the page list differently, respect the count of contained {@link PDPageNode}
     * objects and recurse if appropriate.
     *

     */
    @Test
    public void testInsertPages() throws IOException, COSVisitorException
    {
        PDDocument document = create100Pages();
        PDDocument singlePageDocument = create1Page("A");
        PDPage singlePage = (PDPage) singlePageDocument.getDocumentCatalog().getAllPages().get(0);

        PDPageNode rootPages = document.getDocumentCatalog().getPages();
        rootPages.getKids().add(3-1, singlePage);
        singlePage.setParent(rootPages);
        singlePage = new PDPage(new COSDictionary(singlePage.getCOSDictionary()));
        rootPages.getKids().add(7-1, singlePage);
        singlePage = new PDPage(new COSDictionary(singlePage.getCOSDictionary()));
        rootPages.getKids().add(10-1, singlePage);
        rootPages.updateCount();

        document.save(new File(RESULT_FOLDER, "100-A-at-3.pdf"));
    }

    public PDDocument create100Pages() throws IOException
    {
        PDDocument document = new PDDocument();

        for (int i = 0; i < 100; i++)
        {
            PDPage page = new PDPage();
            document.addPage(page);
            PDPageContentStream content = new PDPageContentStream(document, page);
            content.beginText();
            content.setFont(PDType1Font.HELVETICA_BOLD, 100);
            content.moveTextPositionByAmount(100, 300);
            content.drawString(String.format("-%s-", i + 1));
            content.endText();
            content.close();
        }

        return document;
    }

    public PDDocument create1Page(String mark) throws IOException
    {
        PDDocument document = new PDDocument();

        PDPage page = new PDPage();
        document.addPage(page);
        PDPageContentStream content = new PDPageContentStream(document, page);
        content.beginText();
        content.setFont(PDType1Font.HELVETICA_BOLD, 100);
        content.moveTextPositionByAmount(100, 300);
        content.drawString(mark);
        content.endText();
        content.close();

        return document;
    }
}


text:
package client;

import com.google.common.collect.ConcurrentHashMultiset;
import com.google.common.collect.Multiset;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcedureCallback;

public class BenchmarkCallback implements ProcedureCallback {

    private static Multiset<String> stats = ConcurrentHashMultiset.create();
    String procedureName;
    long maxErrors;

    public static int count( String procedureName, String event ){
        return stats.add(procedureName + event, 1);
    }

    public static int getCount( String procedureName, String event ){
        return stats.count(procedureName + event);
    }

    public static void printProcedureResults(String procedureName) {
        System.out.println("  " + procedureName);
        System.out.println("        calls: " + getCount(procedureName,"call"));
        System.out.println("      commits: " + getCount(procedureName,"commit"));
        System.out.println("    rollbacks: " + getCount(procedureName,"rollback"));
    }

    public BenchmarkCallback(String procedure, long maxErrors) {
        super();
        this.procedureName = procedure;
        this.maxErrors = maxErrors;
    }

    public BenchmarkCallback(String procedure) {
        this(procedure, 5l);
    }

    @Override
    public void clientCallback(ClientResponse cr) {

        count(procedureName,"call");

        if (cr.getStatus() == ClientResponse.SUCCESS) {
            count(procedureName,"commit");
        } else {
            long totalErrors = count(procedureName,"rollback");

            if (totalErrors > maxErrors) {
                System.err.println("exceeded " + maxErrors + " maximum database errors - exiting client");
                System.exit(-1);
            }

            System.err.println("DATABASE ERROR: " + cr.getStatusString());
        }
    }
}


text:
import java.util.*;
import java.io.*;

public class RemoteControl
{
    public static final String INSTRUCTIONS = "instructions.txt";

    public static void main (String[] args)
    {
        boolean debug = false;
        boolean stepsToOxygen = false;

        for (int i = 0; i < args.length; i++)
        {
            if ("-help".equals(args[i]))
            {
                System.out.println("Usage: [-debug] [-steps] [-help]");
                System.exit(0);
            }

            if ("-debug".equals(args[i]))
                debug = true;

            if ("-steps".equals(args[i]))
                stepsToOxygen = true;
        }

        /*
         * Open the data file and read it in.
         */

        BufferedReader reader = null;
        String[] values = null;

        try
        {
            reader = new BufferedReader(new FileReader(INSTRUCTIONS));
            String line = null;

            while ((line = reader.readLine()) != null)
            {
                values = line.split(Intcode.DELIMITER);
            }
        }
        catch (Throwable ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            try
            {
                reader.close();
            }
            catch (Throwable ex)
            {
            }
        }

        Vector<String> instructions = new Vector<String>();

        instructions.addAll(Arrays.asList(values));

        RepairDroid droid = new RepairDroid(instructions, debug);

        if (stepsToOxygen)
        {
            int steps = droid.moveToOxygenStation();

            System.out.println("Number of steps to reach oxygen station: "+steps);
        }
        else
        {
            droid.mapEntireMaze();

            System.out.println(droid.getMaze());

            Coordinate coord = droid.getMaze().getOxygenStation();
            int[] dimensions = droid.getMaze().getDimensons();

            System.out.println("Oxygen station: "+coord);
            System.out.println("Maze dimensions: <"+dimensions[0]+", "+dimensions[2]+"> <"+dimensions[1]+", "+dimensions[3]+">");

            OxygenFiller filler = new OxygenFiller(droid.getMaze(), debug);

            System.out.println("\nNumber of minutes to fill space with oxygen: "+filler.fillWithOxygen());
        }
    }
}


text:
from django.test.utils import override_settings
import six

import cinderclient as cinder_client

from openstack_dashboard import api
from openstack_dashboard.test import helpers as test

class CinderApiTests(test.APITestCase):
    def test_volume_list(self):
        search_opts = {'all_tenants': 1}
        volumes = self.cinder_volumes.list()
        cinderclient = self.stub_cinderclient()
        cinderclient.volumes = self.mox.CreateMockAnything()
        cinderclient.volumes.list(search_opts=search_opts,).AndReturn(volumes)
        self.mox.ReplayAll()

        # No assertions are necessary. Verification is handled by mox.
        api.cinder.volume_list(self.request, search_opts=search_opts)

    def test_volume_snapshot_list(self):
        volume_snapshots = self.cinder_volume_snapshots.list()
        cinderclient = self.stub_cinderclient()
        cinderclient.volume_snapshots = self.mox.CreateMockAnything()
        cinderclient.volume_snapshots.list().AndReturn(volume_snapshots)
        self.mox.ReplayAll()

        api.cinder.volume_snapshot_list(self.request)

    def test_volume_snapshot_list_no_volume_configured(self):
        # remove volume from service catalog
        catalog = self.service_catalog
        for service in catalog:
            if service["type"] == "volume":
                self.service_catalog.remove(service)
        volume_snapshots = self.cinder_volume_snapshots.list()

        cinderclient = self.stub_cinderclient()
        cinderclient.volume_snapshots = self.mox.CreateMockAnything()
        cinderclient.volume_snapshots.list().AndReturn(volume_snapshots)
        self.mox.ReplayAll()

        api.cinder.volume_snapshot_list(self.request)

    def test_absolute_limits_with_negative_values(self):
        values = {"maxTotalVolumes": -1, "totalVolumesUsed": -1}
        expected_results = {"maxTotalVolumes": float("inf"),
                            "totalVolumesUsed": 0}

        limits = self.mox.CreateMockAnything()
        limits.absolute = []
        for key, val in six.iteritems(values):
            limit = self.mox.CreateMockAnything()
            limit.name = key
            limit.value = val
            limits.absolute.append(limit)

        cinderclient = self.stub_cinderclient()
        cinderclient.limits = self.mox.CreateMockAnything()
        cinderclient.limits.get().AndReturn(limits)
        self.mox.ReplayAll()

        ret_val = api.cinder.tenant_absolute_limits(self.request)
        for key in expected_results.keys():
            self.assertEqual(expected_results[key], ret_val[key])

class CinderApiVersionTests(test.TestCase):

    def setUp(self):
        super(CinderApiVersionTests, self).setUp()
        # The version is set when the module is loaded. Reset the
        # active version each time so that we can test with different
        # versions.
        api.cinder.VERSIONS._active = None

    def test_default_client_is_v1(self):
        client = api.cinder.cinderclient(self.request)
        self.assertIsInstance(client, cinder_client.v1.client.Client)

    @override_settings(OPENSTACK_API_VERSIONS={'volume': 1})
    def test_v1_setting_returns_v1_client(self):
        client = api.cinder.cinderclient(self.request)
        self.assertIsInstance(client, cinder_client.v1.client.Client)

    @override_settings(OPENSTACK_API_VERSIONS={'volume': 2})
    def test_v2_setting_returns_v2_client(self):
        client = api.cinder.cinderclient(self.request)
        self.assertIsInstance(client, cinder_client.v2.client.Client)

    def test_get_v1_volume_attributes(self):
        # Get a v1 volume
        volume = self.cinder_volumes.first()
        self.assertTrue(hasattr(volume._apiresource, 'display_name'))
        self.assertFalse(hasattr(volume._apiresource, 'name'))

        name = "A test volume name"
        description = "A volume description"
        setattr(volume._apiresource, 'display_name', name)
        setattr(volume._apiresource, 'display_description', description)
        self.assertEqual(volume.name, name)
        self.assertEqual(volume.description, description)

    def test_get_v2_volume_attributes(self):
        # Get a v2 volume
        volume = self.cinder_volumes.get(name="v2_volume")
        self.assertTrue(hasattr(volume._apiresource, 'name'))
        self.assertFalse(hasattr(volume._apiresource, 'display_name'))

        name = "A v2 test volume name"
        description = "A v2 volume description"
        setattr(volume._apiresource, 'name', name)
        setattr(volume._apiresource, 'description', description)
        self.assertEqual(volume.name, name)
        self.assertEqual(volume.description, description)

    def test_get_v1_snapshot_attributes(self):
        # Get a v1 snapshot
        snapshot = self.cinder_volume_snapshots.first()
        self.assertFalse(hasattr(snapshot._apiresource, 'name'))

        name = "A test snapshot name"
        description = "A snapshot description"
        setattr(snapshot._apiresource, 'display_name', name)
        setattr(snapshot._apiresource, 'display_description', description)
        self.assertEqual(snapshot.name, name)
        self.assertEqual(snapshot.description, description)

    def test_get_v2_snapshot_attributes(self):
        # Get a v2 snapshot
        snapshot = self.cinder_volume_snapshots.get(
            description="v2 volume snapshot description")
        self.assertFalse(hasattr(snapshot._apiresource, 'display_name'))

        name = "A v2 test snapshot name"
        description = "A v2 snapshot description"
        setattr(snapshot._apiresource, 'name', name)
        setattr(snapshot._apiresource, 'description', description)
        self.assertEqual(snapshot.name, name)
        self.assertEqual(snapshot.description, description)

    def test_get_id_for_nameless_volume(self):
        volume = self.cinder_volumes.first()
        setattr(volume._apiresource, 'display_name', "")
        self.assertEqual(volume.name, volume.id)

    @override_settings(OPENSTACK_API_VERSIONS={'volume': 1})
    def test_adapt_dictionary_to_v1(self):
        volume = self.cinder_volumes.first()
        data = {'name': volume.name,
                'description': volume.description,
                'size': volume.size}

        ret_data = api.cinder._replace_v2_parameters(data)
        self.assertIn('display_name', ret_data.keys())
        self.assertIn('display_description', ret_data.keys())
        self.assertNotIn('name', ret_data.keys())
        self.assertNotIn('description', ret_data.keys())

    @override_settings(OPENSTACK_API_VERSIONS={'volume': 2})
    def test_adapt_dictionary_to_v2(self):
        volume = self.cinder_volumes.first()
        data = {'name': volume.name,
                'description': volume.description,
                'size': volume.size}

        ret_data = api.cinder._replace_v2_parameters(data)
        self.assertIn('name', ret_data.keys())
        self.assertIn('description', ret_data.keys())
        self.assertNotIn('display_name', ret_data.keys())
        self.assertNotIn('display_description', ret_data.keys())