text:
/*global QUnit */
sap.ui.define([
	"sap/ui/qunit/QUnitUtils",
	"sap/ui/qunit/utils/createAndAppendDiv",
	"sap/ui/commons/SearchField",
	"sap/ui/core/search/OpenSearchProvider",
	"sap/ui/thirdparty/jquery",
	"sap/ui/core/library"
], function(
	qutils,
	createAndAppendDiv,
	SearchField,
	OpenSearchProvider,
	jQuery,
	coreLibrary
) {
	"use strict";

	// shortcut for sap.ui.core.ValueState
	var ValueState = coreLibrary.ValueState;

	// prepare DOM
	createAndAppendDiv(["uiArea1", "uiArea2", "uiArea3", "uiArea4", "uiArea5",
						"uiArea6", "uiArea7", "uiArea8", "uiArea9", "uiArea10", "uiArea11"]);

	var createSearchField = function(iIdSuffix, oProps){
		if (!oProps) {oProps = {};}
		var oSearch = new SearchField("search" + iIdSuffix, oProps);
		oSearch.placeAt("uiArea" + iIdSuffix);
		return oSearch;
	};

	var oSearch1 = createSearchField(1);
	var oSearch2 = createSearchField(2, {enableListSuggest: false});
	var oSearch3 = createSearchField(3, {enableListSuggest: false, enableClear: true, startSuggestion: 0});
	var oSearch4 = createSearchField(4, {startSuggestion: 1});
	var oSearch5 = createSearchField(5, {enableClear: true, startSuggestion: 20});
	var oSearch6 = createSearchField(6, {maxHistoryItems: 5});
	var oSearch7 = createSearchField(7, {enableListSuggest: false});
	var oSearch8 = createSearchField(8, {searchProvider: new OpenSearchProvider({
		suggestType: "xml",
		suggestUrl: "test-resources/sap/ui/commons/qunit/searchprovidertest.xml",
		icon: sap.ui.require.toUrl("sap/ui/core/mimes/logo/txtonly_16x16.ico")
	})});
	var oSearch9 = createSearchField(9, {searchProvider: new OpenSearchProvider({
		suggestType: "json",
		suggestUrl: "test-resources/sap/ui/commons/qunit/searchprovidertest.json"
	})});
	var oSearch10 = createSearchField(10, {
		suggest: function(oEvent){
			var sVal = oEvent.getParameter("value");
			var aSuggestions = ["a", "b"];
			oSearch10.suggest(sVal, aSuggestions);
		}
	});
	var oSearch11 = createSearchField(11, {enableListSuggest: false, enableFilterMode: true});

	var triggerInputSequence = function(assert, oSearchField, iCount, bDoReset) {
		if (bDoReset){
			var sNew = "";
			oSearchField.setValue(sNew);
			assert.equal(oSearchField.getValue(), sNew, "SearchField' value should have changed.");
			assert.equal(oSearchField.getFocusDomRef().value, sNew, "SearchField' value should have changed in HTML.");
		}
		var aKeys = ["S", "a", "p", "U", "i", "5"];
		var iLength = Math.min(iCount, aKeys.length);
		for (var i = 0; i < iLength; i++){
			qutils.triggerCharacterInput(oSearchField.getFocusDomRef(), aKeys[i]);
			qutils.triggerKeyEvent("keyup", oSearchField.getFocusDomRef(), aKeys[i]);
		}
	};

	var checkFocus = function(assert, sId, sText, bExpectFocus){
		var sActiveId = document.activeElement ? document.activeElement.id : "<undef>";
		if (bExpectFocus){
			assert.ok(sActiveId === sId, sText + " (" + sId + "): " + sActiveId);
		} else {
			assert.ok(sActiveId != sId, sText + " (" + sId + "): " + sActiveId);
		}
	};

	var checkVisible = function(sId, bExpectVisible){
		var bVisible = jQuery("#" + sId).is(":visible");
		return (bExpectVisible && bVisible) || (!bExpectVisible && !bVisible);
	};

	var checkSearch = function(assert, sType, oSearchField, bReadOnly, bWithClear) {
		var done = assert.async();
		if (!bReadOnly){
			oSearchField.focus();
		}

		setTimeout(function(){
			if (!/^ie/.test(jQuery("html").attr("data-sap-ui-browser"))){ //TODO check why this does not work for IE
				checkFocus(assert, oSearchField.getFocusDomRef().id, "SearchField has " + (bReadOnly ? "no " : "") + "focus before user action", !bReadOnly);
			}
			var bEventHandlerCalled = false;
			var handler = function(oControlEvent){
				assert.equal(oControlEvent.getParameter("query"), "SapUi5", "Value of search event:");
				oSearchField.detachSearch(handler);
				bEventHandlerCalled = true;
			};
			oSearchField.attachSearch(handler);
			triggerInputSequence(assert, oSearchField, bReadOnly ? 0 : 6, true); //Reset only in readonly case
			if (sType == "click"){
				qutils.triggerEvent("click", oSearchField._ctrl.getId() + "-searchico");
			} else {
				qutils.triggerKeydown(oSearchField.getFocusDomRef(), "ENTER");
			}

			var bNoChange = bReadOnly || (bWithClear && sType == "click");
			if (bNoChange){
				assert.ok(!bEventHandlerCalled, "Search handler not called.");
				oSearchField.detachSearch(handler);
			} else {
				assert.ok(bEventHandlerCalled, "Search handler called.");
			}

			assert.equal(jQuery(oSearchField.getFocusDomRef()).val(), bNoChange ? "" : "SapUi5", "SearchField' value after user action (HTML)");
			assert.equal(oSearchField.getValue(), bNoChange ? "" : "SapUi5", "SearchField' value after user action (Property)");
			checkFocus(assert, oSearchField.getFocusDomRef().id, "SearchField has " + (bReadOnly ? "no " : "") + "focus after user action", !bReadOnly);

			done();

			// focus is removed for the next test
			if ( document.activeElement ) {
				document.activeElement.blur();
			}
		}, 10);
	};

	var checkSuggestion = function(assert, oSearchField, fSecondPassCheck){
		var done = assert.async();
		oSearchField.clearHistory();
		oSearchField.focus();

		var sSuggestValue = "INITIAL";
		var handler = function(oControlEvent){
			oSearchField.detachSuggest(handler);
			sSuggestValue = oControlEvent.getParameter("value");
		};
		oSearchField.attachSuggest(handler);

		triggerInputSequence(assert, oSearchField, 2, true);
		setTimeout(function(){
			oSearchField.detachSuggest(handler);
			assert.equal(sSuggestValue, "INITIAL", "No suggestions when input has not yet reach configured 'startSuggestion' value");
			sSuggestValue = "INITIAL";
			oSearchField.attachSuggest(handler);
			triggerInputSequence(assert, oSearchField, 3, false);
			setTimeout(function(){
				oSearchField.detachSuggest(handler);
				var aItems = [];
				if (oSearchField.getEnableListSuggest()){
					assert.ok(checkVisible(oSearchField._lb.getId(), true), "List is visible");
					aItems = oSearchField._lb.getItems();
				}
				fSecondPassCheck(sSuggestValue, aItems);
				if (oSearchField.getEnableListSuggest()){
					var bEventHandlerCalled = false;
					var handler2 = function(oControlEvent){
						assert.equal(oControlEvent.getParameter("query"), "b", "Value of search event:");
						oSearchField.detachSearch(handler2);
						bEventHandlerCalled = true;
					};
					oSearchField.attachSearch(handler2);
					qutils.triggerEvent("click", aItems[1].getId());
					assert.ok(bEventHandlerCalled, "Search Event triggered");
					assert.equal(jQuery(oSearchField.getFocusDomRef()).val(), "b", "SearchField' value after user action (HTML)");
					assert.equal(oSearchField.getValue(), "b", "SearchField' value after user action (Property)");
					if (!bEventHandlerCalled){
						oSearchField.detachSearch(handler2);
					}
				}
				done();
			}, 1000);
		}, 500);
	};

	QUnit.module("Properties and Aggregations");

	QUnit.test("Default Values", function(assert) {
		assert.equal(oSearch1.getEnableListSuggest(), true, "Default 'enableListSuggest'");
		assert.equal(oSearch1.getShowListExpander(), true, "Default 'showListExpander'");
		assert.equal(oSearch1.getEnableClear(), false, "Default 'enableClear'");
		assert.equal(oSearch1.getShowExternalButton(), false, "Default 'showExternalButton'");
		assert.equal(oSearch1.getValue(), "", "Default 'value'");
		assert.equal(oSearch1.getWidth(), "", "Default 'width'");
		assert.equal(oSearch1.getEnabled(), true, "Default 'enabled'");
		assert.equal(oSearch1.getEditable(), true, "Default 'editable'");
		assert.equal(oSearch1.getVisible(), true, "Default 'visible'");
		assert.equal(oSearch1.getEnableFilterMode(), false, "Default 'enableFilterMode'");
		assert.equal(oSearch1.getMaxLength(), 0, "Default 'maxLength'");
		assert.equal(oSearch1.getPlaceholder(), "", "Default 'placeholder'");
		assert.equal(oSearch1.getValueState(), ValueState.None, "Default 'valueState'");
		assert.equal(oSearch1.getTextAlign(), "Begin", "Default 'textAlign'");
		assert.equal(oSearch1.getVisibleItemCount(), 20, "Default 'visibleItemCount'");
		assert.equal(oSearch1.getStartSuggestion(), 3, "Default 'startSuggestion'");
		assert.equal(oSearch1.getMaxSuggestionItems(), 10, "Default 'maxSuggestionItems'");
		assert.equal(oSearch1.getMaxHistoryItems(), 0, "Default 'maxHistoryItems'");
		assert.equal(oSearch1.getSearchProvider(), null, "Default aggregation 'searchProvider'");
	});

	QUnit.test("Custom Values", function(assert) {
		oSearch1.setEnableListSuggest(false);
		oSearch1.setShowListExpander(false);
		oSearch1.setEnableClear(true);
		oSearch1.setShowExternalButton(true);
		oSearch1.setValue("Hello");
		oSearch1.setWidth("200px");
		oSearch1.setEnabled(false);
		oSearch1.setEditable(false);
		oSearch1.setVisible(false);
		oSearch1.setEnableFilterMode(true);
		oSearch1.setMaxLength(5);
		oSearch1.setPlaceholder("Click to search");
		oSearch1.setValueState(ValueState.Error);
		oSearch1.setTextAlign("End");
		oSearch1.setVisibleItemCount(10);
		oSearch1.setStartSuggestion(5);
		oSearch1.setMaxSuggestionItems(5);
		oSearch1.setMaxHistoryItems(5);
		oSearch1.setSearchProvider(new OpenSearchProvider("search1_provider"));

		assert.equal(oSearch1.getEnableListSuggest(), false, "Custom 'enableListSuggest'");
		assert.equal(oSearch1.getShowListExpander(), false, "Custom 'showListExpander'");
		assert.equal(oSearch1.getEnableClear(), true, "Custom 'enableClear'");
		assert.equal(oSearch1.getShowExternalButton(), true, "Custom 'showExternalButton'");
		assert.equal(oSearch1.getValue(), "Hello", "Custom 'value'");
		assert.equal(oSearch1.getWidth(), "200px", "Custom 'width'");
		assert.equal(oSearch1.getEnabled(), false, "Custom 'enabled'");
		assert.equal(oSearch1.getEditable(), false, "Custom 'editable'");
		assert.equal(oSearch1.getVisible(), false, "Custom 'visible'");
		assert.equal(oSearch1.getEnableFilterMode(), true, "Custom 'enableFilterMode'");
		assert.equal(oSearch1.getMaxLength(), 5, "Custom 'maxLength'");
		assert.equal(oSearch1.getPlaceholder(), "Click to search", "Custom 'placeholder'");
		assert.equal(oSearch1.getValueState(), ValueState.Error, "Custom 'valueState'");
		assert.equal(oSearch1.getTextAlign(), "End", "Custom 'textAlign'");
		assert.equal(oSearch1.getVisibleItemCount(), 10, "Custom 'visibleItemCount'");
		assert.equal(oSearch1.getStartSuggestion(), 5, "Custom 'startSuggestion'");
		assert.equal(oSearch1.getMaxSuggestionItems(), 5, "Custom 'maxSuggestionItems'");
		assert.equal(oSearch1.getMaxHistoryItems(), 5, "Custom 'maxHistoryItems'");
		assert.equal(oSearch1.getSearchProvider().getId(), "search1_provider", "Custom aggregation 'searchProvider'");
	});

	//***********************************
	QUnit.module("Appearance");

	QUnit.test("Visibility", function(assert) {
		oSearch1.setVisible(false);
		sap.ui.getCore().applyChanges();
		assert.ok(!oSearch1.getDomRef(), "Control is not visible, when property visible is set to false");
		oSearch1.setVisible(true);
		sap.ui.getCore().applyChanges();
		assert.ok(!!oSearch1.getDomRef(), "Control is visible, when property visible is set to true");
	});

	QUnit.test("Width", function(assert) {
		oSearch1.setWidth("200px");
		oSearch1.setVisible(true);

		var checkWidth = function(bSuggList, bWithButton){
			oSearch1.setEnableListSuggest(bSuggList);
			oSearch1.setShowExternalButton(bWithButton);
			sap.ui.getCore().applyChanges();
			assert.equal(jQuery(oSearch1.getDomRef()).outerWidth(true), 200, "Width for SearchField (with suggestion list:" + bSuggList + ", with Button: " + bWithButton + ")");
		};

		checkWidth(false, false);
		checkWidth(false, true);
		checkWidth(true, false);
		checkWidth(true, true);
	});

	QUnit.test("ValueState", function(assert) {
		var iNumberOfClasses;
		oSearch1.setValueState(ValueState.None);
		sap.ui.getCore().applyChanges();
		iNumberOfClasses = jQuery("#" + oSearch1._ctrl.getId()).attr("class").split(" ").length;
		oSearch1.setValueState(ValueState.Error);
		sap.ui.getCore().applyChanges();
		assert.ok(iNumberOfClasses < jQuery("#" + oSearch1._ctrl.getId()).attr("class").split(" ").length, "style class added for error state");
		oSearch1.setValueState(ValueState.None);
		sap.ui.getCore().applyChanges();
		assert.ok(iNumberOfClasses === jQuery("#" + oSearch1._ctrl.getId()).attr("class").split(" ").length, "error state style class removed again");
	});

	QUnit.test("List Expander Visibility", function(assert) {
		assert.ok(checkVisible(oSearch6._ctrl.getId() + "-icon", true), "List expander is not visible");
		oSearch6.setShowListExpander(false);
		sap.ui.getCore().applyChanges();
		assert.ok(checkVisible(oSearch6._ctrl.getId() + "-icon", false), "List expander is not visible");
	});

	QUnit.test("Search Provider Icon Visibility", function(assert) {
		assert.ok(checkVisible(oSearch8._ctrl.getId() + "-providerico", true), "Search Provider Icon is visible when configured");
		assert.ok(checkVisible(oSearch9._ctrl.getId() + "-providerico", false), "Search Provider Icon is not visible when not configured");
	});

	//***********************************
	QUnit.module("Trigger Search", {
		beforeEach: function(){
			oSearch4.clearHistory();
		},
		afterEach: function(){
			oSearch2.setEnabled(true);
			oSearch4.setEnabled(true);
			sap.ui.getCore().applyChanges();
		}
	});

	QUnit.test("TextField - Click on icon", function(assert) {
		checkSearch(assert, "click", oSearch2, false, false);
	});

	QUnit.test("TextField - Press enter", function(assert) {
		checkSearch(assert, "enter", oSearch2, false, false);
	});

	QUnit.test("TextField - Click on icon (disabled)", function(assert) {
		oSearch2.setEnabled(false);
		sap.ui.getCore().applyChanges();
		checkSearch(assert, "click", oSearch2, true, false);
	});

	QUnit.test("ComboBox - Click on icon", function(assert) {
		oSearch4.clearHistory();
		checkSearch(assert, "click", oSearch4, false, false);
	});

	QUnit.test("ComboBox - Press enter", function(assert) {
		oSearch4.clearHistory();
		checkSearch(assert, "enter", oSearch4, false, false);
	});

	QUnit.test("ComboBox - Click on icon (disabled)", function(assert) {
		oSearch4.setEnabled(false);
		sap.ui.getCore().applyChanges();
		checkSearch(assert, "click", oSearch4, true, false);
	});

	//***********************************
	QUnit.module("Clear", {
		beforeEach: function(){
			oSearch5.clearHistory();
		},
		afterEach: function(){
			oSearch3.setEnabled(true);
			oSearch5.setEnabled(true);
			sap.ui.getCore().applyChanges();
		}
	});

	QUnit.test("TextField - Click on icon", function(assert) {
		checkSearch(assert, "click", oSearch3, false, true);
	});

	QUnit.test("TextField - Press enter", function(assert) {
		checkSearch(assert, "enter", oSearch3, false, true);
	});

	QUnit.test("TextField - Click on icon (disabled)", function(assert) {
		oSearch3.setEnabled(false);
		sap.ui.getCore().applyChanges();
		checkSearch(assert, "click", oSearch3, true, true);
	});

	QUnit.test("ComboBox - Click on icon", function(assert) {
		oSearch5.clearHistory();
		checkSearch(assert, "click", oSearch5, false, true);
	});

	QUnit.test("ComboBox - Press enter", function(assert) {
		oSearch5.clearHistory();
		checkSearch(assert, "enter", oSearch5, false, true);
	});

	QUnit.test("ComboBox - Click on icon (disabled)", function(assert) {
		oSearch5.setEnabled(false);
		sap.ui.getCore().applyChanges();
		checkSearch(assert, "click", oSearch5, true, true);
	});

	//***********************************
	QUnit.module("List Handling");

	QUnit.test("Open List with F4 - No List Expander", function(assert) {
		oSearch6.clearHistory();
		oSearch6.setShowListExpander(false);
		sap.ui.getCore().applyChanges();
		oSearch6.focus();
		assert.ok(checkVisible(oSearch6._lb.getId(), false), "List is not visible");
		qutils.triggerKeydown(oSearch6.getFocusDomRef(), "F4");
		assert.ok(checkVisible(oSearch6._lb.getId(), false), "List is still not visible");
	});

	QUnit.test("Open List with F4 - no values", function(assert) {
		oSearch6.clearHistory();
		oSearch6.setShowListExpander(true);
		sap.ui.getCore().applyChanges();
		oSearch6.focus();
		assert.ok(checkVisible(oSearch6._lb.getId(), false), "List is not visible");
		qutils.triggerKeydown(oSearch6.getFocusDomRef(), "F4");
		assert.ok(checkVisible(oSearch6._lb.getId(), false), "List is not visible");
	});

	QUnit.test("Open List with click - no values", function(assert) {
		oSearch6.clearHistory();
		oSearch6.setShowListExpander(true);
		sap.ui.getCore().applyChanges();
		oSearch6.focus();
		assert.ok(checkVisible(oSearch6._lb.getId(), false), "List is not visible");
		qutils.triggerEvent("click", oSearch6._ctrl.getId() + "-icon");
		assert.ok(checkVisible(oSearch6._lb.getId(), false), "List is not visible");
	});

	QUnit.test("Open List with F4", function(assert) {
		oSearch6.focus();
		triggerInputSequence(assert, oSearch6, 1, true);
		qutils.triggerKeydown(oSearch6.getFocusDomRef(), "ENTER"); //Create History entry

		assert.ok(checkVisible(oSearch6._lb.getId(), false), "List is not visible");
		qutils.triggerKeydown(oSearch6.getFocusDomRef(), "F4");
		assert.ok(checkVisible(oSearch6._lb.getId(), true), "List is  visible");
	});

	QUnit.test("Close List with ESCAPE", function(assert) {
		assert.ok(checkVisible(oSearch6._lb.getId(), true), "List is visible");
		qutils.triggerKeydown(oSearch6.getFocusDomRef(), "ESCAPE");
		assert.ok(checkVisible(oSearch6._lb.getId(), false), "List is not visible");
	});

	QUnit.test("Open List with click", function(assert) {
		assert.ok(checkVisible(oSearch6._lb.getId(), false), "List is not visible");
		qutils.triggerEvent("click", oSearch6._ctrl.getId() + "-icon");
		assert.ok(checkVisible(oSearch6._lb.getId(), true), "List is  visible");
	});

	QUnit.test("Close List with click", function(assert) {
		assert.ok(checkVisible(oSearch6._lb.getId(), true), "List is visible");
		qutils.triggerEvent("click", oSearch6._ctrl.getId() + "-icon");
		assert.ok(checkVisible(oSearch6._lb.getId(), false), "List is not visible");
	});

	//***********************************
	QUnit.module("Suggestion");

	QUnit.test("Textfield mode (no suggestion list)", function(assert) {
		checkSuggestion(assert, oSearch7, function(sSuggestValue, aItems){
			assert.equal(sSuggestValue, "SaSap", "Suggest value");
		});
	});

	QUnit.test("Combobox mode (with suggestion list)", function(assert) {
		checkSuggestion(assert, oSearch10, function(sSuggestValue, aItems){
			assert.equal(sSuggestValue, "SaSap", "Suggest value");
			assert.equal(aItems.length, 2, "Number of suggestions correct");
			assert.equal(aItems[0].getText(), "a", "First suggestion item correct");
			assert.equal(aItems[1].getText(), "b", "Second suggestion item correct");
		});
	});

	//***********************************
	QUnit.module("Filter Mode");

	function testFilterMode(assert, bClick, sVal) {
		function trigger(bClick) {
			if (bClick){
				qutils.triggerEvent("click", oSearch11._ctrl.getId() + "-searchico");
			} else {
				qutils.triggerKeydown(oSearch11.getFocusDomRef(), "ENTER");
			}
		}

		oSearch11.setEnableFilterMode(true);
		oSearch11.setValue(sVal);
		sap.ui.getCore().applyChanges();

		var bEventHandlerCalled = false;
		var handler = function(oControlEvent){
			assert.equal(oControlEvent.getParameter("query"), "", "Value of search event is empty:");
			bEventHandlerCalled = true;
		};
		oSearch11.attachSearch(handler);
		trigger(bClick);
		assert.ok(bEventHandlerCalled, "Search handler called.");

		oSearch11.setEnableFilterMode(false);
		oSearch11.setValue(sVal);
		sap.ui.getCore().applyChanges();

		bEventHandlerCalled = false;
		trigger(bClick);
		assert.ok(!bEventHandlerCalled, "Search handler not called.");

		oSearch11.detachSearch(handler);
	}

	QUnit.test("Press ENTER", function(assert) {
		testFilterMode(assert, false, "");
	});

	QUnit.test("Click Search Icon", function(assert) {
		testFilterMode(assert, true, "");
	});

	QUnit.test("Click Clear Icon", function(assert) {
		oSearch11.setEnableClear(true);
		sap.ui.getCore().applyChanges();
		testFilterMode(assert, true, "Test");
	});
});


text:
[![Circle CI](https://circleci.com/gh/Financial-Times/content-rw-neo4j.svg?style=shield)](https://circleci.com/gh/Financial-Times/content-rw-neo4j)
[![Go Report Card](https://goreportcard.com/badge/github.com/Financial-Times/content-rw-neo4j)](https://goreportcard.com/report/github.com/Financial-Times/content-rw-neo4j)
[![Coverage Status](https://coveralls.io/repos/github/Financial-Times/content-rw-neo4j/badge.svg)](https://coveralls.io/github/Financial-Times/content-rw-neo4j)

__An API for reading/writing Content into Neo4j. Expects the content JSON supplied by the ingester.__

## Installation

Download the source code, dependencies, and build the binary:

```
go get github.com/Financial-Times/content-rw-neo4j
cd $GOPATH/src/github.com/Financial-Times/content-rw-neo4j
go install
```

## Running

Run unit tests only:

```shell script
go test -v -race ./...
```

To execute the integration tests, you must provide `GITHUB_USERNAME` and
`GITHUB_TOKEN` because the service depends on internal repositories:

```shell script
GITHUB_USERNAME="<user-name>" GITHUB_TOKEN="<personal-access-token>" \
docker-compose -f docker-compose-tests.yml up -d --build && \
docker logs -f test-runner && \
docker-compose -f docker-compose-tests.yml down -v
```

To run the binary:

```
$GOPATH/bin/content-rw-neo4j \
   --neo-url={neo4jUrl} \
   --port={port} \
   --batchSize=50 \
```

All arguments are optional, run the following command to see the defaults:

```
$GOPATH/bin/content-rw-neo4j --help
```

## Building

The application is continuously built by CircleCI.

The docker image of the service is built by Dockerhub based on the git release tag.

To prepare a new git release, go to the repo page on GitHub and create a new release.

## Updating the Model

Currently we use a subset of the fields that we get from the Ingester but if more fields are needed to be pulled in then update the model.go

The flow of information is as follows: Kafka (CMSPublication) => Ingester => content-rw-neo4j

## Content Types

Currently, the following content types are eligible for being written into Neo:

* Article
* ContentPackage
* Content
* Video
* Graphic
* Audio

Additionally, any content payloads which contain a `body` property, will be written to Neo.

## API

Write content to Neo4j:

```
curl http://localhost:8080/content/:uuid -XPUT -H'Content-Type: application/json' --data '{"uuid":":uuid","body":"<body></body>"}'
```

Read content from Neo4j:

```
curl http://localhost:8080/content/:uuid'
```

Count content in Neo4j:

```
curl http://localhost:8080/content/__count'
```

Delete content from Neo4j:

```
curl http://localhost:8080/content/:uuid -XDELETE '
```

Please see the OpenAPI [spec](./api/api.yml) for details.

### Logging

* The application uses [go-logger](https://github.com/Financial-Times/go-logger ); the log file is initialised in [main.go](main.go).

redpajama_set_name: RedPajamaGithub


text:
const projection = {
  Init: async (store) => {
    // mdis-start read-store-api
    await store.defineTable('TestTable', {
      indexes: {
        firstIndexName: 'number',
        secondIndexName: 'string',
      },
      fields: [
        'firstFieldName',
        'secondFieldName',
        'firstJsonName',
        'secondJsonName',
      ],
    })
    // mdis-stop read-store-api
  },

  INSERT_TEST: async (store, event) => {
    const testEventContent = event.payload.content

    // mdis-start read-store-api
    await store.insert('TestTable', {
      firstIndexName: 1,
      secondIndexName: 'idx-a',
      firstFieldName: testEventContent,
      secondFieldName: 0,
      firstJsonName: { a: 1, b: 2, e: 10 },
      secondJsonName: [1, 2, 3],
    })
    // mdis-stop read-store-api

    await store.insert('TestTable', {
      firstIndexName: 2,
      secondIndexName: 'idx-a',
      firstFieldName: null,
      secondFieldName: 100,
      firstJsonName: { c: 3, d: 4, e: 20 },
      secondJsonName: null,
    })

    await store.insert('TestTable', {
      firstIndexName: 3,
      secondIndexName: 'idx-b',
      firstFieldName: null,
      secondFieldName: 200,
      firstJsonName: null,
      secondJsonName: [3, 2, 1],
    })

    await store.insert('TestTable', {
      firstIndexName: 4,
      secondIndexName: null,
      firstFieldName: testEventContent,
      secondFieldName: null,
      firstJsonName: null,
      secondJsonName: null,
    })
  },

  UPDATE_TEST: async (store, event) => {
    const testEventContent = event.payload.content

    // mdis-start read-store-api
    await store.update(
      'TestTable',
      {
        firstIndexName: { $gt: 1 },
        secondIndexName: 'idx-a',
      },
      {
        $set: {
          'firstJsonName.f': 'inner-field',
          firstFieldName: 'outer-field',
          secondJsonName: ['outer', 'json', 'value', testEventContent],
        },
        $unset: {
          'firstJsonName.d': true,
        },
        $inc: {
          'firstJsonName.e': 5,
          secondFieldName: 42,
        },
      }
    )
    // mdis-stop read-store-api

    await store.update(
      'TestTable',
      {
        $or: [
          {
            $and: [
              { firstIndexName: { $lt: 1 } },
              { secondIndexName: 'idx-a' },
            ],
          },
          { secondIndexName: 'idx-b' },
        ],
      },
      {
        $set: {
          firstFieldName: 'outer-field',
          secondJsonName: ['outer', 'json', 'value', testEventContent],
        },
      }
    )
  },

  UPSERT_TEST: async (store, event) => {
    const testEventContent = event.payload.content

    // mdis-start read-store-api
    await store.update(
      'TestTable',
      { firstIndexName: 10 },
      {
        $set: {
          'firstJsonName.f': 'inner-field',
          firstFieldName: 'outer-field',
          secondJsonName: ['outer', 'json', 'value', testEventContent],
        },
      },
      { upsert: true }
    )
    // mdis-stop read-store-api
  },

  DELETE_TEST: async (store, event) => {
    const testEventContent = event.payload.content

    // mdis-start read-store-api
    await store.delete('TestTable', {
      firstIndexName: { $gt: 1 },
      secondIndexName: 'idx-a',
    })
    // mdis-stop read-store-api

    await store.delete('TestTable', {
      $or: [
        {
          $and: [{ firstIndexName: { $lt: 1 } }, { secondIndexName: 'idx-a' }],
        },
        { secondIndexName: testEventContent },
      ],
    })
  },
}

export default projection
// mdis-stop


text:
<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet href="test-to-html.xsl" type="text/xml"?>

<!--

Copyright (c) 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, Institut National de
Recherche en Informatique et en Automatique, Keio University).  All
Rights Reserved.  This program is distributed under the W3C's Software
Intellectual Property License.  This program is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.

See W3C License http://www.w3.org/Consortium/Legal/ for more details.

-->

<!DOCTYPE test SYSTEM "dom3.dtd">
<test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-3" name="documentadoptnode07">
<metadata>
<title>documentadoptnode07</title>
<creator>IBM</creator>
<description>
	Invoke the adoptNode method on this document with the value of the source parameter as itself.
	Verify if a NOT_SUPPORTED_ERR is thrown.
</description>
<contributor>Neil Delima</contributor>
<date qualifier="created">2002-06-10</date>
<subject resource="http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core#Document3-adoptNode"/>
</metadata>
<var name="doc" type="Document"/>
<var name="adoptedDoc" type="Node"/>
<load var="doc" href="hc_staff" willBeModified="true"/>
<assertDOMException id="throw_NOT_SUPPORTED_ERR">
<NOT_SUPPORTED_ERR>
<adoptNode var="adoptedDoc" obj="doc" source="doc"/>
</NOT_SUPPORTED_ERR>
</assertDOMException>
</test>


text:
package com.opensymphony.xwork2.validator;

import com.opensymphony.xwork2.*;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.test.TestBean2;

import java.util.*;

import org.easymock.EasyMock;

/**
 * VisitorFieldValidatorModelTest
 *
 * @author Jason Carreira
 *         Date: Mar 18, 2004 2:51:42 PM
 */
public class VisitorFieldValidatorModelTest extends XWorkTestCase {

    protected VisitorValidatorModelAction action;

    @Override
    public void setUp() throws Exception {
        super.setUp();
        action = new VisitorValidatorModelAction();

        TestBean bean = action.getBean();
        Calendar cal = new GregorianCalendar(1900, 01, 01);
        bean.setBirth(cal.getTime());
        bean.setCount(-1);

        ActionConfig config = new ActionConfig.Builder("", "name", "").build();
        ActionInvocation invocation = EasyMock.createNiceMock(ActionInvocation.class);
        ActionProxy proxy = EasyMock.createNiceMock(ActionProxy.class);

        EasyMock.expect(invocation.getProxy()).andReturn(proxy).anyTimes();
        EasyMock.expect(invocation.getAction()).andReturn(null).anyTimes();
        EasyMock.expect(invocation.invoke()).andReturn(Action.SUCCESS).anyTimes();
        EasyMock.expect(proxy.getMethod()).andReturn("execute").anyTimes();
        EasyMock.expect(proxy.getConfig()).andReturn(config).anyTimes();

        EasyMock.replay(invocation);
        EasyMock.replay(proxy);

        ActionContext.getContext().setActionInvocation(invocation);

    }

    public void testModelFieldErrorsAddedWithoutFieldPrefix() throws Exception {
        container.getInstance(ActionValidatorManager.class).validate(action, null);
        assertTrue(action.hasFieldErrors());

        Map<String, List<String>> fieldErrors = action.getFieldErrors();

        // the required string validation inherited from the VisitorValidatorTestAction
        assertTrue(fieldErrors.containsKey("context"));

        // the bean validation which is now at the top level because we set the appendPrefix to false
        assertTrue(fieldErrors.containsKey("name"));

        List<String> nameMessages = fieldErrors.get("name");
        assertEquals(1, nameMessages.size());

        String nameMessage = (String) nameMessages.get(0);
        assertEquals("You must enter a name.", nameMessage);
    }

    public void testModelFieldErrorsAddedWithoutFieldPrefixForInterface() throws Exception {
        TestBean origBean = action.getBean();
        TestBean2 bean = new TestBean2();
        bean.setBirth(origBean.getBirth());
        bean.setCount(origBean.getCount());
        action.setBean(bean);
        assertTrue(action.getBean() instanceof TestBean2);

        container.getInstance(ActionValidatorManager.class).validate(action, null);
        assertTrue(action.hasFieldErrors());

        Map<String, List<String>> fieldErrors = action.getFieldErrors();

        // the required string validation inherited from the VisitorValidatorTestAction
        assertTrue(fieldErrors.containsKey("context"));

        // the bean validation which is now at the top level because we set the appendPrefix to false
        assertTrue(fieldErrors.containsKey("name"));

        List<String> nameMessages = fieldErrors.get("name");
        assertEquals(1, nameMessages.size());

        String nameMessage = nameMessages.get(0);
        assertEquals("You must enter a name.", nameMessage);

        // should also have picked up validation check for DataAware interface
        assertTrue(fieldErrors.containsKey("data"));

        List<String> dataMessages = fieldErrors.get("data");
        assertEquals(1, dataMessages.size());

        String dataMessage = dataMessages.get(0);
        assertEquals("You must enter a value for data.", dataMessage);
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
        ActionContext.setContext(null);
    }
}


text:
package org.broadinstitute.hellbender.utils.mcmc;

import org.apache.commons.math3.random.RandomGenerator;
import org.apache.commons.math3.random.RandomGeneratorFactory;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.Function;

/**
 * Created by davidben on 11/24/15.
 */
public final class AdaptiveMetropolisSamplerUnitTest {
    private static final double INITIAL_STEP_SIZE = 0.1;
    private static final double INITIAL_GAUSSIAN_GUESS = 0;
    private static final double INITIAL_BETA_GUESS = 0.5;
    private static final int NUM_BURN_IN_STEPS = 1000;
    private static final int NUM_SAMPLES = 5000;

    private static final int RANDOM_SEED = 13;

    @Test
    public void testBeta() {
        final RandomGenerator rng = RandomGeneratorFactory.createRandomGenerator(new Random(RANDOM_SEED));
        for (final double a : Arrays.asList(10, 20, 30)) {
            for (final double b : Arrays.asList(10, 20, 30)) {

                final double theoreticalMean = a / (a + b);
                final double theoreticalVariance = a*b/((a+b)*(a+b)*(a+b+1));

                //Note: this is the theoretical standard deviation of the sample mean given uncorrelated
                //samples.  The sample mean will have a greater variance here because samples are correlated.
                final double standardDeviationOfMean = Math.sqrt(theoreticalVariance / NUM_SAMPLES);

                final Function<Double, Double> logPDF = x -> (a - 1) * Math.log(x) + (b - 1) * Math.log(1 - x);
                final AdaptiveMetropolisSampler sampler = new AdaptiveMetropolisSampler(INITIAL_BETA_GUESS, INITIAL_STEP_SIZE, 0, 1);
                final List<Double> samples = sampler.sample(rng, logPDF, NUM_SAMPLES, NUM_BURN_IN_STEPS);

                final double sampleMean = samples.stream().mapToDouble(x -> x).average().getAsDouble();
                final double sampleMeanSquare = samples.stream().mapToDouble(x -> x*x).average().getAsDouble();
                final double sampleVariance = (sampleMeanSquare - sampleMean * sampleMean)*NUM_SAMPLES/(NUM_SAMPLES-1);

                Assert.assertEquals(sampleMean, theoreticalMean, 10 * standardDeviationOfMean);
                Assert.assertEquals(sampleVariance, theoreticalVariance, 10e-4);
            }
        }
    }

    @Test
    public void testGaussian() {
        final RandomGenerator rng = RandomGeneratorFactory.createRandomGenerator(new Random(RANDOM_SEED));
        for (final double theoreticalMean : Arrays.asList(0)) {
            for (final double precision : Arrays.asList(1.0)) {
                final double variance = 1/precision;

                //Note: this is the theoretical standard deviation of the sample mean given uncorrelated
                //samples.  The sample mean will have a greater variance here because samples are correlated.
                final double standardDeviationOfMean = Math.sqrt(variance / NUM_SAMPLES);

                final Function<Double, Double> logPDF = x -> -(precision/2)*(x-theoreticalMean)*(x-theoreticalMean);
                final AdaptiveMetropolisSampler sampler = new AdaptiveMetropolisSampler(INITIAL_GAUSSIAN_GUESS, INITIAL_STEP_SIZE,
                        Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
                final List<Double> samples = sampler.sample(rng, logPDF, NUM_SAMPLES, NUM_BURN_IN_STEPS);

                final double sampleMean = samples.stream().mapToDouble(x -> x).average().getAsDouble();
                final double sampleMeanSquare = samples.stream().mapToDouble(x -> x*x).average().getAsDouble();
                final double sampleVariance = (sampleMeanSquare - sampleMean * sampleMean)*NUM_SAMPLES/(NUM_SAMPLES-1);

                Assert.assertEquals(sampleMean, theoreticalMean, 6 * standardDeviationOfMean);
                Assert.assertEquals(sampleVariance, variance, variance/10);
            }
        }
    }
}


text:
export declare type GraphiQLData = {
    endpointURL: string;
    subscriptionsEndpoint?: string;
    query?: string;
    variables?: Object;
    operationName?: string;
    result?: Object;
    passHeader?: string;
    editorTheme?: string;
    websocketConnectionParams?: Object;
    rewriteURL?: boolean;
};
export declare function renderGraphiQL(data: GraphiQLData): string;


text:
import { Component, ViewChild } from '@angular/core';
import { Platform, Nav } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { TranslateService } from 'ng2-translate';
import { HomePage } from '../pages/home/home';
import { MapPage } from '../pages/map/map';
import { RatingPagePage } from '../pages/rating-page/rating-page';

import * as firebase from 'firebase';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) public nav: Nav;

  public rootPage: any = HomePage;
  public pages: Array<{ title: string, component: any }>;

  constructor(platform: Platform, public translate: TranslateService, public statusBar: StatusBar, public splashScreen: Splashscreen) {

    const firebaseConfig = {
      apiKey: "AIzaSyClOWx3rRxBGM1yshjpC-brIQfoyMG4k0M",
      authDomain: "mtransit-5edbf.firebaseapp.com",
      databaseURL: "https://mtransit-5edbf.firebaseio.com",
      storageBucket: "mtransit-5edbf.appspot.com",
      messagingSenderId: "883599256403"
    };

    this.pages = [
      { title: 'Map Page', component: MapPage },
      { title: 'Rating Page', component: RatingPagePage }
    ];

    firebase.initializeApp(firebaseConfig);

    platform.ready().then(() => {
      this.translate.use('en');
      StatusBar.styleDefault();
      Splashscreen.hide();
    });
  }

  public openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
  }

  public swapLanguage() {

    if (this.translate.currentLang == "en") {
      this.translate.use('fr');
    } else {
      this.translate.use('en');
    }
  }

  public logout() {
    this.nav.setRoot(HomePage);
  }

}


text:
.class public Landroid/support/v4/media/session/MediaControllerCompatApi26$TransportControls;
.super Landroid/support/v4/media/session/MediaControllerCompatApi23$TransportControls;
.source "MediaControllerCompatApi26.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/v4/media/session/MediaControllerCompatApi26;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "TransportControls"
.end annotation

# direct methods
.method public constructor <init>()V
    .registers 1

    .prologue
    .line 34
    invoke-direct {p0}, Landroid/support/v4/media/session/MediaControllerCompatApi23$TransportControls;-><init>()V

    return-void
.end method

.method public static setRepeatMode(Ljava/lang/Object;I)V
    .registers 2
    .param p0, "controlsObj"    # Ljava/lang/Object;
    .param p1, "repeatMode"    # I

    .prologue
    .line 36
    check-cast p0, Landroid/media/session/MediaController$TransportControls;

    .end local p0    # "controlsObj":Ljava/lang/Object;
    invoke-virtual {p0, p1}, Landroid/media/session/MediaController$TransportControls;->setRepeatMode(I)V

    .line 37
    return-void
.end method

.method public static setShuffleModeEnabled(Ljava/lang/Object;Z)V
    .registers 2
    .param p0, "controlsObj"    # Ljava/lang/Object;
    .param p1, "enabled"    # Z

    .prologue
    .line 40
    check-cast p0, Landroid/media/session/MediaController$TransportControls;

    .end local p0    # "controlsObj":Ljava/lang/Object;
    invoke-virtual {p0, p1}, Landroid/media/session/MediaController$TransportControls;->setShuffleModeEnabled(Z)V

    .line 41
    return-void
.end method


text:
/*******************************************************************************
* Bossanova PHP Framework 1.0.1
* 2013 Paul Hodel <paul.hodel@gmail.com>
* http://www.bossanova-framework.com
*
* JS UI Accordion
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
********************************************************************************/

.jquery_accordion
{
	background-color:#d4d4d4;
	height:100%;
}
.jquery_accordion > div
{
	background-color:#d4d4d4;
}
.jquery_accordion h1
{
	margin:0px;
	margin-bottom: 1;
	padding: 6px;
	text-align:center;
	-webkit-box-shadow: 0 3px 3px #CCC;
	-moz-box-shadow: 0 3px 3px #CCC;
	background: #e3e3e3;
	filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ededed', endColorstr='#e3e3e3');
	background: -webkit-gradient(linear, left top, left bottom, from(#ededed), to(#e3e3e3));
	background: -moz-linear-gradient(top,  #ededed,  #e3e3e3);
	border: solid 1px #F2F2F2;
	background-color: #e3e3e3;
	font-size:1em;
	font-weight:normal;
	cursor:pointer;
}


text:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace WmcSoft.Drawing
{
    public unsafe abstract class Quantizer
    {
        /// <summary>
        /// Construct the quantizer
        /// </summary>
        /// <param name="singlePass">If true, the quantization only needs to loop through the source pixels once</param>
        /// <remarks>
        /// If you construct this class with a true value for singlePass, then the code will, when quantizing your image,
        /// only call the 'QuantizeImage' function. If two passes are required, the code will call 'InitialQuantizeImage'
        /// and then 'QuantizeImage'.
        /// </remarks>
        protected Quantizer(bool singlePass)
        {
            _singlePass = singlePass;
        }

        /// <summary>
        /// Quantize an image and return the resulting output bitmap
        /// </summary>
        /// <param name="source">The image to quantize</param>
        /// <returns>A quantized version of the image</returns>
        public Bitmap Quantize(Image source)
        {
            // Get the size of the source image
            int height = source.Height;
            int width = source.Width;

            // And construct a rectangle from these dimensions
            Rectangle bounds = new Rectangle(0, 0, width, height);

            // First off take a 32bpp copy of the image
            Bitmap copy = new Bitmap(width, height, PixelFormat.Format32bppArgb);

            // And construct an 8bpp version
            Bitmap output = new Bitmap(width, height, PixelFormat.Format8bppIndexed);

            // Now lock the bitmap into memory
            using (Graphics g = Graphics.FromImage(copy)) {
                g.PageUnit = GraphicsUnit.Pixel;

                // Draw the source image onto the copy bitmap,
                // which will effect a widening as appropriate.
                g.DrawImageUnscaled(source, bounds);
            }

            // Define a pointer to the bitmap data
            BitmapData sourceData = null;

            try {
                // Get the source image bits and lock into memory
                sourceData = copy.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

                // Call the FirstPass function if not a single pass algorithm.
                // For something like an octree quantizer, this will run through
                // all image pixels, build a data structure, and create a palette.
                if (!_singlePass)
                    FirstPass(sourceData, width, height);

                // Then set the color palette on the output bitmap. I'm passing in the current palette
                // as there's no way to construct a new, empty palette.
                output.Palette = this.GetPalette(output.Palette);

                // Then call the second pass which actually does the conversion
                SecondPass(sourceData, output, width, height, bounds);
            } finally {
                // Ensure that the bits are unlocked
                copy.UnlockBits(sourceData);
            }

            // Last but not least, return the output bitmap
            return output;
        }

        /// <summary>
        /// Execute the first pass through the pixels in the image
        /// </summary>
        /// <param name="sourceData">The source data</param>
        /// <param name="width">The width in pixels of the image</param>
        /// <param name="height">The height in pixels of the image</param>
        protected virtual void FirstPass(BitmapData sourceData, int width, int height)
        {
            // Define the source data pointers. The source row is a byte to
            // keep addition of the stride value easier (as this is in bytes)
            byte* pSourceRow = (byte*)sourceData.Scan0.ToPointer();
            Int32* pSourcePixel;

            // Loop through each row
            for (int row = 0; row < height; row++) {
                // Set the source pixel to the first pixel in this row
                pSourcePixel = (Int32*)pSourceRow;

                // And loop through each column
                for (int col = 0; col < width; col++, pSourcePixel++)
                    // Now I have the pixel, call the FirstPassQuantize function...
                    InitialQuantizePixel((Color32*)pSourcePixel);

                // Add the stride to the source row
                pSourceRow += sourceData.Stride;
            }
        }

        /// <summary>
        /// Execute a second pass through the bitmap
        /// </summary>
        /// <param name="sourceData">The source bitmap, locked into memory</param>
        /// <param name="output">The output bitmap</param>
        /// <param name="width">The width in pixels of the image</param>
        /// <param name="height">The height in pixels of the image</param>
        /// <param name="bounds">The bounding rectangle</param>
        protected virtual void SecondPass(BitmapData sourceData, Bitmap output, int width, int height, Rectangle bounds)
        {
            BitmapData outputData = null;

            try {
                // Lock the output bitmap into memory
                outputData = output.LockBits(bounds, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);

                // Define the source data pointers. The source row is a byte to
                // keep addition of the stride value easier (as this is in bytes)
                byte* pSourceRow = (byte*)sourceData.Scan0.ToPointer();
                Int32* pSourcePixel = (Int32*)pSourceRow;
                Int32* pPreviousPixel = pSourcePixel;

                // Now define the destination data pointers
                byte* pDestinationRow = (byte*)outputData.Scan0.ToPointer();
                byte* pDestinationPixel = pDestinationRow;

                // And convert the first pixel, so that I have values going into the loop
                byte pixelValue = QuantizePixel((Color32*)pSourcePixel);

                // Assign the value of the first pixel
                *pDestinationPixel = pixelValue;

                // Loop through each row
                for (int row = 0; row < height; row++) {
                    // Set the source pixel to the first pixel in this row
                    pSourcePixel = (Int32*)pSourceRow;

                    // And set the destination pixel pointer to the first pixel in the row
                    pDestinationPixel = pDestinationRow;

                    // Loop through each pixel on this scan line
                    for (int col = 0; col < width; col++, pSourcePixel++, pDestinationPixel++) {
                        // Check if this is the same as the last pixel. If so use that value
                        // rather than calculating it again. This is an inexpensive optimisation.
                        if (*pPreviousPixel != *pSourcePixel) {
                            // Quantize the pixel
                            pixelValue = QuantizePixel((Color32*)pSourcePixel);

                            // And setup the previous pointer
                            pPreviousPixel = pSourcePixel;
                        }

                        // And set the pixel in the output
                        *pDestinationPixel = pixelValue;
                    }

                    // Add the stride to the source row
                    pSourceRow += sourceData.Stride;

                    // And to the destination row
                    pDestinationRow += outputData.Stride;
                }
            } finally {
                // Ensure that I unlock the output bits
                output.UnlockBits(outputData);
            }
        }

        /// <summary>
        /// Override this to process the pixel in the first pass of the algorithm
        /// </summary>
        /// <param name="pixel">The pixel to quantize</param>
        /// <remarks>
        /// This function need only be overridden if your quantize algorithm needs two passes,
        /// such as an Octree quantizer.
        /// </remarks>
        protected virtual void InitialQuantizePixel(Color32* pixel)
        {
        }

        /// <summary>
        /// Override this to process the pixel in the second pass of the algorithm
        /// </summary>
        /// <param name="pixel">The pixel to quantize</param>
        /// <returns>The quantized value</returns>
        protected abstract byte QuantizePixel(Color32* pixel);

        /// <summary>
        /// Retrieve the palette for the quantized image
        /// </summary>
        /// <param name="original">Any old palette, this is overrwritten</param>
        /// <returns>The new color palette</returns>
        protected abstract ColorPalette GetPalette(ColorPalette original);

        /// <summary>
        /// Flag used to indicate whether a single pass or two passes are needed for quantization.
        /// </summary>
        private bool _singlePass;

        /// <summary>
        /// Struct that defines a 32 bpp colour
        /// </summary>
        /// <remarks>
        /// This struct is used to read data from a 32 bits per pixel image
        /// in memory, and is ordered in this manner as this is the way that
        /// the data is layed out in memory
        /// </remarks>
        [StructLayout(LayoutKind.Explicit)]
        public struct Color32
        {
            /// <summary>
            /// Holds the blue component of the colour
            /// </summary>
            [FieldOffset(0)]
            public byte Blue;
            /// <summary>
            /// Holds the green component of the colour
            /// </summary>
            [FieldOffset(1)]
            public byte Green;
            /// <summary>
            /// Holds the red component of the colour
            /// </summary>
            [FieldOffset(2)]
            public byte Red;
            /// <summary>
            /// Holds the alpha component of the colour
            /// </summary>
            [FieldOffset(3)]
            public byte Alpha;

            /// <summary>
            /// Permits the color32 to be treated as an int32
            /// </summary>
            [FieldOffset(0)]
            public int ARGB;

            /// <summary>
            /// Return the color for this Color32 object
            /// </summary>
            public Color Color {
                get { return Color.FromArgb(Alpha, Red, Green, Blue); }
            }
        }
    }
}


text:
public interface INotificationAdapter {
	public void Send(Notification notification);
}

public interface IDeliveryVerifiableNotificationAdapter : INotificationAdapter { //We extend (inherit) INotificationAdapter via another interface
	public void UpdateDeliveryReport(DeliveryResult result);
}

public class SmsAdapter : IDeliveryVerifiableNotificationAdapter { //Implement IDeliveryVerifiableNotificationAdapter since delivery reports are supported.
	public Send(Notification notification) { /* Implementation for sending SMS */ }
	public void UpdateDeliveryReport(DeliveryResult result) { /* Implementation for updating SMS delivery reports */ }
}

public class EmailAdapter : IDeliveryVerifiableNotificationAdapter { //Implement IDeliveryVerifiableNotificationAdapter since read receipts are supported.
	public Send(Notification notification) { /* Implementation for sending SMS */ }
	public void UpdateDeliveryReport(DeliveryResult result) { /* Implementation for updating Email read receipts */ }
}

public class ApnsAdapter : INotificationAdapter { //Not forced to implement UpdateDeliveryReport
	public Send(Notification notification) { /*Implementation for sending to Apple Push Notifications*/ }
}

public class GcmAdapter : INotificationAdapter { //Not forced to implement UpdateDeliveryReport
	public Send(Notification notification) { /*Implementation for sending Google Cloud Messages*/ }
}


text:
<!DOCTYPE HTML>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport"
          content="target-densitydpi=device-dpi, width=device-width, initial-scale=1.0, user-scalable=no"/>
    <link rel="stylesheet" type="text/css" href="css/index.css">
    <title>uexHandwriting</title>

uexQcloudAV

        <input class="" type="button" value="open" onclick="openButton();"/>
        <input class="" type="button" value="start" onclick="startButton();"/>
        <input class="" type="button" value="play" onclick="playButton();"/>
        <input class="" type="button" value="stop" onclick="stopButton();"/>
        <input class="" type="button" value="pause" onclick="pauseButton();"/>
        <input class="" type="button" value="close" onclick="closeButton();"/>
        <input class="" type="button" value="getCurrentTime" onclick="getCurrentTime();"/>
        <input class="" type="button" value="seekTo" onclick="seekTo();"/>


text:
class CriteriaAssignmentFilesJoin < ActiveRecord::Base
  belongs_to :criterion, polymorphic: true
  belongs_to :assignment_file
  accepts_nested_attributes_for :assignment_file, :criterion

  has_one :template_division

  def build_criterion(params)
    params[:type] ||= 'FlexibleCriterion'
    params[:max_mark] ||= 1
    self.criterion = params[:type].constantize.new(params.except(:type))
  end
end


text:
var startTime;
var curTest = 0;
var nbTests = 1000000;
var typeTest = 1;

function startTest(typeT) {
   typeTest = typeT;
   var d = new Date();
   startTime = d.getTime();
   test();
}

function test() {
   var batchSize = 1;
   var d = new Date();
   diffTime = Math.floor(d.getTime() - startTime) / 1000;
   $("#nbSecs").html(diffTime);
   if (curTest > 0)
      $("#insertsPerSecond").html(curTest*batchSize/diffTime);
   curTest++;
   $("#nbAttempts").html(curTest);
   for (var iAns = 0; iAns < batchSize; iAns++) {
      var qid = Math.floor(Math.random() * 1000000000);
      questionKeys[qid] = "test";
      answersToSend[qid] = { answer: "test" + (curTest * 1000 + iAns), score: curTest, sending:false };
   }
   sendAnswers();
}


text:
<?php

namespace Tests\ConsoleHelpers\SVNBuddy\Repository\RevisionLog;

use ConsoleHelpers\SVNBuddy\Database\DatabaseCache;
use ConsoleHelpers\SVNBuddy\Repository\RevisionLog\RepositoryFiller;

class RepositoryFillerTest extends AbstractDatabaseAwareTestCase
{

	/**
	 * Path collision detector.
	 *
	 * @var RepositoryFiller
	 */
	protected $repositoryFiller;

	protected function setUp()
	{
		parent::setUp();

		$this->repositoryFiller = new RepositoryFiller($this->database, new DatabaseCache($this->database));
	}

	/**
	 * @dataProvider addProjectDataProvider
	 */
	public function testAddProject($is_deleted, $bug_regexp)
	{
		$project_id = $this->repositoryFiller->addProject('/path/', $is_deleted, $bug_regexp);

		$this->assertTableContent(
			'Projects',
			array(
				array(
					'Id' => $project_id,
					'Path' => '/path/',
					'BugRegExp' => $bug_regexp,
					'IsDeleted' => $is_deleted,
				),
			)
		);

		$this->assertTableEmpty('Paths');
	}

	public function addProjectDataProvider()
	{
		return array(
			array('0', null),
			array('0', ''),
			array('1', ''),
		);
	}

	public function testAddRepositoryWideProject()
	{
		$this->repositoryFiller->addProject('/');

		$this->assertTableContent(
			'Paths',
			array(
				array(
					'Id' => '1',
					'Path' => '/',
					'PathNestingLevel' => '0',
					'PathHash' => '2043925204',
					'RefName' => '',
					'ProjectPath' => '/',
					'RevisionAdded' => '0',
					'RevisionDeleted' => null,
					'RevisionLastSeen' => '0',
				),
			)
		);
	}

	/**
	 * @dataProvider setProjectStatusDataProvider
	 */
	public function testSetProjectStatus($is_deleted_add, $is_deleted_edit)
	{
		$project_id = $this->repositoryFiller->addProject('/path/', $is_deleted_add);
		$this->repositoryFiller->setProjectStatus($project_id, $is_deleted_edit);

		$this->assertTableContent(
			'Projects',
			array(
				array(
					'Id' => $project_id,
					'Path' => '/path/',
					'BugRegExp' => null,
					'IsDeleted' => (string)$is_deleted_edit,
				),
			)
		);
	}

	public function setProjectStatusDataProvider()
	{
		return array(
			array(0, 1),
			array(1, 0),
		);
	}

	public function testSetProjectBugRegexp()
	{
		$project_id = $this->repositoryFiller->addProject('/path/');
		$this->repositoryFiller->setProjectBugRegexp($project_id, 'regexp');

		$this->assertTableContent(
			'Projects',
			array(
				array(
					'Id' => $project_id,
					'Path' => '/path/',
					'BugRegExp' => 'regexp',
					'IsDeleted' => '0',
				),
			)
		);
	}

	public function testAddCommit()
	{
		$this->repositoryFiller->addCommit(100, 'user', 123, 'msg');

		$this->assertTableContent(
			'Commits',
			array(
				array(
					'Revision' => '100',
					'Author' => 'user',
					'Date' => '123',
					'Message' => 'msg',
				),
			)
		);
	}

	public function testAddCommitToProject()
	{
		$project_id = $this->repositoryFiller->addProject('/path/to/project/');
		$this->repositoryFiller->addCommit(100, 'user', 123, 'msg');
		$this->repositoryFiller->addCommitToProject(100, $project_id);

		$this->assertTableContent(
			'CommitProjects',
			array(
				array(
					'Revision' => '100',
					'ProjectId' => $project_id,
				),
			)
		);
	}

	public function testAddPath()
	{
		$this->database->setProfiler($this->createStatementProfiler());

		$path1_id = $this->repositoryFiller->addPath(
			'/path/to/project/trunk/file1.txt',
			'trunk',
			'/path/to/project/',
			100
		);

		$path2_id = $this->repositoryFiller->addPath(
			'/path/to/project/trunk/file2.txt',
			'trunk',
			'/path/to/project/',
			100
		);

		$this->assertTableContent(
			'Paths',
			array(
				array(
					'Id' => $path1_id,
					'Path' => '/path/to/project/trunk/file1.txt',
					'PathNestingLevel' => '4',
					'PathHash' => '1256725620',
					'RefName' => 'trunk',
					'ProjectPath' => '/path/to/project/',
					'RevisionAdded' => '100',
					'RevisionDeleted' => null,
					'RevisionLastSeen' => '100',
				),
				array(
					'Id' => $path2_id,
					'Path' => '/path/to/project/trunk/file2.txt',
					'PathNestingLevel' => '4',
					'PathHash' => '222848676',
					'RefName' => 'trunk',
					'ProjectPath' => '/path/to/project/',
					'RevisionAdded' => '100',
					'RevisionDeleted' => null,
					'RevisionLastSeen' => '100',
				),
			)
		);
	}

	public function testAddPathWithPropagation()
	{
		$this->repositoryFiller->addPath('/project/', '', '/project/', 100);
		$this->repositoryFiller->addPath('/project/trunk/', 'trunk', '/project/', 200);

		$this->assertTableContent(
			'Paths',
			array(
				array(
					'Id' => '1',
					'Path' => '/project/',
					'PathNestingLevel' => '1',
					'PathHash' => '3761055950',
					'RefName' => '',
					'ProjectPath' => '/project/',
					'RevisionAdded' => '100',
					'RevisionDeleted' => null,
					'RevisionLastSeen' => '200',
				),
				array(
					'Id' => '2',
					'Path' => '/project/trunk/',
					'PathNestingLevel' => '2',
					'PathHash' => '2969229352',
					'RefName' => 'trunk',
					'ProjectPath' => '/project/',
					'RevisionAdded' => '200',
					'RevisionDeleted' => null,
					'RevisionLastSeen' => '200',
				),
			)
		);
	}

	public function testAddPathToCommit()
	{
		$this->repositoryFiller->addCommit(100, 'user', 123, 'msg');
		$copy_path_id = $this->repositoryFiller->addPath('/file1.txt', '', '/', 100);

		$this->repositoryFiller->addCommit(200, 'user', 123, 'msg');
		$path_id = $this->repositoryFiller->addPath('/file2.txt', '', '/', 200);

		$this->repositoryFiller->addPathToCommit(200, 'A', 'dir', $path_id, 100, $copy_path_id);

		$this->assertTableContent(
			'CommitPaths',
			array(
				array(
					'Revision' => '200',
					'Action' => 'A',
					'Kind' => 'dir',
					'PathId' => $path_id,
					'CopyRevision' => '100',
					'CopyPathId' => $copy_path_id,
				),
			)
		);
	}

	public function testTouchPath()
	{
		$this->repositoryFiller->addCommit(100, 'user', 123, 'msg');
		$this->repositoryFiller->addPath('/file1.txt', '', '/', 100);

		$this->repositoryFiller->touchPath('/file1.txt', 200, array('RevisionAdded' => 500));

		$this->assertTableContent(
			'Paths',
			array(
				array(
					'Id' => '1',
					'Path' => '/file1.txt',
					'PathNestingLevel' => '0',
					'PathHash' => '2532574337',
					'RefName' => '',
					'ProjectPath' => '/',
					'RevisionAdded' => '500',
					'RevisionDeleted' => null,
					'RevisionLastSeen' => '100',
				),
			)
		);
	}

	public function testTouchPathWithPropagation()
	{
		$this->repositoryFiller->addPath('/project/', '', '/project/', 100);
		$this->repositoryFiller->addPath('/project/trunk/', 'trunk', '/project/', 200);
		$this->repositoryFiller->addPath('/project/trunk/file1.txt', 'trunk', '/project/', 300);

		$this->repositoryFiller->touchPath('/project/trunk/file1.txt', 400, array('RevisionAdded' => 500));

		$this->assertTableContent(
			'Paths',
			array(
				array(
					'Id' => '1',
					'Path' => '/project/',
					'PathNestingLevel' => '1',
					'PathHash' => '3761055950',
					'RefName' => '',
					'ProjectPath' => '/project/',
					'RevisionAdded' => '100',
					'RevisionDeleted' => null,
					'RevisionLastSeen' => '400',
				),
				array(
					'Id' => '2',
					'Path' => '/project/trunk/',
					'PathNestingLevel' => '2',
					'PathHash' => '2969229352',
					'RefName' => 'trunk',
					'ProjectPath' => '/project/',
					'RevisionAdded' => '200',
					'RevisionDeleted' => null,
					'RevisionLastSeen' => '400',
				),
				array(
					'Id' => '3',
					'Path' => '/project/trunk/file1.txt',
					'PathNestingLevel' => '2',
					'PathHash' => '456399860',
					'RefName' => 'trunk',
					'ProjectPath' => '/project/',
					'RevisionAdded' => '500',
					'RevisionDeleted' => null,
					'RevisionLastSeen' => '300',
				),
			)
		);
	}

	/**
	 * @expectedException \InvalidArgumentException
	 * @expectedExceptionMessage The "$fields_hash" variable can't be empty.
	 */
	public function testTouchPathWithoutFields()
	{
		$this->repositoryFiller->touchPath('/path/', 100, array());
	}

	/**
	 * @dataProvider getPathTouchFieldsDataProvider
	 */
	public function testGetPathTouchFields($action, $revision, $path_data, $touch_fields)
	{
		$this->assertEquals(
			$touch_fields,
			$this->repositoryFiller->getPathTouchFields($action, $revision, $path_data)
		);
	}

	public function getPathTouchFieldsDataProvider()
	{
		return array(
			'deleted' => array(
				'D',
				100,
				array('RevisionAdded' => 100, 'RevisionDeleted' => null, 'RevisionLastSeen' => 100),
				array('RevisionDeleted' => 100),
			),
			'restored' => array(
				'A',
				300,
				array('RevisionAdded' => 100, 'RevisionDeleted' => 200, 'RevisionLastSeen' => 100),
				array('RevisionDeleted' => null, 'RevisionLastSeen' => 300),
			),
			'added initially' => array(
				'A',
				200,
				array('RevisionAdded' => 100, 'RevisionDeleted' => null, 'RevisionLastSeen' => 100),
				array('RevisionLastSeen' => 200),
			),
			'added twice' => array(
				'A',
				200,
				array('RevisionAdded' => 100, 'RevisionDeleted' => null, 'RevisionLastSeen' => 100),
				array('RevisionLastSeen' => 200),
			),
			'added in past' => array(
				'A',
				100,
				array('RevisionAdded' => 200, 'RevisionDeleted' => null, 'RevisionLastSeen' => 200),
				array('RevisionAdded' => 100),
			),
			'updated' => array(
				'M',
				200,
				array('RevisionAdded' => 100, 'RevisionDeleted' => null, 'RevisionLastSeen' => 100),
				array('RevisionLastSeen' => 200),
			),
			'updated in past' => array(
				'M',
				100,
				array('RevisionAdded' => 100, 'RevisionDeleted' => null, 'RevisionLastSeen' => 200),
				array(),
			),
			'replaced' => array(
				'R',
				200,
				array('RevisionAdded' => 100, 'RevisionDeleted' => null, 'RevisionLastSeen' => 100),
				array('RevisionLastSeen' => 200),
			),
		);
	}

	public function testMovePathsIntoProject()
	{
		$path_id = $this->repositoryFiller->addPath('/path1/', '', '', 100);
		$this->repositoryFiller->addPath('/path2/', '', '', 100);

		$this->assertTableContent(
			'Paths',
			array(
				array(
					'Id' => '1',
					'Path' => '/path1/',
					'PathNestingLevel' => '1',
					'PathHash' => '3304870543',
					'RefName' => '',
					'ProjectPath' => '',
					'RevisionAdded' => '100',
					'RevisionDeleted' => null,
					'RevisionLastSeen' => '100',
				),
				array(
					'Id' => '2',
					'Path' => '/path2/',
					'PathNestingLevel' => '1',
					'PathHash' => '4023451980',
					'RefName' => '',
					'ProjectPath' => '',
					'RevisionAdded' => '100',
					'RevisionDeleted' => null,
					'RevisionLastSeen' => '100',
				),
			)
		);

		$this->repositoryFiller->movePathsIntoProject(array($path_id), '/project/');

		$this->assertTableContent(
			'Paths',
			array(
				array(
					'Id' => '1',
					'Path' => '/path1/',
					'PathNestingLevel' => '1',
					'PathHash' => '3304870543',
					'RefName' => '',
					'ProjectPath' => '/project/',
					'RevisionAdded' => '100',
					'RevisionDeleted' => null,
					'RevisionLastSeen' => '100',
				),
				array(
					'Id' => '2',
					'Path' => '/path2/',
					'PathNestingLevel' => '1',
					'PathHash' => '4023451980',
					'RefName' => '',
					'ProjectPath' => '',
					'RevisionAdded' => '100',
					'RevisionDeleted' => null,
					'RevisionLastSeen' => '100',
				),
			)
		);
	}

	public function testAddBugsToCommit()
	{
		$this->repositoryFiller->addCommit(100, 'user', 123, 'msg');
		$this->repositoryFiller->addBugsToCommit(array('AA', 'BB'), 100);

		$this->assertTableContent(
			'CommitBugs',
			array(
				array(
					'Revision' => '100',
					'Bug' => 'AA',
				),
				array(
					'Revision' => '100',
					'Bug' => 'BB',
				),
			)
		);
	}

	public function testAddMergeCommit()
	{
		$this->repositoryFiller->addCommit(100, 'user', 123, 'msg');
		$this->repositoryFiller->addCommit(200, 'user', 123, 'msg');
		$this->repositoryFiller->addCommit(300, 'user', 123, 'msg');
		$this->repositoryFiller->addMergeCommit(300, array(100, 200));

		$this->assertTableContent(
			'Merges',
			array(
				array(
					'MergeRevision' => '300',
					'MergedRevision' => '100',
				),
				array(
					'MergeRevision' => '300',
					'MergedRevision' => '200',
				),
			)
		);
	}

	public function testAddRefToProject()
	{
		$project_id = $this->repositoryFiller->addProject('/project/');
		$ref_id = $this->repositoryFiller->addRefToProject('trunk', $project_id);

		$this->assertTableContent(
			'ProjectRefs',
			array(
				array(
					'Id' => $ref_id,
					'ProjectId' => $project_id,
					'Name' => 'trunk',
				),
			)
		);
	}

	public function testAddCommitToRef()
	{
		$project_id = $this->repositoryFiller->addProject('/project/');
		$ref_id = $this->repositoryFiller->addRefToProject('trunk', $project_id);

		$this->repositoryFiller->addCommit(100, 'user', 123, 'msg');
		$this->repositoryFiller->addCommitToRef(100, $ref_id);

		$this->assertTableContent(
			'CommitRefs',
			array(
				array(
					'Revision' => '100',
					'RefId' => $ref_id,
				),
			)
		);
	}

}


text:
import {async, ComponentFixture, inject, TestBed} from '@angular/core/testing';
import {TranslateModule} from '@ngx-translate/core';
import {ReactiveFormsModule} from '@angular/forms';
import {CovalentStepsModule} from '@covalent/core';
import {EditEmployeeFormComponent} from './edit.form.component';
import {EmployeeFormComponent} from '../form.component';
import {ActivatedRoute, Router} from '@angular/router';
import {User} from '../../../services/identity/domain/user.model';
import {Employee} from '../../../services/office/domain/employee.model';
import {Observable} from 'rxjs/Observable';
import {EmployeesStore} from '../../store/index';
import {Store} from '@ngrx/store';
import {UPDATE} from '../../store/employee.actions';
import * as fromEmployees from '../../store';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatCardModule, MatInputModule, MatOptionModule, MatSelectModule} from '@angular/material';
import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
import {FimsSharedModule} from '../../../common/common.module';

const userMock: User = {
  identifier: 'test',
  role: 'test'
};

const employeeMock: Employee = {
  identifier: 'test',
  assignedOffice: 'test',
  givenName: 'test',
  middleName: 'test',
  surname: 'test',
  contactDetails: [
    {
      group: 'BUSINESS',
      type: 'EMAIL',
      value: 'test',
      preferenceLevel: 1
    }
  ]
};

const activatedRoute = {
  data: Observable.of({
    user: userMock
  })
};
let router: Router;

describe('Test employee form component', () => {

  let fixture: ComponentFixture<EditEmployeeFormComponent>;

  let testComponent: EditEmployeeFormComponent;

  beforeEach(() => {
    router = jasmine.createSpyObj('Router', ['navigate']);

    TestBed.configureTestingModule({
      declarations: [
        EmployeeFormComponent,
        EditEmployeeFormComponent,
      ],
      imports: [
        TranslateModule.forRoot(),
        FimsSharedModule,
        ReactiveFormsModule,
        MatInputModule,
        MatCardModule,
        MatSelectModule,
        MatOptionModule,
        CovalentStepsModule,
        NoopAnimationsModule
      ],
      providers: [
        { provide: Router, useValue: router},
        { provide: ActivatedRoute, useValue: activatedRoute },
        {
          provide: Store, useClass: class {
            dispatch = jasmine.createSpy('dispatch');
            select = jasmine.createSpy('select').and.returnValue(Observable.empty());
          }
        },
        {
          provide: EmployeesStore, useClass: class {
            dispatch = jasmine.createSpy('dispatch');
            select = jasmine.createSpy('select').and.callFake(selector => {
              if (selector === fromEmployees.getSelectedEmployee) {
                return Observable.of(employeeMock);
              }

              return Observable.empty();
            });
          }
        }
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    });

    fixture = TestBed.createComponent(EditEmployeeFormComponent);
    testComponent = fixture.componentInstance;
  });

  it('should test if employee is updated', async(inject([EmployeesStore], (store: EmployeesStore) => {
    fixture.detectChanges();

    testComponent.formComponent.detailForm.get('password').setValue('newPassword');

    fixture.detectChanges();

    testComponent.formComponent.save();

    fixture.whenStable().then(() => {
      expect(store.dispatch).toHaveBeenCalledWith({ type: UPDATE, payload: {
        employee: employeeMock,
        contactDetails: employeeMock.contactDetails,
        role: userMock.role,
        password: 'newPassword',
        activatedRoute: activatedRoute
      }});
    });

  })));
});


text:
<?php namespace PCI\Models;

use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;
use PCI\Models\Traits\HasSlugUID;

/** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */

/**
 * PCI\Models\Gender
 *
 * @package PCI\Models
 * @author Alejandro Granadillo <slayerfat@gmail.com>
 * @link https://github.com/slayerfat/sistemaPCI Repositorio en linea.
 * @property integer $id
 * @property string $desc
 * @property string $slug
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @property integer $created_by
 * @property integer $updated_by
 * @property-read \Illuminate\Database\Eloquent\Collection|Employee[] $employee
 * @method static \Illuminate\Database\Query\Builder|\PCI\Models\Gender whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\PCI\Models\Gender whereDesc($value)
 * @method static \Illuminate\Database\Query\Builder|\PCI\Models\Gender whereSlug($value)
 * @method static \Illuminate\Database\Query\Builder|\PCI\Models\Gender whereCreatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\PCI\Models\Gender whereUpdatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\PCI\Models\Gender whereCreatedBy($value)
 * @method static \Illuminate\Database\Query\Builder|\PCI\Models\Gender whereUpdatedBy($value)
 */
class Gender extends AbstractBaseModel implements SluggableInterface
{

    use SluggableTrait, HasSlugUID;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['desc'];

    /**
     * Los datos necesarios para generarar un slug en el modelo.
     *
     * @var array
     */
    protected $sluggable = [
        'build_from' => 'desc',
        'save_to'    => 'slug',
    ];

    /**
     * Regresa una coleccion de empleados.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function employee()
    {
        return $this->hasMany(Employee::class);
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Bull. Mens. Soc. Linn. Paris 2:870. 1890 "<I>tholloni</I>"

#### Original name
null

### Remarks
null


text:
> [Introduced][ce-4696] in GitLab 8.10.

With GitLab's Access restrictions you can choose which Git access protocols you
want your users to use to communicate with GitLab. This feature can be enabled
via the `Application Settings` in the Admin interface.

The setting is called `Enabled Git access protocols`, and it gives you the option
to choose between:

- Both SSH and HTTP(S)
- Only SSH
- Only HTTP(s)

![Settings Overview](img/access_restrictions.png)

When both SSH and HTTP(S) are enabled, GitLab will behave as usual, it will give
your users the option to choose which protocol they would like to use.

When you choose to allow only one of the protocols, a couple of things will happen:

- The project page will only show the allowed protocol's URL, with no option to
  change it.
- A tooltip will be shown when you hover over the URL's protocol, if an action
  on the user's part is required, e.g. adding an SSH key, or setting a password.

![Project URL with SSH only access](img/restricted_url.png)

On top of these UI restrictions, GitLab will deny all Git actions on the protocol
not selected.

> **Note:** Please keep in mind that disabling an access protocol does not actually
  block access to the server itself. The ports used for the protocol, be it SSH or
  HTTP, will still be accessible. What GitLab does is restrict access on the
  application level.

[ce-4696]: https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/4696


text:
ruby_version_is "1.8.7" do
  require 'securerandom'

  describe "SecureRandom.hex" do
    it "generates a random hex string of length twice the specified argement" do
      (1..64).each do |idx|
        hex = SecureRandom.hex(idx)
        hex.should be_kind_of(String)
        hex.length.should == 2 * idx
      end

      base64 = SecureRandom.hex(5.5)
      base64.should be_kind_of(String)
      base64.length.should eql(10)
    end

    it "returns an empty string when argument is 0" do
      SecureRandom.hex(0).should == ""
    end

    it "generates different hex strings with subsequent invocations" do
      # quick and dirty check, but good enough
      values = []
      256.times do
        hex = SecureRandom.hex
        # make sure the random values are not repeating
        values.include?(hex).should == false
        values << hex
      end
    end

    it "generates a random hex string of length 32 if no argument is provided" do
      SecureRandom.hex.should be_kind_of(String)
      SecureRandom.hex.length.should == 32
    end

    it "treats nil agrument as default one and generates a random hex string of length 32" do
      SecureRandom.hex(nil).should be_kind_of(String)
      SecureRandom.hex(nil).length.should == 32
    end

    it "raises ArgumentError on negative arguments" do
      lambda {
        SecureRandom.hex(-1)
      }.should raise_error(ArgumentError)
    end

    it "tries to convert the passed argument to an Integer using #to_int" do
      obj = mock("to_int")
      obj.should_receive(:to_int).and_return(5)
      SecureRandom.hex(obj).size.should eql(10)
    end
  end
end


text:
import com.typesafe.sbt.sdlc.Checker
import sbt.MessageOnlyException
import sbt.util.Logger

import java.io.File

/**
 * Based on the default task value of `sdlc` but modified
 * so a single project can easily run it on multiple outputs
 */
class ReusableSbtChecker(val scaladocDir: String,
                         val scanDir: String,
                         val linkBase: String,
                         log: Logger) extends Checker {
  var ok = true

  override def debug(msg: => String): Unit = log.debug(msg)

  override def info(msg: => String): Unit = log.info(msg)

  override def error(msg: => String): Unit = {
    ok = false
    log.error(msg)
  }

  def run(): Unit = {
    if (!new File(scaladocDir).exists())
      throw new MessageOnlyException("sdlcDocDir '" + scaladocDir + "' does not exist")

    detect212()

    buildModel()
    scanPages()

    if (!ok) throw new MessageOnlyException("There were errors during scaladoc link checking")
    else info(s"Scaladoc link checking successful.")
  }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

  	<parent>
	    <groupId>com.heliosapm.streams</groupId>
	    <artifactId>helios-streams-parent</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
  	</parent>

    <groupId>com.heliosapm.streams</groupId>
    <artifactId>sql-compiler</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Helios Streams :: SQL-Compiler</name>
    <description>Helios Streams SQL Compiler</description>
    <packaging>jar</packaging>
    <url>https://github.com/nickman</url>

    <dependencies>

		<dependency>
		    <groupId>junit</groupId>
		    <artifactId>junit</artifactId>
		</dependency>

			<dependency>
			  <groupId>com.lmax</groupId>
			  <artifactId>disruptor</artifactId>
			</dependency>

		    <dependency>
		      <groupId>com.stumbleupon</groupId>
		      <artifactId>async</artifactId>
		    </dependency>

		<!-- ==========================================================
		    Chronicle Dependencies
		    ========================================================== -->

			<dependency>
			  <groupId>net.openhft</groupId>
			  <artifactId>chronicle-queue</artifactId>
			</dependency>

			<dependency>
			  <groupId>net.openhft</groupId>
			  <artifactId>zero-allocation-hashing</artifactId>
			</dependency>

		<!-- ==========================================================
		    Misc Dependencies
		    ========================================================== -->

			<dependency>
				<groupId>com.heliosapm.utils</groupId>
				<artifactId>heliosutils</artifactId>
			</dependency>

            <dependency>
                <groupId>io.dropwizard.metrics</groupId>
                <artifactId>metrics-core</artifactId>
            </dependency>

		<!-- ==========================================================
		    Logging Dependencies
		    ========================================================== -->

		  <dependency>
		    <groupId>org.apache.logging.log4j</groupId>
		    <artifactId>log4j-api</artifactId>
		  </dependency>

		  <dependency>
		    <groupId>org.apache.logging.log4j</groupId>
		    <artifactId>log4j-core</artifactId>
		  </dependency>

		  <dependency>
		    <groupId>org.apache.logging.log4j</groupId>
		    <artifactId>log4j-slf4j-impl</artifactId>
		  </dependency>

		  <dependency>
		    <groupId>org.apache.logging.log4j</groupId>
		    <artifactId>log4j-1.2-api</artifactId>
		  </dependency>

		<!-- ==========================================================
		    JDBC and DB Dependencies
		    ========================================================== -->

		  <dependency>
		    <groupId>com.h2database</groupId>
		    <artifactId>h2</artifactId>
		  </dependency>

			<dependency>
			    <groupId>com.zaxxer</groupId>
			    <artifactId>HikariCP</artifactId>
			</dependency>

		<dependency>
		  <groupId>org.postgresql</groupId>
		  <artifactId>postgresql</artifactId>
		</dependency>

		<!-- ==========================================================
		    Misc Utils
		    ========================================================== -->
	    <dependency>
	      <groupId>com.google.guava</groupId>
	      <artifactId>guava</artifactId>
	      <scope>provided</scope>
	    </dependency>

		<dependency>
		  <groupId>org.javassist</groupId>
		  <artifactId>javassist</artifactId>
		</dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${compiler-plugin.version}</version>
                <configuration>
                    <source>${compiler-source.version}</source>
                    <target>${compiler-target.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>${javadoc-plugin.version}</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <show>public</show>
                    <nohelp>true</nohelp>
                    <quiet>true</quiet>
                </configuration>
            </plugin>
	    <plugin>
		    <groupId>org.apache.maven.plugins</groupId>
		    <artifactId>maven-source-plugin</artifactId>
		    <version>${source-plugin.version}</version>
		    <executions>
			    <execution>
				    <id>attach-sources</id>
				    <phase>verify</phase>
				    <goals>
					    <goal>jar</goal>
				    </goals>
			    </execution>
		    </executions>
	    </plugin>
	    <plugin>
		<groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-jar-plugin</artifactId>
		<version>${jar-plugin.version}</version>
		<configuration>
		  <forceCreation>true</forceCreation>
		</configuration>
	    </plugin>
	    <plugin>
		<groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-eclipse-plugin</artifactId>
		<version>${eclipse-plugin.version}</version>
		<configuration>
		    <downloadJavadocs>${downloadJavadocs}</downloadJavadocs>
		    <downloadSources>${downloadSources}</downloadSources>
		    <classpathContainers>
		    </classpathContainers>
		</configuration>
	    </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
	     <artifactId>maven-surefire-plugin</artifactId>
	     <version>${surefire.version}</version>
	</plugin>

	<plugin>
	  <groupId>org.apache.maven.plugins</groupId>
	  <artifactId>maven-shade-plugin</artifactId>
	  <version>${shade.version}</version>
        <executions>
            <execution>
              <phase>package</phase>
              <goals>
                <goal>shade</goal>
              </goals>
              <configuration>

                <artifactSet>
                  <excludes>
                  <!--
                  	<exclude>log4j:log4j:jar:</exclude>
                  	<exclude>org.slf4j:*:jar:</exclude>
                  	<exclude>org.codehaus.groovy:*:jar:</exclude>
                  -->
					  <exclude>META-INF/*.SF</exclude>
	                  <exclude>META-INF/*.DSA</exclude>
	                  <exclude>META-INF/*.RSA</exclude>
                  </excludes>
                  <includes>

                  </includes>
                </artifactSet>

          		<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
          		<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
          		<includePluginDependencies>false</includePluginDependencies>

        		<transformers>
					<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
	                  <resource>META-INF/spring.handlers</resource>
	                </transformer>
	                <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
	                  <resource>META-INF/spring.schemas</resource>
	                </transformer>
                	<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"/>
                	<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                	<transformer implementation="org.apache.maven.plugins.shade.resource.ComponentsXmlResourceTransformer"/>
                	<transformer implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer">
                		<resource>.SF</resource>
                		<resource>.DSA</resource>
                		<resource>.RSA</resource>
            		</transformer>
                </transformers>
              </configuration>
            </execution>
          </executions>
	</plugin>

   </plugins>
 </build>

</project>


text:
DIRNAME=$(dirname "$0")
DEPLOY_CONFIG_FILE="deploy.config"
MKTEMP_TEMPLATE="deploybuild.XXXXX"

function exitError {

	echo "Error: $1" >&2
	exit 1
}

function writeWarning {

	echo "Warning: $1"
}

function writeNotice {

	echo "Notice: $1"
}

function usage {

	cat <<EOM
Usage: $(basename "$0") [OPTION]...

  -d    dry run deployment
  -t    retain build directory after completion
  -h    display help
EOM

	exit 2
}

function getTempFile {

	local tempFile
	tempFile=$(mktemp --quiet --tmpdir "$MKTEMP_TEMPLATE") || \
		exitError "Unable to create temporary file"

	echo "$tempFile"
}

function getPathCanonical {

	if [[ $2 == "nocheck" ]]; then
		readlink --canonicalize-missing --no-newline "$1"

	else
		# note: will return error = 1 if any path component non-exists (except final) - hence || :
		readlink --canonicalize --no-newline "$1" || :
	fi
}

function loadConfiguration {

	# attempt to load a global configuration file inline with the canonical script path
	# note: global config file may not exist, that's fine
	local globalConfigFile=$(getPathCanonical "$0")
	globalConfigFile="$(dirname "$globalConfigFile")/$DEPLOY_CONFIG_FILE"
	[[ -f $globalConfigFile ]] && . "$globalConfigFile"

	# now load application config file - must exist otherwise fatal error
	local appConfigFile="$DIRNAME/$DEPLOY_CONFIG_FILE"
	[[ -f $appConfigFile ]] || exitError "Unable to locate $appConfigFile."
	. "$appConfigFile"
}

function validateConfiguration {

	# YUI compressor/Google closure compiler jars exist?
	[[ -z $JAR_YUI_COMPRESSOR ]] && exitError "JAR_YUI_COMPRESSOR config parameter not defined."
	[[ -f $JAR_YUI_COMPRESSOR ]] || exitError "Unable to locate YUI compressor jar at $JAR_YUI_COMPRESSOR."

	[[ -z $JAR_GOOGLE_CLOSURE ]] && exitError "JAR_GOOGLE_CLOSURE config parameter not defined."
	[[ -f $JAR_GOOGLE_CLOSURE ]] || exitError "Unable to locate Google Closure Compiler jar at $JAR_GOOGLE_CLOSURE."

	# validate config settings - application source directory
	[[ -z $SOURCE_DIR ]] && exitError "SOURCE_DIR config parameter not defined."

	# canonicalize $SOURCE_DIR and validate directory exists
	sourceDirCanonical=$(getPathCanonical "$DIRNAME/$SOURCE_DIR")
	[[ -d $sourceDirCanonical ]] || exitError "Unable to locate source directory at $sourceDirCanonical"

	# validate config settings - build source filter
	[[ -z $BUILD_SOURCE_FILTER ]] && exitError "BUILD_SOURCE_FILTER config parameter not defined."

	# validate config settings - target server details
	[[ -z $SERVER_HOSTNAME ]] && exitError "SERVER_HOSTNAME config parameter not defined."
	[[ -z $SERVER_SSH_USER ]] && exitError "SERVER_SSH_USER config parameter not defined."
	[[ -z $SERVER_SSH_PORT ]] && exitError "SERVER_SSH_PORT config parameter not defined."

	[[ -z $SERVER_RSYNC_MODULE ]] && exitError "SERVER_RSYNC_MODULE config parameter not defined."
	[[ -z $SERVER_RSYNC_CHMOD ]] && exitError "SERVER_RSYNC_CHMOD config parameter not defined."

	# return truthy
	:
}

function rsyncSourceToBuildDir {

	# create temp file to hold source copy to build dir rsync filter rules
	local filterTmp=$(getTempFile)
	echo "$BUILD_SOURCE_FILTER" >"$filterTmp"

	rsync \
		--filter ". $filterTmp" \
		--out-format "%n" \
		--recursive \
		--times \
		"$sourceDirCanonical/" "$buildDir"

	echo

	rm --force "$filterTmp"
}

function gzipResource {

	# source file exists?
	[[ -f $1 ]] || return

	# compress file and give identical timestamp to source
	# for use with the nginx ngx_http_gzip_static_module module
	# See: https://nginx.org/en/docs/http/ngx_http_gzip_static_module.html
	echo "Compressing resource:"
	echo "Source: $1"
	echo "Target: $1.gz"
	echo

	gzip --best --stdout "$1" >"$1.gz"
	touch --no-create --reference "$1" "$1.gz"
}

function buildSass {

	# if no Sass files defined for build - exit
	[[ -z $BUILD_SASS_LIST ]] && return

	local sassBuildItem

	local IFS=$'\n'
	for sassBuildItem in $BUILD_SASS_LIST; do
		# ensure $sassBuildItem is in [SOURCE_SCSS|TARGET_CSS] format
		if [[ $sassBuildItem =~ ^([^|]+)\|([^|]+)$ ]]; then
			# fetch Sass source and CSS target parts canonicalized
			local sassSource=$(getPathCanonical "$sourceDirCanonical/${BASH_REMATCH[1]}")
			local cssTarget=$(getPathCanonical "$buildDir/${BASH_REMATCH[2]}" "nocheck")

			# source Sass document exists?
			if [[ -f $sassSource ]]; then
				echo "Compiling Sass -> CSS:"
				echo "Source: $sassSource"
				echo "Target: $cssTarget"
				echo

				# create parent directory structure in build target for generated CSS document
				mkdir --parents "$(dirname "$cssTarget")"

				# now compile Sass document to output CSS
				sass \
					--load-path "$(dirname "$sassSource")" \
					--no-cache \
					--require sass-globbing \
					--scss \
					--sourcemap=none \
					"$sassSource" "$cssTarget"

				# minify built CSS using YUI compressor then compress
				cat "$cssTarget" | \
					java -jar "$JAR_YUI_COMPRESSOR" \
					--type css -o "$cssTarget"

				gzipResource "$cssTarget"

			else
				writeWarning "Unable to locate $sassSource for CSS compile"
				echo
			fi

		else
			writeWarning "Invalid Sass build item definition: $sassBuildItem"
			echo
		fi
	done
}

function buildJavaScript {

	# if no JavaScript build files defined - exit
	[[ -z $BUILD_JAVASCRIPT_LIST ]] && return

	local javaScriptBuildItem

	local IFS=$'\n'
	for javaScriptBuildItem in $BUILD_JAVASCRIPT_LIST; do

		# ensure $javaScriptBuildItem is in [SOURCE_JAVASCRIPT_LIST|TARGET_JAVASCRIPT] format
		if [[ $javaScriptBuildItem =~ ^([^|]+)\|([^|]+)$ ]]; then
			local javaScriptBuildTarget=$(getPathCanonical "$buildDir/${BASH_REMATCH[2]}" "nocheck")
			local javaScriptTempConcatTarget=$(getTempFile)
			local buildStepHeaderWritten

			# work over each source JavaScript list item glob
			local javaScriptSourceGlobItem

			local IFS=","
			for javaScriptSourceGlobItem in ${BASH_REMATCH[1]}; do

				# grab file(s) matched by source JavaScript source item
				local javaScriptSourceFileItem
				local globMatch

				# note: don't quote $javaScriptSourceGlobItem as may contain glob patterns
				local IFS=$'\n'
				for javaScriptSourceFileItem in "$sourceDirCanonical/"$javaScriptSourceGlobItem; do

					# get canonical path to source JavaScript file
					javaScriptSourceFileItem=$(getPathCanonical "$javaScriptSourceFileItem")

					if [[ -f $javaScriptSourceFileItem ]]; then
						globMatch=:
						if [[ ! $buildStepHeaderWritten ]]; then
							echo "Concatenate/minifying source JavaScript -> JavaScript:"
							buildStepHeaderWritten=:
						fi

						# add JavaScript to concatenate file target
						echo "Source: $javaScriptSourceFileItem"
						cat "$javaScriptSourceFileItem" >>"$javaScriptTempConcatTarget"
					fi
				done

				if [[ ! $globMatch ]]; then
					# resolved [$sourceDirCanonical/$javaScriptSourceGlobItem] glob path didn't match anything
					writeWarning "JavaScript source glob $javaScriptSourceGlobItem did not match"
				fi
			done

			if [[ -s $javaScriptTempConcatTarget ]]; then
				# successfully concatenated one or more source JavaScript files to target file
				echo "Target: $javaScriptBuildTarget"
				echo

				# create parent directory structure in build target for final JavaScript source file
				mkdir --parents "$(dirname "$javaScriptBuildTarget")"

				# minify temporary JavaScript concatenate target to final build location then compress
				cat "$javaScriptTempConcatTarget" | \
					java -jar "$JAR_GOOGLE_CLOSURE" \
						--js_output_file "$javaScriptBuildTarget" \
						--rewrite_polyfills false

				gzipResource "$javaScriptBuildTarget"

			else
				writeWarning "Unable to create $javaScriptBuildTarget from source JavaScript file(s)"
				echo
			fi

			# delete temporary JavaScript concatenate target
			rm --force "$javaScriptTempConcatTarget"

		else
			writeWarning "Invalid JavaScript build item definition: $javaScriptBuildItem"
			echo
		fi
	done
}

function SSHRsyncBuildDirToServer {

	# create temp file to hold server exclude filter rules for rsync - empty file if not defined
	local filterTmp=$(getTempFile)
	[[ -n $SERVER_EXCLUDE_FILTER ]] && echo "$SERVER_EXCLUDE_FILTER" >"$filterTmp"

	rsync \
		--chmod "$SERVER_RSYNC_CHMOD" \
		--compress \
		--delete \
		--exclude-from "$filterTmp" \
		--itemize-changes \
		--recursive \
		--rsh "ssh -l \"$SERVER_SSH_USER\" -p \"$SERVER_SSH_PORT\"" \
		--times \
		${optionRsyncDryRunOnly:+--dry-run} \
		"$buildDir/" "$SERVER_HOSTNAME::$SERVER_RSYNC_MODULE" || :

	echo

	rm --force "$filterTmp"
}

# parse command line options
optionRsyncDryRunOnly=
optionRetainBuildResultDir=
while getopts ":dth" optKey; do
	case "$optKey" in
		d)
			optionRsyncDryRunOnly=:
			;;
		t)
			optionRetainBuildResultDir=:
			;;
		h|*)
			usage
			;;
	esac
done

# ensure rsync, java and sass all present
[[ -z $(which rsync) ]] && exitError "Unable to locate rsync, installed?"
[[ -z $(which java) ]] && exitError "Unable to locate Java, installed?"
[[ -z $(which sass) ]] && exitError "Unable to locate Sass, installed?"

# load and validate (optional) global and application configuration files
loadConfiguration
validateConfiguration

# everything validated - lets start the build process
echo "Application source: $sourceDirCanonical"
[[ $optionRsyncDryRunOnly ]] && writeNotice "Rsync dry-run deployment only"
[[ $optionRetainBuildResultDir ]] && writeNotice "Retaining temporary build directory after deployment"

# create build directory
buildDir=$(mktemp --directory --tmpdir "$MKTEMP_TEMPLATE")
echo "Build target: $buildDir"
echo

# rsync application source to build directory
rsyncSourceToBuildDir

# build Sass source files to minified/gzipped CSS
buildSass

# build JavaScript source files to bundled/minified/gzipped JavaScript
buildJavaScript

# if defined, run pre deployment hook function now
if [[ $(type -t preDeployHook) == "function" ]]; then
	preDeployHook "$sourceDirCanonical" "$buildDir"
fi

# rsync build directory to destination server via SSH transit
SSHRsyncBuildDirToServer

if [[ $optionRetainBuildResultDir ]]; then
	# retaining build directory
	echo "Build directory retained at: $buildDir"

else
	# remove build directory
	echo "Removing build target work area: $buildDir"
	rm --force --recursive "$buildDir"
fi


text:
Sort Nodes

        The example below shows how to sort nodes in the sidebar.

        <input id="foldersFirst" style="position: relative; top: 2px; left: -1px" type="checkbox"> Folders First

        <input id="caseSensitive" style="position: relative; top: 2px; left: -1px" type="checkbox"> Case Sensitive

        <input id="reverse" style="position: relative; top: 2px; left: -1px" type="checkbox"> Reverse

    <button class="w2ui-btn" onclick="sort()">Sort</button>


text:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class ProjectMenuService {
  private _menuActive = new BehaviorSubject<boolean>(false);
  public get menuActive(): Observable<boolean> {
    return this._menuActive.asObservable();
  }

  setActive() {
    this._menuActive.next(true);
  }

  setInactive() {
    this._menuActive.next(false);
  }
}