text:
(function(){
	"use strict";

	KC3StrategyTabs.fleet = new KC3StrategyTab("fleet");

	KC3StrategyTabs.fleet.definition = {
		tabSelf: KC3StrategyTabs.fleet,
		horizontal: false,

		currentFleetsObj: null,
		suggestedName: "",

		/*
		  "fleets" object format:
		  * an array of "fleet" objects
		  * length is exactly 4, falsy value for non-existing fleet (null is recommended)

		  "fleet" object format:
		  { ships: <an array of "ship" objects>
		  ( length is exactly 6, falsy value for non-existing ship (null is recommended) )
		  , name: <fleet name> (optional)
		  }

		  "ship" object format:
		  { id: <ship master id>
		  , level: <ship level>
		  , morale: <ship morale> (optional)
		  , luck: <ship luck> (optional)
		  , ...<other useful stats> (optional)
		  , mod: <ship modernization> (optional)
		  , equipments: <array of equipments, length = 5 (4+1), falsy for non-existing>
		  }

		  "equipment" object format:
		  { id: <equipment master id>
		  , ace: <aircraft proficiency> (optional) (-1 if "ace" is not applicable)
		  , improve: <improvement level> (optional)
		  }

		 */

		fleetsObjToDeckBuilder: function(fleetsObj, isImgBuilder = false) {
			var self = this;
			var dBuilder = {
				version: 4,
				hqlv: PlayerManager.hq.level
			};
			if(isImgBuilder) {
				dBuilder.theme = ConfigManager.sr_theme;
				if(["kr", "jp", "en", "scn", "tcn"].includes(ConfigManager.language)) {
					dBuilder.lang = ConfigManager.language;
				}
			}

			fleetsObj
				.map( self.createKCFleetObject )
				.map( function(x,i) {
					dBuilder["f" + (i+1)] = x.deckbuilder();
				});
			return dBuilder;
		},

		/* INIT
		   Prepares static data needed
		   ---------------------------------*/
		init :function(){
			// ensure localStorage has the part we need.
			if (typeof localStorage.savedFleets === "undefined") {
				localStorage.savedFleets = JSON.stringify( {} );
			}
		},

		/* RELOAD
		Prepares latest fleets data
		---------------------------------*/
		reload :function(){
			// Latest user config (for eLoS & FPow)
			ConfigManager.load();
			// Latest data for current fleet (ships & gears)
			KC3ShipManager.load();
			KC3GearManager.load();
			PlayerManager.loadFleets();
		},

		/* EXECUTE
		   Places data onto the interface
		   ---------------------------------*/
		execute :function(){
			const self = this;

			$(".ship_tooltip .stat_icon img").each((_, img) => {
				$(img).attr("src", KC3Meta.statIcon($(img).parent().data("stat")));
			});

			$("input#hist_query").on("keydown", function(e) {
				if (e.which === 13) {
					$("button#control_view").click();
					e.preventDefault();
				}
			});

			this.setupUIByViewType( "current" );
			$('input[type=radio][name=view_type]').change(function() {
				self.setupUIByViewType( this.value );
			});

			$("button#control_view").on("click", function() {
				var viewType = $("input[type=radio][name=view_type]:checked").val();
				self.executeView(viewType);
			});

			$("button#control_save").on("click", function() {
				var name = prompt("Input a name",self.suggestedName);
				if (!name) return;
				name = $.trim(name);
				var confirmFlg = true;
				if (self.ifFleetsObjExists(name)) {
					confirmFlg = confirm("Overwrite record with name '" + name + "'?");
				}

				if (confirmFlg) {
					self.saveFleetsObj(name);
					self.refreshSavedFleets();
				}
			});

			$("button#control_saved_rename").on("click", function() {
				var oldName = $("#saved_fleet_sel option:selected").val();
				if (!oldName) return;

				var newName = prompt("Renaming '" + oldName + "' to:");
				newName = $.trim(newName);
				if (!newName) return;
				if (oldName === newName) return;

				var confirmFlg = true;
				if (self.ifFleetsObjExists(newName)) {
					confirmFlg = confirm("Overwrite record with name '" + newName + "'?");
				}

				if (confirmFlg) {
					self.renameFleetsObj(oldName,newName);
					self.refreshSavedFleets();
				}
			});

			$("button#control_saved_delete").on("click", function() {
				var name = $("#saved_fleet_sel option:selected").val();
				if (!name) return;
				var confirmFlg = confirm("Confirm Deleting Record '" + name + "'?");
				if (confirmFlg) {
					self.deleteFleetsObj(name);
					self.refreshSavedFleets();
				}
			});

			$("button#control_export_dbuilder").on("click", function() {
				var converted = self.fleetsObjToDeckBuilder( self.currentFleetsObj );
				console.log( "JSON to be exported", JSON.stringify( converted ) );
				window.open("http://www.kancolle-calc.net/deckbuilder.html?predeck="+
							encodeURI( JSON.stringify( converted )));
			});

			$("button#control_export_imgkcbuilder").on("click", function() {
				var converted = self.fleetsObjToDeckBuilder( self.currentFleetsObj, true );
				console.log( "JSON to be exported", JSON.stringify( converted ) );
				window.open("https://www.nishikuma.net/ImgKCbuilder/?predeck="+
							encodeURI( JSON.stringify( converted )));
			});

			const updateHorizontal = () => {
				if(this.horizontal) {
					$(".fleet_ships").addClass("horizontal");
					$(".fleet_ship").addClass("horizontal");
				} else {
					$(".horizontal").removeClass("horizontal");
				}
			};
			$("button#control_switch_view").on("click", function() {
				self.horizontal = !self.horizontal;
				updateHorizontal();
			});
			updateHorizontal();

			this.refreshSavedFleets();
			if(!!KC3StrategyTabs.pageParams[1]){
				this.executeView(KC3StrategyTabs.pageParams[1], KC3StrategyTabs.pageParams[2] || false);
			}else{
				this.executeView("current");
			}
		},

		ifFleetsObjExists: function(name) {
			name = $.trim(name);
			var savedFleets = JSON.parse( localStorage.savedFleets );
			return !! savedFleets[name];
		},

		renameFleetsObj: function(oldName, newName) {
			newName = $.trim(newName);
			var savedFleets = JSON.parse( localStorage.savedFleets );
			var tmp = savedFleets[oldName];
			delete savedFleets[oldName];
			savedFleets[newName] = tmp;
			localStorage.savedFleets = JSON.stringify( savedFleets );
		},

		deleteFleetsObj: function(name) {
			name = $.trim(name);
			var savedFleets = JSON.parse( localStorage.savedFleets );
			delete savedFleets[name];
			localStorage.savedFleets = JSON.stringify( savedFleets );
		},

		saveFleetsObj: function(name) {
			name = $.trim(name);
			if (name === "") {
				$(".fleet_error_msg").text("empty name").show();
				return;
			}
			if (!this.currentFleetsObj) {
				$(".fleet_error_msg").text("cannot find info of current viewing fleets").show();
				return;
			}

			var savedFleets = JSON.parse( localStorage.savedFleets );
			savedFleets[name] = this.currentFleetsObj;
			localStorage.savedFleets = JSON.stringify( savedFleets );
		},

		refreshSavedFleets: function() {
			var savedFleets = JSON.parse( localStorage.savedFleets );
			var keys = Object.keys( savedFleets );
			keys.sort();
			var selectBox = $("#saved_fleet_sel");
			selectBox.empty();

			$.each( keys, function(_,key) {
				selectBox.append( $("<option></option>")
					.attr("value", key)
					.text(key) );
			});
		},

		executeView: function(viewType, viewName) {
			$(".fleet_error_msg").text("").hide();
			if (viewType === "current") {
				this.showCurrentFleets();
			} else if (viewType === "saved") {
				if (viewName !== undefined) {
					if(!$("#saved").prop("checked")) {
						$("#saved").trigger("click");
					}
					$("#saved_fleet_sel").prop("selectedIndex", viewName || 0);
				}
				var name = $("#saved_fleet_sel option:selected").val();
				if (name) {
					this.showSavedFleets(name);
				}
			} else if (viewType === "history") {
				if (viewName !== undefined) {
					if (!$("#history").prop("checked")) {
						$("#history").trigger("click");
					}
					$("input#hist_query").val(viewName);
				}
				var q = $("input#hist_query").val();
				var sortieId = parseInt(q,10);
				if (!sortieId) {
					$(".fleet_error_msg").text("Invalid sortie id: " + q).show();
					return;
				}
				this.showFleetFromSortieId(sortieId);
			} else {
				console.warn("Unknown view type:", viewType);
				this.showCurrentFleets();
			}
		},

		setupUIByViewType: function(viewType) {
			$("select.control_input").prop("disabled", viewType !== "saved");
			$("input#hist_query").prop("disabled", viewType !== "history");
			$("button#control_save").prop("disabled", viewType === "saved");

			$("button#control_saved_rename").prop("disabled", viewType !== "saved");
			$("button#control_saved_delete").prop("disabled", viewType !== "saved");
		},

		showCurrentFleets: function() {
			this.showAllKCFleets( this.loadCurrentFleets() );
			$("#fleet_description").text("Current Fleets");
			this.currentFleetsObj = this.getCurrentFleetsObj();
			this.suggestedName = "Fleets (" + new Date().format("yyyy-mm-dd HH:MM:ss") + ")";
		},

		showSavedFleets: function(name) {
			name = $.trim(name);
			var savedFleets = JSON.parse( localStorage.savedFleets );
			var fleetsObj = savedFleets[name];
			var self = this;

			if (!fleetsObj) {
				$(".fleet_error_msg").text("No record of '" + name + "'").show();
				return;
			}

			var kcFleets = fleetsObj.map( function( fleetObj ) {
				return self.createKCFleetObject(fleetObj);
			});

			self.showAllKCFleets( kcFleets );
			$("#fleet_description").text("Saved Fleets '" + name + "'");
			this.currentFleetsObj = fleetsObj;
			this.suggestedName = name;
		},

		showFleetFromSortieId: function(sortieId) {
			var self = this;
			KC3Database.get_sortie(sortieId, function(sortieData) {
				if (! sortieData) {
					$(".fleet_error_msg")
						.text("Cannot find data with sortie Id " + sortieId)
						.show();
					return;
				}
				var fleetsObj = [];

				function convertShip(shipData) {
					if (!shipData || shipData.mst_id <= 0) return null;
					var shipObj = {};
					var masterData = KC3Master.ship(shipData.mst_id);
					var slotnum = masterData.api_slot_num;
					shipObj.id = shipData.mst_id;
					shipObj.level = shipData.level;
					shipObj.morale = shipData.morale;
					shipObj.mod = shipData.kyouka;
					shipObj.stats = shipData.stats;
					shipObj.equipments = [];

					$.each( shipData.equip, function(i,gearId) {
						if (gearId <= 0) {
							shipObj.equipments.push(null);
							return;
						}
						shipObj.equipments.push( {id: gearId,
							improve: shipData.stars && shipData.stars[i] > 0 ? shipData.stars[i] : 0,
							ace: shipData.ace ? shipData.ace[i] || 0 : 0
						} );
					});
					while (shipObj.equipments.length < Math.max(slotnum + 1, 5))
						shipObj.equipments.push(null);

					return shipObj;
				}

				function convertFleet(fleetData, fleetNum) {
					var fleetObj = {};
					fleetObj.name = "Fleet #" + fleetNum;
					fleetObj.ships = [];
					$.each(fleetData, function(ind, ship) {
						fleetObj.ships.push(convertShip( ship ));
					});
					return fleetObj;
				}

				fleetsObj.push(convertFleet( sortieData.fleet1, 1));
				fleetsObj.push(convertFleet( sortieData.fleet2, 2));
				fleetsObj.push(convertFleet( sortieData.fleet3, 3));
				fleetsObj.push(convertFleet( sortieData.fleet4, 4));

				var kcFleets = fleetsObj.map( function( fleetObj ) {
					return self.createKCFleetObject(fleetObj);
				});
				self.currentFleetsObj = fleetsObj;
				self.suggestedName = "Sortie #" + sortieId;
				self.showAllKCFleets( kcFleets );
				$("#fleet_description").text("Sortie #" + sortieId + " Fleets");
			});
		},

		showAllKCFleets: function(kcFleetArray) {
			var self = this;
			// Empty fleet list
			$(".tab_fleet .fleet_list").hide().html("");
			$.each(kcFleetArray, function(ind, kcFleet) {
				self.showKCFleet( kcFleet, ind + 1 );
			});
			// Show with duration and check if ship name overflow
			$(".tab_fleet .fleet_list").createChildrenTooltips().show(100, () => {
				$(".tab_fleet .fleet_list .ship_name").each(function() {
					if(KC3StrategyTabs.isTextEllipsis(this))
						$(this).attr("title", $(this).text());
				});
			});
		},

		/* Show single fleet
		   --------------------------------------------*/
		showKCFleet: function(kcFleet, fleetNum) {
			if (!kcFleet.active) return;
			const self = this;

			// Create fleet box
			const fleetBox = $(".tab_fleet .factory .fleet_box").clone()
				.appendTo(".tab_fleet .fleet_list");
			fleetBox.attr("data-fleet", fleetNum);
			$(".fleet_name", fleetBox).text( kcFleet.name );

			let maxSlots = 0;
			$.each( kcFleet.ship(), function(ind, kcShip) {
				self.showKCShip(fleetBox, kcShip, (ind + 1));
				maxSlots = Math.max(maxSlots, kcShip.equipmentMaxCount(true));
			});
			$(".fleet_ships", fleetBox).addClass(`max_slot${maxSlots}`);
			if(maxSlots > 6) $(".fleet_ships", fleetBox).addClass("max_slot6");

			// Show fleet info
			const fstats = kcFleet.totalStats(true, false, true);
			const fstatsImp = kcFleet.totalStats(true, "exped", true);
			$(".detail_level .detail_value", fleetBox).text( kcFleet.totalLevel() )
				.attr("title", "{0}: -\u2605\t+\u2605\n{1}: {6}\t{11}\n{2}: {7}\t{12}\n{3}: {8}\t{13}\n{4}: {9}\t{14}\n{5}: {10}\t{15}".format(
					KC3Meta.term("ExpedTotalImp"),
					KC3Meta.term("ExpedTotalFp"),
					KC3Meta.term("ExpedTotalTorp"),
					KC3Meta.term("ExpedTotalAa"),
					KC3Meta.term("ExpedTotalAsw"),
					KC3Meta.term("ExpedTotalLos"),
					fstats.fp, fstats.tp, fstats.aa, fstats.as, fstats.ls,
					Math.qckInt("floor", fstatsImp.fp , 1),
					Math.qckInt("floor", fstatsImp.tp , 1),
					Math.qckInt("floor", fstatsImp.aa , 1),
					Math.qckInt("floor", fstatsImp.as , 1),
					Math.qckInt("floor", fstatsImp.ls , 1)
				));
			$(".detail_los .detail_icon img", fleetBox).attr("src", "/assets/img/stats/los"+ConfigManager.elosFormula+".png" );
			$(".detail_los .detail_value", fleetBox).text( Math.qckInt("floor", kcFleet.eLoS(), 1) );
			if(ConfigManager.elosFormula > 1) {
				const f33CnHq4 = Array.numbers(1, 5).map(cn =>
					Math.qckInt("floor", kcFleet.eLos4(cn), 1).toLocaleString(undefined, KC3Meta.formatDecimalOptions(1, false)
				));
				const f33CnHq3 = Array.numbers(1, 5).map(cn =>
					Math.qckInt("floor", kcFleet.eLos4(cn, 0.35), 1).toLocaleString(undefined, KC3Meta.formatDecimalOptions(1, false)
				));
				const airReconnScore = Math.qckInt("floor", kcFleet.airReconnScore(), 1)
					.toLocaleString(undefined, KC3Meta.formatDecimalOptions(1, false));
				const airReconnResult = kcFleet.estimateAirReconnResult();
				$(".detail_los .detail_value", fleetBox).attr("title",
					"HLv: x0.4\tx0.35\nCn1: {0}\t{5}\nCn2: {1}\t{6}\nCn3: {2}\t{7}\nCn4: {3}\t{8}\nCn5: {4}\t{9}".format(f33CnHq4.concat(f33CnHq3))
					+ "\nW6-3: {0}".format(airReconnScore)
					+ (airReconnScore > 0 ? "\n G: {0}\n H: {1}".format(airReconnResult.W63G.result, airReconnResult.W63H.result) : "")
				);
			} else {
				$(".detail_los .detail_value").attr("title", "");
			}
			$(".detail_air .detail_value", fleetBox).text( kcFleet.fighterPowerText() )
				.attr("title", KC3Calc.buildFleetsAirstrikePowerText(kcFleet)
					+ KC3Calc.buildFleetsContactChanceText(kcFleet));
			$(".detail_antiair .detail_value", fleetBox).text( kcFleet.adjustedAntiAir(ConfigManager.aaFormation) )
				.attr("title", "{0}: {3}\n{1}: {4}\n{2}: {5}".format(
						KC3Meta.formationText(1), KC3Meta.formationText(2), KC3Meta.formationText(3),
						kcFleet.adjustedAntiAir(1), kcFleet.adjustedAntiAir(2), kcFleet.adjustedAntiAir(3)
					)
				);
			$(".detail_speed .detail_value", fleetBox).text( kcFleet.speed() );
			$(".detail_support .detail_value", fleetBox).text( kcFleet.supportPower() );
			$(".ss_button", fleetBox).on("click", function(e) {
				const thisButton = $(this);
				const thisFleetBox = thisButton.parent(), fleetBoxNative = thisFleetBox.get(0);
				if(fleetBoxNative.scrollIntoViewIfNeeded)
					fleetBoxNative.scrollIntoViewIfNeeded();
				else if(fleetBoxNative.scrollIntoView)
					fleetBoxNative.scrollIntoView();
				thisButton.hide("fast", "linear", self.captureFleetBox.bind(self, thisFleetBox));
			});
		},

		/**
		 * Save fleet box screenshot
		 */
		captureFleetBox: function(fleetBox) {
			const fleetNum = $(fleetBox).data("fleet") || 1;
			const coords = {
				x: $(fleetBox).offset().left,
				y: $(fleetBox).offset().top,
				w: $(fleetBox).width(),
				h: $(fleetBox).height(),
				t: $(document).scrollTop(),
			};
			const dpr = window.devicePixelRatio || 1;
			chrome.tabs.getZoom(undefined, scale => {
				if(scale !== 1 || dpr !== 1) Object.keys(coords).forEach(p => { coords[p] *= scale * dpr; });
				chrome.tabs.captureVisibleTab(undefined, {format: "png"}, (dataUrl) => {
					if(chrome.runtime.lastError) {
						console.log("Failed to screenshot fleet", chrome.runtime.lastError);
						const errMsg = chrome.runtime.lastError.message || "";
						if(errMsg.includes("'activeTab' permission")) {
							alert("Click KC3\u6539 icon on browser toolbar to grant screenshot permission");
						} else {
							alert("Failed to capture fleet screenshot");
						}
						$(".ss_button", fleetBox).show();
						return;
					}
					const canvas = document.createElement("canvas"), img = new Image();
					img.onload = (e) => {
						canvas.width = coords.w;
						canvas.height = coords.h;
						const ctx = canvas.getContext("2d");
						ctx.imageSmoothingEnabled = false;
						ctx.drawImage(img,
							coords.x, coords.y - coords.t, coords.w, coords.h,
							0, 0, coords.w, coords.h);
						new KC3ImageExport(canvas, {
							filename: "{0} #{1} ({2})".format(
								$("#fleet_description").text(),
								fleetNum, dateFormat("yyyy-mm-dd HHMM")
							),
						}).export((error, result) => {
							if(error) {
								console.error("Failed to screenshot fleet", error);
								alert("Failed to generate fleet screenshot");
							} else if(result && result.filename) {
								alert("Saved to {0}".format(result.filename));
							}
							$(".ss_button", fleetBox).show();
						});
					};
					img.src = dataUrl;
				});
			});
		},

		/* Show single ship
		   --------------------------------------------*/
		showKCShip: function(fleetBox, kcShip, index) {
			if (!kcShip || !kcShip.masterId) return;

			var self = this;
			var shipDb = WhoCallsTheFleetDb.getShipStat(kcShip.masterId);
			var shipMst = kcShip.master();
			var shipBox = $(".tab_fleet .factory .fleet_ship").clone();
			$(".fleet_ships", fleetBox).append( shipBox );

			$(".ship_type", shipBox).text( kcShip.stype() );
			$(".ship_pic img", shipBox).attr("src", kcShip.shipIcon() );
			// TODO Link to ship list instead of ship library
			$(".ship_pic img", shipBox).attr("alt", kcShip.masterId );
			$(".ship_pic img", shipBox).click(function(){
				KC3StrategyTabs.gotoTab("mstship", $(this).attr("alt"));
			});
			$(".ship_lv_val", shipBox).text( kcShip.level );
			$(".ship_lk_val", shipBox).text( kcShip.lk[0] );
			$(".ship_luck", shipBox).toggle(kcShip.lk[0] !== undefined);
			$(".ship_cond_icon img", shipBox).attr("src",
				"/assets/img/client/morale/" + kcShip.moraleIcon() + ".png"
			);
			$(".ship_cond_val", shipBox).text( kcShip.morale );
			$(".ship_morale", shipBox).toggle(kcShip.morale !== undefined);
			$(".ship_index", shipBox).text( index );
			var nameBox = $(".ship_name", shipBox);
			nameBox.text( kcShip.name() ).lazyInitTooltip();

			// Only available for current fleet as no ship attribute omitted
			var viewType = $("input[type=radio][name=view_type]:checked").val();
			if(viewType === "current"){
				// Show a rich text tool-tip like stats in game
				const tooltipBox = kcShip.htmlTooltip($(".ship_tooltip", shipBox));
				$(".ship_hover", shipBox).tooltip({
					position: { my: "left top", at: "right+10 top" },
					items: "div",
					content: tooltipBox.prop("outerHTML"),
					open: KC3Ship.onShipTooltipOpen,
				});
			}

			$(".ship_gear > div", shipBox).hide();
			kcShip.equipment(true).forEach((gear, index) => {
				self.showKCGear(
					$(".ship_gear_"+(index+1), shipBox),
					gear,
					kcShip.slots[index],
					kcShip,
					index
				);
			});
		},

		/* Show single equipment
		   --------------------------------------------*/
		showKCGear: function(gearBox, kcGear, capacity, kcShip, index) {
			if (!kcGear.masterId || !kcShip.masterId) {
				gearBox.hide();
				return;
			}
			const masterData = kcGear.master();
			// to avoid red slot size 1 when Large Flying Boat equipped
			const slotMaxSize = masterData.api_type[2] === 41 ? 1 : kcShip.master().api_maxeq[index];
			const isExslot = index >= kcShip.slotnum;
			// ex-slot capacity not implemented yet, no aircraft equippable
			$(".slot_capacity", gearBox).text(isExslot ? "-" : capacity)
				.removeClass("empty taiha chuuha shouha unused")
				.addClass((percent => {
					switch(true){
						case !slotMaxSize: return "";
						case percent <= 0.00: return "empty";
						case percent <= 0.25: return "taiha";
						case percent <= 0.50: return "chuuha";
						case percent <= 0.75: return "shouha";
						default: return "";
					}
				})(capacity / (slotMaxSize || 1)));
			if(isExslot || KC3GearManager.carrierBasedAircraftType3Ids.indexOf(masterData.api_type[3]) < 0){
				$(".slot_capacity", gearBox).addClass("unused");
			}
			$(".gear_icon img", gearBox).attr("src", KC3Meta.itemIcon(masterData.api_type[3]))
				.error(function() { $(this).unbind("error").attr("src", "/assets/img/ui/empty.png"); })
				.attr("alt", masterData.api_id)
				.click(function(){
					KC3StrategyTabs.gotoTab("mstgear", $(this).attr("alt"));
				});
			$(".gear_name", gearBox).text(kcGear.name()).attr("title",
				kcGear.htmlTooltip(capacity, kcShip)).lazyInitTooltip();
			if(kcGear.stars > 0){
				$(".gear_stars", gearBox).text(
					"\u2605{0}".format(kcGear.stars >= 10 ? "m" : kcGear.stars)
				);
			} else {
				$(".gear_stars", gearBox).hide();
			}
			if(kcGear.ace > 0){
				$(".gear_ace img", gearBox).attr("src",
					"/assets/img/client/achev/" + Math.min(kcGear.ace, 7) + ".png"
				);
			} else {
				$(".gear_ace", gearBox).hide();
			}
			gearBox.toggleClass("ex_slot", isExslot).show();
		},

		createKCFleetObject: function(fleetObj) {
			var fleet = new KC3Fleet();
			if(!fleetObj) return fleet;
			fleet.name = fleetObj.name;
			fleet.ships = [ -1, -1, -1, -1, -1, -1 ];
			if (!fleetObj) return;
			fleet.active = true;
			var shipObjArr = [];

			// simulate ShipManager
			fleet.ShipManager = {
				get: function(ind) {
					return shipObjArr[ind-1] || new KC3Ship();
				}
			};

			// fill in instance of Ships
			$.each( fleetObj.ships, function(ind, shipObj) {
				if (!shipObj) return;
				var ship = new KC3Ship();
				shipObjArr.push( ship );
				fleet.ships[ind] = shipObjArr.length;

				var equipmentObjectArr = [];
				var masterData = KC3Master.ship( shipObj.id );
				var slotnum = masterData.api_slot_num;
				ship.rosterId = shipObj.rid || fleet.ships[ind];
				ship.masterId = shipObj.id;
				ship.level = shipObj.level;
				ship.morale = shipObj.morale;

				ship.items = [-1,-1,-1,-1,-1];
				ship.slots = masterData.api_maxeq;
				ship.ex_item = 0;
				ship.slotnum = slotnum;
				ship.GearManager = {
					get: function(ind) {
						return equipmentObjectArr[ind-1] || new KC3Gear();
					}
				};

				$.each( shipObj.equipments, function(ind,equipment) {
					if (!equipment) return;
					var gear = new KC3Gear();
					equipmentObjectArr.push( gear );
					if(ind >= 4 && ind >= ship.slotnum) {
						ship.ex_item = equipmentObjectArr.length;
						gear.itemId = ship.ex_item;
					} else {
						ship.items[ind] = equipmentObjectArr.length;
						gear.itemId = ship.items[ind];
					}
					gear.masterId = equipment.id;
					gear.stars = Number(equipment.improve) || 0;
					gear.ace = Number(equipment.ace) || 0;
				});

				// estimate ship's stats from known facts as possible as we can
				var mod = shipObj.mod || [];
				var noMasterStats = shipObj.stats || {};
				ship.hp[0] = ship.hp[1] = ship.maxHp() + (mod[5] || 0);

				// read saved values first, then fall back to calculate master + mod + equip total
				ship.fp[0] = shipObj.fp || (masterData.api_houg[0] + (mod[0] || 0) + ship.equipmentTotalStats("houg"));
				ship.tp[0] = shipObj.tp || (masterData.api_raig[0] + (mod[1] || 0) + ship.equipmentTotalStats("raig"));
				ship.aa[0] = shipObj.aa || (masterData.api_tyku[0] + (mod[2] || 0) + ship.equipmentTotalStats("tyku"));
				ship.ar[0] = shipObj.ar || (masterData.api_souk[0] + (mod[3] || 0) + ship.equipmentTotalStats("souk"));
				ship.lk[0] = shipObj.luck || (masterData.api_luck[0] + (mod[4] || 0));

				// no value in master data, fall back to calculated naked + equip total
				ship.ls[0] = shipObj.ls || ((noMasterStats.ls || ship.estimateNakedLoS()) + ship.equipmentTotalLoS());
				ship.ev[0] = shipObj.ev || ((noMasterStats.ev || ship.estimateNakedEvasion()) + ship.equipmentTotalStats("houk"));
				ship.as[0] = shipObj.as || ((noMasterStats.as || ship.estimateNakedAsw()) + ship.equipmentTotalStats("tais") + (mod[6] || 0));

				// just fall back to master data, to avoid recompute ship speed by updating a table about speed up ship classes
				ship.speed = shipObj.sp || noMasterStats.sp || masterData.api_soku;
			});

			return fleet;
		},

		loadCurrentFleets: function() {
			PlayerManager.loadFleets();
			return [0,1,2,3].map( function(ind) {
				return PlayerManager.fleets[ind];
			});
		},

		getCurrentFleetsObj: function() {
			var fleetsObj = [];

			function convertEquipmentsOf(ship) {
				var equipments = ship.equipment(true);

				function convertEquipment(e) {
					if (e.masterId === 0)
						return null;
					return {
						id: e.masterId,
						ace: e.ace,
						improve: e.stars
					};
				}
				return equipments.map( convertEquipment );
			}

			function convertFleet(fleet) {
				if (!fleet || !fleet.active) return null;
				var fleetObjShips = [];
				$.each( fleet.ship(), function(ind, ship) {
					if (ship.masterId === 0) {
						fleetObjShips.push( null );
						return;
					}
					var shipObj = {
						id: ship.masterId,
						rid: ship.rosterId,
						level: ship.level,
						morale: ship.morale,
						luck: ship.lk[0],
						ls: ship.ls[0],
						as: ship.as[0],
						fp: ship.fp[0],
						tp: ship.tp[0],
						sp: ship.speed,
						mod: ship.mod,
						equipments: convertEquipmentsOf(ship)
					};
					fleetObjShips.push( shipObj );
				});
				var fleetObj = {
					name: fleet.name,
					ships: fleetObjShips
				};
				return fleetObj;
			}

			PlayerManager.loadFleets();
			$.each([0,1,2,3], function(_,ind) {
				fleetsObj.push(convertFleet( PlayerManager.fleets[ind] ));
			});

			return fleetsObj;
		}
	};

})();


text:
namespace gcm {

namespace {

const char kRequestContentType[] = "application/octet-stream";
const char kGCMChannelTag[] = "gcm_channel";
const int kDefaultPollIntervalSeconds = 60 * 60;  // 60 minutes.
const int kMinPollIntervalSeconds = 30 * 60;  // 30 minutes.

}  // namespace

GCMChannelStatusRequest::GCMChannelStatusRequest(
    const scoped_refptr<net::URLRequestContextGetter>& request_context_getter,
    const std::string& channel_status_request_url,
    const std::string& user_agent,
    const GCMChannelStatusRequestCallback& callback)
    : request_context_getter_(request_context_getter),
      channel_status_request_url_(channel_status_request_url),
      user_agent_(user_agent),
      callback_(callback),
      backoff_entry_(&(GetGCMBackoffPolicy())),
      weak_ptr_factory_(this) {
}

GCMChannelStatusRequest::~GCMChannelStatusRequest() {
}

// static
int GCMChannelStatusRequest::default_poll_interval_seconds() {
  return kDefaultPollIntervalSeconds;
}

// static
int GCMChannelStatusRequest::min_poll_interval_seconds() {
  return kMinPollIntervalSeconds;
}

void GCMChannelStatusRequest::Start() {
  DCHECK(!url_fetcher_.get());

  GURL request_url(channel_status_request_url_);

  sync_pb::ExperimentStatusRequest proto_data;
  proto_data.add_experiment_name(kGCMChannelTag);
  std::string upload_data;
  if (!proto_data.SerializeToString(&upload_data)) {
     NOTREACHED();
  }

  url_fetcher_ =
      net::URLFetcher::Create(request_url, net::URLFetcher::POST, this);
  url_fetcher_->SetRequestContext(request_context_getter_.get());
  url_fetcher_->AddExtraRequestHeader("User-Agent: " + user_agent_);
  url_fetcher_->SetUploadData(kRequestContentType, upload_data);
  url_fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
                             net::LOAD_DO_NOT_SAVE_COOKIES);
  url_fetcher_->Start();
}

void GCMChannelStatusRequest::OnURLFetchComplete(
    const net::URLFetcher* source) {
  if (ParseResponse(source))
    return;

  RetryWithBackoff(true);
}

bool GCMChannelStatusRequest::ParseResponse(const net::URLFetcher* source) {
  if (!source->GetStatus().is_success()) {
    LOG(ERROR) << "GCM channel request failed.";
    return false;
  }

  if (source->GetResponseCode() != net::HTTP_OK) {
    LOG(ERROR) << "GCM channel request failed. HTTP status: "
               << source->GetResponseCode();
    return false;
  }

  std::string response_string;
  if (!source->GetResponseAsString(&response_string)) {
    LOG(ERROR) << "GCM channel response failed to be retrieved.";
    return false;
  }

  // Empty response means to keep the existing values.
  if (response_string.empty()) {
    callback_.Run(false, false, 0);
    return true;
  }

  sync_pb::ExperimentStatusResponse response_proto;
  if (!response_proto.ParseFromString(response_string)) {
    LOG(ERROR) << "GCM channel response failed to be parsed as proto.";
    return false;
  }

  bool enabled = true;
  if (response_proto.experiment_size() == 1 &&
      response_proto.experiment(0).has_gcm_channel() &&
      response_proto.experiment(0).gcm_channel().has_enabled()) {
    enabled = response_proto.experiment(0).gcm_channel().enabled();
  }

  int poll_interval_seconds;
  if (response_proto.has_poll_interval_seconds())
    poll_interval_seconds = response_proto.poll_interval_seconds();
  else
    poll_interval_seconds = kDefaultPollIntervalSeconds;
  if (poll_interval_seconds < kMinPollIntervalSeconds)
    poll_interval_seconds = kMinPollIntervalSeconds;

  callback_.Run(true, enabled, poll_interval_seconds);

  return true;
}

void GCMChannelStatusRequest::RetryWithBackoff(bool update_backoff) {
  if (update_backoff) {
    url_fetcher_.reset();
    backoff_entry_.InformOfRequest(false);
  }

  if (backoff_entry_.ShouldRejectRequest()) {
    DVLOG(1) << "Delaying GCM channel request for "
             << backoff_entry_.GetTimeUntilRelease().InMilliseconds()
             << " ms.";
    base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
        FROM_HERE, base::Bind(&GCMChannelStatusRequest::RetryWithBackoff,
                              weak_ptr_factory_.GetWeakPtr(), false),
        backoff_entry_.GetTimeUntilRelease());
    return;
  }

  Start();
}

}  // namespace gcm

redpajama_set_name: RedPajamaGithub


text:
``` bash
% fab node:example/filer/ setup
```


text:
def importName(modulename, name):
    """ Import a named object from a module in the context of this function,
        which means you should use fully qualified module paths.

        Return None on failure.
    """
    try:
        module = __import__(modulename, globals(), locals(), [name])
    except ImportError:
        return None

    return vars(module)[name]

### MyApp/extensions/spam.py
class Handler:
    def handleSomething(self):
        print "spam!"

### MyApp/extensions/eggs.py
class Handler:
    def handleSomething(self):
        print "eggs!"

### Example
extension_name = "spam" # could be "eggs", too!
Handler = importName("MyApp.extensions." + extension_name, "Handler")
handler = Handler()
handler.handleSomething()


text:
layout: post
title: Prolonger la validité de vos clés PGP
---

Une bonne pratique pour la gestion de vos clés PGP est de créer une clé principale sans date d'expiration et de la
conserver hors ligne stockée de manière sécurisée (clé USB chiffrée par exemple).
Pour une utilisation quotidienne des sous-clés sont créées, chacune ayant une seule finalité (signature, chiffrement ou
authentification).
Ces clés ont elles une date d'expiration relativement courte (6 mois ou 1 an), ce qui réduit les risques en cas de
perte et "force" à remanipuler un peu GPG, qui n'est pas vraiment facile d'accès.

Il faut donc penser régulièrement à prolonger la validité des sous-clés.
Une autre possibilité serait de générer de nouvelles sous-clés, c'est un peu plus sécurisé car cela permet de rendre
impossible l'exploitation d'anciens messages avec ces nouvelles clés mais cela oblige également à chiffrer à nouveau en
utilisant la nouvelle sous-clé de chiffrement.

## Installation de Tails

La première étape est d'installer la distribution [Tails] sur une clé USB. Cela permet de faire toutes les opérations
sur un système plutôt sûr.
En fonction de votre modèle de menace vous pouvez bien sûr décider d'utiliser votre système habituel.

Une fois [Tails] installé, démarrez sur la clé USB et pensez à activer le mode root afin de pouvoir installer les
paquets nécessaires :

    sudo apt update && sudo apt install gnupg2 gnupg-agent \
        cryptsetup scdaemon pcscd yubikey-personalization \
        dirmngr secure-delete

Vous pouvez vous déconnecter du réseau lorsque l'installation des paquets supplémentaires est terminée afin de
manipuler vos clés PGP hors ligne.

## Import des clés

Afin de manipuler vos clés il faut les réimporter dans GnuPG.

Pour cela branchez votre clé USB chiffrée contenant la sauvegarde de votre clé principale et montez la :

    sudo cryptsetup open /dev/sdc1 usb
    sudo mkdir -p /mnt/encrypted-usb
    sudo mount /dev/mapper/usb /mnt/encrypted-usb

Créez un répertoire afin de stocker les données de GnuPG :

    export GNUPGHOME=$(mktemp -d)
    cd $GNUPGHOME

Importez vos clés et récupérez la configuration de GnuPG :

    gpg --import /mnt/encrypted-usb/<tmp.XXX>/mastersub.key
    cp -v /mnt/encrypted-usb/<tmp.XXX>/ $GNUPGHOME

Editez votre clé :

    export KEYID=0x<ID>
    gpg --edit-key --expert $KEYID

Pour chacune des sous-clés (signature, chiffrement et authentification) utilisez la commande `expire` afin de prolonger
la date de validité :

    key 1
    expire
    1y
    # Déselectionnez la clé précédemment sélectionnée, la commande expire ne fonctionne que sur une clé à la fois
    key 1
    key 2
    expire
    ...
    # Sauvegardez les modifications effectuées
    save

Exportez la clé principale et les sous-clés et sauvegardez les sur la clé USB chiffrée :

    gpg --armor --export-secret-keys $KEYID >$GNUPGHOME/mastersub.key
    gpg --armor --export-secret-subkeys $KEYID >$GNUPGHOME/sub.key
    sudo cp -avi $GNUPGHOME /mnt/encrypted-usb

Vous pouvez éventuellement supprimer sur la clé USB chiffrée l'ancien répertoire `tmp.XXX` qui contient la sauvegarde
précédente :

    sudo rm -rf /mnt/encrypted-usb/<tmp.XXX>

Démontez la clé USB :

    sudo umount /mnt/encrypted-usb
    sudo cryptsetup close usb

Exportez la clé publique :

    sudo mkdir /mnt/public
    sudo mount /dev/sdb2 /mnt/public
    gpg --armor --export $KEYID | sudo tee /mnt/public/$KEYID-$(date +%F).txt
    sudo umount /mnt/public

Il ne reste plus qu'à transférer les nouvelles sous-clés sur votre clé YubiKey si vous en utilisez une :

    gpg --edit-key --expert $KEYID
    key 1
    keytocard
    key 1
    key 2
    keytocard
    ...
    save

Vous pouvez enfin redémarrer et stockez en lieu sûr votre clé USB chiffrée pour la ressortir l'année prochaine.

---
[Tails]: https://tails.boum.org/


text:
package com.pivotal.gemfirexd.internal.impl.store.access.btree.index;

import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.services.sanity.SanityManager;
import com.pivotal.gemfirexd.internal.iapi.store.access.ConglomerateController;
import com.pivotal.gemfirexd.internal.iapi.store.access.TransactionController;
import com.pivotal.gemfirexd.internal.iapi.store.access.conglomerate.TransactionManager;
import com.pivotal.gemfirexd.internal.iapi.store.raw.FetchDescriptor;
import com.pivotal.gemfirexd.internal.iapi.store.raw.LockingPolicy;
import com.pivotal.gemfirexd.internal.iapi.store.raw.RecordHandle;
import com.pivotal.gemfirexd.internal.iapi.store.raw.Transaction;
import com.pivotal.gemfirexd.internal.iapi.types.DataValueDescriptor;
import com.pivotal.gemfirexd.internal.iapi.types.RowLocation;
import com.pivotal.gemfirexd.internal.impl.store.access.btree.BTree;
import com.pivotal.gemfirexd.internal.impl.store.access.btree.BTreeLockingPolicy;
import com.pivotal.gemfirexd.internal.impl.store.access.btree.BTreeRowPosition;
import com.pivotal.gemfirexd.internal.impl.store.access.btree.ControlRow;
import com.pivotal.gemfirexd.internal.impl.store.access.btree.LeafControlRow;
import com.pivotal.gemfirexd.internal.impl.store.access.btree.OpenBTree;
import com.pivotal.gemfirexd.internal.impl.store.access.btree.WaitError;

/**

Implements the jdbc serializable isolation level using row locks.

Holds read and write locks until end of transaction.
Obtains previous key locks to protect from phantom reads.

**/
class B2IRowLocking3 implements BTreeLockingPolicy
{

    /**************************************************************************
     * Private/Protected fields of This class:
     **************************************************************************
     */

    /**
     * The container id of the base container for this index.  Used to build
     * record handles to make lock calls on.
     **/
    protected ConglomerateController        base_cc;

    /**
     * The OpenBtree to use if we have to lock anything in the btree vs.
     * base row locking.
     **/
    protected OpenBTree                     open_btree;

    /**
     * The locking policy to use to get and release the scan locks.  We could
     * cache this somewhere better.
     **/
    private LockingPolicy                   scan_locking_policy;

    /**
     * The transaction to associate lock requests with.
     **/
    private Transaction                     rawtran;

    /**************************************************************************
     * Constructors for This class:
     **************************************************************************
     */
    B2IRowLocking3(
    Transaction             rawtran,
    int                     lock_level,
    LockingPolicy           locking_policy,
    ConglomerateController  base_cc,
    OpenBTree               open_btree)
    {
        this.rawtran             = rawtran;
        this.base_cc             = base_cc;
        this.open_btree          = open_btree;
        this.scan_locking_policy =
            rawtran.newLockingPolicy(
                LockingPolicy.MODE_RECORD,
                TransactionController.ISOLATION_READ_COMMITTED, true);
    }

    /**************************************************************************
     * Private methods of This class:
     **************************************************************************
     */

    private boolean _lockScan(
    RecordHandle    rh,
    boolean         forUpdate,
    boolean         wait)
		throws StandardException
    {
        boolean ret_val = true;

        // only get the scan lock if we are record locking.

        if (!forUpdate)
        {
            ret_val =
                scan_locking_policy.lockRecordForRead(
                    rawtran, open_btree.getContainerHandle(),
                    rh, wait, false);
        }
        else
        {
            ret_val =
                scan_locking_policy.lockRecordForWrite(
                    rawtran, rh, false, wait);
        }

        return(ret_val);
    }

    /**
     * Lock key previous to first key in btree.
     *

     * In the previous key locking protocol repeatable read and phantom
     * protection is guaranteed by locking a range of keys in the btree.
     * The range is defined by the key previous to the first key you look
     * at and all subsequent keys you look at.  The first key in the index
     * is a special case, as there are no keys previous to it.  In that
     * case a special key is declared the "previous key" to the first key
     * in the btree and is locked instead.
     *

     * In this implementation that first key is defined to be in the base
     * container, page ContainerHandle.FIRST_PAGE_NUMBER, record id
     * PREVIOUS_KEY_HANDLE.
     *

     * Note that the previous key is the same for all indexes on a given
     * conglomerate.  It seemed better for all locks on a base table to have
     * the same containerid, rather than having some locks generated from
     * a btree have a containerid from base table and some having a containerid
     * from the btree.  If this turns out to be a problem we could either
     * have 2 different containerid's, be more creative with the record id, or
     * even add more to the lock key.
     *
     * @param aux_leaf          If non-null, this leaf is unlatched if the
     *                          routine has to wait on the lock.
     * @param lock_operation    Whether to lock exclusive or share.
     * @param lock_duration     For what duration should the lock be held,
     *                          if INSTANT_DURATION, then the routine will
     *                          guarantee that lock was acquired while holding
     *                          the latch, but then immediately release the
     *                          lock.  If COMMIT_DURATION or MANUAL_DURATION
     *                          then the lock be held when routine returns
     *                          successfully.
     *
	 * @exception  StandardException  Standard exception policy.
     **/
    private boolean lockPreviousToFirstKey(
    LeafControlRow          current_leaf,
    LeafControlRow          aux_leaf,
    int                     lock_operation,
    int                     lock_duration)
		throws StandardException
    {
        // This is first row in table, lock the special key that
        // represents the key previous to the first key of the table.

        // First try to get the lock NOWAIT, while latch is held.
        boolean ret_status =
            base_cc.lockRow(
                BTree.ROOTPAGEID,
                RecordHandle.PREVIOUS_KEY_HANDLE,
                lock_operation,
                false /* NOWAIT */,
                lock_duration);

        if (!ret_status)
        {
            current_leaf.release();
            current_leaf = null;

            if (aux_leaf != null)
            {
                aux_leaf.release();
                aux_leaf = null;
            }

            // Couldn't get the lock NOWAIT, release latch and wait for lock.
            base_cc.lockRow(
                BTree.ROOTPAGEID,
                RecordHandle.PREVIOUS_KEY_HANDLE,
                lock_operation,
                true /* WAIT */,
                lock_duration);
        }

        return(ret_status);
    }

    /**
     * Lock a btree row (row is at given slot in page).
     *

     * Lock the row at the given slot in the page.  Meant to be used if caller
     * only has the slot on the page to be locked, and has not read the row
     * yet.  This routine fetches the row location field from the page, and then
     * locks that rowlocation in the base container.
     *

     * Lock a btree row, enforcing the standard lock/latch protocol.
     * On return the row is locked.  Return status indicates if the lock
     * was waited for, which will mean a latch was dropped while waiting.
     * In general a false status means that the caller will either have
     * to research the tree unless some protocol has been implemented that
     * insures that the row will not have moved while the latch was dropped.
     *

     * This routine request a row lock NOWAIT on the in-memory row
     * "current_row.".  If the lock is granted the routine will return true.
     * If the lock cannot be granted NOWAIT, then the routine will release
     * the latch on "current_leaf" and "aux_leaf" (if aux_leaf is non-null),
     * and then it will request a WAIT lock on the row.
     *

     *
     * @param btree             The conglomerate we are locking.
     * @param current_leaf      Latched current leaf where "current" key is.
     * @param aux_leaf          If non-null, this leaf is unlatched if the
     *                          routine has to wait on the lock.
     * @param current_slot      Slot of row to lock.
     * @param lock_fetch_desc   Descriptor for fetching just the RowLocation,
     *                          used for locking.
     * @param check_changed_rowloc
     *                          whether to check for the changed rowloc or not.
     * @param lock_operation    Whether lock is for key prev to insert or not.
     * @param lock_duration     For what duration should the lock be held,
     *                          if INSTANT_DURATION, then the routine will
     *                          guarantee that lock was acquired while holding
     *                          the latch, but then immediately release the
     *                          lock.  If COMMIT_DURATION or MANUAL_DURATION
     *                          then the lock be held when routine returns
     *                          successfully.
     *
	 * @exception  StandardException  Standard exception policy.
     **/
    private boolean lockRowOnPage(
    BTree                   btree,
    LeafControlRow          current_leaf,
    LeafControlRow          aux_leaf,
    int                     current_slot,
    boolean                 check_changed_rowloc,
    FetchDescriptor         lock_fetch_desc,
    DataValueDescriptor[]   lock_template,
    RowLocation             lock_row_loc,
    int                     lock_operation,
    int                     lock_duration)
		throws StandardException
    {
        if (SanityManager.DEBUG)
        {
            SanityManager.ASSERT(current_leaf != null);

            if (current_slot <= 0 ||
                current_slot >= current_leaf.getPage().recordCount())
            {
                SanityManager.THROWASSERT(
                    "current_slot = " + current_slot +
                    "; current_leaf.getPage().recordCount() = " +
                        current_leaf.getPage().recordCount());
            }

            if (!(btree instanceof B2I))
            {
                SanityManager.THROWASSERT(
                    "btree not instance of B2I, it is " +
                    btree.getClass().getName());
            }

            SanityManager.ASSERT(lock_template != null, "template is null");

            // For now the RowLocation is expected to be the object located in
            // the last column of the lock_template, this may change if we
            // ever support rows with RowLocations somewhere else.
            SanityManager.ASSERT(
                lock_row_loc == lock_template[lock_template.length - 1],
                "row_loc is not the object in last column of lock_template.");
        }

        // Fetch the row location to lock.
        RecordHandle rec_handle =
            current_leaf.getPage().fetchFromSlot(
                (RecordHandle) null, current_slot,
                lock_template, lock_fetch_desc, true);

        // First try to get the lock NOWAIT, while latch is held.
        boolean ret_status =
            base_cc.lockRow(
                lock_row_loc,
                lock_operation,
                false /* NOWAIT */, lock_duration);

        if (!ret_status)
        {
            // Could not get the lock NOWAIT, release latch and wait for lock.

            if (current_leaf != null)
            {
                current_leaf.release();
                current_leaf = null;
            }
            if (aux_leaf != null)
            {
                aux_leaf.release();
                aux_leaf = null;
            }

            base_cc.lockRow(
                lock_row_loc,
                lock_operation,
                true /* WAIT */, lock_duration);
        }

        return(ret_status);
    }

    /**
     * move left in btree and lock previous key.
     *

     * Enter routine with "current_leaf" latched.  This routine implements
     * the left travel ladder locking protocol to search the leaf pages from
     * right to left for the previous key to 1st key on current_leaf.
     *
     * There are 2 cases:
     * 1) the previous page has keys, in which case the last key on that
     *    page is locked, other wise search continues on the next page to
     *    the left.
     * 2) there are no keys on the current page and there is no page to the
     *    left.  In this case the special "leftmost key" lock is gotten by
     *    calling lockPreviousToFirstKey().
     *
     * Left laddar locking is used if all latches can be obtained immediately
     * with NOWAIT.  This means that current latch is held while asking for
     * left latch NOWAIT, and if left latch is granted then subsequently
     * current latch can be released.  If this protocol is followed and
     * all latches are granted then caller is guaranteed that the correct
     * previous key has been locked and current_page latch remains.  The
     * NOWAIT protocol is used to avoid latch/latch deadlocks.  The overall
     * protocol is that one never holds a latch while waiting on another unless
     * the direction of travel is down and to the right.
     *

     * If along the search a latch has to be waited on then latches are
     * released and a wait is performed, and "false" status is returned to
     * caller.  In this case the routine can no longer be sure of it's current
     * position and may have to retry the whole operation.
     *
     * @return true if previous key found without ever waiting on a latch,
     *         false if latch released in order to wait for other latch.
     *
     * @exception  StandardException  Standard exception policy.
     **/
    private boolean searchLeftAndLockPreviousKey(
    B2I                     b2i,
    LeafControlRow          current_leaf,
    int                     current_slot,
    FetchDescriptor         lock_fetch_desc,
    DataValueDescriptor[]   lock_template,
    RowLocation             lock_row_loc,
    OpenBTree               open_btree,
    int                     lock_operation,
    int                     lock_duration)
		throws StandardException
    {
        boolean         latches_released = false;
        LeafControlRow  prev_leaf;
        LeafControlRow  prev_prev_leaf;

        try
        {
            // Move left in tree, page latch will be requested nowait,
            // and WaitError will be thrown if latch not granted.

            prev_leaf =
                (LeafControlRow) current_leaf.getLeftSibling(open_btree);
        }
        catch (WaitError e)
        {
            // initial latch request on leaf left of current could not be
            // granted NOWAIT.

            long previous_pageno = current_leaf.getleftSiblingPageNumber();

            current_leaf.release();
            current_leaf = null;

            // wait on the left leaf, which we could not be granted NOWAIT.
            prev_leaf = (LeafControlRow)
                ControlRow.get(open_btree, previous_pageno);

            latches_released = true;
        }

        while (true)
        {
            try
            {
                // loop searching left in the btree until you either find
                // a record to lock, or you reach the leftmost empty leaf.

                if (prev_leaf.getPage().recordCount() > 1)
                {

                    // lock the last row on the page, which is the previous
                    // record to the first row on the next page.

                    boolean ret_status =
                        lockRowOnPage(
                            b2i,
                            prev_leaf,
                            current_leaf,
                            prev_leaf.getPage().recordCount() - 1,
                            false,
                            lock_fetch_desc,
                            lock_template,
                            lock_row_loc,
                            lock_operation,
                            lock_duration);

                    if (!ret_status)
                    {
                        // needed to wait on a row lock, so both prev_leaf and
                        // current_leaf latches have been released by
                        // lockRowOnPage()
                        prev_leaf        = null;
                        current_leaf     = null;
                        latches_released = true;
                    }

                    break;
                }
                else if (prev_leaf.isLeftmostLeaf())
                {
                    // Table's first row, lock the key that represents the
                    // key previous to first key of the table.
                    boolean ret_status =
                        lockPreviousToFirstKey(
                            prev_leaf, current_leaf,
                            lock_operation, lock_duration);

                    if (!ret_status)
                    {
                        // needed to wait on a row lock, so both prev_leaf and
                        // current_leaf latches have been released by
                        // lockPreviousToFirstKey()

                        prev_leaf        = null;
                        current_leaf     = null;
                        latches_released = true;
                    }

                    break;
                }

                // Move left in tree, page latch will be requested nowait,
                // and WaitError will be thrown if latch not granted.
                // Release latches on pages between "current_leaf" and
                // where the search leads, so that at most 3 latched pages
                // (current_leaf, prev_leaf, prev_prev_leaf) are held during
                // the search.  Do left ladder locking as you walk left.

                prev_prev_leaf =
                    (LeafControlRow) prev_leaf.getLeftSibling(open_btree);
                prev_leaf.release();
                prev_leaf = prev_prev_leaf;
                prev_prev_leaf = null;

            }
            catch (WaitError e)
            {
                long previous_pageno = prev_leaf.getleftSiblingPageNumber();

                // error going left.  Release current page latch and
                // original page latch continue the search.
                if (current_leaf != null)
                {
                    // current_leaf may have already been released as part of
                    // previous calls, need to check null status.
                    current_leaf.release();
                    current_leaf = null;
                }

                // can only get here by above getLeftSibling() call so prev_leaf
                // should always be valid and latched at this point.  No null
                // check necessary.
                prev_leaf.release();
                prev_leaf = null;

                // wait on the left page, which we could not get before.
                prev_leaf = (LeafControlRow)
                    ControlRow.get(open_btree, previous_pageno);

                latches_released = true;
            }
        }

        if (prev_leaf != null)
            prev_leaf.release();

        return(!latches_released);
    }

    /**************************************************************************
     * Protected methods of This class:
     **************************************************************************
     */

    /**
     * Lock a row as part of doing the scan.
     *

     * Lock the row at the given slot (or the previous row if slot is 0).
     * Get the scan lock on the page if "request_scan_lock" is true.
     *

     * If this routine returns true all locks were acquired while maintaining
     * the latch on leaf.  If this routine returns false, locks may or may
     * not have been acquired, and the routine should be called again after
     * the client has researched the tree to reget the latch on the
     * appropriate page.
     * (p>
     * As a sided effect stores the value of the record handle of the current
     * scan lock.
     *
	 * @return Whether locks were acquired without releasing latch on leaf.
     *
     * @param open_btree        The open_btree to associate latches with -
     *                          used if routine has to scan backward.
     * @param btree             the conglomerate info.
     * @param pos               The position of the row to lock.
     * @param request_row_lock  Whether to request the row lock, should
     *                          only be requested once per page in the scan.
     * @param request_scan_lock Whether to request the page scan lock, should
     *                          only be requested once per page in the scan.
     * @param lock_fetch_desc   The fetch descriptor to use to fetch the
     *                          row location for the lock request.
     * @param lock_template     A scratch area to use to read in rows.
     * @param previous_key_lock Is this a previous key lock call?
     * @param forUpdate         Is the scan for update or for read only.
     *
	 * @exception  StandardException  Standard exception policy.
     **/
    protected boolean _lockScanRow(
    OpenBTree               open_btree,
    BTree                   btree,
    BTreeRowPosition        pos,
    boolean                 request_row_lock,
    boolean                 request_scan_lock,
    FetchDescriptor         lock_fetch_desc,
    DataValueDescriptor[]   lock_template,
    RowLocation             lock_row_loc,
    boolean                 previous_key_lock,
    boolean                 forUpdate,
    int                     lock_operation)
		throws StandardException
    {
        boolean latch_released = false;
        B2I     b2i            = (B2I) btree;

        if (request_row_lock)
        {
            // In order to implement a serialized scan based on previous
            // key locking, this method acquires a row lock on
            // the base table's row from the index row at [startpage/startslot].
            // This will be the 'previous key'.

            if (pos.current_slot == 0)
            {
                // this call will take care of searching left in the btree
                // to find the previous row to lock, 0 is the control row and
                // not a valid thing to lock as a previous key.

                // it is ok to call the non-scan as this is just a special
                // case of a previous key lock call.  The only scan code that
                // will call this routine with slot == 0 will retry if this
                // routine returns that a latch was released.

                latch_released =
                    !lockNonScanPreviousRow(
                        btree,
                        pos.current_leaf,
                        1 /* lock row previous to row at slot 1 */,
                        lock_fetch_desc,
                        lock_template,
                        lock_row_loc,
                        open_btree,
                        lock_operation,
                        TransactionManager.LOCK_COMMIT_DURATION);

                // special test to see if latch release code works
                if (SanityManager.DEBUG)
                {
                    latch_released =
                        OpenBTree.test_errors(
                            open_btree,
                            "B2iRowLocking3_1_lockScanRow",  false,
                            this, pos.current_leaf, latch_released);
                }
            }
            else
            {
                // Just lock the row at "slot"

                latch_released =
                    !lockRowOnPage(
                        btree,
                        pos.current_leaf,
                        (LeafControlRow) null /* no other latch currently */,
                        pos.current_slot,
                        true,
                        lock_fetch_desc,
                        lock_template,
                        lock_row_loc,
                        lock_operation,
                        TransactionManager.LOCK_COMMIT_DURATION);

                // special test to see if latch release code works
                if (SanityManager.DEBUG)
                {
                    latch_released =
                        OpenBTree.test_errors(
                            open_btree,
                            "B2iRowLocking3_2_lockScanRow", false,
                            this, pos.current_leaf, latch_released);
                }
            }
        }

        if (request_scan_lock && !latch_released)
        {
            // Get the scan lock on the start page.

            // Get shared RECORD_ID_PROTECTION_HANDLE lock to make sure that
            // we wait for scans in other transactions to move off of this page
            // before we split.

            latch_released =
                !lockScan(
                    pos.current_leaf,
                    (LeafControlRow) null, // no other latch currently
                    false,
                    ConglomerateController.LOCK_READ);// read scan lock position

            // special test to see if latch release code works
            if (SanityManager.DEBUG)
            {
                /* RESOLVE - need to get a container here */
                latch_released =
                    OpenBTree.test_errors(
                        open_btree,
                        "B2iRowLocking3_3_lockScanRow", true,
                        this, pos.current_leaf, latch_released);
            }
        }

        return(!latch_released);
    }

    /**************************************************************************
     * Public Methods of This class:
     **************************************************************************
     */

    /**************************************************************************
     * Abstract Protected lockScan*() locking methods of BTree:
     *     lockScan                 - lock the scan page
     *     lockScanForReclaimSpace  - lock page for reclaiming deleted rows.
     *     lockScanRow              - lock row and possibly the scan page
     *     unlockScan               - unlock the scan page
     *     unlockScanRecordAfterRead- unlock the scan record
     **************************************************************************
     */

    /**
     * Lock a control row page for scan.
     *

     * Scanners get shared lock on the page while positioned on a row within
     * the page, splitter/purgers/mergers get exclusive lock on the page.
     *
     * See BTree.lockScan() for more info.
     *
	 * @exception  StandardException  Standard exception policy.
     **/
    public boolean lockScan(
    LeafControlRow          current_leaf,
    ControlRow              aux_control_row,
    boolean                 forUpdate,
    int                     lock_operation)
		throws StandardException
    {
        // The scan page lock is implemented as a row lock on the reserved
        // row id on the page (RecordHandle.RECORD_ID_PROTECTION_HANDLE).
        RecordHandle scan_lock_rh =
            current_leaf.getPage().getProtectionRecordHandle();

        // First try to get the lock NOWAIT, while latch is held.
        boolean ret_status =
            _lockScan(scan_lock_rh, forUpdate, false /* NOWAIT */);

        if (!ret_status)
        {
            current_leaf.release();
            current_leaf = null;

            if (aux_control_row != null)
            {
                aux_control_row.release();
                aux_control_row = null;
            }

            // Could not get the lock NOWAIT, release latch and wait
            // for the lock.
            _lockScan(scan_lock_rh, forUpdate, true /* WAIT */);

            // once we get the lock, give it up as we need to get the lock
            // while we have the latch.  When the lock manager gives us the
            // ability to do instantaneous locks do that.  We just wait on the
            // lock to give the split a chance to finish before we interfere.

            if (!forUpdate)
            {
                scan_locking_policy.unlockRecordAfterRead(
                    rawtran, open_btree.getContainerHandle(),
                    scan_lock_rh, false, true);
            }
            else
            {
                // RESOLVE - need instantaneous locks as there is no way
                // currently to release a write lock.  This lock will only
                // be requested by split, and will be released by internal
                // transaction.
            }
        }

        return(ret_status);
    }

    /**
     * Lock a control row page for reclaiming deleted rows.
     *

     * When reclaiming deleted rows during split need to get an exclusive
     * scan lock on the page, which will mean there are no other scans
     * positioned on the page.  If there are other scans positioned, just
     * give up on reclaiming space now.
     *
	 * @return true if lock was granted nowait, else false and not lock was
     *         granted.
     *
	 * @exception  StandardException  Standard exception policy.
     **/
    public boolean lockScanForReclaimSpace(
    LeafControlRow          current_leaf)
		throws StandardException
    {
        // The scan page lock is implemented as a row lock on the reserved
        // row id on the page (RecordHandle.RECORD_ID_PROTECTION_HANDLE).
        RecordHandle scan_lock_rh =
            current_leaf.getPage().getProtectionRecordHandle();

        // First try to get the lock NOWAIT, while latch is held.
        return(
            _lockScan(scan_lock_rh, true /* update */, false /* NOWAIT */));
    }

    /**
     * Lock a btree row to determine if it is a committed deleted row.
     *

     * @see BTreeLockingPolicy#lockScanCommittedDeletedRow
     *
	 * @exception  StandardException  Standard exception policy.
     **/
    public boolean lockScanCommittedDeletedRow(
    OpenBTree               open_btree,
    LeafControlRow          leaf,
    DataValueDescriptor[]   template,
    FetchDescriptor         lock_fetch_desc,
    int                     slot_no)
		throws StandardException
    {
        if (SanityManager.DEBUG)
        {
            SanityManager.ASSERT(leaf != null);

            if (slot_no <= 0 || slot_no >= leaf.getPage().recordCount())
            {
                SanityManager.THROWASSERT(
                    "slot_no = " + slot_no +
                    "; leaf.getPage().recordCount() = " +
                        leaf.getPage().recordCount());
            }

            SanityManager.ASSERT(template != null, "template is null");
        }

        RowLocation row_loc = (RowLocation)
            template[((B2I) open_btree.getConglomerate()).rowLocationColumn];

        // Fetch the row location to lock.
        leaf.getPage().fetchFromSlot(
            (RecordHandle) null, slot_no, template, lock_fetch_desc, true);

        // Request the lock NOWAIT, return status
        return(
            base_cc.lockRow(row_loc,
                ConglomerateController.LOCK_UPD,
                false /* NOWAIT */,
                TransactionManager.LOCK_COMMIT_DURATION));
    }

    /**
     * Lock a row as part of doing the scan.
     *

     * Lock the row at the given slot (or the previous row if slot is 0).
     * Get the scan lock on the page if "request_scan_lock" is true.
     *

     * If this routine returns true all locks were acquired while maintaining
     * the latch on leaf.  If this routine returns false, locks may or may
     * not have been acquired, and the routine should be called again after
     * the client has researched the tree to reget the latch on the
     * appropriate page.
     * (p>
     * As a sided effect stores the value of the record handle of the current
     * scan lock.
     *
	 * @return Whether locks were acquired without releasing latch on leaf.
     *
     * @param open_btree        The open_btree to associate latches with -
     *                          used if routine has to scan backward.
     * @param btree             the conglomerate info.
     * @param pos               The position of the row to lock.
     * @param request_scan_lock Whether to request the page scan lock, should
     *                          only be requested once per page in the scan.
     * @param lock_template     A scratch area to use to read in rows.
     * @param previous_key_lock Is this a previous key lock call?
     * @param forUpdate         Is the scan for update or for read only.
     *
	 * @exception  StandardException  Standard exception policy.
     **/
    public boolean lockScanRow(
    OpenBTree               open_btree,
    BTree                   btree,
    BTreeRowPosition        pos,
    boolean                 request_scan_lock,
    FetchDescriptor         lock_fetch_desc,
    DataValueDescriptor[]   lock_template,
    RowLocation             lock_row_loc,
    boolean                 previous_key_lock,
    boolean                 forUpdate,
    int                     lock_operation)
		throws StandardException
    {
        return(
            _lockScanRow(
                open_btree,
                btree,
                pos,
                true,  // request the row lock (always true for iso 3 )
                request_scan_lock,
                lock_fetch_desc,
                lock_template,
                lock_row_loc,
                previous_key_lock,
                forUpdate,
                lock_operation));
    }

    /**
     * Release read lock on a row.
     *
     * For serializable, there is no work to do.
     *
     *
     **/
    public void unlockScanRecordAfterRead(
    BTreeRowPosition        pos,
    boolean                 forUpdate)
		throws StandardException
    {
        return;
    }

    /**
     * Release the lock gotten by calling lockScan.  This call can only be
     * made to release read scan locks, write scan locks must be held until
     * end of transaction.
     *

     * See BTree.unlockScan() for more info.
     *
     **/
    public void unlockScan(RecordHandle scan_lock_rh)
    {
        // This is first row in table, lock the special key that
        // represents the key previous to the first key of the table.
        try
        {
            scan_locking_policy.unlockRecordAfterRead(
                rawtran, open_btree.getContainerHandle(),
                scan_lock_rh, false, true);
        }
        catch (StandardException se)
        {
			if (SanityManager.DEBUG)
				SanityManager.THROWASSERT(se);
        }

    }

    /**************************************************************************
     * Abstract Protected lockNonScan*() locking methods of BTree:
     *
     *     lockNonScanPreviousRow   - lock the row previous to the current
     *     lockNonScanRow           - lock the input row
     **************************************************************************
     */

    /**
     * Lock the row previous to the input row.
     *

     * See BTreeLockingPolicy.lockNonScanPreviousRow
     *
	 * @exception  StandardException  Standard exception policy.
     **/
    public boolean lockNonScanPreviousRow(
    BTree                   btree,
    LeafControlRow          current_leaf,
    int                     current_slot,
    FetchDescriptor         lock_fetch_desc,
    DataValueDescriptor[]   lock_template,
    RowLocation             lock_row_loc,
    OpenBTree               open_btree,
    int                     lock_operation,
    int                     lock_duration)
		throws StandardException
    {
        boolean          ret_status;

        if (SanityManager.DEBUG)
        {
            SanityManager.ASSERT(btree instanceof B2I);
        }

        if (current_slot > 1)
        {
            // Easy case, just lock the key previous to the current one.

            // Lock (current_slot - 1)

            ret_status =
                lockRowOnPage(
                    btree,
                    current_leaf, (LeafControlRow) null,
                    current_slot - 1,
                    false,
                    lock_fetch_desc,
                    lock_template,
                    lock_row_loc,
                    lock_operation, lock_duration);
        }
        else
        {
            // Should only be called while pointing at a valid location, 0
            // is not a valid key slot - it is the control row.
			if (SanityManager.DEBUG)
				SanityManager.ASSERT(current_slot == 1);

            if (current_leaf.isLeftmostLeaf())
            {
                // This is first row in table, lock the special key that
                // represents the key previous to the first key of the table.
                ret_status =
                    lockPreviousToFirstKey(
                        current_leaf, (LeafControlRow) null,
                        lock_operation, lock_duration);
            }
            else
            {
                // The previous key is on a previous page, search left
                // through the pages to find the key to latch.

                // RESOLVE RLL (mikem) - do I need to do the
                // RECORD_ID_PROTECTION_HANDLE lock.
                // First guarantee that record id's will not move off this
                // current page while searching for previous key, by getting
                // the RECORD_ID_PROTECTION_HANDLE lock on the current page.
                // Since we have a latch on the cur

                // RESOLVE RLL (mikem) - NO RECORD_ID PROTECTION IN EFFECT.
                // caller must research, get new locks if this routine
                // releases latches.
                ret_status = this.searchLeftAndLockPreviousKey(
                    (B2I) btree,
                    current_leaf, current_slot,
                    lock_fetch_desc, lock_template, lock_row_loc,
                    open_btree, lock_operation, lock_duration);
            }
        }

        return(ret_status);
    }

    /**
     * Lock the in memory row.
     *

     * See BTree.lockRow() for more info.
     *
	 * @exception  StandardException  Standard exception policy.
     **/
    public boolean lockNonScanRow(
    BTree                   btree,
    LeafControlRow          current_leaf,
    LeafControlRow          aux_leaf,
    DataValueDescriptor[]   current_row,
    int                     lock_operation)
		throws StandardException
    {
        if (SanityManager.DEBUG)
        {
            SanityManager.ASSERT(btree instanceof B2I);
        }
        B2I b2i = (B2I) btree;

        // First try to get the lock NOWAIT, while latch is held.
        boolean ret_status =
            base_cc.lockRow(
                (RowLocation) current_row[b2i.rowLocationColumn],
                lock_operation,
                false /* NOWAIT */,
                TransactionManager.LOCK_COMMIT_DURATION);

        if (!ret_status)
        {
            // Could not get the lock NOWAIT, release latch and wait for lock.

            if (current_leaf != null)
            {
                current_leaf.release();
                current_leaf = null;
            }
            if (aux_leaf != null)
            {
                aux_leaf.release();
                aux_leaf = null;
            }

            base_cc.lockRow(
                (RowLocation) current_row[b2i.rowLocationColumn],
                lock_operation,
                true /* WAIT */,
                TransactionManager.LOCK_COMMIT_DURATION);
        }

        return(ret_status);
    }

    public boolean lockNonScanRowOnPage(
    BTree                   btree,
    LeafControlRow          current_leaf,
    int                     current_slot,
    FetchDescriptor         lock_fetch_desc,
    DataValueDescriptor[]   lock_template,
    RowLocation             lock_row_loc,
    int                     lock_operation)
		throws StandardException
    {
        return(
            lockRowOnPage(
                btree,
                current_leaf,
                null,
                current_slot,
                false,
                lock_fetch_desc,
                lock_template,
                lock_row_loc,
                lock_operation,
                TransactionManager.LOCK_COMMIT_DURATION));
    }
}


text:
FROM ubuntu:14.04

MAINTAINER  eder.roger.souza@gmail.com

ENV REFRESHED_AT 2015-12-21

RUN apt-get -y update

RUN apt-get install -y libssl1.0.0 libpcre3 --no-install-recommends

RUN apt-get install -y haproxy

RUN apt-get install -y socat

# Define mountable directories.
VOLUME ["/haproxy-override"]

# Add files.
ADD haproxy.cfg /etc/haproxy/haproxy.cfg
ADD start.bash /haproxy-start

RUN sed -i 's/^ENABLED=.*/ENABLED=1/' /etc/default/haproxy

WORKDIR /etc/haproxy

CMD ["bash", "/haproxy-start"]

EXPOSE 80
EXPOSE 443


text:
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

using EventStore.Core.Bus;
using EventStore.Core.Services.Transport.Http.Authentication;
using EventStore.Core.Services.Transport.Http.Messages;

namespace EventStore.Core.Services.Transport.Http
{
    class IncomingHttpRequestAuthenticationManager : IHandle<IncomingHttpRequestMessage>
    {
        private readonly HttpAuthenticationProvider[] _providers;

        public IncomingHttpRequestAuthenticationManager(HttpAuthenticationProvider[] providers)
        {
            _providers = providers;
        }

        public void Handle(IncomingHttpRequestMessage message)
        {
            Authenticate(message);
        }

        private void Authenticate(IncomingHttpRequestMessage message)
        {
            try
            {
                foreach (var provider in _providers)
                {
                    if (provider.Authenticate(message))
                        break;
                }
            }
            catch
            {
                HttpAuthenticationProvider.ReplyUnauthorized(message.Entity);
            }
        }

    }
}


text:
"""
Author: Dr. John T. Hwang <hwangjt@umich.edu>

This package is distributed under New BSD license.
"""

import numpy as np
import unittest
import inspect

from collections import OrderedDict

from smt.problems import Sphere, TensorProduct
from smt.sampling_methods import LHS

from smt.utils.sm_test_case import SMTestCase
from smt.utils.silence import Silence

try:
    from smt.surrogate_models import IDW, RBF, RMTC, RMTB

    compiled_available = True
except:
    compiled_available = False

print_output = False

class Test(SMTestCase):
    def setUp(self):
        ndim = 3
        nt = 500
        ne = 100

        problems = OrderedDict()
        problems["sphere"] = Sphere(ndim=ndim)

        sms = OrderedDict()
        if compiled_available:
            sms["RMTC"] = RMTC(num_elements=6, extrapolate=True)
            sms["RMTB"] = RMTB(order=4, num_ctrl_pts=10, extrapolate=True)

        self.nt = nt
        self.ne = ne
        self.problems = problems
        self.sms = sms

    def run_test(self, sname, extrap_train=False, extrap_predict=False):
        prob = self.problems["sphere"]
        sampling = LHS(xlimits=prob.xlimits)

        np.random.seed(0)
        xt = sampling(self.nt)
        yt = prob(xt)

        sm0 = self.sms[sname]

        sm = sm0.__class__()
        sm.options = sm0.options.clone()
        if sm.options.is_declared("xlimits"):
            sm.options["xlimits"] = prob.xlimits
        sm.options["print_global"] = False

        x = np.zeros((1, xt.shape[1]))
        x[0, :] = prob.xlimits[:, 1] + 1.0
        y = prob(x)

        sm.set_training_values(xt, yt)
        if extrap_train:
            sm.set_training_values(x, y)

        with Silence():
            sm.train()

        if extrap_predict:
            sm.predict_values(x)

    @unittest.skipIf(not compiled_available, "Compiled Fortran libraries not available")
    def test_RMTC(self):
        self.run_test("RMTC", False, False)

    @unittest.skipIf(not compiled_available, "Compiled Fortran libraries not available")
    def test_RMTC_train(self):
        with self.assertRaises(Exception) as context:
            self.run_test("RMTC", True, False)
        self.assertEqual(str(context.exception), "Training points above max for 0")

    @unittest.skipIf(not compiled_available, "Compiled Fortran libraries not available")
    def test_RMTC_predict(self):
        self.run_test("RMTC", False, True)

    @unittest.skipIf(not compiled_available, "Compiled Fortran libraries not available")
    def test_RMTB(self):
        self.run_test("RMTB", False, False)

    @unittest.skipIf(not compiled_available, "Compiled Fortran libraries not available")
    def test_RMTB_train(self):
        with self.assertRaises(Exception) as context:
            self.run_test("RMTB", True, False)
        self.assertEqual(str(context.exception), "Training points above max for 0")

    @unittest.skipIf(not compiled_available, "Compiled Fortran libraries not available")
    def test_RMTB_predict(self):
        self.run_test("RMTB", False, True)

if __name__ == "__main__":
    unittest.main()


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

namespace ISimpleHttpServer.Model
{
    public interface IParseControl
    {
        bool IsEndOfRequest { get; }

        bool IsRequestTimedOut { get; }

        bool IsUnableToParseHttp { get; }
    }
}


text:
package org.rhq.metrics.netty.collectd.packet;

/**
 * Collectd Value Part.
 *
 * @author Thomas Segismont
 */
public final class ValuePart extends Part<Values> {
    public ValuePart(PartType partType, Values values) {
        super(partType, values);
    }
}


text:
#ifndef	_LINUX_BITOPS_H_
#define	_LINUX_BITOPS_H_

#ifdef __LP64__
#define	BITS_PER_LONG		64
#else
#define	BITS_PER_LONG		32
#endif
#define	BIT_MASK(n)		(~0UL >> (BITS_PER_LONG - (n)))
#define	BITS_TO_LONGS(n)	howmany((n), BITS_PER_LONG)
#define BIT_WORD(nr)		((nr) / BITS_PER_LONG)

static inline int
__ffs(int mask)
{
	return (ffs(mask) - 1);
}

static inline int
__fls(int mask)
{
	return (fls(mask) - 1);
}

static inline int
__ffsl(long mask)
{
	return (ffsl(mask) - 1);
}

static inline int
__flsl(long mask)
{
	return (flsl(mask) - 1);
}

#define	ffz(mask)	__ffs(~(mask))

static inline int get_count_order(unsigned int count)
{
        int order;

        order = fls(count) - 1;
        if (count & (count - 1))
                order++;
        return order;
}

static inline unsigned long
find_first_bit(unsigned long *addr, unsigned long size)
{
	long mask;
	int bit;

	for (bit = 0; size >= BITS_PER_LONG;
	    size -= BITS_PER_LONG, bit += BITS_PER_LONG, addr++) {
		if (*addr == 0)
			continue;
		return (bit + __ffsl(*addr));
	}
	if (size) {
		mask = (*addr) & BIT_MASK(size);
		if (mask)
			bit += __ffsl(mask);
		else
			bit += size;
	}
	return (bit);
}

static inline unsigned long
find_first_zero_bit(unsigned long *addr, unsigned long size)
{
	long mask;
	int bit;

	for (bit = 0; size >= BITS_PER_LONG;
	    size -= BITS_PER_LONG, bit += BITS_PER_LONG, addr++) {
		if (~(*addr) == 0)
			continue;
		return (bit + __ffsl(~(*addr)));
	}
	if (size) {
		mask = ~(*addr) & BIT_MASK(size);
		if (mask)
			bit += __ffsl(mask);
		else
			bit += size;
	}
	return (bit);
}

static inline unsigned long
find_last_bit(unsigned long *addr, unsigned long size)
{
	long mask;
	int offs;
	int bit;
	int pos;

	pos = size / BITS_PER_LONG;
	offs = size % BITS_PER_LONG;
	bit = BITS_PER_LONG * pos;
	addr += pos;
	if (offs) {
		mask = (*addr) & BIT_MASK(offs);
		if (mask)
			return (bit + __flsl(mask));
	}
	while (--pos) {
		addr--;
		bit -= BITS_PER_LONG;
		if (*addr)
			return (bit + __flsl(mask));
	}
	return (size);
}

static inline unsigned long
find_next_bit(unsigned long *addr, unsigned long size, unsigned long offset)
{
	long mask;
	int offs;
	int bit;
	int pos;

	if (offset >= size)
		return (size);
	pos = offset / BITS_PER_LONG;
	offs = offset % BITS_PER_LONG;
	bit = BITS_PER_LONG * pos;
	addr += pos;
	if (offs) {
		mask = (*addr) & ~BIT_MASK(offs);
		if (mask)
			return (bit + __ffsl(mask));
		bit += BITS_PER_LONG;
		addr++;
	}
	for (size -= bit; size >= BITS_PER_LONG;
	    size -= BITS_PER_LONG, bit += BITS_PER_LONG, addr++) {
		if (*addr == 0)
			continue;
		return (bit + __ffsl(*addr));
	}
	if (size) {
		mask = (*addr) & BIT_MASK(size);
		if (mask)
			bit += __ffsl(mask);
		else
			bit += size;
	}
	return (bit);
}

static inline unsigned long
find_next_zero_bit(unsigned long *addr, unsigned long size,
    unsigned long offset)
{
	long mask;
	int offs;
	int bit;
	int pos;

	if (offset >= size)
		return (size);
	pos = offset / BITS_PER_LONG;
	offs = offset % BITS_PER_LONG;
	bit = BITS_PER_LONG * pos;
	addr += pos;
	if (offs) {
		mask = ~(*addr) & ~BIT_MASK(offs);
		if (mask)
			return (bit + __ffsl(mask));
		bit += BITS_PER_LONG;
		addr++;
	}
	for (size -= bit; size >= BITS_PER_LONG;
	    size -= BITS_PER_LONG, bit += BITS_PER_LONG, addr++) {
		if (~(*addr) == 0)
			continue;
		return (bit + __ffsl(~(*addr)));
	}
	if (size) {
		mask = ~(*addr) & BIT_MASK(size);
		if (mask)
			bit += __ffsl(mask);
		else
			bit += size;
	}
	return (bit);
}

static inline void
bitmap_zero(unsigned long *addr, int size)
{
	int len;

	len = BITS_TO_LONGS(size) * sizeof(long);
	memset(addr, 0, len);
}

static inline void
bitmap_fill(unsigned long *addr, int size)
{
	int tail;
	int len;

	len = (size / BITS_PER_LONG) * sizeof(long);
	memset(addr, 0xff, len);
	tail = size & (BITS_PER_LONG - 1);
	if (tail)
		addr[size / BITS_PER_LONG] = BIT_MASK(tail);
}

static inline int
bitmap_full(unsigned long *addr, int size)
{
	long mask;
	int tail;
	int len;
	int i;

	len = size / BITS_PER_LONG;
	for (i = 0; i < len; i++)
		if (addr[i] != ~0UL)
			return (0);
	tail = size & (BITS_PER_LONG - 1);
	if (tail) {
		mask = BIT_MASK(tail);
		if ((addr[i] & mask) != mask)
			return (0);
	}
	return (1);
}

static inline int
bitmap_empty(unsigned long *addr, int size)
{
	long mask;
	int tail;
	int len;
	int i;

	len = size / BITS_PER_LONG;
	for (i = 0; i < len; i++)
		if (addr[i] != 0)
			return (0);
	tail = size & (BITS_PER_LONG - 1);
	if (tail) {
		mask = BIT_MASK(tail);
		if ((addr[i] & mask) != 0)
			return (0);
	}
	return (1);
}

#define	NBLONG	(NBBY * sizeof(long))

#define	set_bit(i, a)							\
    atomic_set_long(&((volatile long *)(a))[(i)/NBLONG], 1UL << (i) % NBLONG)

#define	clear_bit(i, a)							\
    atomic_clear_long(&((volatile long *)(a))[(i)/NBLONG], 1UL << (i) % NBLONG)

#define	test_bit(i, a)							\
    !!(atomic_load_acq_long(&((volatile long *)(a))[(i)/NBLONG]) &	\
    1UL << ((i) % NBLONG))

static inline long
test_and_clear_bit(long bit, long *var)
{
	long val;

	var += bit / (sizeof(long) * NBBY);
	bit %= sizeof(long) * NBBY;
	bit = 1 << bit;
	do {
		val = *(volatile long *)var;
	} while (atomic_cmpset_long(var, val, val & ~bit) == 0);

	return !!(val & bit);
}

static inline long
test_and_set_bit(long bit, long *var)
{
	long val;

	var += bit / (sizeof(long) * NBBY);
	bit %= sizeof(long) * NBBY;
	bit = 1 << bit;
	do {
		val = *(volatile long *)var;
	} while (atomic_cmpset_long(var, val, val | bit) == 0);

	return !!(val & bit);
}

#define BITMAP_FIRST_WORD_MASK(start) (~0UL << ((start) % BITS_PER_LONG))
#define BITMAP_LAST_WORD_MASK(nbits)                                    \
(                                                                       \
        ((nbits) % BITS_PER_LONG) ?                                     \
                (1UL<<((nbits) % BITS_PER_LONG))-1 : ~0UL               \
)

static inline void
bitmap_set(unsigned long *map, int start, int nr)
{
	unsigned long *p = map + BIT_WORD(start);
	const int size = start + nr;
	int bits_to_set = BITS_PER_LONG - (start % BITS_PER_LONG);
	unsigned long mask_to_set = BITMAP_FIRST_WORD_MASK(start);

	while (nr - bits_to_set >= 0) {
		*p |= mask_to_set;
		nr -= bits_to_set;
		bits_to_set = BITS_PER_LONG;
		mask_to_set = ~0UL;
		p++;
	}
	if (nr) {
		mask_to_set &= BITMAP_LAST_WORD_MASK(size);
		*p |= mask_to_set;
	}
}

static inline void
bitmap_clear(unsigned long *map, int start, int nr)
{
	unsigned long *p = map + BIT_WORD(start);
	const int size = start + nr;
	int bits_to_clear = BITS_PER_LONG - (start % BITS_PER_LONG);
	unsigned long mask_to_clear = BITMAP_FIRST_WORD_MASK(start);

	while (nr - bits_to_clear >= 0) {
		*p &= ~mask_to_clear;
		nr -= bits_to_clear;
		bits_to_clear = BITS_PER_LONG;
		mask_to_clear = ~0UL;
		p++;
	}
	if (nr) {
		mask_to_clear &= BITMAP_LAST_WORD_MASK(size);
		*p &= ~mask_to_clear;
	}
}

enum {
        REG_OP_ISFREE,          /* true if region is all zero bits */
        REG_OP_ALLOC,           /* set all bits in region */
        REG_OP_RELEASE,         /* clear all bits in region */
};

static int __reg_op(unsigned long *bitmap, int pos, int order, int reg_op)
{
        int nbits_reg;          /* number of bits in region */
        int index;              /* index first long of region in bitmap */
        int offset;             /* bit offset region in bitmap[index] */
        int nlongs_reg;         /* num longs spanned by region in bitmap */
        int nbitsinlong;        /* num bits of region in each spanned long */
        unsigned long mask;     /* bitmask for one long of region */
        int i;                  /* scans bitmap by longs */
        int ret = 0;            /* return value */

        /*
         * Either nlongs_reg == 1 (for small orders that fit in one long)
         * or (offset == 0 && mask == ~0UL) (for larger multiword orders.)
         */
        nbits_reg = 1 << order;
        index = pos / BITS_PER_LONG;
        offset = pos - (index * BITS_PER_LONG);
        nlongs_reg = BITS_TO_LONGS(nbits_reg);
        nbitsinlong = min(nbits_reg,  BITS_PER_LONG);

        /*
         * Can't do "mask = (1UL << nbitsinlong) - 1", as that
         * overflows if nbitsinlong == BITS_PER_LONG.
         */
        mask = (1UL << (nbitsinlong - 1));
        mask += mask - 1;
        mask <<= offset;

        switch (reg_op) {
        case REG_OP_ISFREE:
                for (i = 0; i < nlongs_reg; i++) {
                        if (bitmap[index + i] & mask)
                                goto done;
                }
                ret = 1;        /* all bits in region free (zero) */
                break;

        case REG_OP_ALLOC:
                for (i = 0; i < nlongs_reg; i++)
                        bitmap[index + i] |= mask;
                break;

        case REG_OP_RELEASE:
                for (i = 0; i < nlongs_reg; i++)
                        bitmap[index + i] &= ~mask;
                break;
        }
done:
        return ret;
}

/**
 * bitmap_find_free_region - find a contiguous aligned mem region
 *      @bitmap: array of unsigned longs corresponding to the bitmap
 *      @bits: number of bits in the bitmap
 *      @order: region size (log base 2 of number of bits) to find
 *
 * Find a region of free (zero) bits in a @bitmap of @bits bits and
 * allocate them (set them to one).  Only consider regions of length
 * a power (@order) of two, aligned to that power of two, which
 * makes the search algorithm much faster.
 *
 * Return the bit offset in bitmap of the allocated region,
 * or -errno on failure.
 */
static inline int
bitmap_find_free_region(unsigned long *bitmap, int bits, int order)
{
        int pos, end;           /* scans bitmap by regions of size order */

        for (pos = 0 ; (end = pos + (1 << order)) <= bits; pos = end) {
                if (!__reg_op(bitmap, pos, order, REG_OP_ISFREE))
                        continue;
                __reg_op(bitmap, pos, order, REG_OP_ALLOC);
                return pos;
        }
        return -ENOMEM;
}

/**
 * bitmap_release_region - release allocated bitmap region
 *      @bitmap: array of unsigned longs corresponding to the bitmap
 *      @pos: beginning of bit region to release
 *      @order: region size (log base 2 of number of bits) to release
 *
 * This is the complement to __bitmap_find_free_region() and releases
 * the found region (by clearing it in the bitmap).
 *
 * No return value.
 */
static inline void
bitmap_release_region(unsigned long *bitmap, int pos, int order)
{
        __reg_op(bitmap, pos, order, REG_OP_RELEASE);
}

#endif	/* _LINUX_BITOPS_H_ */