text:
<!DOCTYPE HTML>
<html>
	<head>
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<title>TableSelectDialog - sap.m</title>
		<script src="../../../resources/sap-ui-core.js"
			type="text/javascript"
			id="sap-ui-bootstrap"
			data-sap-ui-libs="sap.m"
			data-sap-ui-compatVersion="1.16"
			data-sap-ui-theme="sap_bluecrystal">
		</script>
		<script type="text/javascript">
		jQuery.sap.require("sap.ui.core.util.MockServer");
		jQuery.sap.require("sap.ui.model.odata.ODataModel");

		var sServiceURI = "/service/" ;
		var sMetaDataURI = "qunit/data/";

		// configure respond to requests delay
		sap.ui.core.util.MockServer.config({
			autoRespond : true,
			autoRespondAfter : 1000
		});

		// create mockserver
		var oMockServer = new sap.ui.core.util.MockServer({
			rootUri : sServiceURI
		});

		// start mockserver
		oMockServer.simulate(sMetaDataURI + "metadata.xml", sMetaDataURI);
		oMockServer.start();

		jQuery.sap.require("sap.ui.model.FilterOperator");
		jQuery.sap.require("sap.m.MessageBox");

		// filter function for the list search
		var fnDoSearch = function (oEvent, bProductSearch) {
			var aFilters = [],
				sSearchValue = oEvent.getParameter("value"),
				itemsBinding = oEvent.getParameter("itemsBinding");

			// create the local filter to apply
			if(sSearchValue !== undefined && sSearchValue.length > 0) {
				if(bProductSearch) {
					// create multi-field filter to allow search over all attributes
					aFilters.push(new sap.ui.model.Filter("ProductId", sap.ui.model.FilterOperator.Contains , sSearchValue));
					// apply the filter to the bound items, and the Select Dialog will update
					itemsBinding.filter(aFilters, "Application");
				} else {
					// create multi-field filter to allow search over all attributes
					aFilters.push(new sap.ui.model.Filter("name", sap.ui.model.FilterOperator.Contains , sSearchValue));
					aFilters.push(new sap.ui.model.Filter("lname", sap.ui.model.FilterOperator.Contains , sSearchValue));
					aFilters.push(new sap.ui.model.Filter("ean13", sap.ui.model.FilterOperator.Contains , sSearchValue));
					aFilters.push(new sap.ui.model.Filter("ean8", sap.ui.model.FilterOperator.Contains , sSearchValue));
					aFilters.push(new sap.ui.model.Filter("qty", sap.ui.model.FilterOperator.Contains , sSearchValue));
					aFilters.push(new sap.ui.model.Filter("limit", sap.ui.model.FilterOperator.Contains , sSearchValue));
					aFilters.push(new sap.ui.model.Filter("backorder", sap.ui.model.FilterOperator.Contains , sSearchValue));
					aFilters.push(new sap.ui.model.Filter("price", sap.ui.model.FilterOperator.Contains , sSearchValue));
					// apply the filter to the bound items, and the Select Dialog will update
					itemsBinding.filter(new sap.ui.model.Filter(aFilters, false), "Application"); // filters connected with OR
				}
			} else {
				// filter with empty array to reset filters
				itemsBinding.filter(aFilters);
			}
		};

		// filter function for the product search
		var fnDoProductSearch = function (oEvent) {
			fnDoSearch(oEvent, true);
		};

		// filter function to align the binding with the search term
		var fnCreatePrefilter = function (sSearchValue, bProductSearch) {
			var aFilters = [];

			// create the local filter to apply
			if(sSearchValue !== undefined) {
				aFilters.push(new sap.ui.model.Filter((bProductSearch ? "ProductId" : "name" ), sap.ui.model.FilterOperator.Contains , sSearchValue));
			}
			return aFilters;
		};

		var fnPrefilterDialog = function (sSearchValue){
			// create an array to hold the filters we create
			var aFilters = fnCreatePrefilter(sSearchValue),
				itemsBinding = oTableSelectDialog1.getBinding("items");

			itemsBinding.filter(aFilters);
		};

		/* dialog data */
		var oDialogData = {
			title: "Choose your tech..",
			noDataMessage: "We don't have any tech to show here and we are very sorry for that!"
		};

		var oModelDialog = new sap.ui.model.json.JSONModel();
		oModelDialog.setData(oDialogData);

		// create the data to be shown in the table
		var oProductData1 = {
		items : [{
				name : "Headphone",
				qty : "10 EA",
				limit : "15.00 Eur",
				price : "12.00 EUR"
			}, {
				name : "Mouse Pad",
				qty : "1 EA",
				limit : "5.00 Eur",
				price : "3.00 EUR"
			}, {
				name : "Monitor",
				qty : "8 EA",
				limit : "60.00 Eur",
				price : "45.00 EUR"
			}, {
				name : "Optic Mouse",
				qty : "2 EA",
				limit : "40.00 Eur",
				price : "15.00 EUR"
			}, {
				name : "Dock Station",
				qty : "1 EA",
				limit : "90.00 Eur",
				price : "55.00 EUR"
			}]
		};

		// create the model to hold the data
		var oModel1 = new sap.ui.model.json.JSONModel();
		oModel1.setDefaultBindingMode("OneWay");
		oModel1.setData(oProductData1);

		// create the data to be shown in the table
		var oProductData2 = {
			items : [{
				name : "Tablet",
				qty : "1 EA",
				limit : "150.00 Eur",
				price : "120.00 EUR"
			}, {
				name : "Docking Station",
				qty : "1 EA",
				limit : "15.00 Eur",
				price : "13.00 EUR"
			}, {
				name : "DVD-R",
				qty : "10 EA",
				limit : "6.00 Eur",
				price : "4.00 EUR"
			}, {
				name : "Headset",
				qty : "1 EA",
				limit : "20.00 Eur",
				price : "15.00 EUR"
			}, {
				name : "Power Supply",
				qty : "1 EA",
				limit : "32.00 Eur",
				price : "20.00 EUR"
			}]
		};

		// create the model to hold the data
		var oModel2 = new sap.ui.model.json.JSONModel();
		oModel2.setDefaultBindingMode("OneWay");
		oModel2.setData(oProductData2);

		// create the data to be shown in the table
		var oProductData3 = {
			items : [{
				name : "Headphone",
				lname : "Headphone 1234567890120 12345678",
				ean13 : "1234567890120",
				ean8 : "12345678",
				qty : "10 EA",
				limit : "15.00 Eur",
				backorder : "10,000",
				price : "12.00 EUR"
			}, {
				name : "Mouse Pad",
				lname : "Mouse Pad 1234565544123 1234565544123",
				ean13 : "1234565544123",
				ean8 : "1234565544123",
				qty : "1 EA",
				limit : "5.00 Eur",
				backorder : "25,000",
				price : "3.00 EUR"
			}, {
				name : "Monitor",
				lname : "Monitor 1234565544133 15675678",
				ean13 : "1234565544133",
				ean8 : "15675678",
				qty : "8 EA",
				limit : "60.00 Eur",
				backorder : "125,000",
				price : "45.00 EUR"
			}, {
				name : "Optic Mouse",
				lname : "Optic Mouse 2222365544133 15232678",
				ean13 : "2222365544133",
				ean8 : "15232678",
				qty : "2 EA",
				limit : "40.00 Eur",
				backorder : "125,500",
				price : "15.00 EUR"
			}, {
				name : "Dock Station",
				lname : "Dock Station 2221121244133 15675222",
				ean13 : "2221121244133",
				ean8 : "15675222",
				qty : "1 EA",
				limit : "90.00 Eur",
				backorder : "25,000",
				price : "55.00 EUR"
			}, {
				name : "Dock Station",
				lname : "Dock Station 2221121244133 15675222",
				ean13 : "2221121244133",
				ean8 : "15675222",
				qty : "1 EA",
				limit : "90.00 Eur",
				backorder : "25,000",
				price : "55.00 EUR"
			}, {
				name : "Dock Station",
				lname : "Dock Station 2221121244133 15675222",
				ean13 : "2221121244133",
				ean8 : "15675222",
				qty : "1 EA",
				limit : "90.00 Eur",
				backorder : "25,000",
				price : "55.00 EUR"
			}]
		};

		// create the model to hold the data
		var oModel3 = new sap.ui.model.json.JSONModel();
		oModel3.setDefaultBindingMode("OneWay");
		oModel3.setData(oProductData3);

		// create our new Table Select Dialog
		var oTableSelectDialog1 = new sap.m.TableSelectDialog("TableSelectDialog1", {
			title: "Choose a piece of tech",
			noDataText: "Sorry, no tech available today",
			search : fnDoSearch,
			liveChange: fnDoSearch,
			columns : [
				new sap.m.Column({
					styleClass : "name",
					hAlign : "Begin",
					header : new sap.m.Label({
						text : "Name"
					})
				}),
				new sap.m.Column({
					hAlign : "Center",
					styleClass : "qty",
					popinDisplay : "Inline",
					header : new sap.m.Label({
						text : "Qty"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "End",
					styleClass : "limit",
					width : "30%",
					header : new sap.m.Label({
						text : "Value"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "End",
					styleClass : "price",
					width : "30%",
					popinDisplay : "Inline",
					header : new sap.m.Label({
						text : "Price"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				})
			]
		});

		// create the template for the items binding
		var oItemTemplate1 = new sap.m.ColumnListItem({
			type : "Active",
			unread : false,
			cells : [
				new sap.m.Label({
					text : "{name}"
				}),
				new sap.m.Label({
					text: "{qty}"
				}), new sap.m.Label({
					text: "{limit}"
				}), new sap.m.Label({
					text : "{price}"
				})
			]
		});

		// create the template for the items binding
		var oItemTemplate2 = new sap.m.ColumnListItem({
			type : "Active",
			unread : false,
			cells : [
				new sap.m.Label({
					text : "{name}"
				}),
				new sap.m.Label({
					text: "{qty}"
				}), new sap.m.Label({
					text: "{limit}"
				}), new sap.m.Label({
					text : "{backorder}"
				}), new sap.m.Label({
					text : "{price}"
				})
			]
		});

		// create the template for the items binding
		var oItemTemplate3 = new sap.m.ColumnListItem({
			type : "Active",
			unread : false,
			cells : [
				new sap.m.Label({
					text : "{name}"
				}),  new sap.m.Label({
					text : "{lname}"
				}),  new sap.m.Label({
					text : "{ean13}"
				}),  new sap.m.Label({
					text : "{ean8}"
				}),  new sap.m.Label({
					text: "{qty}"
				}), new sap.m.Label({
					text: "{limit}"
				}), new sap.m.Label({
					text : "{backorder}"
				}), new sap.m.Label({
					text : "{price}"
				})
			]
		});

		// create the template for the web service binding
		var oProductItemTemplate = new sap.m.ColumnListItem({
			type : "Active",
			unread : false,
			cells : [
				new sap.m.Label({
					text : "{ProductId}"
				}),  new sap.m.Label({
					text : "{Name}"
				}),  new sap.m.Label({
					text : "{Price}"
				}),  new sap.m.Label({
					text : "{Weight}"
				})
			]
		});

		// set model & bind Aggregation
		oTableSelectDialog1.setModel(oModel3);
		oTableSelectDialog1.bindAggregation("items", "/items", oItemTemplate1);

		// attach confirm listener
		oTableSelectDialog1.attachConfirm(function (evt) {
			var selectedItem = evt.getParameter("selectedItem");
			if (selectedItem) {
				//Get all the cells and pull back the first one which will be the name content
				var oCells = selectedItem.getCells();
				var oCell = oCells[0];
				//Now update the input with the value
				oInput1.setValue("Item selected is : " + oCell.getText());
			}
		});

		var oInput1 = new sap.m.Input({
			type: "Text",
			placeholder: "Open TableSelectDialog with Items Binding",
			showValueHelp: true,
			valueHelpRequest: function () {
				oTableSelectDialog1.open(oInput1.getValue());

				oTableSelectDialog1.setModel(oModel3);
				oTableSelectDialog1.bindAggregation("items", "/items", oItemTemplate1);

				fnPrefilterDialog(oInput1.getValue());
			}
		});

		/* 2) table select dialog with binding and dialog binding */
		var oTableSelectDialog2 = new sap.m.TableSelectDialog("TableSelectDialog2", {
			title: "{dialog>/title}",
			noDataText: "{dialog>/noDataMessage}",
			search : fnDoSearch,
			liveChange: fnDoSearch,
			columns : [
				new sap.m.Column({
					styleClass : "name",
					hAlign : "Begin",
					header : new sap.m.Label({
						text : "Name"
					})
				}),
				new sap.m.Column({
					hAlign : "Center",
					styleClass : "qty",
					popinDisplay : "Inline",
					header : new sap.m.Label({
						text : "Qty"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "End",
					styleClass : "limit",
					width : "30%",
					header : new sap.m.Label({
						text : "Value"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "End",
					styleClass : "price",
					width : "30%",
					popinDisplay : "Inline",
					header : new sap.m.Label({
						text : "Price"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				})
			]
		});

		var oInput2 = new sap.m.Input('tsdWithBindingInput', {
			type: "Text",
			placeholder: "Open TableSelectDialog with Dialog Binding & Items Binding",
			showValueHelp: true,
			valueHelpRequest: function () {
				oTableSelectDialog2.open(oInput2.getValue());

				// then set model & bind Aggregation
				oTableSelectDialog2.bindAggregation("items", "/items", oItemTemplate1);
				oTableSelectDialog2.setModel(oModel1);
				oTableSelectDialog2.setModel(oModelDialog,"dialog");
			}
		});

		// attach confirm listener
		oTableSelectDialog2.attachConfirm(function (evt) {
			var selectedItem = evt.getParameter("selectedItem");
			if (selectedItem) {
				//Get all the cells and pull back the first one which will be the name content
				var oCells = selectedItem.getCells();
				var oCell = oCells[0];
				//Now update the input with the value
				oInput2.setValue("Item selected is : " + oCell.getText());
			}
		});

		/* 3) table dialog with binding auto destroy on close */
		var oTableSelectDialog3 = new sap.m.TableSelectDialog("TableSelectDialog3", {
			title: "{dialog>/title}",
			noDataText: "{dialog>/noDataMessage}",
			search : fnDoSearch,
			liveChange: fnDoSearch,
			columns : [
				new sap.m.Column({
					hAlign : "Begin",
					header : new sap.m.Label({
						text : "Name"
					})
				}),
				new sap.m.Column({
					hAlign : "Center",
					popinDisplay : "Inline",
					header : new sap.m.Label({
						text : "Qty"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "End",
					width : "30%",
					header : new sap.m.Label({
						text : "Value"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "End",
					width : "30%",
					popinDisplay : "Inline",
					header : new sap.m.Label({
						text : "Price"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				})
			]
		});

		// attach confirm listener
		oTableSelectDialog3.attachConfirm(function (evt) {
			var selectedItem = evt.getParameter("selectedItem");
			if (selectedItem) {
				//Get all the cells and pull back the first one which will be the name content
				var oCells = selectedItem.getCells();
				var oCell = oCells[0];
				//Now update the input with the value
				sap.m.MessageBox.alert("Item selected is : " + oCell.getText());
			}
			//Now destroy it
			oTableSelectDialog3.destroy();
			oTableSelectDialog3 = null;
		});

		var oButton3 = new sap.m.Button("Button3", {
			text: "Open TableSelectDialog with destroy call in close event & late binding",
			press: function (evt) {
				oTableSelectDialog3.open();

				// then set model & bind Aggregation
				oTableSelectDialog3.bindAggregation("items", "/items", oItemTemplate1);
				oTableSelectDialog3.setModel(oModel1);
			}
		});

		/* 4) multi select table dialog with binding  */
		var oTableSelectDialog4 = new sap.m.TableSelectDialog("TableSelectDialog4", {
			title: "Choose several tech products",
			noDataText: "Sorry, no tech today",
			multiSelect: true,
			search : fnDoSearch,
			liveChange: fnDoSearch,
			columns : [
				new sap.m.Column({
					hAlign : "Begin",
					header : new sap.m.Label({
						text : "Name"
					})
				}),
				new sap.m.Column({
					hAlign : "Center",
					popinDisplay : "Inline",
					header : new sap.m.Label({
						text : "Qty"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "End",
					header : new sap.m.Label({
						text : "Value"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "End",
					popinDisplay : "Inline",
					header : new sap.m.Label({
						text : "Price"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				})
			]
		});

		// set model & bind Aggregation
		oTableSelectDialog4.setModel(oModel1);
		oTableSelectDialog4.bindAggregation("items", "/items", oItemTemplate1);

		// attach confirm listener
		oTableSelectDialog4.attachConfirm(function (evt) {
			var aSelectedItems = evt.getParameter("selectedItems");
			if (aSelectedItems) {
				var sSelectedItems = "";
				//Loop through all selected items
				for (var i=0; i<aSelectedItems.length; i++) {
					//Get all the cells and pull back the first one which will be the name content
					var oCells = aSelectedItems[i].getCells();
					var oCell = oCells[0];
					//Update the text
					sSelectedItems += oCell.getText();
					if (i < aSelectedItems.length - 1) {
						sSelectedItems += ', ';
					}
				}
				sap.m.MessageBox.alert("You selected: "+ sSelectedItems);
			}
		});

		var oButton4 = new sap.m.Button("tsdWithMultiSelectButton", {
			text: "Open TableSelectDialog in MultiSelect mode",
			press: function () {
				// open dialog
				oTableSelectDialog4.open();
			}
		});

		/* 5) multi select table dialog with large binding */
		var oTableSelectDialog5 = new sap.m.TableSelectDialog("TableSelectDialog5", {
			title: "Choose several extended tech products",
			noDataText: "Sorry, no tech today",
			multiSelect: true,
			search : fnDoSearch,
			liveChange: fnDoSearch,
			columns : [
				new sap.m.Column({
					width : "150px",
					hAlign : "Begin",
					header : new sap.m.Label({
						text : "Name"
					})
				}),
				new sap.m.Column({
					hAlign : "Center",
					width : "90px",
					popinDisplay : "Inline",
					header : new sap.m.Label({
						text : "Qty"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "End",
					width : "100px",
					header : new sap.m.Label({
						text : "Value"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "Center",
					width : "150px",
					popinDisplay : "Inline",
					header : new sap.m.Label({
						text : "Back Order"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "End",
					width : "150px",
					popinDisplay : "Inline",
					header : new sap.m.Label({
						text : "Price"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				})
			]
		});

		// set model & bind Aggregation
		oTableSelectDialog5.setModel(oModel2);
		oTableSelectDialog5.bindAggregation("items", "/items", oItemTemplate2);

		// attach confirm listener
		oTableSelectDialog5.attachConfirm(function (evt) {
			var aSelectedItems = evt.getParameter("selectedItems");
			if (aSelectedItems) {
				var sSelectedItems = "";
				//Loop through all selected items
				for (var i=0; i<aSelectedItems.length; i++) {
					//Get all the cells and pull back the first one which will be the name content
					var oCells = aSelectedItems[i].getCells();
					var oCell = oCells[0];
					//Update the text
					sSelectedItems += oCell.getText();
					if (i < aSelectedItems.length - 1) {
						sSelectedItems += ', ';
					}
				}
				sap.m.MessageBox.alert("You selected: "+ sSelectedItems);
			}
		});

		var oButton5 = new sap.m.Button("tsdWithLargeDataAndMultiSelectButton", {
			text: "Open TableSelectDialog in MultiSelect mode with large data",
			press: function () {
				// open dialog
				oTableSelectDialog5.open();
			}
		});

		/* 6) table dialog with large binding */
		var oTableSelectDialog6 = new sap.m.TableSelectDialog("TableSelectDialog6", {
			title: "Choose an extended tech products",
			noDataText: "Sorry, no tech today",
			search : fnDoSearch,
			liveChange: fnDoSearch,
			columns : [
				new sap.m.Column({
					width : "150px",
					hAlign : "Begin",
					header : new sap.m.Label({
						text : "Name"
					})
				}),
				new sap.m.Column({
					width : "250px",
					hAlign : "Begin",
					header : new sap.m.Label({
						text : "Long Name"
					}),
					popinDisplay : "Inline",
					minScreenWidth : "Tablet",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "Center",
					width : "290px",
					popinDisplay : "Inline",
					header : new sap.m.Label({
						text : "EAN 13"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "Center",
					width : "290px",
					popinDisplay : "Inline",
					header : new sap.m.Label({
						text : "EAN 8"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "Center",
					width : "190px",
					popinDisplay : "Inline",
					header : new sap.m.Label({
						text : "Qty"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "End",
					width : "200px",
					header : new sap.m.Label({
						text : "Value"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "Center",
					width : "250px",
					popinDisplay : "Inline",
					header : new sap.m.Label({
						text : "Back Order"
					}),
					minScreenWidth : "2400px",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "End",
					width : "250px",
					popinDisplay : "Inline",
					header : new sap.m.Label({
						text : "Price"
					}),
					minScreenWidth : "2400px",
					demandPopin : true
				})
			]
		});

		// set model & bind Aggregation
		oTableSelectDialog6.setModel(oModel3);
		oTableSelectDialog6.bindAggregation("items", "/items", oItemTemplate3);

		// attach confirm listener
		oTableSelectDialog6.attachConfirm(function (evt) {
			if (oTableSelectDialog6.getMultiSelect()) {
				var aSelectedItems = evt.getParameter("selectedItems");
				if (aSelectedItems) {
					var sSelectedItems = "";
					//Loop through all selected items
					for (var i=0; i<aSelectedItems.length; i++) {
						//Get all the cells and pull back the first one which will be the name content
						var oCells = aSelectedItems[i].getCells();
						var oCell = oCells[0];
						//Update the text
						sSelectedItems += oCell.getText();
						if (i < aSelectedItems.length - 1) {
							sSelectedItems += ', ';
						}
					}
					sap.m.MessageBox.alert("You selected: "+ sSelectedItems);
				}
			} else {
				var selectedItem = evt.getParameter("selectedItem");
				if (selectedItem) {
					//Get all the cells and pull back the first one which will be the name content
					var oCells = selectedItem.getCells();
					var oCell = oCells[0];
					//Now update the input with the value
					sap.m.MessageBox.alert("Item selected is : " + oCell.getText());
				}
			}
		});

		var oButton6 = new sap.m.Button("tsdWithVeryLargeDataButton", {
			text: "Open TableSelectDialog with very large data",
			press: function () {
				// open dialog
				oTableSelectDialog6.setMultiSelect(false);
				oTableSelectDialog6.open();
			}
		});

		var oButton7 = new sap.m.Button("Button7", {
			text: "Open TableSelectDialog with multi Select and very large data",
			press: function () {
				// open dialog
				oTableSelectDialog6.setMultiSelect(true);
				oTableSelectDialog6.open();
			}
		});

		/* 8) table select dialog with web service binding, prefiltered by "id_1" */
		var oTableSelectDialog8 = new sap.m.TableSelectDialog("TableSelectDialog8", {
			title: "Choose an extended tech products",
			noDataText: "Sorry, no tech today",
			multiSelect: true,
			search : fnDoProductSearch,
			liveChange: fnDoProductSearch,
			columns : [
					new sap.m.Column({
						styleClass : "name",
						hAlign : "Begin",
						header : new sap.m.Label({
							text : "ID"
						})
					}),
					new sap.m.Column({
						hAlign : "Center",
						styleClass : "qty",
						popinDisplay : "Inline",
						header : new sap.m.Label({
							text : "Name"
						}),
						minScreenWidth : "Tablet",
						demandPopin : true
					}),
					new sap.m.Column({
						hAlign : "End",
						styleClass : "limit",
						width : "30%",
						header : new sap.m.Label({
							text : "Price"
						}),
						minScreenWidth : "Tablet",
						demandPopin : true
					}),
					new sap.m.Column({
						hAlign : "End",
						styleClass : "price",
						width : "30%",
						popinDisplay : "Inline",
						header : new sap.m.Label({
							text : "Weight"
						}),
						minScreenWidth : "Tablet",
						demandPopin : true
					})
				]
		});

		// attach confirm listener
		oTableSelectDialog8.attachConfirm(function (evt) {
			if (oTableSelectDialog6.getMultiSelect()) {
				var aSelectedItems = evt.getParameter("selectedItems");
				if (aSelectedItems) {
					var sSelectedItems = "";
					//Loop through all selected items
					for (var i=0; i<aSelectedItems.length; i++) {
						//Get all the cells and pull back the first one which will be the name content
						var oCells = aSelectedItems[i].getCells();
						var oCell = oCells[0];
						//Update the text
						sSelectedItems += oCell.getText();
						if (i < aSelectedItems.length - 1) {
							sSelectedItems += ', ';
						}
					}
					sap.m.MessageBox.alert("You selected: "+ sSelectedItems);
				}
			} else {
				var selectedItem = evt.getParameter("selectedItem");
				if (selectedItem) {
					//Get all the cells and pull back the first one which will be the name content
					var oCells = selectedItem.getCells();
					var oCell = oCells[0];
					//Now update the input with the value
					sap.m.MessageBox.alert("Item selected is : " + oCell.getText());
				}
			}
		});

		var oButton8 = new sap.m.Button("Button8", {
			text: "Open TableSelectDialog in MultiSelect mode, Web service binding, prefiltered by \"id_1\" with web service binding and no fixed width",
			press: function () {
				// initiate model
				var oModel = new sap.ui.model.odata.ODataModel(sServiceURI, true);
				oTableSelectDialog8.setModel(oModel);

				// bind aggregation with filters
				oTableSelectDialog8.bindAggregation("items", {
					path: "/Products",
					filters: fnCreatePrefilter("id_1", true),
					template: oProductItemTemplate
				});

				// open dialog
				oTableSelectDialog8.open("id_1");
			}
		});

		/* 9) table select dialog with web service binding, prefiltered by "id_1" and fixed width set to 800px */

		var oTableSelectDialog9 = new sap.m.TableSelectDialog("TableSelectDialog9", {
			contentWidth: "800px",
			title: "Choose an extended tech products",
			noDataText: "Sorry, no tech today",
			multiSelect: true,
			search : fnDoProductSearch,
			liveChange: fnDoProductSearch,
			columns : [
				new sap.m.Column({
					styleClass : "name",
					hAlign : "Begin",
					header : new sap.m.Label({
						text : "ID"
					})
				}),
				new sap.m.Column({
					hAlign : "Center",
					styleClass : "qty",
					popinDisplay : "Inline",
					header : new sap.m.Label({
						text : "Name"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "End",
					styleClass : "limit",
					width : "30%",
					header : new sap.m.Label({
						text : "Currency"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				}),
				new sap.m.Column({
					hAlign : "End",
					styleClass : "price",
					width : "30%",
					popinDisplay : "Inline",
					header : new sap.m.Label({
						text : "Price"
					}),
					minScreenWidth : "Tablet",
					demandPopin : true
				})
			]
		});

		// attach confirm listener
		oTableSelectDialog9.attachConfirm(function (evt) {
			if (oTableSelectDialog6.getMultiSelect()) {
				var aSelectedItems = evt.getParameter("selectedItems");
				if (aSelectedItems) {
					var sSelectedItems = "";
					//Loop through all selected items
					for (var i=0; i<aSelectedItems.length; i++) {
						//Get all the cells and pull back the first one which will be the name content
						var oCells = aSelectedItems[i].getCells();
						var oCell = oCells[0];
						//Update the text
						sSelectedItems += oCell.getText();
						if (i < aSelectedItems.length - 1) {
							sSelectedItems += ', ';
						}
					}
					sap.m.MessageBox.alert("You selected: "+ sSelectedItems);
				}
			} else {
				var selectedItem = evt.getParameter("selectedItem");
				if (selectedItem) {
					//Get all the cells and pull back the first one which will be the name content
					var oCells = selectedItem.getCells();
					var oCell = oCells[0];
					//Now update the input with the value
					sap.m.MessageBox.alert("Item selected is : " + oCell.getText());
				}
			}
		});

		var oButton9 = new sap.m.Button("Button9", {
			text: "Open TableSelectDialog in MultiSelect mode, Web service binding, late binding, with web service binding and 400px width",
			press: function () {
				// open dialog
				oTableSelectDialog9.open("");

				// initiate model
				var oModel = new sap.ui.model.odata.ODataModel(sServiceURI, true);
				oTableSelectDialog9.setModel(oModel);

				// bind aggregation with filters
				oTableSelectDialog9.bindAggregation("items", {
					path: "/Products",
					filters: fnCreatePrefilter("", true),
					template: oProductItemTemplate
				});

			}
		});

		// create the application page
		var oPage = new sap.m.Page("page", {
			title:"Mobile TableSelectDialog Control",
			content:[
				new sap.m.VBox({
					items: [
						oInput1,
						oInput2,
						oButton3,
						oButton4,
						oButton5,
						oButton6,
						oButton7,
						oButton8,
						oButton9
					]
				})
			]
		});

		var oApp = new sap.m.App("myApp", {initialPage:"page"});
		oApp.addPage(oPage).placeAt("content");

	</script>
	</head>
	<body id="body" class="sapUiBody">
		<div id="content"></div>
	</body>
</html>


text:
package com.sin.android.demo;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.sin.android.pl2303hxa.R;
import com.sin.android.sinlibs.activities.BaseActivity;
import com.sin.android.sinlibs.base.Callable;
import com.sin.android.sinlibs.utils.InjectUtils;
import com.sin.android.usb.pl2303hxa.PL2303Driver;
import com.sin.android.usb.pl2303hxa.PL2303Exception;

public class MainActivity extends BaseActivity {
	private Spinner sp_baudrate = null;
	private Button btn_open = null;
	private Button btn_close = null;
	private CheckBox cb_hex = null;
	private CheckBox cb_hex_rev = null;
	private Button btn_send = null;
	private EditText et_send = null;
	private TextView tv_log = null;

	private TextView et_sleep = null;
	private CheckBox cb_auto = null;

	// PL2303驱动
	private PL2303Driver curDriver = null;

	private static final String TEXT_CHARSET = "UTF-8"; // 字符编码方式

	private static final String[] BAUDRATES = { "9600", "14400", "19200", "38400", "56000", "57600", "115200" };

	private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (com.sin.android.usb.pl2303hxa.PL2303Driver.ACTION_PL2303_PERMISSION.equals(action)) {
				synchronized (this) {
					if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
						AddLog("授权成功");
						open();
					} else {
						curDriver = null;
						AddLog("授权失败");
					}
				}
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		sharedPreferences = getSharedPreferences("config", MODE_PRIVATE);

		setContentView(R.layout.activity_main);

		initControls();

		// 注册USB广播接收器,用于监听授权
		IntentFilter filter = new IntentFilter(PL2303Driver.ACTION_PL2303_PERMISSION);
		filter.addAction(PL2303Driver.ACTION_PL2303_PERMISSION);
		this.registerReceiver(mUsbReceiver, filter);
	}

	private void initControls() {
		// find and set all View to this.xx
		InjectUtils.injectViews(this, R.id.class);

		sp_baudrate = (Spinner) findViewById(R.id.sp_baudrate);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, BAUDRATES);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp_baudrate.setAdapter(adapter);

		tv_log.setOnLongClickListener(new View.OnLongClickListener() {

			@Override
			public boolean onLongClick(View arg0) {
				logct = 0;
				tv_log.setText("");
				return false;
			}
		});

		// event
		btn_open.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				preOpen();
			}
		});

		btn_close.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				close();
			}
		});

		btn_send.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				send();
			}
		});

		cb_auto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				refreshButton();
			}
		});

		refreshButton();
	}

	private int logct = 0;

	private void AddLog(String ftm, Object... args) {
		String log = String.format(ftm, args);
		safeCall(new Callable() {
			@Override
			public void call(Object... args) {
				++logct;
				tv_log.append(String.format("%03d ", logct));
				tv_log.append(args[0].toString());
				tv_log.append("\n");

				((ScrollView) tv_log.getParent()).post(new Runnable() {
					@Override
					public void run() {
						((ScrollView) tv_log.getParent()).fullScroll(ScrollView.FOCUS_DOWN);
					}
				});
			}
		}, log);
	}

	// 招到PL2303并请求打开
	private void preOpen() {
		// 试用第1个PL2303设备
		List<UsbDevice> devices = PL2303Driver.getAllSupportedDevices(this);
		if (devices.size() == 0) {
			AddLog("请先插入PL2303HXA设备");
		} else {
			AddLog("当前PL2303HXA设备:");
			for (UsbDevice d : devices) {
				AddLog(" " + d.getDeviceId());
			}

			// 使用找到的第1个PL2303HXA设备
			PL2303Driver dev = new PL2303Driver(this, devices.get(0));
			openPL2302Device(dev);
		}

		// 打开选择对话框选择设备
		/*
		 * PL2303Selector.createSelectDialog(this, 0, false, new
		 * PL2303Selector.Callback() {
		 *
		 * @Override public boolean whenPL2303Selected(PL2303Driver driver) {
		 * openPL2302Device(driver); return true; } }).show();
		 */
	}

	private void openPL2302Device(PL2303Driver dev) {
		if (dev != null) {
			curDriver = dev;
			if (curDriver.checkPermission()) {
				// 如果已经授权就直接打开
				open();
			}
		}
	}

	private String getReceive(ArrayList<Byte> recs) {
		StringBuffer sb = new StringBuffer();
		sb.append("收到: ");
		if (cb_hex_rev.isChecked()) {
			for (Byte b : recs) {
				sb.append(String.format("%02x ", b));
			}
		} else {
			int len = recs.size();
			byte[] data = new byte[len];
			for (int i = 0; i < len; ++i) {
				data[i] = recs.get(i);
			}
			try {
				sb.append(new String(data, TEXT_CHARSET));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				AddLog("转换编码失败");
			}
		}
		return sb.toString();
	}

	// 接收线程,始终接收
	private void startReceiveThread() {
		asynCall(new Callable() {
			@Override
			public void call(Object... arg0) {
				AddLog("开始接收");

				ArrayList<Byte> recs = new ArrayList<Byte>();
				long pretime = System.currentTimeMillis();
				while (curDriver != null) {
					PL2303Driver tDriver = curDriver;
					byte dat = 0;
					synchronized (tDriver) {
						dat = tDriver.read();
					}
					if (tDriver.isReadSuccess()) {
						recs.add(dat);
					} else {
						// 暂时没有收到数据
						pretime = 0;
						try {
							Thread.sleep(50);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}

					}

					// 至少没200ms显示一下接收到的数据
					if ((System.currentTimeMillis() - pretime) > 200 && recs.size() > 0) {
						AddLog(getReceive(recs));
						recs.clear();
						pretime = System.currentTimeMillis();
					}
					if (recs.size() == 0)
						pretime = System.currentTimeMillis();
				}
				AddLog("接收结束");
			}
		});
	}

	private void startAutoSendThread() {
		asynCall(new Callable() {
			@Override
			public void call(Object... arg0) {

				int sleep = 1000;
				while (curDriver != null) {
					if (cb_auto.isChecked()) {
						// 自动发送
						send();

						try {
							int v = Integer.parseInt(et_sleep.getText().toString());
							// 最快不能小于10ms
							if (v >= 10)
								sleep = v;
						} catch (Exception e) {
							AddLog("间隔错误");
						}

						try {
							Thread.sleep(sleep);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					} else {
						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		});
	}

	// 打开串口
	private void open() {
		if (curDriver == null)
			return;
		try {
			if (curDriver.isOpened()) {
				curDriver.cleanRead();
				curDriver.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		AddLog("打开串口", curDriver.getDeviceID());
		try {
			curDriver.setBaudRate(Integer.parseInt(sp_baudrate.getSelectedItem().toString()));
			curDriver.open();

			startReceiveThread();
			startAutoSendThread();
			refreshButton();
		} catch (PL2303Exception e) {
			AddLog("打开失败");
			AddLog(e.getMessage());
			e.printStackTrace();
		}
	}

	private void close() {
		AddLog("关闭串口");
		synchronized (curDriver) {
			curDriver.cleanRead();
			curDriver.close();
		}
		curDriver = null;
		AddLog("关闭成功");

		refreshButton();
	}

	private void send() {
		if (curDriver == null) {
			AddLog("请先打开串口");
			return;
		}

		String ins = et_send.getText().toString();
		if (cb_hex.isChecked()) {
			// HEX
			ins = ins.trim();
			if (ins.length() > 0) {
				String[] hexs = ins.split(" ");
				List<Byte> data = new ArrayList<Byte>();
				boolean okflag = true;
				for (String hex : hexs) {
					try {
						int d = Integer.parseInt(hex, 16);
						if (d > 255) {
							AddLog("%s 大于0xff", hex);
							okflag = false;
						} else {
							data.add((byte) d);
						}
					} catch (NumberFormatException e) {
						AddLog("%s 不是十六进制数", hex);
						e.printStackTrace();
						okflag = false;
					}
				}
				if (okflag && data.size() > 0) {
					for (Byte b : data) {
						curDriver.write(b);
					}
				}
			} else {
				AddLog("要发送的十六进制数据为空");
			}
		} else {
			try {
				byte[] data = ins.getBytes(TEXT_CHARSET);
				curDriver.write(data);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				AddLog("转换编码失败");
			}
		}
	}

	private void refreshButton() {
		btn_open.setVisibility(curDriver != null ? View.GONE : View.VISIBLE);
		btn_close.setVisibility(curDriver == null ? View.GONE : View.VISIBLE);
		sp_baudrate.setEnabled(curDriver == null);
		btn_send.setEnabled(curDriver != null);

		et_sleep.setEnabled(!cb_auto.isChecked());
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(mUsbReceiver);
	}

	private SharedPreferences sharedPreferences = null;

	@Override
	protected void onPause() {
		Editor edit = sharedPreferences.edit();
		edit.putBoolean("cb_hex", cb_hex.isChecked());
		edit.putBoolean("cb_hex_rev", cb_hex_rev.isChecked());
		edit.putInt("sp_baudrate", sp_baudrate.getSelectedItemPosition());
		edit.putString("et_send", et_send.getText().toString());
		edit.putString("et_sleep", et_sleep.getText().toString());
		edit.putBoolean("cb_auto", cb_auto.isChecked());
		edit.commit();
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (cb_auto != null) {
			cb_hex.setChecked(sharedPreferences.getBoolean("cb_hex", true));
			cb_hex_rev.setChecked(sharedPreferences.getBoolean("cb_hex_rev", true));
			cb_auto.setChecked(sharedPreferences.getBoolean("cb_auto", false));

			sp_baudrate.setSelection(sharedPreferences.getInt("sp_baudrate", 0));
			et_send.setText(sharedPreferences.getString("et_send", ""));
			et_sleep.setText(sharedPreferences.getString("et_sleep", "1000"));

			refreshButton();
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
layout:     post
title:      "Web Api - HTMLElement"
subtitle:   ""
date:       2015-12-14 12:00:00
author:     "wangxu"
header-img: "img/post-bg-js-version.jpg"
tags:
    - Javascript
    - Web Api
    - DOM
---

#### [HTMLElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement)

**HTMLElement**继承了Element

#### Properties

一部分属性继承自[Element](https://developer.mozilla.org/en-US/docs/Web/API/Element)

##### HTMLElement.draggable

指示元素是否可以被拖拽,当元素有draggable="true"属性时返回true,否则返回false

##### HTMLElement.hidden

指示元素是否隐藏,也可以通过改变hidden属性来设置元素隐藏或显示。

##### [HTMLElement.style](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style)

style属性返回一个[CSSStyleDeclaration](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration)对象,用来描述元素style属性。

设置style:

```html
<div id="test">test</div>
```

```javascript
elt.style.color = "blue";  // 直接设置

var st = elt.style;
st.color = "blue";  // 间接设置
```

设置之后html为:

```html
<div id="test" style="color:blue">test</div>
```

*通常来说使用`style`属性要比使用`elt.setAttribute('style', '...')`要好,因为使用`style`属性不会覆盖在style节点的样式*

Getting style:

**Example1**

```html
<div id="test" style="color:blue">test</div>
```

```javascript
var div = document.getElementById('test');

// get div's color
var color = div.style.color;

// or
var st = div.style;
color = st.color;
```

**Example2**

```html
<div id="test">test</div>
```

```css
#test {
    color: blue
}
```

```javascript
var div = document.getElementById('test');

// get div's color
var color = div.style.color;    // color 为 "", div.style 只能获取内联样式
```

*因为style属性无法读取在style标签内的css样式(只能获取元素的内联样式),要想获取元素全部的css属性需要使用window.getComputedStyle()来替代*

##### [HTMLElement.title](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/title)

设置或读取元素的title属性

**Example**

```html
<button id="btn1">button1</button>
```

```javascript
var button1 = document.getElementById('btn1');
button1.title = "click to refresh";
```

设置title属性之后:

```html
<button id="btn1" title="click to refresh">button1</button>
```

##### [HTMLElement.dataset](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset)

获取或设置自定义属性(data-*)的值

**Example**

```html
<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth="1960-10-03">John Doe</div>
```
```javascript
var el = document.querySelector('#user');

// 读取属性值
console.log(el.dataset.id);
console.log(el.dataset.user);
console.log(el.dataset.dateOfBirth);

// 设置属性值
el.dataset.dateOfBirth = '1981-08-25';
```
设置完成之后:

```html
<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth="1981-08-25">John Doe</div>
```

##### [HTMLElement.offsetHeight](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight)

返回元素的高度(包括垂直的padding,border)。比`Element.clientHeight`多出border的长度

##### [HTMLElement.offsetWidth](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth)

返回元素的宽度(包括padding,border)

##### [HTMLElement.offsetParent](https://developer.mozilla.org/en-US/docs/Web/API/HTMLelement/offsetParent)

返回一个包含这个元素并且离它最近的一个带有定位的元素

##### [HTMLElement.offsetTop](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop)

返回当前元素顶部(不包含margin)相对于offsetParent元素的偏移。

##### [HTMLElement.offsetLeft](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetLeft)

返回当前元素左侧(不包含margin)相对于offsetParent元素的偏移。


text:
package fzf

import (
	"regexp"
	"strings"

	"github.com/junegunn/fzf/src/algo"
	"github.com/junegunn/fzf/src/util"
)

// fuzzy
// 'exact
// ^exact-prefix
// exact-suffix$
// !not-fuzzy
// !'not-exact
// !^not-exact-prefix
// !not-exact-suffix$

type termType int

const (
	termFuzzy termType = iota
	termExact
	termPrefix
	termSuffix
	termEqual
)

type term struct {
	typ           termType
	inv           bool
	text          []rune
	caseSensitive bool
	origText      []rune
}

type termSet []term

// Pattern represents search pattern
type Pattern struct {
	fuzzy         bool
	extended      bool
	caseSensitive bool
	forward       bool
	text          []rune
	termSets      []termSet
	cacheable     bool
	delimiter     Delimiter
	nth           []Range
	procFun       map[termType]func(bool, bool, util.Chars, []rune) algo.Result
}

var (
	_patternCache map[string]*Pattern
	_splitRegex   *regexp.Regexp
	_cache        ChunkCache
)

func init() {
	_splitRegex = regexp.MustCompile("\\s+")
	clearPatternCache()
	clearChunkCache()
}

func clearPatternCache() {
	// We can uniquely identify the pattern for a given string since
	// search mode and caseMode do not change while the program is running
	_patternCache = make(map[string]*Pattern)
}

func clearChunkCache() {
	_cache = NewChunkCache()
}

// BuildPattern builds Pattern object from the given arguments
func BuildPattern(fuzzy bool, extended bool, caseMode Case, forward bool,
	cacheable bool, nth []Range, delimiter Delimiter, runes []rune) *Pattern {

	var asString string
	if extended {
		asString = strings.Trim(string(runes), " ")
	} else {
		asString = string(runes)
	}

	cached, found := _patternCache[asString]
	if found {
		return cached
	}

	caseSensitive := true
	termSets := []termSet{}

	if extended {
		termSets = parseTerms(fuzzy, caseMode, asString)
	Loop:
		for _, termSet := range termSets {
			for idx, term := range termSet {
				// If the query contains inverse search terms or OR operators,
				// we cannot cache the search scope
				if !cacheable || idx > 0 || term.inv {
					cacheable = false
					break Loop
				}
			}
		}
	} else {
		lowerString := strings.ToLower(asString)
		caseSensitive = caseMode == CaseRespect ||
			caseMode == CaseSmart && lowerString != asString
		if !caseSensitive {
			asString = lowerString
		}
	}

	ptr := &Pattern{
		fuzzy:         fuzzy,
		extended:      extended,
		caseSensitive: caseSensitive,
		forward:       forward,
		text:          []rune(asString),
		termSets:      termSets,
		cacheable:     cacheable,
		nth:           nth,
		delimiter:     delimiter,
		procFun:       make(map[termType]func(bool, bool, util.Chars, []rune) algo.Result)}

	ptr.procFun[termFuzzy] = algo.FuzzyMatch
	ptr.procFun[termEqual] = algo.EqualMatch
	ptr.procFun[termExact] = algo.ExactMatchNaive
	ptr.procFun[termPrefix] = algo.PrefixMatch
	ptr.procFun[termSuffix] = algo.SuffixMatch

	_patternCache[asString] = ptr
	return ptr
}

func parseTerms(fuzzy bool, caseMode Case, str string) []termSet {
	tokens := _splitRegex.Split(str, -1)
	sets := []termSet{}
	set := termSet{}
	switchSet := false
	for _, token := range tokens {
		typ, inv, text := termFuzzy, false, token
		lowerText := strings.ToLower(text)
		caseSensitive := caseMode == CaseRespect ||
			caseMode == CaseSmart && text != lowerText
		if !caseSensitive {
			text = lowerText
		}
		origText := []rune(text)
		if !fuzzy {
			typ = termExact
		}

		if text == "|" {
			switchSet = false
			continue
		}

		if strings.HasPrefix(text, "!") {
			inv = true
			text = text[1:]
		}

		if strings.HasPrefix(text, "'") {
			// Flip exactness
			if fuzzy {
				typ = termExact
				text = text[1:]
			} else {
				typ = termFuzzy
				text = text[1:]
			}
		} else if strings.HasPrefix(text, "^") {
			if strings.HasSuffix(text, "$") {
				typ = termEqual
				text = text[1 : len(text)-1]
			} else {
				typ = termPrefix
				text = text[1:]
			}
		} else if strings.HasSuffix(text, "$") {
			typ = termSuffix
			text = text[:len(text)-1]
		}

		if len(text) > 0 {
			if switchSet {
				sets = append(sets, set)
				set = termSet{}
			}
			set = append(set, term{
				typ:           typ,
				inv:           inv,
				text:          []rune(text),
				caseSensitive: caseSensitive,
				origText:      origText})
			switchSet = true
		}
	}
	if len(set) > 0 {
		sets = append(sets, set)
	}
	return sets
}

// IsEmpty returns true if the pattern is effectively empty
func (p *Pattern) IsEmpty() bool {
	if !p.extended {
		return len(p.text) == 0
	}
	return len(p.termSets) == 0
}

// AsString returns the search query in string type
func (p *Pattern) AsString() string {
	return string(p.text)
}

// CacheKey is used to build string to be used as the key of result cache
func (p *Pattern) CacheKey() string {
	if !p.extended {
		return p.AsString()
	}
	cacheableTerms := []string{}
	for _, termSet := range p.termSets {
		if len(termSet) == 1 && !termSet[0].inv && (p.fuzzy || termSet[0].typ == termExact) {
			cacheableTerms = append(cacheableTerms, string(termSet[0].origText))
		}
	}
	return strings.Join(cacheableTerms, " ")
}

// Match returns the list of matches Items in the given Chunk
func (p *Pattern) Match(chunk *Chunk) []*Result {
	// ChunkCache: Exact match
	cacheKey := p.CacheKey()
	if p.cacheable {
		if cached, found := _cache.Find(chunk, cacheKey); found {
			return cached
		}
	}

	// Prefix/suffix cache
	var space []*Result
Loop:
	for idx := 1; idx < len(cacheKey); idx++ {
		// [---------| ] | [ |---------]
		// [--------|  ] | [  |--------]
		// [-------|   ] | [   |-------]
		prefix := cacheKey[:len(cacheKey)-idx]
		suffix := cacheKey[idx:]
		for _, substr := range [2]*string{&prefix, &suffix} {
			if cached, found := _cache.Find(chunk, *substr); found {
				space = cached
				break Loop
			}
		}
	}

	matches := p.matchChunk(chunk, space)

	if p.cacheable {
		_cache.Add(chunk, cacheKey, matches)
	}
	return matches
}

func (p *Pattern) matchChunk(chunk *Chunk, space []*Result) []*Result {
	matches := []*Result{}

	if space == nil {
		for _, item := range *chunk {
			if match, _ := p.MatchItem(item); match != nil {
				matches = append(matches, match)
			}
		}
	} else {
		for _, result := range space {
			if match, _ := p.MatchItem(result.item); match != nil {
				matches = append(matches, match)
			}
		}
	}
	return matches
}

// MatchItem returns true if the Item is a match
func (p *Pattern) MatchItem(item *Item) (*Result, []Offset) {
	if p.extended {
		if offsets, bonus, trimLen := p.extendedMatch(item); len(offsets) == len(p.termSets) {
			return buildResult(item, offsets, bonus, trimLen), offsets
		}
		return nil, nil
	}
	offset, bonus, trimLen := p.basicMatch(item)
	if sidx := offset[0]; sidx >= 0 {
		offsets := []Offset{offset}
		return buildResult(item, offsets, bonus, trimLen), offsets
	}
	return nil, nil
}

func (p *Pattern) basicMatch(item *Item) (Offset, int, int) {
	input := p.prepareInput(item)
	if p.fuzzy {
		return p.iter(algo.FuzzyMatch, input, p.caseSensitive, p.forward, p.text)
	}
	return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.forward, p.text)
}

func (p *Pattern) extendedMatch(item *Item) ([]Offset, int, int) {
	input := p.prepareInput(item)
	offsets := []Offset{}
	var totalBonus int
	var totalTrimLen int
	for _, termSet := range p.termSets {
		var offset Offset
		var bonus int
		var trimLen int
		matched := false
		for _, term := range termSet {
			pfun := p.procFun[term.typ]
			off, pen, tLen := p.iter(pfun, input, term.caseSensitive, p.forward, term.text)
			if sidx := off[0]; sidx >= 0 {
				if term.inv {
					continue
				}
				offset, bonus, trimLen = off, pen, tLen
				matched = true
				break
			} else if term.inv {
				offset, bonus, trimLen = Offset{0, 0}, 0, 0
				matched = true
				continue
			}
		}
		if matched {
			offsets = append(offsets, offset)
			totalBonus += bonus
			totalTrimLen += trimLen
		}
	}
	return offsets, totalBonus, totalTrimLen
}

func (p *Pattern) prepareInput(item *Item) []Token {
	if item.transformed != nil {
		return item.transformed
	}

	var ret []Token
	if len(p.nth) == 0 {
		ret = []Token{Token{text: &item.text, prefixLength: 0, trimLength: int32(item.text.TrimLength())}}
	} else {
		tokens := Tokenize(item.text, p.delimiter)
		ret = Transform(tokens, p.nth)
	}
	item.transformed = ret
	return ret
}

func (p *Pattern) iter(pfun func(bool, bool, util.Chars, []rune) algo.Result,
	tokens []Token, caseSensitive bool, forward bool, pattern []rune) (Offset, int, int) {
	for _, part := range tokens {
		if res := pfun(caseSensitive, forward, *part.text, pattern); res.Start >= 0 {
			sidx := int32(res.Start) + part.prefixLength
			eidx := int32(res.End) + part.prefixLength
			return Offset{sidx, eidx}, res.Bonus, int(part.trimLength)
		}
	}
	return Offset{-1, -1}, 0, -1
}


text:
package fr.paris.lutece.portal.web.l10n;

import fr.paris.lutece.portal.service.datastore.DatastoreService;
import fr.paris.lutece.portal.service.util.AppLogService;
import fr.paris.lutece.portal.service.util.AppPropertiesService;
import java.util.ArrayList;
import java.util.List;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * LocaleService
 */
public final class LocaleService
{
    private static final String ATTRIBUTE_SELECTED_LOCALE = "LUTECE_ATTRIBUTE_USER_SELECTED_LOCALE";
    private static final String DSKEY_LANGUAGE_DEFAULT = "portal.site.site_property.locale.default";
    private static final String PROPERTY_LANG_LIST = "lutece.i18n.availableLocales";
    private static final String PROPERTY_LANG_DEFAULT = "lutece.i18n.defaultLocale";
    private static Locale _locale;
    private static List<Locale> _supportedLocales;

    /**
     * Private constructor
     */
    private LocaleService( )
    {
    }

    /**
     * Set the locale selected by the user in the front office. The user may select a language without been authenticated.
     *
     * @param request
     *            The request
     * @param locale
     *            The locale
     */
    public static void setUserSelectedLocale( HttpServletRequest request, Locale locale )
    {
        HttpSession session = request.getSession( true );
        session.setAttribute( ATTRIBUTE_SELECTED_LOCALE, locale );
    }

    /**
     * Get a Locale selected by the user in front office
     *
     * @param request
     *            The HTTP request
     * @return The locale selected, or the default jvm locale if no locale has been selected
     */
    public static Locale getUserSelectedLocale( HttpServletRequest request )
    {
        Locale locale = LocaleService.getDefault( );
        HttpSession session = request.getSession( );

        if ( session != null )
        {
            Locale localeSession = (Locale) session.getAttribute( ATTRIBUTE_SELECTED_LOCALE );

            if ( localeSession != null )
            {
                locale = localeSession;
            }
        }

        return locale;
    }

    /**
     * Return a Lutece defined default Locale
     *
     * @return The locale
     */
    public static synchronized Locale getDefault( )
    {
        if ( _locale != null )
        {
            return _locale;
        }
        else
        {
            String dsLang = DatastoreService.getInstanceDataValue( DSKEY_LANGUAGE_DEFAULT, null );

            if ( dsLang != null )
            {
                for ( String strISOLang : Locale.getISOLanguages( ) )
                {
                    if ( strISOLang.equals( dsLang ) )
                    {
                        _locale = new Locale( dsLang );
                        AppLogService.info( "LocaleService : default locale set to : {}", dsLang );

                        return _locale;
                    }
                }
            }

            // otherwise, get the default locale from properties
            _locale = new Locale( AppPropertiesService.getProperty( PROPERTY_LANG_DEFAULT ) );
            AppLogService.error( "LocaleService : invalid defined locale {} - default set to {}", dsLang, _locale.getLanguage( ) );

            return _locale;
        }
    }

    /**
     * Retrieve the best supported locale for the user's session Priority order : 1- selected locale session attribute 2- browser locale (if supported) 3-
     * default server locale
     *
     * @param request
     *            The HTTP request
     * @return The locale
     */
    public static Locale getContextUserLocale( HttpServletRequest request )
    {
        // consider the current session locale
        if ( request != null )
        {
            HttpSession session = request.getSession( false );
            if ( session != null )
            {
                Locale userSessionLocale = (Locale) session.getAttribute( ATTRIBUTE_SELECTED_LOCALE );
                if ( userSessionLocale != null )
                {
                    if ( isSupported( userSessionLocale ) )
                    {
                        return userSessionLocale;
                    }
                }
            }
        }

        // consider the browser language
        Locale locale = new Locale( request.getLocale( ).getLanguage( ).substring( 0, 2 ) );
        if ( isSupported( locale ) )
        {
            return locale;
        }

        // otherwise consider the server default
        return getDefault( );
    }

    /**
     * check if Locale is supported according to locale list in lutece properties
     *
     * @param locale
     * @return true if supported
     */
    public static boolean isSupported( Locale locale )
    {
        if ( _supportedLocales == null )
        {
            getSupportedLangList( );
        }

        // check if the mandatory language is supported
        for ( Locale supportedLocale : _supportedLocales )
        {
            if ( supportedLocale.equals( locale ) )
            {
                return true;
            }
        }

        return false;
    }

    /**
     * get Supported Lang List
     *
     * @return the Supported Lang List
     */
    public static synchronized List<Locale> getSupportedLangList( )
    {
        if ( _supportedLocales == null )
        {
            String [ ] strLangList = AppPropertiesService.getProperty( PROPERTY_LANG_LIST ).split( "," );
            _supportedLocales = new ArrayList<>( );
            for ( String lang : strLangList )
            {
                _supportedLocales.add( new Locale( lang ) );
            }
        }

        return _supportedLocales;
    }
}


text:
Quickstart
==========

.. toctree::
   :maxdepth: 10

   introduction.rst
   i_am/index.rst
   getting_started/index.rst


text:
@interface PodsDummy_Pods_WYTestTests : NSObject
@end
@implementation PodsDummy_Pods_WYTestTests
@end


text:
Messages = new Mongo.Collection('messages');
Template.main.helpers({
  lightStateClass: function() {
    return Template.instance().defaultLight().state ? 'success' : 'danger';
  },
  messages: function() {
    return Messages.find({}, {
      sort: {
        created: -1
      }
    });
  },
  isMessageType: function(messageType) {
    return this.messageType === messageType;
  }
});
Template.main.events({
  'click #clearMessages': function(e, t) {
    e.preventDefault();
    var messages = Messages.find().fetch();
    messages.forEach(function(message) {
      Meteor.call('removeMessage', message._id);
    });
  },
  'click #toggleLight': function(e, t) {
    e.preventDefault();
    Meteor.call('toggleLight', t.defaultLight());
  },
  'click #getLightState': function(e, t) {
    e.preventDefault();
    Meteor.call('getLightState', t.defaultLight());
  }
});
Template.main.onCreated(function() {
  var self = this;
  var defaultLight = Lights.find({
    pin: 13
  });
  self.subscribe('lights');
  self.defaultLight = function() {
    return defaultLight && defaultLight.fetch()[0];
  }
  defaultLight.observe({
    changed: function(newDoc, oldDoc) {
      var tmpDoc = newDoc;
      tmpDoc.created = new Date();
      tmpDoc.messageType = 'pinChange';
      delete tmpDoc._id;
      Meteor.call('message', tmpDoc);
    }
  });
  self.subscribe('messages');
});


text:
package main

import _ "github.com/ying32/govcl/samples/customLibTest/alib"
import "github.com/ying32/govcl/vcl"

type TMainForm struct {
	*vcl.TForm
}

var (
	mainForm *TMainForm
)

func main() {

	vcl.RunApp(&mainForm)
}


text:
package main

import (
	"testing"

	"github.com/kelda/kelda/integration-tester/util"
)

func TestNetwork(t *testing.T) {
	clnt, err := util.GetDefaultDaemonClient()
	if err != nil {
		t.Fatalf("couldn't get api client: %s", err.Error())
	}
	defer clnt.Close()

	containers, err := clnt.QueryContainers()
	if err != nil {
		t.Fatalf("couldn't query containers: %s", err.Error())
	}

	machines, err := clnt.QueryMachines()
	if err != nil {
		t.Fatalf("failed to query machines: %s", err)
	}

	loadBalancers, err := clnt.QueryLoadBalancers()
	if err != nil {
		t.Fatalf("failed to query load balancers: %s", err)
	}

	connections, err := clnt.QueryConnections()
	if err != nil {
		t.Fatalf("Failed to query connections: %s", err)
	}

	sshUtil, err := util.NewSSHUtil(machines)
	if err != nil {
		t.Fatalf("failed to create SSH util client: %s", err)
	}

	t.Run("DNS", func(t *testing.T) {
		t.Parallel()
		testDNS(t, sshUtil, containers, loadBalancers)
	})

	t.Run("Ping", func(t *testing.T) {
		t.Parallel()
		testPing(t, sshUtil, containers, loadBalancers, connections)
	})

	t.Run("HPing", func(t *testing.T) {
		t.Parallel()
		testHPing(t, sshUtil, containers, connections)
	})
}


text:
// node modules
var sys = require('sys'),
    http = require('http'),
    url = require('url');

// dependency modules
var sha1 = require('../dependencies/sha1');

// bomber modules
var Response = require('./response').Response,
    Request = require('./request').Request,
    processAction = require('./action').processAction,
    Cookies = require('./cookies').Cookies,
    SessionManager = require('./session').SessionManager;

/* Server(project)
 *
 * A Server uses Nodes `http` module to listen for HTTP requests on a given
 * port, and then parses those requests and uses the passed in app to find an
 * action for the request, and then processes that aciton.
 *
 * Parameters:
 *
 * + `app`: Bomberjs `App` object. The app to hand the incoming HTTP
 *   requests to.
 */
var Server = exports.Server = function(project, config) {
  this.project = project;
  project.server = this;

  // grab the server settings from the project
  this.project.config.server = process.mixin(Server.__defaultOptions, this.project.config.server, config);

  // Warn if no signing secret is set -- and create a temporary one
  if (!this.project.config.security || !this.project.config.security.signing_secret) {
    sys.error( "\nWARNING: No signing secret is set in your configuration file.\n" +
               " The secret is used to sign secure cookies, validate session and encrypt user\n"+
               " passwords, so it's extremely important for you to set a unique and secure secret.\n" +
               " A temporary secret will be used for now, but all cookies, session and user\n" +
               " accounts will be invalidated when the server is restarted!\n" );

    // set the random signing secret
    this.project.security = this.project.security || {};
    this.project.security.signing_secret = sha1.hex_hmac_sha1(Math.random(), Math.random());
  }

  this.session_manager = new SessionManager(this.project.config.server.sessions);
};

/* Server.__defaultOoptions
 *
 * The default options for the server.
 *
 * This gets merged with the options specified for the server in the project config
 */
Server.__defaultOptions = {
  port: 8400,
  sessions: {
    storage_method: 'disk',
    disk_storage_location: '/tmp/',
    expire_minutes: 600,
    renew_minutes: 10,
    cookie: {
      name: 'session_key',
      domain: '',
      path: '/',
      secure: false
    }
  }
};

/* Server.prototype.stop()
 *
 * Stop listening.
 */
Server.prototype.stop = function() {
  this.httpServer.close();
};

/* Server.prototype.start()
 *
 * Start listening.
 */
Server.prototype.start = function() {
  var server = this;
  var base_app = this.project.base_app;

  this.httpServer = http.createServer(function (req, res) {
      try {
        sys.puts("\nReceived " + req.method + " request for " + req.url);

        // Routers only get a path, we parse the url now so it only happens once
        var parsedURL = url.parse(req.url, true);

        var route = base_app.getRoute(req.method, parsedURL.pathname);
        if(!route) { return server.send404(res, parsedURL.pathname); }

        // wrap the request and the response
        var request = new Request(req, parsedURL, route);
        var response = new Response(res);
        // Append cookies and sessions objects to request and response
        request.cookies = response.cookies = new Cookies(request, response, server.project);
        request.session = response.session = server.session_manager.getSession(request);

        // get the action designated by the route, and run it
        var action = base_app.getAction(route.action);
        processAction(request, response, action);

        // Finish the session (this is unlikely to be the perfect place for it, at last if we're running stuff async)
        // There's probably a need for a way to specify tasks/callbacks after the action has run anyway.
        request.session.finish();
      }
      catch(err) {
        res.sendHeader(500, {'Content-Type': 'text/plain'});
        res.sendBody('500 error!\n\n' + (err.stack || err));
        res.finish();
      }
    });
  this.httpServer.listen(this.project.config.server.port);

  sys.puts('Bomber Server running at http://localhost:'+this.project.config.server.port);
};

/* Server.prototype.send404()
 *
 * In the event that a route can't be found for a request, this function is
 * called to send the HTTP 404 response.
 *
 * Parameters:
 *
 * `res`: A Node `http.serverResponse` object.
 * `path`: The path for which a route couldn't be found.
 */
Server.prototype.send404 = function(res, path) {
  res.sendHeader(404, {'Content-Type': 'text/plain'});
  var body = 'Not found: ' + path;
  if( this.project.base_app.router ) {
    body += '\n\nRoutes tried:';
    this.project.base_app.router._routes.forEach(function(route) {
        body += '\n  ' + route.regex;
      });
  }
  res.sendBody(body);
  res.finish();
}


text:
class SkSPRITE_CLASSNAME : public SkSpriteBlitter {
public:
    SkSPRITE_CLASSNAME(const SkBitmap& source SkSPRITE_ARGS)
        : SkSpriteBlitter(source)
    {
        SkSPRITE_INIT
    }
    virtual void blitRect(int x, int y, int width, int height)
    {
        SkASSERT(width > 0 && height > 0);
        int srcX = x - fLeft;
        int srcY = y - fTop;
        SkSPRITE_DST_TYPE*          dst = fDevice->SkSPRITE_DST_GETADDR(x, y);
        const SkSPRITE_SRC_TYPE*    src = fSource->SkSPRITE_SRC_GETADDR(srcX, srcY);
        unsigned                    dstRB = fDevice->rowBytes();
        unsigned                    srcRB = fSource->rowBytes();

        SkDEBUGCODE((void)fDevice->SkSPRITE_DST_GETADDR(x + width - 1, y + height - 1);)
        SkDEBUGCODE((void)fSource->SkSPRITE_SRC_GETADDR(srcX + width  - 1, srcY + height - 1);)

        SkSPRITE_PREAMBLE((*fSource), srcX, srcY);

        do {
            SkSPRITE_DST_TYPE* d = dst;
            const SkSPRITE_SRC_TYPE* s = src;
#ifdef SkSPRITE_BEGIN_ROW
            SkSPRITE_BEGIN_ROW
#endif
            int w = width;
            do {
                SkSPRITE_SRC_TYPE sc = *s++;
                SkSPRITE_BLIT_PIXEL(d, sc);
                d += 1;
            } while (--w != 0);
            dst = (SkSPRITE_DST_TYPE*)((char*)dst + dstRB);
            src = (const SkSPRITE_SRC_TYPE*)((const char*)src + srcRB);
            SkSPRITE_NEXT_ROW
        } while (--height != 0);

        SkSPRITE_POSTAMBLE((*fSource));
    }
private:
    SkSPRITE_FIELDS
};

#undef SkSPRITE_BLIT_PIXEL
#undef SkSPRITE_CLASSNAME
#undef SkSPRITE_DST_TYPE
#undef SkSPRITE_SRC_TYPE
#undef SkSPRITE_DST_GETADDR
#undef SkSPRITE_SRC_GETADDR
#undef SkSPRITE_PREAMBLE
#undef SkSPRITE_POSTAMBLE
#undef SkSPRITE_ARGS
#undef SkSPRITE_FIELDS
#undef SkSPRITE_INIT
#undef SkSPRITE_NEXT_ROW
#undef SkSPRITE_BEGIN_ROW


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

namespace OwinHelpers
{
    using System.Threading.Tasks;
    using BodyDelegate = System.Func<System.IO.Stream,System.Threading.CancellationToken,System.Threading.Tasks.Task>;
    internal class StringBody : IObservable<ArraySegment<byte>>
    {
        private readonly byte[] _bytes;

        public StringBody(string text) : this(text, Encoding.Default)
        {
        }

        public StringBody(string text, Encoding encoding)
        {
            _bytes = encoding.GetBytes(text);
        }

        public BodyDelegate ToAction()
        {
            return (stream, token) => Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, _bytes, 0, _bytes.Length, null);
        }

        public int Length
        {
            get { return _bytes.Length; }
        }

        public IDisposable Subscribe(IObserver<ArraySegment<byte>> observer)
        {
            Action action = () =>
                                {
                                    observer.OnNext(new ArraySegment<byte>(_bytes));
                                    observer.OnCompleted();
                                };
            action.BeginInvoke(action.EndInvoke, null);
            return new NullDisposable();
        }

    }
}


text:
import chai from 'chai';
import db from '../../src/models';
import { loadFixtures } from '../helpers';

chai.should();

describe('APIToken Model', () => {
  describe('.generate', () => {
    it('should generate a random token', () => {
      const body = {
        name: 'test'
      };

      return db.APIToken.generate(body).then(auth => {
        auth.token.length.should.equal(32);
        Object.keys(body).forEach(field => {
          auth.get(field).should.equal(body[field]);
        });
      });
    });

    it('should throw validation errors', done => {
      const body = {};

      db.APIToken.generate(body).catch(err => {
        err.message.should.equal(
          'notNull Violation: APIToken.name cannot be null'
        );
        done();
      });
    });
  });
});


text:
/* -*- indent-tabs-mode: nil; js-indent-level: 4 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// helper function to shortcut component creation
function doCreate(aContract, aInterface)
{
    return Components.classes[aContract].createInstance(aInterface);
}

// for the items, loading a text file
const IOSERVICE_CTRID = "@mozilla.org/network/io-service;1";
const nsIIOService    = Components.interfaces.nsIIOService;
const SIS_CTRID       = "@mozilla.org/scriptableinputstream;1"
const nsISIS          = Components.interfaces.nsIScriptableInputStream;

// rdf foo, onload handler
const kRDFSvcContractID = "@mozilla.org/rdf/rdf-service;1";
const kRDFInMemContractID =
    "@mozilla.org/rdf/datasource;1?name=in-memory-datasource";
const kRDFContUtilsID = "@mozilla.org/rdf/container-utils;1";
const kRDFXMLSerializerID = "@mozilla.org/rdf/xml-serializer;1";
const kIOSvcContractID  = "@mozilla.org/network/io-service;1";
const kStandardURL = Components.classes["@mozilla.org/network/standard-url;1"];
const nsIURL = Components.interfaces.nsIURL;
const nsIStandardURL = Components.interfaces.nsIStandardURL;
const nsIFilePicker = Components.interfaces.nsIFilePicker;
const nsIXULTreeBuilder = Components.interfaces.nsIXULTreeBuilder;
const nsIXULTemplateBuilder = Components.interfaces.nsIXULTemplateBuilder;
const kIOSvc = Components.classes[kIOSvcContractID]
    .getService(Components.interfaces.nsIIOService);
const nsIRDFService = Components.interfaces.nsIRDFService;
const nsIRDFDataSource = Components.interfaces.nsIRDFDataSource;
const nsIRDFRemoteDataSource = Components.interfaces.nsIRDFRemoteDataSource;
const nsIRDFPurgeableDataSource =
    Components.interfaces.nsIRDFPurgeableDataSource;
const nsIRDFResource = Components.interfaces.nsIRDFResource;
const nsIRDFLiteral = Components.interfaces.nsIRDFLiteral;
const nsIRDFInt = Components.interfaces.nsIRDFInt;
const nsIRDFContainerUtils = Components.interfaces.nsIRDFContainerUtils;
const nsIRDFXMLSerializer = Components.interfaces.nsIRDFXMLSerializer;
const nsIRDFXMLSource = Components.interfaces.nsIRDFXMLSource;
const kRDFSvc =
    Components.classes[kRDFSvcContractID].getService(nsIRDFService);
const krTypeCat = kRDFSvc.GetResource("http://home.netscape.com/NC-rdf#category");
const krTypeFailCount = kRDFSvc.GetResource("http://home.netscape.com/NC-rdf#failCount");
const krTypeName = kRDFSvc.GetResource("http://home.netscape.com/NC-rdf#name");
const krTypeSucc = kRDFSvc.GetResource("http://home.netscape.com/NC-rdf#succ");
const krTypeOrigSucc = kRDFSvc.GetResource("http://home.netscape.com/NC-rdf#orig_succ");
const krTypeOrigFailCount = kRDFSvc.GetResource("http://home.netscape.com/NC-rdf#orig_failCount");
const krTypeOrigSuccCount = kRDFSvc.GetResource("http://home.netscape.com/NC-rdf#orig_succCount");
const krTypePath = kRDFSvc.GetResource("http://home.netscape.com/NC-rdf#path");
const krTypeParent = kRDFSvc.GetResource("http://home.netscape.com/NC-rdf#parent");
const krTypePurp = kRDFSvc.GetResource("http://home.netscape.com/NC-rdf#purp");
const krTypeSuccCount = kRDFSvc.GetResource("http://home.netscape.com/NC-rdf#succCount");
const kGood  = kRDFSvc.GetLiteral("yes");
const kBad   = kRDFSvc.GetLiteral("no");
const kMixed = kRDFSvc.GetLiteral("+-");
const kContUtils = doCreate(kRDFContUtilsID, nsIRDFContainerUtils);

function doCreateRDFFP(aTitle, aMode)
{
    var fp = doCreate("@mozilla.org/filepicker;1", nsIFilePicker);
    fp.init(window, aTitle, aMode);
    fp.appendFilter('*.rdf', '*.rdf');
    fp.appendFilters(nsIFilePicker.filterAll);
    return fp;
}

function goDoCommand(aCommand)
{
    try {
        var controller =
            top.document.commandDispatcher.getControllerForCommand(aCommand);
        if (controller && controller.isCommandEnabled(aCommand))
            controller.doCommand(aCommand);
    }
    catch(e) {
        dump("An error "+e+" occurred executing the "+aCommand+" command\n");
    }
}

function registerController(aController)
{
    top.controllers.appendController(aController);
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.wpi.first.wpilibj.templates.commands;

import edu.wpi.first.wpilibj.templates.subsystems.Claw;

/**
 *
 * @author Nicster34
 */
public class ClawClose extends CommandBase{
    Claw claw = new Claw();
    public ClawClose() {
        requires(claw);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    /**
     * Have the drivetrain drive tank drive with the latest values from joysticks.
     */
    protected void execute() {
        claw.clawClose();
    }

    // Make this return true when this Command no longer needs to run execute()
    /**
     * @return false, so that it executes forever or until another command
     *         interrupts it.
     */
    protected boolean isFinished() {
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
        claw.clawStop();
    }

}


text:
//=======================================================================
// Copyright Baptiste Wicht 2011-2014.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef STOP_WATCH_H
#define STOP_WATCH_H

#include <chrono>

namespace eddic {

typedef std::chrono::high_resolution_clock Clock;

/*!
 * \class StopWatch
 * \brief Simple stopwatch to keep track of elapsed time between two points.
 *
 * The stopwatch starts automatically when instantiated. This stopwatch use Boost Chrono to keep tracks of time.
 */
class StopWatch {
    public:
        StopWatch();
        double elapsed();
        double micro_elapsed();

    private:
        Clock::time_point startTime;
};

} //end of eddic

#endif


text:
import multiprocessing
import time

def worker(num):
    """thread worker function"""
    print 'Worker:', num
    return

def slow_worker():
    print 'Starting worker'
    time.sleep(0.1)
    print 'Finished worker'

if __name__ == '__main__':
    p = multiprocessing.Process(target=slow_worker)
    print 'BEFORE:', p, p.is_alive()

    p.start()
    print 'DURING:', p, p.is_alive()

    p.terminate()
    print 'TERMINATED:', p, p.is_alive()

    p.join()
    print 'JOINE:', p, p.is_alive()


text:
from migrate.versioning.shell import main

if __name__ == '__main__':
    main(six='<module 'six' from 'D:\Python27\lib\site-packages\six.pyc'>')


text:
package com.aaront.sorting.algorithm;

import java.util.Arrays;

/**
 * @author tonyhui
 * @since 16/5/2
 */
public abstract class BaseAlgorithm {
    public void print(int[] array) {
        System.out.println(Arrays.toString(array));
    }
}


text:
<?php

namespace Magento\SalesRule\Test\Block\Adminhtml\Promo\Quote\Edit\Tab;

use Magento\Mtf\Client\Element\SimpleElement;
use Magento\Backend\Test\Block\Widget\Tab;

/**
 * Sales rule condition tab.
 */
class Conditions extends Tab
{
    /**
     * Field Prefix Constant
     */
    const FIELD_PREFIX = '#conditions__1__';

    /**
     * Set the mapping and fill the form.
     *
     * @param array $fields
     * @param SimpleElement|null $element
     * @return $this
     *
     * @SuppressWarnings(PHPMD.UnusedLocalVariable)
     */
    public function fillFormTab(array $fields, SimpleElement $element = null)
    {
        foreach ($fields as $key => $value) {
            $this->mapping[$key] = self::FIELD_PREFIX . $key;
        }
        return parent::fillFormTab($fields, $element);
    }
}


text:
#include "xcompositeint.h"

XCompositeExtInfo XCompositeExtensionInfo;

const char XCompositeExtensionName[] = COMPOSITE_NAME;

/*
 * XCompositeExtRemoveDisplay - remove the indicated display from the
 * extension object. (Replaces XextRemoveDisplay.)
 */
static int
XCompositeExtRemoveDisplay (XCompositeExtInfo *extinfo, Display *dpy)
{
    XCompositeExtDisplayInfo *info, *prev;

    /*
     * locate this display and its back link so that it can be removed
     */
    _XLockMutex(_Xglobal_lock);
    prev = NULL;
    for (info = extinfo->head; info; info = info->next) {
	if (info->display == dpy) break;
	prev = info;
    }
    if (!info) {
	_XUnlockMutex(_Xglobal_lock);
	return 0;		/* hmm, actually an error */
    }

    /*
     * remove the display from the list; handles going to zero
     */
    if (prev)
	prev->next = info->next;
    else
	extinfo->head = info->next;

    extinfo->ndisplays--;
    if (info == extinfo->cur) extinfo->cur = NULL;  /* flush cache */
    _XUnlockMutex(_Xglobal_lock);

    Xfree ((char *) info);
    return 1;
}

static int
XCompositeCloseDisplay (Display *dpy, XExtCodes *codes)
{
    return XCompositeExtRemoveDisplay (&XCompositeExtensionInfo, dpy);
}

/*
 * XCompositeExtAddDisplay - add a display to this extension. (Replaces
 * XextAddDisplay)
 */
static XCompositeExtDisplayInfo *
XCompositeExtAddDisplay (XCompositeExtInfo	*extinfo,
			 Display		*dpy,
			 const char		*ext_name)
{
    XCompositeExtDisplayInfo    *info;
    int			    ev;

    info = (XCompositeExtDisplayInfo *) Xmalloc (sizeof (XCompositeExtDisplayInfo));
    if (!info) return NULL;
    info->display = dpy;

    info->codes = XInitExtension (dpy, ext_name);

    /*
     * if the server has the extension, then we can initialize the
     * appropriate function vectors
     */
    if (info->codes) {
	xCompositeQueryVersionReply	rep;
	xCompositeQueryVersionReq	*req;
        XESetCloseDisplay (dpy, info->codes->extension,
                           XCompositeCloseDisplay);
	/*
	 * Get the version info
	 */
	LockDisplay (dpy);
	GetReq (CompositeQueryVersion, req);
	req->reqType = info->codes->major_opcode;
	req->compositeReqType = X_CompositeQueryVersion;
	req->majorVersion = COMPOSITE_MAJOR;
	req->minorVersion = COMPOSITE_MINOR;
	if (!_XReply (dpy, (xReply *) &rep, 0, xTrue))
	{
	    UnlockDisplay (dpy);
	    SyncHandle ();
	    return 0;
	}
	info->major_version = rep.majorVersion;
	info->minor_version = rep.minorVersion;
	UnlockDisplay (dpy);
    } else {
	/* The server doesn't have this extension.
	 * Use a private Xlib-internal extension to hang the close_display
	 * hook on so that the "cache" (extinfo->cur) is properly cleaned.
	 * (XBUG 7955)
	 */
	XExtCodes *codes = XAddExtension(dpy);
	if (!codes) {
	    XFree(info);
	    return NULL;
	}
        XESetCloseDisplay (dpy, codes->extension, XCompositeCloseDisplay);
    }

    /*
     * now, chain it onto the list
     */
    _XLockMutex(_Xglobal_lock);
    info->next = extinfo->head;
    extinfo->head = info;
    extinfo->cur = info;
    extinfo->ndisplays++;
    _XUnlockMutex(_Xglobal_lock);
    return info;
}

/*
 * XCompositeExtFindDisplay - look for a display in this extension; keeps a
 * cache of the most-recently used for efficiency. (Replaces
 * XextFindDisplay.)
 */
static XCompositeExtDisplayInfo *
XCompositeExtFindDisplay (XCompositeExtInfo *extinfo,
		      Display	    *dpy)
{
    XCompositeExtDisplayInfo *info;

    /*
     * see if this was the most recently accessed display
     */
    if ((info = extinfo->cur) && info->display == dpy)
	return info;

    /*
     * look for display in list
     */
    _XLockMutex(_Xglobal_lock);
    for (info = extinfo->head; info; info = info->next) {
	if (info->display == dpy) {
	    extinfo->cur = info;     /* cache most recently used */
	    _XUnlockMutex(_Xglobal_lock);
	    return info;
	}
    }
    _XUnlockMutex(_Xglobal_lock);

    return NULL;
}

XCompositeExtDisplayInfo *
XCompositeFindDisplay (Display *dpy)
{
    XCompositeExtDisplayInfo *info;

    info = XCompositeExtFindDisplay (&XCompositeExtensionInfo, dpy);
    if (!info)
	info = XCompositeExtAddDisplay (&XCompositeExtensionInfo, dpy,
				    XCompositeExtensionName);
    return info;
}

Bool
XCompositeQueryExtension (Display *dpy, int *event_basep, int *error_basep)
{
    XCompositeExtDisplayInfo *info = XCompositeFindDisplay (dpy);

    if (XCompositeHasExtension(info))
    {
	*event_basep = info->codes->first_event;
	*error_basep = info->codes->first_error;
	return True;
    }
    else
	return False;
}

Status
XCompositeQueryVersion (Display *dpy,
		    int	    *major_versionp,
		    int	    *minor_versionp)
{
    XCompositeExtDisplayInfo	*info = XCompositeFindDisplay (dpy);

    XCompositeCheckExtension (dpy, info, 0);
    *major_versionp = info->major_version;
    *minor_versionp = info->minor_version;
    UnlockDisplay (dpy);
    SyncHandle ();
    return 1;
}

int
XCompositeVersion (void)
{
    return XCOMPOSITE_VERSION;
}

void
XCompositeRedirectWindow (Display *dpy, Window window, int update)
{
    XCompositeExtDisplayInfo	    *info = XCompositeFindDisplay (dpy);
    xCompositeRedirectWindowReq	    *req;

    XCompositeSimpleCheckExtension (dpy, info);
    LockDisplay (dpy);
    GetReq (CompositeRedirectWindow, req);
    req->reqType = info->codes->major_opcode;
    req->compositeReqType = X_CompositeRedirectWindow;
    req->window = window;
    req->update = update;
    UnlockDisplay (dpy);
    SyncHandle ();
}

void
XCompositeRedirectSubwindows (Display *dpy, Window window, int update)
{
    XCompositeExtDisplayInfo	    *info = XCompositeFindDisplay (dpy);
    xCompositeRedirectSubwindowsReq *req;

    XCompositeSimpleCheckExtension (dpy, info);
    LockDisplay (dpy);
    GetReq (CompositeRedirectSubwindows, req);
    req->reqType = info->codes->major_opcode;
    req->compositeReqType = X_CompositeRedirectSubwindows;
    req->window = window;
    req->update = update;
    UnlockDisplay (dpy);
    SyncHandle ();
}

void
XCompositeUnredirectWindow (Display *dpy, Window window, int update)
{
    XCompositeExtDisplayInfo	    *info = XCompositeFindDisplay (dpy);
    xCompositeUnredirectWindowReq   *req;

    XCompositeSimpleCheckExtension (dpy, info);
    LockDisplay (dpy);
    GetReq (CompositeUnredirectWindow, req);
    req->reqType = info->codes->major_opcode;
    req->compositeReqType = X_CompositeUnredirectWindow;
    req->window = window;
    req->update = update;
    UnlockDisplay (dpy);
    SyncHandle ();
}

void
XCompositeUnredirectSubwindows (Display *dpy, Window window, int update)
{
    XCompositeExtDisplayInfo		*info = XCompositeFindDisplay (dpy);
    xCompositeUnredirectSubwindowsReq	*req;

    XCompositeSimpleCheckExtension (dpy, info);
    LockDisplay (dpy);
    GetReq (CompositeUnredirectSubwindows, req);
    req->reqType = info->codes->major_opcode;
    req->compositeReqType = X_CompositeUnredirectSubwindows;
    req->window = window;
    req->update = update;
    UnlockDisplay (dpy);
    SyncHandle ();
}

XserverRegion
XCompositeCreateRegionFromBorderClip (Display *dpy, Window window)
{
    XCompositeExtDisplayInfo		    *info = XCompositeFindDisplay (dpy);
    xCompositeCreateRegionFromBorderClipReq *req;
    XserverRegion			    region;

    XCompositeCheckExtension (dpy, info, 0);
    LockDisplay (dpy);
    GetReq (CompositeCreateRegionFromBorderClip, req);
    req->reqType = info->codes->major_opcode;
    req->compositeReqType = X_CompositeCreateRegionFromBorderClip;
    req->window = window;
    region = req->region = XAllocID (dpy);
    UnlockDisplay (dpy);
    SyncHandle ();
    return region;
}

Pixmap
XCompositeNameWindowPixmap (Display *dpy, Window window)
{
    XCompositeExtDisplayInfo	    *info = XCompositeFindDisplay (dpy);
    xCompositeNameWindowPixmapReq   *req;
    Pixmap			    pixmap;

    XCompositeCheckExtension (dpy, info, 0);
    LockDisplay (dpy);
    GetReq (CompositeNameWindowPixmap, req);
    req->reqType = info->codes->major_opcode;
    req->compositeReqType = X_CompositeNameWindowPixmap;
    req->window = window;
    pixmap = req->pixmap = XAllocID (dpy);
    UnlockDisplay (dpy);
    SyncHandle ();
    return pixmap;
}


text:
% function [miss, false_alarm]=groundtruth(ground_file, sky_file, time_range)
%
% ground_file and sky_file are voc list text files.  each row is a
% vocalization, the four tab-delimited columns are the start and stop times
% and low and high frequencies
%
% time_range is 2-element array specifing the subset of the files to
% consider in seconds.  use [] for the whole file.
%
% miss.area, miss.freq, and miss.time are vectors indicating the fraction
% of the area, frequency, and time of each manually annotated
% vocalizations' bounding box that is overlapped by automatically annotated
% vocalizations, and miss.num is the number of the latter which overlap the
% former (splits).
%
% false_alarm.area, false_alarm.freq, and false_alarm.time are vectors
% indicating the fraction of the area, frequency, and time of each
% automatically annotated vocalization's bounding box that is overlapped by
% manually annotated vocalizations, and false_alarm.num is the number of
% the latter which overlap the former (lumps).
%
% the area calculations depend on the mapping toolbox, and are set to nan
% if it is not available
%
% e.g.
% [miss, false_alarm] = groundtruth(...
% '/groups/egnor/egnorlab/ben/groundtruth/kelly_vs_meghan/m53606_m50733_urine_together_20121218_KellyAxGT20140311.voc',...
% '/groups/egnor/egnorlab/ben/groundtruth/kelly_vs_meghan/m53606_m50733_urine_together_20121218_MeganAxGT20140311.voc',...
% [90 105]);

function [miss, false_alarm]=groundtruth(ground_file, sky_file, time_range)

plot_flag=true;

ground_box=load(ground_file);  % a .txt file from e.g. Tempo
sky_box=load(sky_file);  % a .txt file from e.g. Ax

if(~isempty(time_range))
  idx=find((ground_box(:,1)>time_range(1)) & (ground_box(:,1)<time_range(2)) & (ground_box(:,2)>time_range(1)) & (ground_box(:,2)<time_range(2)));
  ground_box=ground_box(idx,:);
  if ~isempty(sky_box)
    idx=find((sky_box(:,1)>time_range(1)) & (sky_box(:,1)<time_range(2)) & (sky_box(:,2)>time_range(1)) & (sky_box(:,2)<time_range(2)));
    sky_box=sky_box(idx,:);
  end
end

if(plot_flag)
  figure;
  subplot(4,1,1);  hold on;
end
miss=groundtruth_guts(ground_box, sky_box, 1, plot_flag);
false_alarm=groundtruth_guts(sky_box, ground_box, 3, plot_flag);

if(plot_flag)
  plot_guts(3, miss.area, miss.num, 'area', 1)
  plot_guts(4, false_alarm.area, false_alarm.num, 'area', 2)
  plot_guts(5, miss.freq, miss.num, 'freq', 1)
  plot_guts(6, false_alarm.freq, false_alarm.num, 'freq', 2)
  plot_guts(7, miss.time, miss.num, 'time', 1)
  plot_guts(8, false_alarm.time, false_alarm.num, 'time', 2)
end

function plot_guts(idx, data, n, txt, type)

if type==1
  txt = {'% misses, ', '% splits', ['miss ' txt ' score']};
else
  txt = {'% false alarms, ', '% lumps', ['false alarm ' txt ' score']};
end

subplot(4,2,idx);
[n,x]=hist(data,50);
bar(x,n,'barwidth',1,'facecolor','k');
num=sum(data>0.5);  den=length(data);
title([num2str(num) '/' num2str(den) '=' num2str(num/den*100,3) txt{1} ...
    num2str(sum(n>1)/den*100,3) txt{2}]);
xlabel(txt{3});
ylabel('# vocs');
axis tight;

function [x,y]=bbox2polygon(bbox)

x=[bbox(1) bbox(1) bbox(2) bbox(2) bbox(1)];
y=[bbox(3) bbox(4) bbox(4) bbox(3) bbox(3)];

function overlap = groundtruth_guts(this, that, color, plot_flag)

overlap.area=nan(size(this,1),1);
overlap.freq=nan(size(this,1),1);
overlap.time=nan(size(this,1),1);
overlap.num=zeros(size(this,1),1);
overlap.size=(this(:,2)-this(:,1)).*(this(:,4)-this(:,3));  % in Hz-sec
for idx_this=1:size(this,1)
  [x0,y0]=bbox2polygon(this(idx_this,:));
  x0p=x0;  y0p=y0;
  freqB=[]; freqT=[];
  timeL=[]; timeR=[];
  for idx_that=1:size(that,1)
    if ((this(idx_this,2)<that(idx_that,1)) || (this(idx_this,1)>that(idx_that,2)) || ...
        (this(idx_this,4)<that(idx_that,3)) || (this(idx_this,3)>that(idx_that,4)))  continue;  end
    try
      [x,y]=bbox2polygon(that(idx_that,:));
      [x0p,y0p]=polybool('subtraction',x0p,y0p,x,y);
    end
    [freqB freqT]=MergeBrackets([freqB that(idx_that,3)],[freqT that(idx_that,4)]);
    [timeL timeR]=MergeBrackets([timeL that(idx_that,1)],[timeR that(idx_that,2)]);
    overlap.num(idx_this) = overlap.num(idx_this) + 1;
  end
  try
    [x0p,y0p]=polysplit(x0p,y0p);
    overlap.area(idx_this) = sum(cellfun(@(x,y) (ispolycw(x,y)*2-1)*polyarea(x,y), x0p,y0p)) / ...
        polyarea(x0,y0);
  end
  [l r]=RangeIntersection(freqB,freqT,min(y0),max(y0));
  overlap.freq(idx_this) = ((max(y0)-min(y0)) - sum(r-l)) / (max(y0)-min(y0));
  [l r]=RangeIntersection(timeL,timeR,min(x0),max(x0));
  overlap.time(idx_this) = ((max(x0)-min(x0)) - sum(r-l)) / (max(x0)-min(x0));
  if(plot_flag)
    c=[0 0 0];
    if ~isnan(overlap.area(idx_this))
      c(color)=max(0,overlap.area(idx_this));
    else
      c(color)=max(0,overlap.freq(idx_this).*overlap.time(idx_this));
    end
    line(this(idx_this,[1 2 2 1 1]),this(idx_this,[3 3 4 4 3]),'color',c,'linewidth',2);
  end
end


text:
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var OuterSubscriber_1 = require('../OuterSubscriber');
var subscribeToResult_1 = require('../util/subscribeToResult');
/**
 * Returns a new Observable by applying a function that you supply to each item emitted by the source Observable that
 * returns an Observable, and then emitting the items emitted by the most recently emitted of these Observables.
 *
 * <img src="./img/switchMap.png" width="100%">
 *
 * @param {Observable} a function that, when applied to an item emitted by the source Observable, returns an Observable.
 * @returns {Observable} an Observable that emits the items emitted by the Observable returned from applying func to
 * the most recently emitted item emitted by the source Observable.
 */
function switchMap(project, resultSelector) {
    return this.lift(new SwitchMapOperator(project, resultSelector));
}
exports.switchMap = switchMap;
var SwitchMapOperator = (function () {
    function SwitchMapOperator(project, resultSelector) {
        this.project = project;
        this.resultSelector = resultSelector;
    }
    SwitchMapOperator.prototype.call = function (subscriber) {
        return new SwitchMapSubscriber(subscriber, this.project, this.resultSelector);
    };
    return SwitchMapOperator;
}());
var SwitchMapSubscriber = (function (_super) {
    __extends(SwitchMapSubscriber, _super);
    function SwitchMapSubscriber(destination, project, resultSelector) {
        _super.call(this, destination);
        this.project = project;
        this.resultSelector = resultSelector;
        this.index = 0;
    }
    SwitchMapSubscriber.prototype._next = function (value) {
        var result;
        var index = this.index++;
        try {
            result = this.project(value, index);
        }
        catch (error) {
            this.destination.error(error);
            return;
        }
        this._innerSub(result, value, index);
    };
    SwitchMapSubscriber.prototype._innerSub = function (result, value, index) {
        var innerSubscription = this.innerSubscription;
        if (innerSubscription) {
            innerSubscription.unsubscribe();
        }
        this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, result, value, index));
    };
    SwitchMapSubscriber.prototype._complete = function () {
        var innerSubscription = this.innerSubscription;
        if (!innerSubscription || innerSubscription.isUnsubscribed) {
            _super.prototype._complete.call(this);
        }
    };
    SwitchMapSubscriber.prototype._unsubscribe = function () {
        this.innerSubscription = null;
    };
    SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) {
        this.remove(innerSub);
        this.innerSubscription = null;
        if (this.isStopped) {
            _super.prototype._complete.call(this);
        }
    };
    SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        if (this.resultSelector) {
            this._tryNotifyNext(outerValue, innerValue, outerIndex, innerIndex);
        }
        else {
            this.destination.next(innerValue);
        }
    };
    SwitchMapSubscriber.prototype._tryNotifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
        var result;
        try {
            result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
        }
        catch (err) {
            this.destination.error(err);
            return;
        }
        this.destination.next(result);
    };
    return SwitchMapSubscriber;
}(OuterSubscriber_1.OuterSubscriber));
//# sourceMappingURL=switchMap.js.map


text:
module Abstract.Impl.Libs.Counter.MVar.Dec (
 module Abstract.Interfaces.Counter.Dec,
 mkCounter'MVar'Dec
) where

import Abstract.Interfaces.Counter.Dec
import qualified Abstract.Impl.Libs.Counter.MVar.Internal as MVAR (mkCounter'MVar)

mkCounter'MVar'Dec t = do
 v <- MVAR.mkCounter'MVar t
 return $ counterToDec v


text:
package com.rodrigodev.xgen4j_table_generator;

import com.rodrigodev.xgen4j_table_generator.TableGenerator.InjectedFields;
import com.rodrigodev.xgen4j_table_generator.service.ServiceModule;
import dagger.Module;
import dagger.Provides;

/**
 * Created by Rodrigo Quesada on 27/06/15.
 */
@Module(includes = ServiceModule.class)
public class MainModule {

    @Provides
    public TableGenerator provideExceptionsGenerator(InjectedFields injectedFields) {
        return new TableGenerator(injectedFields);
    }
}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes       #-}
module Web.ServerSpec where

import           Data.Aeson          (Object, decode, encode)
import           Data.ByteString.Lazy
import           Data.Maybe
import           Test.Hspec
import           Test.Hspec.Wai
import           Test.Hspec.Wai.JSON
import           Text.RawString.QQ
import           Web.Server

eventData :: ByteString
eventData = encode . fromJust $ (decode rawJson :: Maybe Object)
      where rawJson = [r|
        {
          "series": [{
        		"metric": "bosh.healthmonitor.system.cpu.user",
        		"points": [
        			[1456458457, 0.2]
        		],
        		"type": "gauge",
        		"host": null,
        		"device": null,
        		"tags": ["job:worker_cpi", "index:10", "deployment:project", "agent:8440617 f - d298 - 4 fa1 - 8 f94 - 1177 bcf513d7"]
        	}]
        }
      |]

spec :: Spec
spec = with app $
  describe "POST /metrics" $ do
    it "responds with 201" $
      post "/metrics" eventData `shouldRespondWith` 201

    it "responds with metric json" $ do
      _ <- post "/metrics" eventData
      get "/monitoring" `shouldRespondWith` [json|{time: 1456458457, metric:{name: "cpu", value: 0.2}}|]


text:
<?php

require_once(__DIR__ . '/../GitHubObject.php');

class GitHubFeedsLinksCurrentUserPublic extends GitHubObject
{
	/* (non-PHPdoc)
	 * @see GitHubObject::getAttributes()
	 */
	protected function getAttributes()
	{
		return array_merge(parent::getAttributes(), array(
			'href' => 'string',
			'type' => 'string',
		));
	}

	/**
	 * @var string
	 */
	protected $href;

	/**
	 * @var string
	 */
	protected $type;

	/**
	 * @return string
	 */
	public function getHref()
	{
		return $this->href;
	}

	/**
	 * @return string
	 */
	public function getType()
	{
		return $this->type;
	}

}


text:
    /** Output for "-verbose" option.
     *  @param key The key to look up the correct internationalized string.
     *  @param arg An argument for substitution into the output string.
     */
    private void printVerbose(String key, CharSequence arg) {
        Log.printLines(log.noticeWriter, Log.getLocalizedString("verbose." + key, arg));
    }

    /** Output for "-checkclassfile" option.
     *  @param key The key to look up the correct internationalized string.
     *  @param arg An argument for substitution into the output string.
     */
    private void printCCF(String key, Object arg) {
        Log.printLines(log.noticeWriter, Log.getLocalizedString(key, arg));
    }


text:
module Intercom
  module Traits
    module IncrementableAttributes

      def increment(key, value=1)
        existing_value = self.custom_attributes[key]
        existing_value ||= 0
        self.custom_attributes[key] = existing_value + value
      end
    end
  end
end