text:
/**
 * This file contains javascript associated with a autosuggest control.
 */

/**
 * The autosuggest class, used to display a selection list of members
 *
 * @param {object} oOptions
 */
function smc_AutoSuggest(oOptions)
{
	this.opt = oOptions;

	// Store the handle to the text box.
	this.oTextHandle = document.getElementById(this.opt.sControlId);
	this.oRealTextHandle = null;
	this.oSuggestDivHandle = null;

	this.sLastSearch = '';
	this.sLastDirtySearch = '';
	this.oSelectedDiv = null;
	this.aCache = [];
	this.aDisplayData = [];
	this.sRetrieveURL = 'sRetrieveURL' in this.opt ? this.opt.sRetrieveURL : '%scripturl%action=suggest;api=xml';

	// How many objects can we show at once?
	this.iMaxDisplayQuantity = 'iMaxDisplayQuantity' in this.opt ? this.opt.iMaxDisplayQuantity : 12;

	// How many characters shall we start searching on?
	this.iMinimumSearchChars = 'iMinimumSearchChars' in this.opt ? this.opt.iMinimumSearchChars : 2;

	// Should selected items be added to a list?
	this.bItemList = 'bItemList' in this.opt ? this.opt.bItemList : false;

	// Are there any items that should be added in advance?
	this.aListItems = 'aListItems' in this.opt ? this.opt.aListItems : [];

	this.sItemTemplate = 'sItemTemplate' in this.opt ? this.opt.sItemTemplate : '<input type="hidden" name="%post_name%[]" value="%item_id%" />%item_name% ';
	this.sTextDeleteItem = 'sTextDeleteItem' in this.opt ? this.opt.sTextDeleteItem : '';
	this.oCallback = {};
	this.bDoAutoAdd = false;
	this.iItemCount = 0;
	this.oHideTimer = null;
	this.bPositionComplete = false;

	this.oXmlRequestHandle = null;

	// Just make sure the page is loaded before calling the init.
	window.addEventListener("load", this.init.bind(this));
}

// Initialize our autosuggest object, adds events and containers to the element we monitor
smc_AutoSuggest.prototype.init = function ()
{
	// Create a div that'll contain the results later on.
	this.oSuggestDivHandle = document.createElement('div');
	this.oSuggestDivHandle.className = 'auto_suggest_div';
	document.body.appendChild(this.oSuggestDivHandle);

	// Create a backup text input.
	this.oRealTextHandle = document.createElement('input');
	this.oRealTextHandle.type = 'hidden';
	this.oRealTextHandle.name = this.oTextHandle.name;
	this.oRealTextHandle.value = this.oTextHandle.value;
	this.oTextHandle.form.appendChild(this.oRealTextHandle);

	// Disable autocomplete in any browser by obfuscating the name.
	this.oTextHandle.name = 'dummy_' + Math.floor(Math.random() * 1000000);
	this.oTextHandle.autocomplete = 'off';

	// Set up all the event monitoring
	this.oTextHandle.onkeydown = this.handleKey.bind(this);
	this.oTextHandle.onkeyup = this.autoSuggestUpdate.bind(this);
	this.oTextHandle.onchange = this.autoSuggestUpdate.bind(this);
	this.oTextHandle.onblur = this.autoSuggestHide.bind(this);
	this.oTextHandle.onfocus = this.autoSuggestUpdate.bind(this);

	// Adding items to a list, then we need a place to insert them
	if (this.bItemList)
	{
		if ('sItemListContainerId' in this.opt)
		{
			this.oItemList = document.getElementById(this.opt.sItemListContainerId);
		}
		else
		{
			this.oItemList = document.createElement('div');
			this.oTextHandle.parentNode.insertBefore(this.oItemList, this.oTextHandle.nextSibling);
		}
	}

	// Items provided to add to the top of the selection list?
	if (this.aListItems.length > 0)
	{
		for (var i = 0, n = this.aListItems.length; i < n; i++)
		{
			this.addItemLink(this.aListItems[i].sItemId, this.aListItems[i].sItemName);
		}
	}

	return true;
};

/**
 * Handle keypress events for the suggest controller
 *
 * @param oEvent
 */
smc_AutoSuggest.prototype.handleKey = function (oEvent)
{
	// Grab the event object, one way or the other
	if (!oEvent)
	{
		oEvent = window.event;
	}

	// Get the keycode of the key that was pressed.
	var iKeyPress = 0;
	if ('which' in oEvent)
	{
		iKeyPress = oEvent.which;
	}
	else if ('keyCode' in oEvent)
	{
		iKeyPress = oEvent.keyCode;
	}

	// Check what key they have pressed
	switch (iKeyPress)
	{
		// Tab.
		case 9:
			if (this.aDisplayData.length > 0)
			{
				if (this.oSelectedDiv !== null)
				{
					this.itemClicked(this.oSelectedDiv);
				}
				else
				{
					this.handleSubmit();
				}
			}

			// Continue to the next control.
			return true;

		// Was it an Enter key - if so assume they are trying to select something.
		case 13:
			if (this.aDisplayData.length > 0 && this.oSelectedDiv !== null)
			{
				this.itemClicked(this.oSelectedDiv);

				// Do our best to stop it submitting the form!
				return false;
			}
			else
			{
				return true;
			}
			break;

		// Up/Down arrow?
		case 38:
		case 40:
			if (this.aDisplayData.length && this.oSuggestDivHandle.style.visibility !== 'hidden')
			{
				// Loop through the display data trying to find our entry.
				var bPrevHandle = false,
					oToHighlight = null;

				for (var i = 0; i < this.aDisplayData.length; i++)
				{
					// If we're going up and yet the top one was already selected don't go around.
					if (this.oSelectedDiv !== null && this.oSelectedDiv === this.aDisplayData[i] && i === 0 && iKeyPress === 38)
					{
						oToHighlight = this.oSelectedDiv;
						break;
					}

					// If nothing is selected and we are going down then we select the first one.
					if (this.oSelectedDiv === null && iKeyPress === 40)
					{
						oToHighlight = this.aDisplayData[i];
						break;
					}

					// If the previous handle was the actual previously selected one and we're hitting down then this is the one we want.
					if (bPrevHandle !== false && bPrevHandle === this.oSelectedDiv && iKeyPress === 40)
					{
						oToHighlight = this.aDisplayData[i];
						break;
					}

					// If we're going up and this is the previously selected one then we want the one before, if there was one.
					if (bPrevHandle !== false && this.aDisplayData[i] === this.oSelectedDiv && iKeyPress === 38)
					{
						oToHighlight = bPrevHandle;
						break;
					}

					// Make the previous handle this!
					bPrevHandle = this.aDisplayData[i];
				}

				// If we don't have one to highlight by now then it must be the last one that we're after.
				if (oToHighlight === null)
				{
					oToHighlight = bPrevHandle;
				}

				// Remove any old highlighting.
				if (this.oSelectedDiv !== null)
				{
					this.itemMouseOut(this.oSelectedDiv);
				}

				// Mark what the selected div now is.
				this.oSelectedDiv = oToHighlight;
				this.itemMouseOver(this.oSelectedDiv);
			}
			break;
	}

	return true;
};

// Functions for integration.
smc_AutoSuggest.prototype.registerCallback = function (sCallbackType, sCallback)
{
	switch (sCallbackType)
	{
		case 'onBeforeAddItem':
			this.oCallback.onBeforeAddItem = sCallback;
			break;

		case 'onAfterAddItem':
			this.oCallback.onAfterAddItem = sCallback;
			break;

		case 'onAfterDeleteItem':
			this.oCallback.onAfterDeleteItem = sCallback;
			break;

		case 'onBeforeUpdate':
			this.oCallback.onBeforeUpdate = sCallback;
			break;
	}
};

// User hit submit?
smc_AutoSuggest.prototype.handleSubmit = function ()
{
	var bReturnValue = true,
		oFoundEntry = null;

	// Do we have something that matches the current text?
	for (var i = 0; i < this.aCache.length; i++)
	{
		if (this.sLastSearch.toLowerCase() === this.aCache[i].sItemName.toLowerCase().substr(0, this.sLastSearch.length))
		{
			// Exact match?
			if (this.sLastSearch.length === this.aCache[i].sItemName.length)
			{
				// This is the one!
				oFoundEntry = {
					sItemId: this.aCache[i].sItemId,
					sItemName: this.aCache[i].sItemName
				};

				break;
			}
			// Not an exact match, but it'll do for now.
			else
			{
				// If we have two matches don't find anything.
				if (oFoundEntry !== null)
				{
					bReturnValue = false;
				}
				else
				{
					oFoundEntry = {
						sItemId: this.aCache[i].sItemId,
						sItemName: this.aCache[i].sItemName
					};
				}
			}
		}
	}

	if (oFoundEntry === null || bReturnValue === false)
	{
		return bReturnValue;
	}

	this.addItemLink(oFoundEntry.sItemId, oFoundEntry.sItemName, true);
	return false;
};

// Positions the box correctly on the window.
smc_AutoSuggest.prototype.positionDiv = function ()
{
	// Only do it once.
	if (this.bPositionComplete)
	{
		return true;
	}

	this.bPositionComplete = true;

	// Put the div under the text box.
	var aParentPos = elk_itemPos(this.oTextHandle);

	this.oSuggestDivHandle.style.left = aParentPos[0] + 'px';
	this.oSuggestDivHandle.style.top = (aParentPos[1] + this.oTextHandle.offsetHeight) + 'px';
	this.oSuggestDivHandle.style.width = this.oTextHandle.clientWidth + 'px';

	return true;
};

// Do something after clicking an item.
smc_AutoSuggest.prototype.itemClicked = function (oEvent)
{
	// Is there a div that we are populating?
	if (this.bItemList)
	{
		this.addItemLink(oEvent.target.sItemId, oEvent.target.innerHTML);
	}
	// Otherwise clear things down.
	else
	{
		this.oTextHandle.value = oEvent.target.innerHTML.php_unhtmlspecialchars();
	}

	this.oRealTextHandle.value = this.oTextHandle.value;
	this.autoSuggestActualHide();
	this.oSelectedDiv = null;
};

// Remove the last searched for name from the search box.
smc_AutoSuggest.prototype.removeLastSearchString = function ()
{
	// Remove the text we searched for from the div.
	var sTempText = this.oTextHandle.value.toLowerCase(),
		iStartString = sTempText.indexOf(this.sLastSearch.toLowerCase());

	// Just attempt to remove the bits we just searched for.
	if (iStartString !== -1)
	{
		while (iStartString > 0)
		{
			if (sTempText.charAt(iStartString - 1) === '"' || sTempText.charAt(iStartString - 1) === ',' || sTempText.charAt(iStartString - 1) === ' ')
			{
				iStartString--;
				if (sTempText.charAt(iStartString - 1) === ',')
				{
					break;
				}
			}
			else
			{
				break;
			}
		}

		// Now remove anything from iStartString upwards.
		this.oTextHandle.value = this.oTextHandle.value.substr(0, iStartString);
	}
	// Just take it all.
	else
	{
		this.oTextHandle.value = '';
	}
};

// Add a result if not already done.
smc_AutoSuggest.prototype.addItemLink = function (sItemId, sItemName, bFromSubmit)
{
	// Increase the internal item count.
	this.iItemCount++;

	// If there's a callback then call it.
	if (typeof this.oCallback.onBeforeAddItem === 'function')
	{
		// If it returns false the item must not be added.
		if (!this.oCallback.onBeforeAddItem.call(this, sItemId))
		{
			return;
		}
	}

	var oNewDiv = document.createElement('div');
	oNewDiv.id = 'suggest_' + this.opt.sSuggestId + '_' + sItemId;
	oNewDiv.innerHTML = this.sItemTemplate
		.replace(/%post_name%/g, this.opt.sPostName)
		.replace(/%item_id%/g, sItemId)
		.replace(/%item_href%/g, elk_prepareScriptUrl(elk_scripturl) + this.opt.sURLMask.replace(/%item_id%/g, sItemId))
		.replace(/%item_name%/g, sItemName)
		.replace(/%images_url%/g, elk_images_url).replace(/%delete_text%/g, this.sTextDeleteItem);
	oNewDiv.getElementsByTagName('img')[0].addEventListener("click", this.deleteAddedItem.bind(this));
	this.oItemList.appendChild(oNewDiv);

	// If there's a registered callback, call it.
	if (typeof this.oCallback.onAfterAddItem === 'function')
	{
		this.oCallback.onAfterAddItem.call(this, oNewDiv.id);
	}

	// Clear the div a bit.
	this.removeLastSearchString();

	// If we came from a submit, and there's still more to go, turn on auto add for all the other things.
	this.bDoAutoAdd = this.oTextHandle.value !== '' && bFromSubmit;

	// Update the fellow..
	this.autoSuggestUpdate();
};

// Delete an item that has been added, if at all?
smc_AutoSuggest.prototype.deleteAddedItem = function (oEvent)
{
	var oDiv;

	// A registerCallback, e.g. PM preventing duplicate entries
	if (typeof oEvent === 'string')
	{
		oDiv = document.getElementById('suggest_' + this.opt.sSuggestId + '_' + oEvent);
	}

	// Or the remove button
	if (typeof oEvent === 'object')
	{
		oDiv = oEvent.target.parentNode;
	}

	// Remove the div if it exists.
	if (oDiv !== null)
	{
		this.oItemList.removeChild(oDiv);

		// Decrease the internal item count.
		this.iItemCount--;

		// If there's a registered callback, call it.
		if (typeof this.oCallback.onAfterDeleteItem === 'function')
		{
			this.oCallback.onAfterDeleteItem.call(this);
		}
	}

	return false;
};

// Hide the box.
smc_AutoSuggest.prototype.autoSuggestHide = function ()
{
	// Delay to allow events to propagate through....
	this.oHideTimer = setTimeout(this.autoSuggestActualHide.bind(this), 350);
};

// Do the actual hiding after a timeout.
smc_AutoSuggest.prototype.autoSuggestActualHide = function ()
{
	this.oSuggestDivHandle.style.display = 'none';
	this.oSuggestDivHandle.style.visibility = 'hidden';
	this.oSelectedDiv = null;
};

// Show the box.
smc_AutoSuggest.prototype.autoSuggestShow = function ()
{
	if (this.oHideTimer)
	{
		clearTimeout(this.oHideTimer);
		this.oHideTimer = false;
	}

	this.positionDiv();
	this.oSuggestDivHandle.style.visibility = 'visible';
	this.oSuggestDivHandle.style.display = '';
};

// Populate the actual div.
smc_AutoSuggest.prototype.populateDiv = function (aResults)
{
	// Cannot have any children yet.
	while (this.oSuggestDivHandle.childNodes.length > 0)
	{
		// Tidy up the events etc too.
		this.oSuggestDivHandle.childNodes[0].onmouseover = null;
		this.oSuggestDivHandle.childNodes[0].onmouseout = null;
		this.oSuggestDivHandle.childNodes[0].onclick = null;

		this.oSuggestDivHandle.removeChild(this.oSuggestDivHandle.childNodes[0]);
	}

	// Something to display?
	if (typeof aResults === 'undefined')
	{
		this.aDisplayData = [];
		return false;
	}

	var aNewDisplayData = [];
	for (var i = 0; i < (aResults.length > this.iMaxDisplayQuantity ? this.iMaxDisplayQuantity : aResults.length); i++)
	{
		// Create the sub element
		var oNewDivHandle = document.createElement('div');

		oNewDivHandle.sItemId = aResults[i].sItemId;
		oNewDivHandle.className = 'auto_suggest_item';
		oNewDivHandle.innerHTML = aResults[i].sItemName;
		//oNewDivHandle.style.width = this.oTextHandle.style.width;

		this.oSuggestDivHandle.appendChild(oNewDivHandle);

		// Attach some events to it so we can do stuff.
		oNewDivHandle.onmouseover = function ()
		{
			this.className = 'auto_suggest_item_hover';
		};
		oNewDivHandle.onmouseout = function ()
		{
			this.className = 'auto_suggest_item';
		};
		oNewDivHandle.onclick = this.itemClicked.bind(this);

		aNewDisplayData[i] = oNewDivHandle;
	}

	this.aDisplayData = aNewDisplayData;

	return true;
};

// Callback function for the XML request, should contain the list of users that match
smc_AutoSuggest.prototype.onSuggestionReceived = function (oXMLDoc)
{
	if (oXMLDoc === false)
	{
		return;
	}

	let aItems = oXMLDoc.getElementsByTagName('item');

	// Go through each item received
	this.aCache = [];
	for (var i = 0; i < aItems.length; i++)
	{
		this.aCache[i] = {
			sItemId: aItems[i].getAttribute('id'),
			sItemName: aItems[i].childNodes[0].nodeValue
		};

		// If we're doing auto add and we found the exact person, then add them!
		if (this.bDoAutoAdd && this.sLastSearch === this.aCache[i].sItemName)
		{
			var oReturnValue = {
				sItemId: this.aCache[i].sItemId,
				sItemName: this.aCache[i].sItemName
			};

			this.aCache = [];
			return this.addItemLink(oReturnValue.sItemId, oReturnValue.sItemName, true);
		}
	}

	// Check we don't try to keep auto updating!
	this.bDoAutoAdd = false;

	// Populate the div.
	this.populateDiv(this.aCache);

	// Make sure we can see it - if we can.
	if (aItems.length === 0)
	{
		this.autoSuggestHide();
	}
	else
	{
		this.autoSuggestShow();
	}

	return true;
};

// Get a new suggestion.
smc_AutoSuggest.prototype.autoSuggestUpdate = function ()
{
	// If there's a callback then call it.
	if (typeof this.oCallback.onBeforeUpdate === 'function')
	{
		// If it returns false the item must not be added.
		if (!this.oCallback.onBeforeUpdate.call(this))
		{
			return false;
		}
	}

	this.oRealTextHandle.value = this.oTextHandle.value;

	if (isEmptyText(this.oTextHandle))
	{
		this.aCache = [];
		this.populateDiv();
		this.autoSuggestHide();

		return true;
	}

	// Nothing changed?
	if (this.oTextHandle.value === this.sLastDirtySearch)
	{
		return true;
	}
	this.sLastDirtySearch = this.oTextHandle.value;

	// We're only actually interested in the last string.
	var sSearchString = this.oTextHandle.value.replace(/^("[^"]+",[ ]*)+/, '').replace(/^([^,]+,[ ]*)+/, '');
	if (sSearchString.substr(0, 1) === '"')
	{
		sSearchString = sSearchString.substr(1);
	}

	// Stop replication ASAP.
	var sRealLastSearch = this.sLastSearch;
	this.sLastSearch = sSearchString;

	// Either nothing or we've completed a sentence.
	if (sSearchString === '' || sSearchString.substr(sSearchString.length - 1) === '"')
	{
		this.populateDiv();
		return true;
	}

	// Nothing?
	if (sRealLastSearch === sSearchString)
	{
		return true;
	}
	// Too small?
	else if (sSearchString.length < this.iMinimumSearchChars)
	{
		this.aCache = [];
		this.autoSuggestHide();
		return true;
	}
	else if (sSearchString.substr(0, sRealLastSearch.length) === sRealLastSearch)
	{
		// Instead of hitting the server again, just narrow down the results...
		var aNewCache = [],
			j = 0,
			sLowercaseSearch = sSearchString.toLowerCase();

		for (var k = 0; k < this.aCache.length; k++)
		{
			if (this.aCache[k].sItemName.substr(0, sSearchString.length).toLowerCase() === sLowercaseSearch)
			{
				aNewCache[j++] = this.aCache[k];
			}
		}

		this.aCache = [];
		if (aNewCache.length !== 0)
		{
			this.aCache = aNewCache;

			// Repopulate.
			this.populateDiv(this.aCache);

			// Check it can be seen.
			this.autoSuggestShow();

			return true;
		}
	}

	// In progress means destroy!
	if (typeof this.oXmlRequestHandle === 'object' && this.oXmlRequestHandle !== null)
	{
		this.oXmlRequestHandle.abort();
	}

	// Clean the text handle.
	sSearchString = sSearchString.php_urlencode();

	// Get the document.
	var obj = {
			"suggest_type": this.opt.sSearchType,
			"search": sSearchString,
			"time": new Date().getTime()
		},
		postString;

	// Post values plus session
	postString = "jsonString=" + JSON.stringify(obj) + "&" + this.opt.sSessionVar + "=" + this.opt.sSessionId;

	sendXMLDocument.call(this, this.sRetrieveURL.replace(/%scripturl%/g, elk_prepareScriptUrl(elk_scripturl)), postString, this.onSuggestionReceived);

	return true;
};


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

public static class Program {
    public static void Main () {
        var ints = new[] { 1, 2, 3, 4 };

        foreach (var i in ints.Skip(2))
            Console.WriteLine(i);

    }
}

redpajama_set_name: RedPajamaGithub


text:
package api

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/go-martini/martini"
	"launchpad.net/gocheck"

	"github.com/wiliamsouza/apollo/db"
	"github.com/wiliamsouza/apollo/test"
	"github.com/wiliamsouza/apollo/token"
)

func (s *S) TestNewCicle(c *gocheck.C) {
	// It returns Id too we remove it cause we can't predict before hand what it will be
	b := `{"name":"Test maguro","device":"maguro","packages":["bluetooth.jar","wifi.jar"]}`
	defer db.Session.Cicle().DropCollection()
	body := strings.NewReader(b)
	request, err := http.NewRequest("POST", "cicles", body)
	c.Assert(err, gocheck.IsNil)
	t, err := token.New("jhon@doe.com")
	c.Assert(err, gocheck.IsNil)
	request.Header.Set("Authorization", fmt.Sprintf("Bearer %v", t))
	tt, err := token.Validate(request)
	c.Assert(err, gocheck.IsNil)
	request.Header.Set("Content-Type", "application/json")
	response := httptest.NewRecorder()
	tk := &token.Token{Email: tt.Claims["email"].(string), Exp: tt.Claims["exp"].(float64)}
	NewCicle(response, request, tk)
	c.Assert(response.Code, gocheck.Equals, http.StatusCreated)
	var r test.Cicle
	err = json.Unmarshal([]byte(response.Body.String()), &r)
	c.Assert(err, gocheck.IsNil)
	cicle := test.Cicle{Name: r.Name, Device: r.Device, Packages: r.Packages}
	result, err := json.Marshal(cicle)
	c.Assert(err, gocheck.IsNil)
	ct := response.HeaderMap["Content-Type"][0]
	c.Assert(ct, gocheck.Equals, "application/json; charset=utf-8")
	c.Assert(string(result), gocheck.Equals, b)
}

func (s *S) TestNewCicleInvalidJson(c *gocheck.C) {
	result := "Error parssing json request, unexpected end of JSON input\n"
	invalid := `{"name":"Test maguro","device":"maguro","packages":["bluetooth.jar","wifi.jar"]`
	body := strings.NewReader(invalid)
	request, err := http.NewRequest("POST", "cicles", body)
	c.Assert(err, gocheck.IsNil)
	t, err := token.New("jhon@doe.com")
	c.Assert(err, gocheck.IsNil)
	request.Header.Set("Authorization", fmt.Sprintf("Bearer %v", t))
	tt, err := token.Validate(request)
	c.Assert(err, gocheck.IsNil)
	request.Header.Set("Content-Type", "application/json")
	response := httptest.NewRecorder()
	tk := &token.Token{Email: tt.Claims["email"].(string), Exp: tt.Claims["exp"].(float64)}
	NewCicle(response, request, tk)
	c.Assert(response.Code, gocheck.Equals, http.StatusBadRequest)
	ct := response.HeaderMap["Content-Type"][0]
	c.Assert(ct, gocheck.Equals, "text/plain; charset=utf-8")
	c.Assert(response.Body.String(), gocheck.Equals, result)
}

func (s *S) TestListCicles(c *gocheck.C) {
	r := `[{"id":"%v","name":"Test maguro","device":"maguro","packages":["bluetooth.jar","wifi.jar"]},{"id":"%v","name":"Test yakju","device":"yakju","packages":["bluetooth.jar","wifi.jar"]}]`
	cicle1 := test.Cicle{Name: "Test maguro", Device: "maguro",
		Packages: []string{"bluetooth.jar", "wifi.jar"}}
	cicle2 := test.Cicle{Name: "Test yakju", Device: "yakju",
		Packages: []string{"bluetooth.jar", "wifi.jar"}}
	test1, err := test.NewCicle(cicle1)
	c.Assert(err, gocheck.IsNil)
	test2, err := test.NewCicle(cicle2)
	c.Assert(err, gocheck.IsNil)
	defer db.Session.Cicle().RemoveId(test1.Id)
	defer db.Session.Cicle().RemoveId(test2.Id)
	request, err := http.NewRequest("GET", "cicles", nil)
	c.Assert(err, gocheck.IsNil)
	tkn, err := token.New("jhon@doe.com")
	c.Assert(err, gocheck.IsNil)
	request.Header.Set("Authorization", fmt.Sprintf("Bearer %v", tkn))
	tt, err := token.Validate(request)
	c.Assert(err, gocheck.IsNil)
	response := httptest.NewRecorder()
	tk := &token.Token{Email: tt.Claims["email"].(string), Exp: tt.Claims["exp"].(float64)}
	ListCicles(response, request, tk)
	c.Assert(response.Code, gocheck.Equals, http.StatusOK)
	results := fmt.Sprintf(r, test1.Id.Hex(), test2.Id.Hex())
	ct := response.HeaderMap["Content-Type"][0]
	c.Assert(ct, gocheck.Equals, "application/json; charset=utf-8")
	c.Assert(response.Body.String(), gocheck.Equals, results)
}

func (s *S) TestDetailCicle(c *gocheck.C) {
	r := `{"id":"%v","name":"Test maguro","device":"maguro","packages":["bluetooth.jar","wifi.jar"]}`
	cicle := test.Cicle{Name: "Test maguro", Device: "maguro",
		Packages: []string{"bluetooth.jar", "wifi.jar"}}
	testCicle, err := test.NewCicle(cicle)
	c.Assert(err, gocheck.IsNil)
	result := fmt.Sprintf(r, testCicle.Id.Hex())
	defer db.Session.Cicle().RemoveId(testCicle.Id)
	url := fmt.Sprintf("cicles/%s", testCicle.Id.Hex())
	request, err := http.NewRequest("GET", url, nil)
	c.Assert(err, gocheck.IsNil)
	tkn, err := token.New("jhon@doe.com")
	c.Assert(err, gocheck.IsNil)
	request.Header.Set("Authorization", fmt.Sprintf("Bearer %v", tkn))
	tt, err := token.Validate(request)
	c.Assert(err, gocheck.IsNil)
	response := httptest.NewRecorder()
	tk := &token.Token{Email: tt.Claims["email"].(string), Exp: tt.Claims["exp"].(float64)}
	p := make(map[string]string)
	p["id"] = testCicle.Id.Hex()
	params := martini.Params(p)
	DetailCicle(response, request, tk, params)
	c.Assert(response.Code, gocheck.Equals, http.StatusOK)
	ct := response.HeaderMap["Content-Type"][0]
	c.Assert(ct, gocheck.Equals, "application/json; charset=utf-8")
	c.Assert(response.Body.String(), gocheck.Equals, result)
}

func (s *S) TestModifyCicle(c *gocheck.C) {
	cicle := test.Cicle{Name: "Test maguro", Device: "maguro",
		Packages: []string{"bluetooth.jar", "wifi.jar"}}
	testCicle, err := test.NewCicle(cicle)
	c.Assert(err, gocheck.IsNil)
	r := `{"id":"%v","name":"Test yakju","device":"yakju","packages":["bluetooth.jar","wifi.jar"]}`
	b := fmt.Sprintf(r, testCicle.Id.Hex())
	body := strings.NewReader(b)
	defer db.Session.Cicle().RemoveId(testCicle.Id)
	url := fmt.Sprintf("cicles/%s", testCicle.Id.Hex())
	var org test.Cicle
	err = json.Unmarshal([]byte(b), &org)
	c.Assert(err, gocheck.IsNil)
	request, err := http.NewRequest("PUT", url, body)
	c.Assert(err, gocheck.IsNil)
	tkn, err := token.New("jhon@doe.com")
	c.Assert(err, gocheck.IsNil)
	request.Header.Set("Authorization", fmt.Sprintf("Bearer %v", tkn))
	tt, err := token.Validate(request)
	c.Assert(err, gocheck.IsNil)
	request.Header.Set("Content-Type", "application/json")
	response := httptest.NewRecorder()
	tk := &token.Token{Email: tt.Claims["email"].(string), Exp: tt.Claims["exp"].(float64)}
	p := make(map[string]string)
	p["id"] = testCicle.Id.Hex()
	params := martini.Params(p)
	ModifyCicle(response, request, tk, params)
	c.Assert(response.Code, gocheck.Equals, http.StatusOK)
	var orgDb test.Cicle
	err = db.Session.Cicle().FindId(testCicle.Id).One(&orgDb)
	c.Assert(err, gocheck.IsNil)
	c.Assert(orgDb, gocheck.DeepEquals, org)
}

func (s *S) TestDeleteCicle(c *gocheck.C) {
	cicle := test.Cicle{Name: "Test maguro", Device: "maguro",
		Packages: []string{"bluetooth.jar", "wifi.jar"}}
	testCicle, err := test.NewCicle(cicle)
	c.Assert(err, gocheck.IsNil)
	url := fmt.Sprintf("cicles/%s", testCicle.Id.Hex())
	request, err := http.NewRequest("DELETE", url, nil)
	c.Assert(err, gocheck.IsNil)
	tkn, err := token.New("jhon@doe.com")
	c.Assert(err, gocheck.IsNil)
	request.Header.Set("Authorization", fmt.Sprintf("Bearer %v", tkn))
	tt, err := token.Validate(request)
	c.Assert(err, gocheck.IsNil)
	response := httptest.NewRecorder()
	tk := &token.Token{Email: tt.Claims["email"].(string), Exp: tt.Claims["exp"].(float64)}
	p := make(map[string]string)
	p["id"] = testCicle.Id.Hex()
	params := martini.Params(p)
	DeleteCicle(response, request, tk, params)
	c.Assert(response.Code, gocheck.Equals, http.StatusOK)
	lenght, err := db.Session.Cicle().FindId(testCicle.Id).Count()
	c.Assert(err, gocheck.IsNil)
	c.Assert(lenght, gocheck.Equals, 0)
}

func (s *S) TestDeleteCicleNoExist(c *gocheck.C) {
	result := "Error deleting cicle, Invalid cicle object id hex\n"
	cicle := test.Cicle{Name: "Test maguro", Device: "maguro",
		Packages: []string{"bluetooth.jar", "wifi.jar"}}
	testCicle, err := test.NewCicle(cicle)
	c.Assert(err, gocheck.IsNil)
	defer db.Session.Cicle().RemoveId(testCicle.Id)
	url := fmt.Sprintf("cicles/%s", "noexist")
	request, err := http.NewRequest("DELETE", url, nil)
	c.Assert(err, gocheck.IsNil)
	tkn, err := token.New("jhon@doe.com")
	c.Assert(err, gocheck.IsNil)
	request.Header.Set("Authorization", fmt.Sprintf("Bearer %v", tkn))
	tt, err := token.Validate(request)
	c.Assert(err, gocheck.IsNil)
	response := httptest.NewRecorder()
	tk := &token.Token{Email: tt.Claims["email"].(string), Exp: tt.Claims["exp"].(float64)}
	p := make(map[string]string)
	p["id"] = "noexist"
	params := martini.Params(p)
	DeleteCicle(response, request, tk, params)
	c.Assert(response.Code, gocheck.Equals, http.StatusBadRequest)
	c.Assert(response.Body.String(), gocheck.Equals, result)
}


text:
package org.ujorm.extensions;

import junit.framework.TestCase;
import org.ujorm.criterion.Operator;
import java.util.Date;
import java.io.Serializable;
import java.util.List;
import org.ujorm.implementation.quick.SmartUjo;

/**
 * PropertyTest
 * @author Pavel Ponec
 */
public class PropertyTest extends TestCase {

    /** Number zero */
    private static final Integer NIL = 0;
    /** Number one */
    private static final Integer ONE = 1;
    /** Number tow */
    private static final Integer TWO = 2;

    public PropertyTest(String testName) {
        super(testName);
    }

    /**
     * Test of getName method, of class Property.
     */
    public void testGetName() {
        System.out.println("getName");
        assertEquals("id", Person.ID.getName());
        assertEquals("born", Person.BORN.getName());
        assertEquals("mother", Person.MOTHER.getName());
        assertEquals("children", Person.CHILDREN.getName());
        assertEquals("mother.born", Person.MOTHER.add(Person.BORN).getName());
    }

    /**
     * Test of getFullName method, of class Property.
     */
    public void testGetFullName() {
        System.out.println("getFullName");
        assertEquals("Person.id", Person.ID.getFullName());
        assertEquals("Person.born", Person.BORN.getFullName());
        assertEquals("Person.mother", Person.MOTHER.getFullName());
        assertEquals("Person.children", Person.CHILDREN.getFullName());
    }

    /**
     * Test of getType method, of class Property.
     */
    public void testGetType() {
        System.out.println("getType");
        assertEquals(Integer.class, Person.ID.getType());
        assertEquals(Date.class, Person.BORN.getType());
        assertEquals(Person.class, Person.MOTHER.getType());
        assertEquals(List.class, Person.CHILDREN.getType());
    }

    /**
     * Test of getDomainType method, of class Property.
     */
    public void testGetDomainType() {
        System.out.println("getDomainType");
        assertEquals(Person.class, Person.ID.getDomainType());
        assertEquals(Person.class, Person.BORN.getDomainType());
        assertEquals(Person.class, Person.MOTHER.getDomainType());
        assertEquals(Person.class, Person.CHILDREN.getDomainType());
    }

    /**
     * Test of getIndex method, of class Property.
     */
    public void testGetIndex() {
        System.out.println("getIndex");
        assertEquals(0, Person.ID.getIndex());
        assertEquals(1, Person.BORN.getIndex());
        assertEquals(2, Person.MOTHER.getIndex());
        assertEquals(3, Person.CHILDREN.getIndex());
    }

    /**
     * Test of the {@code getValue} method, from a Property class.
     */
    public void testGetValue() {
        System.out.println("getValue");
        Integer expectedResult = TWO;
        Person ujo = new Person(expectedResult);
        assertSame(expectedResult, Person.ID.getValue(ujo));
        assertSame(expectedResult, ujo.get(Person.ID));
    }

    /**
     * Test of the {@code of} method, from a Property class.
     */
    public void testOf() {
        System.out.println("of");
        Integer expectedResult = TWO;
        Person ujo = new Person(expectedResult);
        assertSame(expectedResult, Person.ID.of(ujo));
        assertSame(expectedResult, ujo.get(Person.ID));
    }

    /**
     * Test of getDefault method, of class Property.
     */
    public void testGetDefault() {
        System.out.println("getDefault");
        assertSame(NIL, Person.ID.getDefault());
        assertNull(Person.BORN.getDefault());
        assertNull(Person.MOTHER.getDefault());
        assertNull(Person.CHILDREN.getDefault());
    }

    /**
     * Test of isDefault method, of class Property.
     */
    public void testIsDefault() {
        System.out.println("isDefault");
        assertSame(NIL , Person.ID.getDefault());
        assertSame(null, Person.BORN.getDefault());
        assertSame(null, Person.MOTHER.getDefault());
        assertSame(null, Person.CHILDREN.getDefault());
        //
        assertEquals(NIL, new Person(null).getId());
        assertEquals(NIL, new Person(NIL).getId());
        assertEquals(ONE, new Person(ONE).getId());
        assertEquals(TWO, new Person(TWO).getId());
    }

    /**
     * Test of isComposite method, of class Property.
     */
    public void testIsComposite() {
        System.out.println("isComposite");
        assertFalse(Person.ID.isComposite());
        assertFalse(Person.BORN.isComposite());
        assertFalse(Person.MOTHER.isComposite());
        assertTrue (Person.MOTHER.add(Person.MOTHER).isComposite());
    }

    /**
     * Test of isAscending method, of class Property.
     */
    public void testIsAscending() {
        System.out.println("isAscending");
        assertTrue (Person.BORN.isAscending());
        assertFalse(Person.BORN.descending().isAscending());
        assertTrue (Person.MOTHER.isAscending());
        assertFalse(Person.MOTHER.add(Person.MOTHER).descending().isAscending());
    }

    /**
     * Test of copy method, of class Property.
     */
    public void testCopy() {
        System.out.println("copy");
        Person u1 = new Person(ONE);
        Person u2 = new Person(TWO);
        Person.ID.copy(u1, u2);

        assertSame(ONE, u1.getId());
        assertSame(ONE, u2.getId());
        assertTrue(Person.ID.equals(u1,ONE));
        assertTrue(Person.ID.equals(u2,ONE));
        assertSame(u1.getId(), u2.getId());
    }

    /**
     * Test of isTypeOf method, of class Property.
     */
    public void testIsTypeOf() {
        System.out.println("isTypeOf");
        assertTrue (Person.ID.isTypeOf(Object.class));
        assertTrue (Person.ID.isTypeOf(Number.class));
        assertTrue (Person.ID.isTypeOf(Serializable.class));
        assertTrue (Person.ID.isTypeOf(Integer.class));
        assertFalse(Person.ID.isTypeOf(String.class));
        assertFalse(Person.ID.isTypeOf(Person.class));
        //
        assertTrue (Person.BORN.isTypeOf(Object.class));
        assertTrue (Person.BORN.isTypeOf(Serializable.class));
        assertTrue (Person.BORN.isTypeOf(java.util.Date.class));
        assertFalse(Person.BORN.isTypeOf(java.sql.Date.class));
        assertFalse(Person.BORN.isTypeOf(Number.class));
        assertFalse(Person.BORN.isTypeOf(Integer.class));
        assertFalse(Person.BORN.isTypeOf(Person.class));
        //
        assertTrue (Person.MOTHER.isTypeOf(Object.class));
        assertTrue (Person.MOTHER.isTypeOf(Serializable.class));
        assertTrue (Person.MOTHER.isTypeOf(Person.class));
        assertFalse(Person.MOTHER.isTypeOf(java.util.Date.class));
        assertFalse(Person.MOTHER.isTypeOf(java.sql.Date.class));
        assertFalse(Person.MOTHER.isTypeOf(Number.class));
        assertFalse(Person.MOTHER.isTypeOf(Integer.class));
        assertFalse(Person.MOTHER.isTypeOf(new Person(1) {
        }.getClass()));
        //
        assertTrue (Person.CHILDREN.isTypeOf(Object.class));
        assertTrue (Person.CHILDREN.isTypeOf(List.class));
        assertFalse(Person.CHILDREN.isTypeOf(Integer.class));
        assertFalse(Person.CHILDREN.isTypeOf(Person.class));
    }

    /**
     * Test of isDomainOf method, of class Property.
     */
    public void testIsDomainOf() {
        System.out.println("isDomainOf");
        assertTrue (Person.BORN.isDomainOf(Object.class));
        assertTrue (Person.BORN.isDomainOf(SmartUjo.class));
        assertTrue (Person.BORN.isDomainOf(Person.class));
        assertFalse(Person.BORN.isDomainOf(Date.class));
        assertFalse(Person.BORN.isDomainOf(Integer.class));
        assertFalse(Person.BORN.isDomainOf((new Person(1){}).getClass()));
    }

    /**
     * Test of equals method, of class Property.
     */
    public void testEquals() {
        System.out.println("equals");
        Integer id = TWO;
        Person ujo = new Person(id);
        assertTrue(Person.ID.equals(ujo, id));
    }

    /**
     * Test of equalsName method, of class Property.
     */
    public void testEqualsName() {
        System.out.println("equalsName");
        assertTrue(Person.ID.equalsName(Person.ID.getName()));
    }

    /**
     * Test of compareTo method, of class Property.
     */
    public void testCompareTo() {
        System.out.println("compareTo");
        assertEquals(-1, Person.BORN.compareTo(Person.MOTHER));
        assertEquals( 0, Person.MOTHER.compareTo(Person.MOTHER));
        assertEquals(+1, Person.CHILDREN.compareTo(Person.MOTHER));
    }

    /**
     * Test of charAt method, of class Property.
     */
    public void testCharAt() {
        System.out.println("charAt");
        assertEquals('b', Person.BORN.charAt(0));
        assertEquals('o', Person.BORN.charAt(1));
        assertEquals('r', Person.BORN.charAt(2));
        assertEquals('n', Person.BORN.charAt(3));
    }

    /**
     * Test of length method, of class Property.
     */
    public void testLength() {
        System.out.println("length");
        assertEquals("born".length(), Person.BORN.length());
    }

    /**
     * Test of subSequence method, of class Property.
     */
    public void testSubSequence() {
        System.out.println("subSequence");
        assertEquals("b", Person.BORN.subSequence(0, 1));
        assertEquals("o", Person.BORN.subSequence(1, 2));
        assertEquals("r", Person.BORN.subSequence(2, 3));
        assertEquals("n", Person.BORN.subSequence(3, 4));
    }

    /**
     * Test of toString method, of class Property.
     */
    public void testToString() {
        System.out.println("toString");
        assertEquals("born"  , Person.BORN.toString());
        assertEquals("mother", Person.MOTHER.toString());
        //
        assertSame(Person.BORN.getName()  , Person.BORN.toString());
        assertSame(Person.MOTHER.getName(), Person.MOTHER.toString());
    }

    /**
     * Test of where method, of class Property.
     */
    public void testWhere() {
        System.out.println("where");
        assertTrue(Person.ID.whereEq(TWO).evaluate(new Person(TWO)));
        assertTrue(Person.ID.whereEq(ONE).evaluate(new Person(ONE)));
        assertTrue(Person.ID.whereEq(NIL).evaluate(new Person(null)));
        //
        assertTrue(Person.ID.whereLt(TWO).evaluate(new Person(ONE)));
        assertTrue(Person.ID.whereLt(ONE).evaluate(new Person(NIL)));
        assertFalse(Person.ID.whereLt(NIL).evaluate(new Person(NIL)));
    }

    /**
     * Test of forSql method, of class Property.
     */
    public void testForSql() {
        System.out.println("forSql");
        assertSame(Operator.XSQL, Person.ID.forSql("{0}=1").getOperator());
    }

    /**
     * Test of forAll method, of class Property.
     */
    public void testForAll() {
        System.out.println("forAll");
        assertTrue(Person.ID.forAll().evaluate(new Person(null)));
        assertTrue(Person.ID.forAll().evaluate(new Person(NIL)));
        assertTrue(Person.ID.forAll().evaluate(new Person(ONE)));
        assertTrue(Person.ID.forAll().evaluate(new Person(TWO)));
    }

    /**
     * Test of forNone method, of class Property.
     */
    public void testForNone() {
        System.out.println("forNone");
        assertFalse(Person.ID.forNone().evaluate(new Person(null)));
        assertFalse(Person.ID.forNone().evaluate(new Person(NIL)));
        assertFalse(Person.ID.forNone().evaluate(new Person(ONE)));
        assertFalse(Person.ID.forNone().evaluate(new Person(TWO)));
    }

}


text:
Rails.application.config.assets.version = '1.0'

# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# Rails.application.config.assets.precompile += %w( search.js )

# Need to initialize Rails environment for issue_tracker_icons.css.erb
Rails.application.config.assets.initialize_on_precompile = true


text:
package org.gradoop.temporal.model.impl.functions.predicates;

import org.gradoop.temporal.model.api.functions.TemporalPredicate;

import java.time.LocalDateTime;

import static org.gradoop.temporal.util.TimeFormatConversion.toEpochMilli;

/**
 * Implementation of the Between temporal predicate.
 * Given a certain time-interval, this predicate will match all intervals that start
 * before or at that interval's end and end after the start of that interval.
 *

 * Predicate: {@code elementFrom <= queryTo && elementTo > queryFrom}
 */
public class Between implements TemporalPredicate {

  /**
   * The start of the query time-interval in Milliseconds since Unix Epoch.
   */
  private final long queryFrom;

  /**
   * The end of the query time-interval in Milliseconds since Unix Epoch.
   */
  private final long queryTo;

  /**
   * Creates a Between instance with the given time stamps.
   *
   * @param from The start of the query time-interval in Milliseconds since Unix Epoch.
   * @param to   The end of the query time-interval in Milliseconds since Unix Epoch.
   */
  public Between(long from, long to) {
    queryFrom = from;
    queryTo = to;
  }

  /**
   * Creates a Between instance with the given time stamps.
   * The provided arguments will be converted to milliseconds since Unix Epoch for UTC time zone.
   *
   * @param from The beginning of the query time-interval.
   * @param to The end of the query time-interval.
   */
  public Between(LocalDateTime from, LocalDateTime to) {
    queryFrom = toEpochMilli(from);
    queryTo = toEpochMilli(to);
  }

  @Override
  public boolean test(long from, long to) {
    return from <= queryTo && to > queryFrom;
  }

  @Override
  public String toString() {
    return "BETWEEN " + queryFrom + " AND " + queryTo;
  }
}


text:
package org.olat.system.mail;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

import org.apache.log4j.Logger;
import org.olat.system.commons.StringHelper;
import org.olat.system.logging.log4j.LoggerHelper;
import org.olat.system.security.OLATPrincipal;

/**
 * The ContactList is used to group e-mail addresses and name such a group. It is the frameworks implementation of a MailList. The e-mail adresses are given either by
 * providing them as strings or in the form of identities (OLATPrincipal). Further it is possible to add all contacts from another ContactList.
 *

 * TODO:pb:a remove dependency to EmailPrioInstitutional if a solution for core.id.user is found Moreover one can specify to use the users institional e-mail
 * first and use the other e-mail as fall-back. Initial Date: Sep 23, 2004
 *
 * @author patrick
 */

public class ContactList {

    private String name;
    private String description;
    // container for addresses contributed as strings
	private Hashtable<String, String> stringEmails = new Hashtable<String, String>();
	// container for addresses contributed as olatprincipals
    private Hashtable<String, OLATPrincipal> emailToIdentityMap = new Hashtable<String, OLATPrincipal>();
    private boolean emailPrioInstitutional = false;
    private static final Logger log = LoggerHelper.getLogger();

    /**
     * A ContacList must have at least a name != null, matching ^[^;,:]*$
     *
     * @param name
     */
    public ContactList(String name) {
        setName(name);
        this.description = null;
    }

    /**
     * A ContactList must have at least a name != null, matching ^[a-zA-Z ]*$, and can have a description.
     *
     * @param name
     * @param description
     */
    public ContactList(String name, String description) {
        setName(name);
        this.description = description;
    }

    /**
     * check the priority of the institutional mail is set.
     *
     * @return Returns the emailPrioInstitutional.
     */
    public boolean isEmailPrioInstitutional() {
        return emailPrioInstitutional;
    }

    /**
     * set the priority of the institutional mail.
     *
     * @param emailPrioInstitutional
     *            The emailPrioInstitutional to set.
     */
    public void setEmailPrioInstitutional(boolean emailPrioInstitutional) {
        this.emailPrioInstitutional = emailPrioInstitutional;
    }

    /**
     * contribute a contact as a string email address.
     *
     * @param emailAddress
     */
    public void add(String emailAddress) {
        stringEmails.put(keyFrom(emailAddress), emailAddress);
    }

    /**
     * contribute a contact as an identity.
     *
     * @param identity
     */
    public void add(OLATPrincipal principal) {
        String email = principal.getAttributes().getEmail();
        emailToIdentityMap.put(keyFrom(email), principal);
    }

    public void remove(OLATPrincipal principal) {
        String email = principal.getAttributes().getEmail();
        emailToIdentityMap.remove(keyFrom(email));
    }

    /**
     * Name getter
     *
     * @return
     */
    public String getName() {
        return name;
    }

    /**
     * ContactList-name as String formatted according to  RFC2822
     *
     * @return
     */
    public String getRFC2822Name() {
        return name + ":";
    }

    /**
     * ContactList-name and e-mail adresses as String formatted according to http://www.rfc.net/rfc2822.html
     *
     * @return
     */
    public String getRFC2822NameWithAddresses() {
        return name + ":" + toString() + ";";
    }

    /**
     * Description getter
     *
     * @return
     */
    public String getDescription() {
        return description;
    }

    /**
     * the returned ArrayList contains String Objects representing the e-mail addresses added.
     *
     * @return
     */
    public ArrayList<String> getEmailsAsStrings() {
        ArrayList<String> ret = new ArrayList<String>(stringEmails.values());
        /*
         * if priority is on institutional email get all the institutional emails first, if they are present, remove the identity from the hashtable. If they were not
         * present, the user email is used in the next loop.
         */
        Enumeration<OLATPrincipal> enumeration = emailToIdentityMap.elements();
        String addEmail = null;
        if (emailPrioInstitutional) {
            while (enumeration.hasMoreElements()) {
                OLATPrincipal tmp = enumeration.nextElement();
                addEmail = tmp.getAttributes().getInstitutionalEmail();
                if (addEmail != null) {
                    ret.add(addEmail);
                    emailToIdentityMap.remove(tmp);
                }
            }
        }
        /*
         * loops over the (remaining) identities, fetches the user email.
         */
        while (enumeration.hasMoreElements()) {
            OLATPrincipal tmp = enumeration.nextElement();
            ret.add(tmp.getAttributes().getEmail());
        }
        return ret;
    }

    /**
     * add members of another ContactList to this ContactList.
     *
     * @param emailList
     */
    public void add(ContactList emailList) {
        stringEmails.putAll(emailList.getStringEmails());
        emailToIdentityMap.putAll(emailList.getIdentityEmails());
    }

    /**
     * A comma separated list of e-mail addresses. The ContactList name is ommitted, if the form
     * ContactList.Name:member1@host.suffix,member2@host.suffix,...,memberN@host.suffix; is needed, please use the appropriate getRFC2822xxx getter method.
     *
     */
    @Override
    public String toString() {
        String retVal = "";
        String sep = "";
        ArrayList emails = getEmailsAsStrings();
        Iterator iter = emails.iterator();
        while (iter.hasNext()) {
            retVal += sep + (String) iter.next();
            sep = ", ";
        }
        return retVal;
    }

    /**
     * add all identity-Objects in the provided list.
     *
     * @param listOfIdentity
     *            List containing OLATPrincipal
     */
    public void addAllIdentites(List<? extends OLATPrincipal> listOfIdentity) {
        Iterator<? extends OLATPrincipal> iter = listOfIdentity.iterator();
        while (iter.hasNext()) {
            add(iter.next());
        }
    }

    /**
     * The e-mail addresses are generated as InternetAddresses, the priority of the institutional email is taken in account.
     *
     * @return the email addresses as InternetAddresses
     * @throws AddressException
     */
    public InternetAddress[] getEmailsAsAddresses() throws AddressException {
        return InternetAddress.parse(toString());
    }

	Hashtable<String, String> getStringEmails() {
        return stringEmails;
    }

	public Hashtable<String, OLATPrincipal> getIdentityEmails() {
        return emailToIdentityMap;
    }

    private String keyFrom(String unformattedEmailAddr) {
        String key = unformattedEmailAddr.trim();
        return key.toUpperCase();
    }

    private void setName(String nameP) {
        if (!StringHelper.containsNoneOfCoDouSemi(nameP)) {
            log.warn("Contact list name \"" + nameP + "\" doesn't match " + StringHelper.ALL_WITHOUT_COMMA_2POINT_STRPNT, null);
            // replace bad chars with bad char in rfc compliant comments
            nameP = nameP.replaceAll(":", "¦");
            nameP = nameP.replaceAll(";", "_");
            nameP = nameP.replaceAll(",", "-");

        }

        this.name = nameP;
    }

}


text:
  for (::arrow::Status _st = ::arrow::internal::GenericToStatus((expr));          \
       !_st.Is##ENUM();)                                                          \
  FAIL() << "Expected '" ARROW_STRINGIFY(expr) "' to fail with " ARROW_STRINGIFY( \
                ENUM) ", but got "                                                \
         << _st.ToString()

#define ASSERT_RAISES_WITH_MESSAGE(ENUM, message, expr)                               \
  do {                                                                                \
    auto _res = (expr);                                                               \
    ::arrow::Status _st = ::arrow::internal::GenericToStatus(_res);                   \
    if (!_st.Is##ENUM()) {                                                            \
      FAIL() << "Expected '" ARROW_STRINGIFY(expr) "' to fail with " ARROW_STRINGIFY( \
                    ENUM) ", but got "                                                \
             << _st.ToString();                                                       \
    }                                                                                \
    ASSERT_EQ((message), _st.ToString());                                             \
  } while (false)

#define EXPECT_RAISES_WITH_MESSAGE_THAT(ENUM, matcher, expr)                             \
  do {                                                                                \
    auto _res = (expr);                                                                  \
    ::arrow::Status _st = ::arrow::internal::GenericToStatus(_res);                      \
    EXPECT_TRUE(_st.Is##ENUM()) << "Expected '" ARROW_STRINGIFY(expr) "' to fail with "  \
                                << ARROW_STRINGIFY(ENUM) ", but got " << _st.ToString(); \
    EXPECT_THAT(_st.ToString(), (matcher));                                              \
  } while (false)

#define EXPECT_RAISES_WITH_CODE_AND_MESSAGE_THAT(code, matcher, expr) \
  do {                                                                \
    auto _res = (expr);                                               \
    ::arrow::Status _st = ::arrow::internal::GenericToStatus(_res);   \
    EXPECT_EQ(_st.CodeAsString(), Status::CodeAsString(code));        \
    EXPECT_THAT(_st.ToString(), (matcher));                           \
  } while (false)

#define ASSERT_OK(expr)                                                              \
  for (::arrow::Status _st = ::arrow::internal::GenericToStatus((expr)); !_st.ok();) \
  FAIL() << "'" ARROW_STRINGIFY(expr) "' failed with " << _st.ToString()

#define ASSERT_OK_NO_THROW(expr) ASSERT_NO_THROW(ASSERT_OK(expr))

#define ARROW_EXPECT_OK(expr)                                           \
  do {                                                                  \
    auto _res = (expr);                                                 \
    ::arrow::Status _st = ::arrow::internal::GenericToStatus(_res);     \
    EXPECT_TRUE(_st.ok()) << "'" ARROW_STRINGIFY(expr) "' failed with " \
                          << _st.ToString();                            \
  } while (false)

#define ASSERT_NOT_OK(expr)                                                         \
  for (::arrow::Status _st = ::arrow::internal::GenericToStatus((expr)); _st.ok();) \
  FAIL() << "'" ARROW_STRINGIFY(expr) "' did not failed" << _st.ToString()

#define ABORT_NOT_OK(expr)                                          \
  do {                                                              \
    auto _res = (expr);                                             \
    ::arrow::Status _st = ::arrow::internal::GenericToStatus(_res); \
    if (ARROW_PREDICT_FALSE(!_st.ok())) {                           \
      _st.Abort();                                                  \
    }                                                               \
  } while (false);

#define ASSIGN_OR_HANDLE_ERROR_IMPL(handle_error, status_name, lhs, rexpr) \
  auto&& status_name = (rexpr);                                            \
  handle_error(status_name.status());                                      \
  lhs = std::move(status_name).ValueOrDie();

#define ASSERT_OK_AND_ASSIGN(lhs, rexpr) \
  ASSIGN_OR_HANDLE_ERROR_IMPL(           \
      ASSERT_OK, ARROW_ASSIGN_OR_RAISE_NAME(_error_or_value, __COUNTER__), lhs, rexpr);

#define ASSIGN_OR_ABORT(lhs, rexpr)                                                     \
  ASSIGN_OR_HANDLE_ERROR_IMPL(ABORT_NOT_OK,                                             \
                              ARROW_ASSIGN_OR_RAISE_NAME(_error_or_value, __COUNTER__), \
                              lhs, rexpr);

#define EXPECT_OK_AND_ASSIGN(lhs, rexpr)                                                \
  ASSIGN_OR_HANDLE_ERROR_IMPL(ARROW_EXPECT_OK,                                          \
                              ARROW_ASSIGN_OR_RAISE_NAME(_error_or_value, __COUNTER__), \
                              lhs, rexpr);

#define ASSERT_OK_AND_EQ(expected, expr)        \
  do {                                          \
    ASSERT_OK_AND_ASSIGN(auto _actual, (expr)); \
    ASSERT_EQ(expected, _actual);               \
  } while (0)

// A generalized version of GTest's SCOPED_TRACE that takes arbitrary arguments.
//   ARROW_SCOPED_TRACE("some variable = ", some_variable, ...)

#define ARROW_SCOPED_TRACE(...) SCOPED_TRACE(::arrow::util::StringBuilder(__VA_ARGS__))

namespace arrow {

// ----------------------------------------------------------------------
// Useful testing::Types declarations

inline void PrintTo(StatusCode code, std::ostream* os) {
  *os << Status::CodeAsString(code);
}

using NumericArrowTypes =
    ::testing::Types<UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int8Type, Int16Type,
                     Int32Type, Int64Type, FloatType, DoubleType>;

using RealArrowTypes = ::testing::Types<FloatType, DoubleType>;

using IntegralArrowTypes = ::testing::Types<UInt8Type, UInt16Type, UInt32Type, UInt64Type,
                                            Int8Type, Int16Type, Int32Type, Int64Type>;

using PhysicalIntegralArrowTypes =
    ::testing::Types<UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int8Type, Int16Type,
                     Int32Type, Int64Type, Date32Type, Date64Type, Time32Type, Time64Type,
                     TimestampType, MonthIntervalType>;

using PrimitiveArrowTypes =
    ::testing::Types<BooleanType, Int8Type, UInt8Type, Int16Type, UInt16Type, Int32Type,
                     UInt32Type, Int64Type, UInt64Type, FloatType, DoubleType>;

using TemporalArrowTypes =
    ::testing::Types<Date32Type, Date64Type, TimestampType, Time32Type, Time64Type>;

using DecimalArrowTypes = ::testing::Types<Decimal128Type, Decimal256Type>;

using BaseBinaryArrowTypes =
    ::testing::Types<BinaryType, LargeBinaryType, StringType, LargeStringType>;

using BinaryArrowTypes = ::testing::Types<BinaryType, LargeBinaryType>;

using StringArrowTypes = ::testing::Types<StringType, LargeStringType>;

using ListArrowTypes = ::testing::Types<ListType, LargeListType>;

using UnionArrowTypes = ::testing::Types<SparseUnionType, DenseUnionType>;

class Array;
class ChunkedArray;
class RecordBatch;
class Table;
struct Datum;

ARROW_TESTING_EXPORT
std::vector<Type::type> AllTypeIds();

#define ASSERT_ARRAYS_EQUAL(lhs, rhs) AssertArraysEqual((lhs), (rhs))
#define ASSERT_BATCHES_EQUAL(lhs, rhs) AssertBatchesEqual((lhs), (rhs))
#define ASSERT_BATCHES_APPROX_EQUAL(lhs, rhs) AssertBatchesApproxEqual((lhs), (rhs))
#define ASSERT_TABLES_EQUAL(lhs, rhs) AssertTablesEqual((lhs), (rhs))

// Default EqualOptions for testing
static inline EqualOptions TestingEqualOptions() {
  return EqualOptions{}.nans_equal(true).signed_zeros_equal(false);
}

// If verbose is true, then the arrays will be pretty printed
ARROW_TESTING_EXPORT void AssertArraysEqual(
    const Array& expected, const Array& actual, bool verbose = false,
    const EqualOptions& options = TestingEqualOptions());
ARROW_TESTING_EXPORT void AssertArraysApproxEqual(
    const Array& expected, const Array& actual, bool verbose = false,
    const EqualOptions& options = TestingEqualOptions());
// Returns true when values are both null
ARROW_TESTING_EXPORT void AssertScalarsEqual(
    const Scalar& expected, const Scalar& actual, bool verbose = false,
    const EqualOptions& options = TestingEqualOptions());
ARROW_TESTING_EXPORT void AssertScalarsApproxEqual(
    const Scalar& expected, const Scalar& actual, bool verbose = false,
    const EqualOptions& options = TestingEqualOptions());
ARROW_TESTING_EXPORT void AssertBatchesEqual(const RecordBatch& expected,
                                             const RecordBatch& actual,
                                             bool check_metadata = false);
ARROW_TESTING_EXPORT void AssertBatchesApproxEqual(const RecordBatch& expected,
                                                   const RecordBatch& actual);
ARROW_TESTING_EXPORT void AssertChunkedEqual(const ChunkedArray& expected,
                                             const ChunkedArray& actual);
ARROW_TESTING_EXPORT void AssertChunkedEqual(const ChunkedArray& actual,
                                             const ArrayVector& expected);
// Like ChunkedEqual, but permits different chunk layout
ARROW_TESTING_EXPORT void AssertChunkedEquivalent(const ChunkedArray& expected,
                                                  const ChunkedArray& actual);
ARROW_TESTING_EXPORT void AssertChunkedApproxEquivalent(
    const ChunkedArray& expected, const ChunkedArray& actual,
    const EqualOptions& options = TestingEqualOptions());
ARROW_TESTING_EXPORT void AssertBufferEqual(const Buffer& buffer,
                                            const std::vector<uint8_t>& expected);
ARROW_TESTING_EXPORT void AssertBufferEqual(const Buffer& buffer,
                                            const std::string& expected);
ARROW_TESTING_EXPORT void AssertBufferEqual(const Buffer& buffer, const Buffer& expected);

ARROW_TESTING_EXPORT void AssertTypeEqual(const DataType& lhs, const DataType& rhs,
                                          bool check_metadata = false);
ARROW_TESTING_EXPORT void AssertTypeEqual(const std::shared_ptr<DataType>& lhs,
                                          const std::shared_ptr<DataType>& rhs,
                                          bool check_metadata = false);
ARROW_TESTING_EXPORT void AssertFieldEqual(const Field& lhs, const Field& rhs,
                                           bool check_metadata = false);
ARROW_TESTING_EXPORT void AssertFieldEqual(const std::shared_ptr<Field>& lhs,
                                           const std::shared_ptr<Field>& rhs,
                                           bool check_metadata = false);
ARROW_TESTING_EXPORT void AssertSchemaEqual(const Schema& lhs, const Schema& rhs,
                                            bool check_metadata = false);
ARROW_TESTING_EXPORT void AssertSchemaEqual(const std::shared_ptr<Schema>& lhs,
                                            const std::shared_ptr<Schema>& rhs,
                                            bool check_metadata = false);

ARROW_TESTING_EXPORT void AssertTypeNotEqual(const DataType& lhs, const DataType& rhs,
                                             bool check_metadata = false);
ARROW_TESTING_EXPORT void AssertTypeNotEqual(const std::shared_ptr<DataType>& lhs,
                                             const std::shared_ptr<DataType>& rhs,
                                             bool check_metadata = false);
ARROW_TESTING_EXPORT void AssertFieldNotEqual(const Field& lhs, const Field& rhs,
                                              bool check_metadata = false);
ARROW_TESTING_EXPORT void AssertFieldNotEqual(const std::shared_ptr<Field>& lhs,
                                              const std::shared_ptr<Field>& rhs,
                                              bool check_metadata = false);
ARROW_TESTING_EXPORT void AssertSchemaNotEqual(const Schema& lhs, const Schema& rhs,
                                               bool check_metadata = false);
ARROW_TESTING_EXPORT void AssertSchemaNotEqual(const std::shared_ptr<Schema>& lhs,
                                               const std::shared_ptr<Schema>& rhs,
                                               bool check_metadata = false);

ARROW_TESTING_EXPORT Result<std::optional<std::string>> PrintArrayDiff(
    const ChunkedArray& expected, const ChunkedArray& actual);

ARROW_TESTING_EXPORT void AssertTablesEqual(const Table& expected, const Table& actual,
                                            bool same_chunk_layout = true,
                                            bool flatten = false);

ARROW_TESTING_EXPORT void AssertDatumsEqual(const Datum& expected, const Datum& actual,
                                            bool verbose = false);
ARROW_TESTING_EXPORT void AssertDatumsApproxEqual(
    const Datum& expected, const Datum& actual, bool verbose = false,
    const EqualOptions& options = TestingEqualOptions());

template <typename C_TYPE>
void AssertNumericDataEqual(const C_TYPE* raw_data,
                            const std::vector<C_TYPE>& expected_values) {
  for (auto expected : expected_values) {
    ASSERT_EQ(expected, *raw_data);
    ++raw_data;
  }
}

ARROW_TESTING_EXPORT void CompareBatch(const RecordBatch& left, const RecordBatch& right,
                                       bool compare_metadata = true);

ARROW_TESTING_EXPORT void ApproxCompareBatch(const RecordBatch& left,
                                             const RecordBatch& right,
                                             bool compare_metadata = true);

// Check if the padding of the buffers of the array is zero.
// Also cause valgrind warnings if the padding bytes are uninitialized.
ARROW_TESTING_EXPORT void AssertZeroPadded(const Array& array);

// Check if the valid buffer bytes are initialized
// and cause valgrind warnings otherwise.
ARROW_TESTING_EXPORT void TestInitialized(const ArrayData& array);
ARROW_TESTING_EXPORT void TestInitialized(const Array& array);

#define DECL_T() typedef typename TestFixture::T T;

#define DECL_TYPE() typedef typename TestFixture::Type Type;

// ArrayFromJSON: construct an Array from a simple JSON representation

ARROW_TESTING_EXPORT
std::shared_ptr<Array> ArrayFromJSON(const std::shared_ptr<DataType>&,
                                     std::string_view json);

ARROW_TESTING_EXPORT
std::shared_ptr<Array> DictArrayFromJSON(const std::shared_ptr<DataType>& type,
                                         std::string_view indices_json,
                                         std::string_view dictionary_json);

ARROW_TESTING_EXPORT
std::shared_ptr<RecordBatch> RecordBatchFromJSON(const std::shared_ptr<Schema>&,
                                                 std::string_view);

ARROW_TESTING_EXPORT
std::shared_ptr<ChunkedArray> ChunkedArrayFromJSON(const std::shared_ptr<DataType>&,
                                                   const std::vector<std::string>& json);

ARROW_TESTING_EXPORT
std::shared_ptr<Scalar> ScalarFromJSON(const std::shared_ptr<DataType>&,
                                       std::string_view json);

ARROW_TESTING_EXPORT
std::shared_ptr<Scalar> DictScalarFromJSON(const std::shared_ptr<DataType>&,
                                           std::string_view index_json,
                                           std::string_view dictionary_json);

ARROW_TESTING_EXPORT
std::shared_ptr<Table> TableFromJSON(const std::shared_ptr<Schema>&,
                                     const std::vector<std::string>& json);

// Given an array, return a new identical array except for one validity bit
// set to a new value.
// This is useful to force the underlying "value" of null entries to otherwise
// invalid data and check that errors don't get reported.
ARROW_TESTING_EXPORT
std::shared_ptr<Array> TweakValidityBit(const std::shared_ptr<Array>& array,
                                        int64_t index, bool validity);

ARROW_TESTING_EXPORT
void SleepFor(double seconds);

// Sleeps for a very small amount of time.  The thread will be yielded
// at least once ensuring that context switches could happen.  It is intended
// to be used for stress testing parallel code and shouldn't be assumed to do any
// reliable timing.
ARROW_TESTING_EXPORT
void SleepABit();

// Wait until predicate is true or timeout in seconds expires.
ARROW_TESTING_EXPORT
void BusyWait(double seconds, std::function<bool()> predicate);

// \see SleepABit
ARROW_TESTING_EXPORT
Future<> SleepABitAsync();

ARROW_TESTING_EXPORT bool FileIsClosed(int fd);

template <typename T>
std::vector<T> IteratorToVector(Iterator<T> iterator) {
  EXPECT_OK_AND_ASSIGN(auto out, iterator.ToVector());
  return out;
}

ARROW_TESTING_EXPORT
bool LocaleExists(const char* locale);

// A RAII-style object that switches to a new locale, and switches back
// to the old locale when going out of scope.  Doesn't do anything if the
// new locale doesn't exist on the local machine.
// ATTENTION: may crash with an assertion failure on Windows debug builds.
// See ARROW-6108, also https://gerrit.libreoffice.org/#/c/54110/
class ARROW_TESTING_EXPORT LocaleGuard {
 public:
  explicit LocaleGuard(const char* new_locale);
  ~LocaleGuard();

 protected:
  class Impl;
  std::unique_ptr<Impl> impl_;
};

class ARROW_TESTING_EXPORT EnvVarGuard {
 public:
  EnvVarGuard(const std::string& name, const std::string& value);
  ~EnvVarGuard();

 protected:
  const std::string name_;
  std::string old_value_;
  bool was_set_;
};

namespace internal {
class SignalHandler;
}

class ARROW_TESTING_EXPORT SignalHandlerGuard {
 public:
  typedef void (*Callback)(int);

  SignalHandlerGuard(int signum, Callback cb);
  SignalHandlerGuard(int signum, const internal::SignalHandler& handler);
  ~SignalHandlerGuard();

 protected:
  struct Impl;
  std::unique_ptr<Impl> impl_;
};

#ifndef ARROW_LARGE_MEMORY_TESTS
#define LARGE_MEMORY_TEST(name) DISABLED_##name
#else
#define LARGE_MEMORY_TEST(name) name
#endif

inline void PrintTo(const Status& st, std::ostream* os) { *os << st.ToString(); }

template <typename T>
void PrintTo(const Result<T>& result, std::ostream* os) {
  if (result.ok()) {
    ::testing::internal::UniversalPrint(result.ValueOrDie(), os);
  } else {
    *os << result.status();
  }
}

// A data type with only move constructors (no copy, no default).
struct MoveOnlyDataType {
  explicit MoveOnlyDataType(int x) : data(new int(x)) {}

  MoveOnlyDataType(const MoveOnlyDataType& other) = delete;
  MoveOnlyDataType& operator=(const MoveOnlyDataType& other) = delete;

  MoveOnlyDataType(MoveOnlyDataType&& other) { MoveFrom(&other); }
  MoveOnlyDataType& operator=(MoveOnlyDataType&& other) {
    MoveFrom(&other);
    return *this;
  }

  MoveOnlyDataType& operator=(int x) {
    if (data != nullptr) {
      delete data;
    }
    data = new int(x);
    return *this;
  }

  ~MoveOnlyDataType() { Destroy(); }

  void Destroy() {
    if (data != nullptr) {
      delete data;
      data = nullptr;
      moves = -1;
    }
  }

  void MoveFrom(MoveOnlyDataType* other) {
    Destroy();
    data = other->data;
    other->data = nullptr;
    moves = other->moves + 1;
  }

  int ToInt() const { return data == nullptr ? -42 : *data; }

  bool operator==(const MoveOnlyDataType& other) const {
    return data != nullptr && other.data != nullptr && *data == *other.data;
  }
  bool operator<(const MoveOnlyDataType& other) const {
    return data == nullptr || (other.data != nullptr && *data < *other.data);
  }

  bool operator==(int other) const { return data != nullptr && *data == other; }
  friend bool operator==(int left, const MoveOnlyDataType& right) {
    return right == left;
  }

  int* data = nullptr;
  int moves = 0;
};

// A task that blocks until unlocked.  Useful for timing tests.
class ARROW_TESTING_EXPORT GatingTask {
 public:
  explicit GatingTask(double timeout_seconds = 10);
  /// \brief During destruction we wait for all pending tasks to finish
  ~GatingTask();

  /// \brief Creates a new waiting task (presumably to spawn on a thread).  It will return
  /// invalid if the timeout arrived before the unlock.  The task will not complete until
  /// unlocked or timed out
  ///
  /// Note: The GatingTask must outlive any Task instances
  std::function<void()> Task();
  /// \brief Creates a new waiting task as a future.  The future will not complete
  /// until unlocked.
  Future<> AsyncTask();
  /// \brief Waits until at least count tasks are running.
  Status WaitForRunning(int count);
  /// \brief Unlocks all waiting tasks.  Returns an invalid status if any waiting task has
  /// timed out
  Status Unlock();

  static std::shared_ptr<GatingTask> Make(double timeout_seconds = 10);

 private:
  class Impl;
  std::shared_ptr<Impl> impl_;
};

}  // namespace arrow


text:
import ConfigPatternCache from '../src/ConfigPatternCache';
import MockConfigContainer from './MockConfigContainer';

describe('ConfigPatternCache', () => {
    const container = new MockConfigContainer();

    let patternCache;

    beforeEach(() => {
        patternCache = container.resolve(ConfigPatternCache);
    });

    describe('#set()', () => {
        it('should always add compiled `Function`', () => {
            patternCache.set('foo', 'foo');
            patternCache.set(1, 2);

            expect(patternCache.get('foo')).toEqual(jasmine.any(Function));
            expect(patternCache.get(1)).toEqual(jasmine.any(Function));
        });
    });

    describe('#getOrSet()', () => {
        it('should `.compile` to `Function` once', () => {
            const value1 = patternCache.getOrSet('value'),
                value2 = patternCache.getOrSet('value');

            expect(value1).toBe(value2);
            expect(value1).toEqual(value2);
        });
    });

    describe('#compile()', () => {
        it('should compile to `Function`', () => {
            expect(patternCache.compile('foo')).toEqual(jasmine.any(Function));
        });
    });

    describe('#eval()', () => {
        it('should replace `[foo]` with `bar`', () => {
            expect(patternCache.eval('[foo]-[foo]', {
                foo: 'bar'
            })).toEqual('bar-bar');

            expect(patternCache.eval('[ foo ]-[ foo ]', {
                foo: 'bar'
            })).toEqual('bar-bar');
        });

        it('should not replace `JSON.stringify`-strings', () => {
            const str = JSON.stringify({
                foo: [
                    { x: 1 },
                    { y: 2 },
                    { z: 3 }
                ]
            });

            expect(patternCache.eval(str, {})).toEqual(str);
        });
    });

    describe('#interpolate', () => {
        it('should replace `{foo}` with `bar` using custom `interpolate`', () => {
            patternCache.interpolate = /{([\w\s]+?)}/g;

            const value = patternCache.eval('{foo}-{foo}', {
                foo: 'bar'
            });

            expect(value).toEqual('bar-bar');
        });
    });
});


text:
#pragma once

#include "jdksavdecc_aecp.h"
#include "jdksavdecc_aecp_aa.h"
#include "jdksavdecc_aecp_aem.h"
#include "jdksavdecc_aecp_vendor.h"
#include "jdksavdecc_aecp_hdcp_apm.h"
#include "jdksavdecc_aecp_print.h"
#include "jdksavdecc_aem_command.h"
#include "jdksavdecc_aem_descriptor.h"

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @brief aecp_aem_form_msg
 *
 * Create an jdksavdecc_aecpdu_aecpdu message ethernet frame with the specified message_type,
 * possibly directed to the specified target_entity (as ascii)
 *
 * @param frame Pointer to the ethernet frame that will be filled in except for SA
 * @param message_type Pointer to ascii string for the message type
 * @return 0 success
 */
int aecp_aem_form_msg( struct jdksavdecc_frame *frame,
                       struct jdksavdecc_aecpdu_aem *aemdu,
                       uint16_t message_type_code,
                       uint16_t command_code,
                       uint16_t sequence_id,
                       struct jdksavdecc_eui48 destination_mac,
                       struct jdksavdecc_eui64 target_entity_id,
                       const uint8_t *command_payload,
                       size_t command_payload_length );

int aecp_aem_form_read_descriptor_command( struct jdksavdecc_frame *frame,
                                           struct jdksavdecc_aem_command_read_descriptor *pdu,
                                           uint16_t sequence_id,
                                           struct jdksavdecc_eui48 destination_mac,
                                           struct jdksavdecc_eui64 target_entity_id,
                                           uint16_t descriptor_type,
                                           uint16_t descriptor_index );

int aecp_aem_form_get_control_command( struct jdksavdecc_frame *frame,
                                       struct jdksavdecc_aem_command_get_control *pdu,
                                       uint16_t sequence_id,
                                       struct jdksavdecc_eui48 destination_mac,
                                       struct jdksavdecc_eui64 target_entity_id,
                                       uint16_t descriptor_index );

int aecp_aem_form_set_control_command( struct jdksavdecc_frame *frame,
                                       struct jdksavdecc_aem_command_set_control *pdu,
                                       uint16_t sequence_id,
                                       struct jdksavdecc_eui48 destination_mac,
                                       struct jdksavdecc_eui64 target_entity_id,
                                       uint16_t descriptor_index,
                                       const uint8_t *control_data_payload,
                                       size_t control_data_payload_length );

/**
 * @brief aecp_aem_check
 *
 * Validate an ethernet frame to see if it contains an aecpdu message, potentially from the target entity
 *
 * @param frame The ethernet frame to validate
 * @param aecpdudu The aecpdu AEM structure that will be filled in if the frame is matching
 * @param controller_entity_id The target entity_id to expect
 * @param target_entity_id The target entity_id to expect, or 0 for any
 @ @param sequence_id The command sequence id to expect
 * @return 0 on success
 */
int aecp_aem_check( const struct jdksavdecc_frame *frame,
                    struct jdksavdecc_aecpdu_aem *aem,
                    const struct jdksavdecc_eui64 controller_entity_id,
                    const struct jdksavdecc_eui64 target_entity_id,
                    uint16_t sequence_id );

#ifdef __cplusplus
}
#endif


text:
*nspawn* is simple *systemd-nspawn* deployment utility.

Basic idea is to allow running containers across clusters of machines.

Communication between local machine and cluster of machines (also known as nodes) has to be secure by design. For this reason we use SSH for all communication between all nodes in system.

# Remote machines

Arch Linux post-install requires:
```
# pacman-key --init
# pacman-key --populate archlinux
# pacman-key --refresh-keys
# pacman -Syu
```

## systemd-nspawn

```
# pacman -Sy arch-install-scripts
# systemctl enable machines.target
# systemctl start machines.target
```

## SSH

You will need to know all servers addresses, and they all need to have SSH server running on each remote server.

```
# pacman -S opensshd
# systemctl enable sshd
# systemctl start sshd
```

## sudo

Make sure user 'dcloud' does not require password for sudo.

## Users

Create user 'dcloud'.

# Local machine

## Generate private and public SSH keys

Make sure you have valid RSA keys generated, if not run this command:

```
$ ssh-keygen -t rsa
```

## Copy local public SSH key to remote server

Next step is to copy local public SSH key to each remote server. Lets say that remote server behind 192.168.0.100 has user "dcloud".

```
$ ssh-copy-id dcloud@192.168.0.100
```

Or using:

```
$ cat ~/.ssh/id_rsa.pub | ssh dcloud@192.168.0.100 'cat >> .ssh/authorized_keys'
```

## Test SSH connection from local machine to remote server
Now, lets test if we can connect without typing password.

```
$ ssh dcloud@192.168.0.100
```

If you could connect to remote server without typing password, everything is good. Otherwise, please check your SSH keys, and try to copy them from local machine to remote server.

# Troubleshoot

## Force Reboot Machine

```
echo 1 > /proc/sys/kernel/sysrq
echo b > /proc/sysrq-trigger
```

# TODO

1) SSH root with password
2) Copy root key
3) SSH root without password
4) SSH root only with key


text:
package org.robolectric.annotation;

/**
 * Indicates that a JUnit test class or method should not be checked for I18N/L10N-safety
 * under any circumstances.
 *
 * @deprecated Use Android Lint instead.
 * @see EnableStrictI18n
 */
@java.lang.annotation.Documented
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE, java.lang.annotation.ElementType.METHOD})
public @interface DisableStrictI18n {
}


text:
title: load css, inject css
date: 2019-07-26
private:
---
# load css
两种都可以

## load/unload inner-style

    s=document.createElement('style')
    s.innerHTML=`body{color:red}`
    document.body.append(s)
    document.body.removeChild(s)

## load/unload css file

    l=document.createElement('link')
    l.rel= 'stylesheet';
    l.href='/a.css'
    l.type='text/css'
    document.head.append(l)
    document.head.removeChild(l)


text:
package 'goLang' do
	action :install
end

# Create the temp directory to compile the Go app
directory 'appserverDir' do
	path '/tmp/src/appserver'
	recursive true
end

# Deploy the Go app code we'll compile
cookbook_file 'appserverCode' do
	path '/tmp/src/appserver/appserver.go'
	source 'appserver.go'
end

# Deploy a simple script to compile the Go code
cookbook_file 'compileScript' do
	path '/tmp/compile_script.sh'
	source 'compile_script.sh'
	mode '0775'
end

# Compile the Go code, but only if we've not already deployed it
execute 'compileCode' do
	command '/tmp/compile_script.sh'
  action :run
  not_if do ::File.exists?('/usr/local/bin/appserver') end
end

# Create a service to run the app code
service "appserverService" do
  supports :start => true
  start_command 'nohup /usr/local/bin/appserver &'
  action :start
end


text:
{-# LANGUAGE RoleAnnotations #-}

module Roles4 where

type role C1 nominal
class C1 a where
  meth1 :: a -> a

type Syn1 a = [a]

class C3 a where
  meth3 :: a -> Syn1 a


text:
package io.cdap.plugin.googleads.common;

import com.google.api.ads.common.lib.exception.OAuthException;
import com.google.api.ads.common.lib.exception.ValidationException;
import io.cdap.cdap.api.annotation.Description;
import io.cdap.cdap.api.annotation.Macro;
import io.cdap.cdap.api.annotation.Name;
import io.cdap.cdap.etl.api.FailureCollector;
import io.cdap.plugin.common.ReferencePluginConfig;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * Provides all required configuration for reading Google AdWords reports
 */
public class BaseGoogleAdsConfig extends ReferencePluginConfig {

  public static final String REFRESH_TOKEN = "refreshToken";
  public static final String CLIENT_ID = "clientId";
  public static final String CLIENT_SECRET = "clientSecret";
  public static final String DEVELOPER_TOKEN = "developerToken";
  public static final String CLIENT_CUSTOMER_ID = "clientCustomerId";
  public static final String START_DATE = "startDate";
  public static final String END_DATE = "endDate";
  public static final String INCLUDE_REPORT_SUMMARY = "includeReportSummary";
  public static final String USE_RAW_ENUM_VALUES = "useRawEnumValues";
  public static final String INCLUDE_ZERO_IMPRESSIONS = "includeZeroImpressions";
  @Name(REFRESH_TOKEN)
  @Description("Authorization to download the report")
  @Macro
  public String refreshToken;
  @Name(CLIENT_ID)
  @Description("OAuth 2.0 client ID from console")
  @Macro
  public String clientId;
  @Name(CLIENT_SECRET)
  @Description("OAuth 2.0 client Secret from console")
  @Macro
  public String clientSecret;
  @Name(DEVELOPER_TOKEN)
  @Description("Developer token which is a unique string")
  @Macro
  public String developerToken;
  @Name(CLIENT_CUSTOMER_ID)
  @Description("Customer ID of the client account")
  @Macro
  public String clientCustomerId;
  @Name(INCLUDE_REPORT_SUMMARY)
  @Description("Specifies whether report include a summary row containing the report totals.")
  @Macro
  public Boolean includeReportSummary;
  @Name(USE_RAW_ENUM_VALUES)
  @Description("Set to true if you want the returned format to be the actual enum value," +
    " for example, \"IMAGE_AD\" instead of \"Image ad\"." +
    " Set to false or omit this header if you want the returned format to be the display value.")
  @Macro
  public Boolean useRawEnumValues;
  @Name(INCLUDE_ZERO_IMPRESSIONS)
  @Description("Specifies whether the report includes rows where all specified metric fields equal to zero")
  @Macro
  public Boolean includeZeroImpressions;
  @Name(START_DATE)
  @Description("Start date for the report data. YYYYMMDD format." +
    " \"LAST_30_DAYS\", \"LAST_60_DAYS\" and \"LAST_90_DAYS\" values are allowed.")
  @Macro
  public String startDate;
  @Name(END_DATE)
  @Description("End date for the report data. YYYYMMDD format. \"TODAY\" value is allowed.")
  @Macro
  public String endDate;

  public BaseGoogleAdsConfig(String referenceName) {
    super(referenceName);
  }

  public void validate(FailureCollector failureCollector) {
    GoogleAdsHelper googleAdsHelper = new GoogleAdsHelper();
    validateAuthorization(failureCollector, googleAdsHelper);
    validateDateRange(failureCollector);
  }

  protected void validateAuthorization(FailureCollector failureCollector, GoogleAdsHelper googleAdsHelper) {
    if (containsMacro(REFRESH_TOKEN)
      || containsMacro(CLIENT_ID)
      || containsMacro(CLIENT_SECRET)
      || containsMacro(DEVELOPER_TOKEN)
      || containsMacro(CLIENT_CUSTOMER_ID)) {
      return;
    }
    try {
      googleAdsHelper.getAdWordsSession(this);
    } catch (OAuthException e) {
      failureCollector.addFailure(e.getMessage(), "Enter valid credentials");
    } catch (ValidationException e) {
      failureCollector.addFailure(
        String.format("invalid value '%s' : %s", e.getTrigger(), e.getMessage()),
        "Enter valid credentials");
    }
  }

  protected void validateDateRange(FailureCollector failureCollector) {
    if (containsMacro(START_DATE)
      || containsMacro(END_DATE)) {
      return;
    }
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyDDmm");
    Date startDate = null;
    Date endDate = null;
    try {
      startDate = simpleDateFormat.parse(getStartDate());
    } catch (ParseException e) {
      failureCollector.addFailure("Invalid startDate format.", "Use YYYYMMDD date format.")
        .withConfigProperty(START_DATE);
    }
    try {
      endDate = simpleDateFormat.parse(getEndDate());
    } catch (ParseException e) {
      failureCollector.addFailure("Invalid endDate format.", "Use YYYYMMDD date format.")
        .withConfigProperty(END_DATE);
    }
    if (startDate != null &&
      endDate != null &&
      startDate.after(endDate)) {
      failureCollector.addFailure("startDate must be earlier than endDate.", "Enter valid date.");
    }
  }

  public String getStartDate() {
    return getDate(startDate);
  }

  public String getEndDate() {
    return getDate(endDate);
  }

  private String getDate(String date) {

    DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    Date today = new Date();
    if (date.equalsIgnoreCase("TODAY")) {
      return dateFormat.format(today);
    }
    Calendar cal = new GregorianCalendar();
    cal.setTime(today);
    if (date.equalsIgnoreCase("LAST_30_DAYS")) {
      cal.add(Calendar.DAY_OF_MONTH, -30);
      Date today30 = cal.getTime();
      return dateFormat.format(today30);
    } else if (date.equalsIgnoreCase("LAST_60_DAYS")) {
      cal.add(Calendar.DAY_OF_MONTH, -60);
      Date today60 = cal.getTime();
      return dateFormat.format(today60);
    } else if (date.equalsIgnoreCase("LAST_90_DAYS")) {
      cal.add(Calendar.DAY_OF_MONTH, -90);
      Date today90 = cal.getTime();
      return dateFormat.format(today90);
    }
    return date;
  }
}


text:
package testing

import (
	"testing"

	"github.com/gophercloud/gophercloud/openstack/keymanager/v1/secrets"
	"github.com/gophercloud/gophercloud/pagination"
	th "github.com/gophercloud/gophercloud/testhelper"
	"github.com/gophercloud/gophercloud/testhelper/client"
)

func TestListSecrets(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleListSecretsSuccessfully(t)

	count := 0
	err := secrets.List(client.ServiceClient(), nil).EachPage(func(page pagination.Page) (bool, error) {
		count++

		actual, err := secrets.ExtractSecrets(page)
		th.AssertNoErr(t, err)

		th.AssertDeepEquals(t, ExpectedSecretsSlice, actual)

		return true, nil
	})
	th.AssertNoErr(t, err)
	th.AssertEquals(t, count, 1)
}

func TestListSecretsAllPages(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleListSecretsSuccessfully(t)

	allPages, err := secrets.List(client.ServiceClient(), nil).AllPages()
	th.AssertNoErr(t, err)
	actual, err := secrets.ExtractSecrets(allPages)
	th.AssertNoErr(t, err)
	th.AssertDeepEquals(t, ExpectedSecretsSlice, actual)
}

func TestGetSecret(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleGetSecretSuccessfully(t)

	actual, err := secrets.Get(client.ServiceClient(), "1b8068c4-3bb6-4be6-8f1e-da0d1ea0b67c").Extract()
	th.AssertNoErr(t, err)
	th.AssertDeepEquals(t, FirstSecret, *actual)
}

func TestCreateSecret(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleCreateSecretSuccessfully(t)

	createOpts := secrets.CreateOpts{
		Algorithm:          "aes",
		BitLength:          256,
		Mode:               "cbc",
		Name:               "mysecret",
		Payload:            "foobar",
		PayloadContentType: "text/plain",
		SecretType:         secrets.OpaqueSecret,
	}

	actual, err := secrets.Create(client.ServiceClient(), createOpts).Extract()
	th.AssertNoErr(t, err)
	th.AssertDeepEquals(t, ExpectedCreateResult, *actual)
}

func TestDeleteSecret(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleDeleteSecretSuccessfully(t)

	res := secrets.Delete(client.ServiceClient(), "1b8068c4-3bb6-4be6-8f1e-da0d1ea0b67c")
	th.AssertNoErr(t, res.Err)
}

func TestUpdateSecret(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleUpdateSecretSuccessfully(t)

	updateOpts := secrets.UpdateOpts{
		Payload: "foobar",
	}

	err := secrets.Update(client.ServiceClient(), "1b8068c4-3bb6-4be6-8f1e-da0d1ea0b67c", updateOpts).ExtractErr()
	th.AssertNoErr(t, err)
}

func TestGetPayloadSecret(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleGetPayloadSuccessfully(t)

	res := secrets.GetPayload(client.ServiceClient(), "1b8068c4-3bb6-4be6-8f1e-da0d1ea0b67c", nil)
	th.AssertNoErr(t, res.Err)
	payload, err := res.Extract()
	th.AssertNoErr(t, err)
	th.AssertDeepEquals(t, GetPayloadResponse, string(payload))
}

func TestGetMetadataSuccessfully(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleGetMetadataSuccessfully(t)

	actual, err := secrets.GetMetadata(client.ServiceClient(), "1b8068c4-3bb6-4be6-8f1e-da0d1ea0b67c").Extract()
	th.AssertNoErr(t, err)
	th.AssertDeepEquals(t, ExpectedMetadata, actual)
}

func TestCreateMetadataSuccessfully(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleCreateMetadataSuccessfully(t)

	createOpts := secrets.MetadataOpts{
		"foo":       "bar",
		"something": "something else",
	}

	actual, err := secrets.CreateMetadata(client.ServiceClient(), "1b8068c4-3bb6-4be6-8f1e-da0d1ea0b67c", createOpts).Extract()
	th.AssertNoErr(t, err)
	th.AssertDeepEquals(t, ExpectedCreateMetadataResult, actual)
}

func TestGetMetadatumSuccessfully(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleGetMetadatumSuccessfully(t)

	actual, err := secrets.GetMetadatum(client.ServiceClient(), "1b8068c4-3bb6-4be6-8f1e-da0d1ea0b67c", "foo").Extract()
	th.AssertNoErr(t, err)
	th.AssertDeepEquals(t, ExpectedMetadatum, *actual)
}

func TestCreateMetadatumSuccessfully(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleCreateMetadatumSuccessfully(t)

	createOpts := secrets.MetadatumOpts{
		Key:   "foo",
		Value: "bar",
	}

	err := secrets.CreateMetadatum(client.ServiceClient(), "1b8068c4-3bb6-4be6-8f1e-da0d1ea0b67c", createOpts).ExtractErr()
	th.AssertNoErr(t, err)
}

func TestUpdateMetadatumSuccessfully(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleUpdateMetadatumSuccessfully(t)

	updateOpts := secrets.MetadatumOpts{
		Key:   "foo",
		Value: "bar",
	}

	actual, err := secrets.UpdateMetadatum(client.ServiceClient(), "1b8068c4-3bb6-4be6-8f1e-da0d1ea0b67c", updateOpts).Extract()
	th.AssertNoErr(t, err)
	th.AssertDeepEquals(t, ExpectedMetadatum, *actual)
}

func TestDeleteMetadatumSuccessfully(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	HandleDeleteMetadatumSuccessfully(t)

	err := secrets.DeleteMetadatum(client.ServiceClient(), "1b8068c4-3bb6-4be6-8f1e-da0d1ea0b67c", "foo").ExtractErr()
	th.AssertNoErr(t, err)
}


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

namespace OmegaMUD
{
    public class TollExitData : ExitData
    {
        public TollExitData(Room room, Direction direction, int exitRoom, ExitType exitType, int p1, int p2, int p3, int p4)
            : base(room, direction, exitRoom, exitType, p1, p2, p3, p4)
        {
        }

        public int TollAmountRequired { get { return Parameter1; } }

        public override ExitUsageRequirements CanUseExit(MajorModelEntities model, PathfindingSettings settings)
        {
            var reqs = new ExitUsageRequirements();
            var moneyRequired = model.TollMultiplier * TollAmountRequired;

            if (settings.PartyCharacters.Any(x => x.GetTotalMoney(model) < moneyRequired))
            {
                // someone doesn't have enough money, or hasn't disclosed that they have the money.
                // So, mark the exit as needing money.
                reqs.Method = ExitMethod.NeedMoney;
                reqs.RequiredMoneyAmount = moneyRequired;
                return reqs;
            }

            // All party members have the required money, we're good to go.
            reqs.Method = ExitMethod.Normal;
            return reqs;
        }
    }
}


text:
angular.module('holidu.pmc.layout', [
    'pascalprecht.translate'
]);


text:
<!doctype html>

		<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
		<meta name="viewport"
			  content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no"/>
		<meta name="apple-mobile-web-app-capable" content="yes"/>

		<title>Accordion - Controller</title>

		<link rel="stylesheet" href="../../delite/themes/defaultapp.css">

		On this sample the content of the panels is loaded when a panel is opened
		<d-accordion id="accordion" mode="multipleOpen" openIconClass="icon-right" closedIconClass="icon-down"
				selectedChildId="p2" style="height: 800px">
			<d-panel id="p1" label="Panel1">
			</d-panel>
			<d-panel id="p2" label="Panel2">
			</d-panel>
			<d-panel id="p3" label="Panel3">
			</d-panel>
		</d-accordion>
		<button is="d-button" onclick="loadP2Content()">Load widget on Panel2</button>
		<button is="d-button" onclick="createP3Content()">Load new content for Panel3</button>
		<button is="d-button" onclick="accordion.show('new Panel')">Load new Panel</button>
		<button is="d-button" onclick="accordion.show('Another Panel', {contentId: 'StarRating3'})">
			Load new Panel with widget
		</button>


text:
<!--
  Generated template for the EditStockModificationPage page.

  See http://ionicframework.com/docs/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-header>
  <ion-navbar>
    <ion-buttons start>
      <button ion-button (click)="dismiss()">
        {{ 'BACK' | translate }}
      </button>
    </ion-buttons>
    <ion-title>{{ 'STOCK_MODIFICATION.TITLE' | translate }}</ion-title>
  </ion-navbar>
  <ion-toolbar color="primary">
    <ion-searchbar [placeholder]="'SEARCH_PLACEHOLDER' | translate" (ionInput)="searchRawMaterials($event)"></ion-searchbar>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-list>
    <button ion-item *ngFor="let material of rawMaterials | async" (click)="openEditStockModificationDetail(material)">
      {{ material.name }}
      <ion-badge item-right *ngIf="stockModifications[material.$key]">{{ stockModifications[material.$key] }}</ion-badge>
    </button>
  </ion-list>
</ion-content>


text:
{% extends "lifeflow/editor/base.html" %}

{% block body %}

  Title & Summary
   Body & Files
   Flows
   Tags
   Series
   Date & Options
   Authors & Translations

 Click on the flows you want to include this article in.

      {% for flow, selected in flows %}
       {{ flow.title }}
      {% endfor %}

    <form method="post" action="/editor/create_model/">

 Create a new flow.

Title: 	<input name="title">

	<input type="hidden" value="flow" name="model">

	<button type="submit" class="button positive"> Create </button>

      </form>

{% endblock %}