text:
-- =============================================
-- Author:		Sorin Oboroceanu
-- Create date: 03/05/2013
-- Description:	Gets all the records from threeUpgradeBandValues table
-- =============================================
CREATE PROCEDURE [dbo].[threeUpgradeGetBandValues]

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	SELECT *
	FROM [dbo].[threeUpgradeBandValues]
	ORDER BY bandvalue
END

GRANT EXECUTE ON threeUpgradeGetBandValues TO b4nuser
GO


text:
package ocr

type Message interface {
  // TODO maybe serialize
}

type MessageProgress struct {
  // implements Message
}

type MessageNewEpoch struct {
  Pj int // ID of the source peer
  EPrime int // new epoch the source peer communicates
}

func newMessageNewEpoch(ePrime, id int) *MessageNewEpoch {
  return &MessageNewEpoch{
    Pj: id,
    EPrime: ePrime,
  }
}

type MessageObserveReq struct {
  Pj int // ID of the source peer
  RPrime int // Round number
}

func newMessageObserveReq(pj, rPrime int) MessageObserveReq {
  return MessageObserveReq{
    Pj: pj,
    RPrime: rPrime,
  }
}

type MessageObserve struct {
  Pj int // id of the source of the message
  // TODO in the reporting leader algo, Rf is called RPrime.
  Rf int // current round of observation
  Value int // observation value
  Signature string // message signature
}

func newMessageObserve(rf, value, signature) *MessageObserve {
  return &MessageObserve{
    Rf: rf,
    Value: value,
    Signature: signature,
  }
}

type MessageReport struct {
  Pj int // id of the source node of the message
  RPrime int // round number
  R Report // report
  Tau int // Q: what is this tau?
}

type MessageReportRequest struct {
  Pj int // id of the source of the message
  RPrime int // round number
  R Report
}

type Report struct {
  Measurements []Measurement
}

func (r Report) Compressed() []NonSignedMeasurement {
}

type NonSignedMeasurement struct {
  W, K int
}

type Measurement struct {
  W, K int
  Signature []byte
}

type MessageFinal struct {
  Pj int
  RPrime int
  O int
}

type MessageFinalEcho struct {
  Pj int
  RPrime int
  O int
}

func newMessageFinalEcho(id, r, O int) MessageFinalEcho {
  return MessageFinalEcho{
    Pj: id,
    RPrime: r,
    O: O,
  }
}

type Network interface {
  Broadcast(message Message, senderID int)
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef DeskRight_H
#define DeskRight_H

#include "includes.h"
#include "Debug.h"
#include <winsock2.h>
#include <windows.h>

#define ADD_RIGHT    1
#define REMOVE_RIGHT 0

#define WINSTA_ALL (WINSTA_ACCESSCLIPBOARD  | WINSTA_ACCESSGLOBALATOMS | \
                    WINSTA_CREATEDESKTOP    | WINSTA_ENUMDESKTOPS      | \
                    WINSTA_ENUMERATE        | WINSTA_EXITWINDOWS       | \
                    WINSTA_READATTRIBUTES   | WINSTA_READSCREEN        | \
                    WINSTA_WRITEATTRIBUTES  | DELETE                   | \
                    READ_CONTROL            | WRITE_DAC                | \
                    WRITE_OWNER)

#define DESKTOP_ALL (DESKTOP_CREATEMENU      | DESKTOP_CREATEWINDOW  | \
                     DESKTOP_ENUMERATE       | DESKTOP_HOOKCONTROL   | \
                     DESKTOP_JOURNALPLAYBACK | DESKTOP_JOURNALRECORD | \
                     DESKTOP_READOBJECTS     | DESKTOP_SWITCHDESKTOP | \
                     DESKTOP_WRITEOBJECTS    | DELETE                | \
                     READ_CONTROL            | WRITE_DAC             | \
                     WRITE_OWNER)

#define GENERIC_ACCESS (GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL)

int ModifyRightsToDesktop(HANDLE hToken, int mode);
int ModifyRightsToDesktopBySid(PSID psid, int mode);

#endif


text:
require 'rubygems/test_case'

class TestGemResolverAPISpecification < Gem::TestCase

  def test_initialize
    set = Gem::Resolver::APISet.new
    data = {
      :name     => 'rails',
      :number   => '3.0.3',
      :platform => 'ruby',
      :dependencies => [
        ['bundler',  '~> 1.0'],
        ['railties', '= 3.0.3'],
      ],
    }

    spec = Gem::Resolver::APISpecification.new set, data

    assert_equal 'rails',                   spec.name
    assert_equal Gem::Version.new('3.0.3'), spec.version
    assert_equal Gem::Platform::RUBY,       spec.platform

    expected = [
      Gem::Dependency.new('bundler',  '~> 1.0'),
      Gem::Dependency.new('railties', '= 3.0.3'),
    ]

    assert_equal expected, spec.dependencies
  end

  def test_installable_platform_eh
    set = Gem::Resolver::APISet.new
    data = {
      :name     => 'a',
      :number   => '1',
      :platform => 'ruby',
      :dependencies => [],
    }

    a_spec = Gem::Resolver::APISpecification.new set, data

    assert a_spec.installable_platform?

    data = {
      :name     => 'b',
      :number   => '1',
      :platform => 'cpu-other_platform-1',
      :dependencies => [],
    }

    b_spec = Gem::Resolver::APISpecification.new set, data

    refute b_spec.installable_platform?

    data = {
      :name     => 'c',
      :number   => '1',
      :platform => Gem::Platform.local.to_s,
      :dependencies => [],
    }

    c_spec = Gem::Resolver::APISpecification.new set, data

    assert c_spec.installable_platform?
  end

  def test_source
    set = Gem::Resolver::APISet.new
    data = {
      :name         => 'a',
      :number       => '1',
      :platform     => 'ruby',
      :dependencies => [],
    }

    api_spec = Gem::Resolver::APISpecification.new set, data

    assert_equal set.source, api_spec.source
  end

  def test_spec
    spec_fetcher do |fetcher|
      fetcher.spec 'a', 1
    end

    dep_uri = URI(@gem_repo) + 'api/v1/dependencies'
    set = Gem::Resolver::APISet.new dep_uri
    data = {
      :name         => 'a',
      :number       => '1',
      :platform     => 'ruby',
      :dependencies => [],
    }

    api_spec = Gem::Resolver::APISpecification.new set, data

    spec = api_spec.spec

    assert_kind_of Gem::Specification, spec
    assert_equal 'a-1', spec.full_name
  end

end


text:
package com.github.kawakicchi.developer;

import java.awt.Insets;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;

public class DeveloperFrame extends JFrame {

	public static void main(final String[] args) {
		DeveloperFrame frm = new DeveloperFrame();
		frm.setVisible(true);
	}

	/** serialVersionUID */
	private static final long serialVersionUID = -8105655263394442225L;

	private JDesktopPane desktop;

	public DeveloperFrame() {
		setLayout(null);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);

		desktop = new JDesktopPane();
		add(desktop);

		JInternalFrame iframe1 = new JInternalFrame();
		iframe1.setTitle("TEST");
		iframe1.setSize(150, 100);
		iframe1.setLocation(10, 10);
		iframe1.setVisible(true);
		iframe1.setResizable(true);
		iframe1.setMaximizable(true);
		iframe1.setIconifiable(true);
		iframe1.setClosable(true);

		desktop.add(iframe1);

		addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent e) {
				Insets insets = getInsets();
				int width = getWidth() - (insets.left + insets.right);
				int height = getHeight() - (insets.top + insets.bottom);
				desktop.setSize(width, height);
			}
		});

		setSize(1024, 900);
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LinkedData.Helpers;
using Sitecore.Links;
using VDS.RDF;

namespace LinkedData.Formatters
{
    public class StripLinkFieldFormatter : ITripleFormatter
    {
        public Triple FormatTriple(Triple triple)
        {
            var g = new Graph();

            IUriNode sub = g.CreateUriNode(new Uri(triple.Subject.ToString()));
            IUriNode pred = g.CreateUriNode(new Uri(SitecoreTripleHelper.RemoveLinkFieldFromPredicate(triple.Predicate)));
            IUriNode obj = g.CreateUriNode(new Uri(triple.Object.ToString()));

            triple = new Triple(sub, pred, obj);

            return triple;
        }
    }
}


text:
/*global QUnit, sinon */
sap.ui.define([
	"sap/ui/core/LocalBusyIndicatorSupport",
	"sap/m/BusyDialog",
	"sap/m/Button",
	"sap/m/List",
	"sap/m/Slider",
	"sap/m/StandardListItem",
	"sap/m/VBox",
	"sap/ui/core/Control",
	"sap/ui/core/Element",
	"sap/ui/core/mvc/XMLView",
	"sap/ui/events/KeyCodes",
	"sap/ui/thirdparty/jquery",
	"sap/ui/qunit/QUnitUtils"
], function(LocalBusyIndicatorSupport, BusyDialog, Button, List, Slider, StandardListItem, VBox, Control, Element, XMLView, KeyCodes, jQuery, qutils) {
	"use strict";

	// Checks whether the given DomRef is contained or equals (in) one of the given container
	function isContained(aContainers, oRef) {
		for (var i = 0; i < aContainers.length; i++) {
			if (aContainers[i] === oRef || jQuery.contains(aContainers[i], oRef)) {
				return true;
			}
		}
		return false;
	}

	// Returns a jQuery object which contains all next/previous (bNext) tabbable DOM elements of the given starting point (oRef) within the given scopes (DOMRefs)
	function findTabbables(oRef, aScopes, bNext) {
		var $Ref = jQuery(oRef),
			$All, $Tabbables;

		if (bNext) {
			$All = jQuery.merge($Ref.find("*"), jQuery.merge($Ref.nextAll(), $Ref.parents().nextAll()));
			$Tabbables = $All.find(':sapTabbable').addBack(':sapTabbable');
		} else {
			$All = jQuery.merge($Ref.prevAll(), $Ref.parents().prevAll());
			$Tabbables = jQuery.merge($Ref.parents(':sapTabbable'), $All.find(':sapTabbable').addBack(':sapTabbable'));
		}

		$Tabbables = jQuery.uniqueSort($Tabbables);
		return $Tabbables.filter(function() {
			return isContained(aScopes, this);
		});
	}

	function simulateTabEvent(oTarget, bBackward) {
		var oParams = {};
		oParams.keyCode = KeyCodes.TAB;
		oParams.which = oParams.keyCode;
		oParams.shiftKey = !!bBackward;
		oParams.altKey = false;
		oParams.metaKey = false;
		oParams.ctrlKey = false;

		if (typeof (oTarget) == "string") {
			oTarget = document.getElementById(oTarget);
		}

		var oEvent = jQuery.Event({type: "keydown"});
		for (var x in oParams) {
			oEvent[x] = oParams[x];
			oEvent.originalEvent[x] = oParams[x];
		}

		jQuery(oTarget).trigger(oEvent);

		if (oEvent.isDefaultPrevented()) {
			return;
		}

		var $Tabbables = findTabbables(document.activeElement, [document.getElementById("target1")], !bBackward);
		if ($Tabbables.length) {
			$Tabbables.get(bBackward ? $Tabbables.length - 1 : 0).focus();
		}
	}

	/**
	 * Check whether an element is focused.
	 * @param {jQuery|HTMLElement} oElement The element to check.
	 * @param {Object} assert QUnit assert object.
	 * @returns {jQuery} A jQuery object containing the active element.
	 */
	function checkFocus(oElement, assert) {
		var $ActiveElement = jQuery(document.activeElement);
		var $Element = jQuery(oElement);

		assert.ok($Element[0] === document.activeElement, "Focus is on: " + $ActiveElement.attr("id") + ", should be on: " + $Element.attr("id"));

		return $ActiveElement;
	}

	// create page content
	["target1", "target2", "target3", "failsafeTests"].forEach(function(sId) {
		var oDIV = document.createElement("div");
		oDIV.id = sId;
		document.body.appendChild(oDIV);
	});

	QUnit.module("Basic", {
		beforeEach : function() {
			this.oFocusBefore = new Button("FocusBefore").placeAt("target1");
			this.oListBox = new List({
				tooltip : "Country",
				width : "200px",
				items : [ new StandardListItem({
					title : "I'm an item, and you?"
				}) ]
			}).placeAt("target1");
			this.oFocusAfter = new Button("FocusAfter").placeAt("target1");
			this.oSlider = new Slider().placeAt("target2");

			sap.ui.getCore().applyChanges();
		},

		afterEach : function() {
			this.oFocusBefore.destroy();
			this.oFocusAfter.destroy();
			this.oListBox.destroy();
			this.oSlider.destroy();
		}
	});

	// make sure the controls are not busy
	QUnit.test("InitialCheck", function(assert) {
		assert.equal(this.oSlider.getBusy(), false, "Slider is not busy");
		assert.equal(this.oListBox.getBusy(), false, "Listbox is not busy");
	});

	QUnit.test("Accessibility", function(assert) {
		var done = assert.async();
		this.oListBox.setBusy(true);
		var $LB = this.oListBox.$();
		var iChildren = $LB.children().length;

		setTimeout(function() {
			var oBusyIndicatorDOM = $LB.children('.sapUiLocalBusyIndicator')[0];
			assert.equal($LB.children().length, iChildren + 1, 'Busy Indicator added to DOM tree');
			assert.ok(!$LB[0].hasAttribute("aria-busy"), "ARIA busy isn't set to Control");
			assert.equal(oBusyIndicatorDOM.getAttribute("role"), "progressbar", 'ARIA role "progressbar" is set to busy indicator');
			assert.ok(oBusyIndicatorDOM.hasAttribute("title"), 'title is set to busy indicator');
			assert.ok(oBusyIndicatorDOM.hasAttribute("aria-valuemin"), 'aria-valuemin is set to busy indicator');
			assert.ok(oBusyIndicatorDOM.hasAttribute("aria-valuemax"), 'aria-valuemax is set to busy indicator');
			assert.ok(oBusyIndicatorDOM.hasAttribute("aria-valuetext"), 'aria-valuetext is set to busy indicator');
			done();
		}, 1200);
	});

	QUnit.test("tab chain - busy delay 0", function(assert) {
		var done = assert.async(),
			oElem;
		this.oFocusBefore.getDomRef().focus();
		this.oListBox.setBusyIndicatorDelay(0);
		this.oListBox.setBusy(true);
		simulateTabEvent(this.oFocusBefore.getDomRef());
		oElem = this.oListBox.getDomRef("busyIndicator");
		checkFocus(oElem, assert);
		simulateTabEvent(oElem);
		checkFocus(this.oFocusAfter.getDomRef(), assert);
		simulateTabEvent(this.oFocusAfter.getDomRef(), true);
		checkFocus(oElem, assert);
		simulateTabEvent(oElem, true);
		checkFocus(this.oFocusBefore.getDomRef(), assert);
		done();
	});

	QUnit.test("tab chain - normal delay", function(assert) {
		var done = assert.async(),
			oElem;
		this.oFocusBefore.getDomRef().focus();
		this.oListBox.setBusy(true);

		simulateTabEvent(this.oFocusBefore.getDomRef());
		oElem = document.getElementById(this.oListBox.getItems()[0].getId());
		checkFocus(oElem, assert);
		simulateTabEvent(oElem);
		checkFocus(this.oFocusAfter.getDomRef(), assert);
		simulateTabEvent(this.oFocusAfter.getDomRef(), true);
		checkFocus(oElem, assert);
		simulateTabEvent(oElem, true);
		checkFocus(this.oFocusBefore.getDomRef(), assert);

		setTimeout(function() {
			simulateTabEvent(this.oFocusBefore.getDomRef());
			oElem = this.oListBox.getDomRef("busyIndicator");
			checkFocus(oElem, assert);
			simulateTabEvent(oElem);
			checkFocus(this.oFocusAfter.getDomRef(), assert);
			simulateTabEvent(this.oFocusAfter.getDomRef(), true);
			oElem = this.oListBox.getDomRef("busyIndicator");
			checkFocus(oElem, assert);
			simulateTabEvent(oElem, true);
			checkFocus(this.oFocusBefore.getDomRef(), assert);
			done();
		}.bind(this), 1200);
	});

	QUnit.test("Check suppressed events", function(assert) {
		var done = assert.async();
		this.oListBox.setBusyIndicatorDelay(0);
		this.oListBox.setBusy(true);
		var $LB = this.oListBox.$();

		var aPreventedEvents = [
			"focusin",
			"focusout",
			"keydown",
			"keypress",
			"keyup",
			"mousedown",
			"touchstart",
			"touchmove",
			"mouseup",
			"touchend",
			"click"
		];

		var sListenerCalled = 'not called';
		function fnEventListener(oEvent) {
			sListenerCalled = 'called';
		}

		// register listener for all prevented events
		// Note: the issues described in BCP 1680184582 only occurs when the prevent-listener of the LocalBusyIndicator
		// is executed __BEFORE__ this listener here. As jQuery uses a while(--i) loop, this means we have to register
		// our listener before the LBI registers its own listener.
		// TODO consider using a capturing phase listener in LBI to make this more robust.
		for (var i = 0; i < aPreventedEvents.length; i++) {
			$LB.on(aPreventedEvents[i], fnEventListener);
		}

		setTimeout(function() {

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

				try {
					sListenerCalled = 'not called';
					qutils.triggerEvent(aPreventedEvents[i], $LB);
					assert.equal(sListenerCalled, 'not called', "Event '" + aPreventedEvents[i] + "' should be suppressed");
				} catch (ex) {
					assert.ok(false, "Event '" + aPreventedEvents[i] + "' NOT suppressed");
				}

			}

			// hide busy indicator and test that events are no longer prevented
			this.oListBox.setBusy(false);
			$LB = this.oListBox.$();

			setTimeout(function() {

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

					try {
						sListenerCalled = 'not called';
						qutils.triggerEvent(aPreventedEvents[i], $LB);
						assert.equal(sListenerCalled, 'called', "Event '" + aPreventedEvents[i] + "' should no longer be suppressed");
					} catch (ex) {
						// assert.ok(false, "Event '" + aPreventedEvents[i] + "' NOT suppressed");
					}

				}

				done();

			}, 250);

		}.bind(this), 250);
	});

	QUnit.module("Open and Close", {
		beforeEach : function() {
			this.oListBox = new List({
				tooltip : "Country",
				width : "200px",
				items : [ new StandardListItem({
					title : "I'm an item, and you?"
				}) ]
			}).placeAt("target1");

			this.oSlider = new Slider().placeAt("target2");

			sap.ui.getCore().applyChanges();
		},

		afterEach : function() {
			this.oListBox.destroy();
			this.oSlider.destroy();
		}
	});

	QUnit.test("Delayed opening", function(assert) {
		var done = assert.async();
		var that = this;
		this.oListBox.setBusy(true);

		assert.equal(this.oListBox.$().children('.sapUiLocalBusyIndicator').length, 0, 'Busy Indicator not yet added to DOM');
		assert.equal(this.oListBox.getBusy(), true, 'ListBox is busy');

		setTimeout(function() {
			assert.equal(that.oListBox.$().children('.sapUiLocalBusyIndicator').length, 1, 'Busy Indicator is part of the DOM');
			done();
		}, 1200);
	});

	QUnit.test("Close Busy Indicator", function(assert) {
		var done = assert.async();
		assert.expect(7);
		var that = this;
		this.oListBox.setBusy(true);

		assert.equal(this.oListBox.$().children('.sapUiLocalBusyIndicator').length, 0, 'Busy Indicator not yet added to DOM');
		assert.equal(this.oListBox.getBusy(), true, 'ListBox is busy');
		assert.equal(this.oListBox.getDomRef().parentElement.children.length, 1, 'No additional elements in dom');

		setTimeout(function() {
			assert.equal(that.oListBox.$().children('.sapUiLocalBusyIndicator').length, 1, 'Busy Indicator is part of the DOM');

			that.oListBox.setBusy(false);

			setTimeout(function() {
				assert.equal(that.oListBox.$().children('.sapUiLocalBusyIndicator').length, 0, 'Busy Indicator was romoved from DOM');
				assert.equal(that.oListBox.getBusy(), false, 'ListBox is not busy anymore');
				assert.equal(that.oListBox.getDomRef().parentElement.children.length, 1, 'No additional elements in dom');
				done();
			}, 250);
		}, 1200);
	});

	/**
	 * This test checks if the busy indicator does not crash after the outer control was already
	 * removed from the DOM, when the
	 */
	QUnit.test("BusyIndicator and Already Closed sap.m.BusyDialog does not crash", function(assert) {
		var done = assert.async();

		var dialog = new BusyDialog({
			title: "Loading",
			text: "something loading..."
		});

		dialog.open();
		setTimeout(function () {
			Element.closestTo("#__dialog0-busyInd").setBusy(true);
			dialog.close();
			assert.ok("everythings fine");
			done();
		}, 250);

	});

	QUnit.test("Open multiple busy indicators", function(assert) {
		var done = assert.async();
		var that = this;

		this.oListBox.setBusy(true);
		this.oSlider.setBusy(true);

		assert.equal(this.oListBox.$().children('.sapUiLocalBusyIndicator').length, 0, 'Listbox Busy Indicator not yet added to DOM');
		assert.equal(this.oSlider.$().children('.sapUiLocalBusyIndicator').length, 0, 'Slider Busy Indicator not yet added to DOM');
		assert.equal(this.oListBox.getBusy(), true, 'ListBox is busy');
		assert.equal(this.oSlider.getBusy(), true, 'Slider is busy');

		setTimeout(function() {
			assert.equal(that.oListBox.$().children('.sapUiLocalBusyIndicator').length, 1, 'Listbox Busy Indicator is part of the DOM');
			assert.equal(that.oSlider.$().children('.sapUiLocalBusyIndicator').length, 1, 'Slider Busy Indicator is part of the DOM');
			done();
		}, 1200);
	});

	// as XML-View maintains the DOM itself, busy indicator should treat this particularly, as otherwise duplicate
	// busy indicators would be created when rerendering and never removed
	QUnit.test("Busy indicator on XML View", function(assert) {
		var done = assert.async();
		// setup the busy view
		return XMLView.create({
			definition: '<mvc:View xmlns:mvc="sap.ui.core.mvc" busyIndicatorDelay="0"></mvc:View>'
		}).then(function(myView) {
			myView.placeAt('target1');
			sap.ui.getCore().applyChanges();
			myView.setBusy(true);
			// this rerendering is crucial to test the behavior
			myView.rerender();
			setTimeout(function() {
				// assert
				assert.ok(myView.$("busyIndicator").length, "BusyIndicator rendered");
				myView.setBusy(false);
				assert.ok(!myView.$("busyIndicator").length, "All BusyIndicators removed");
				//cleanup
				myView.destroy();
				done();
			}, 50);
		});
	});

	QUnit.test("span elements for tab chain", function(assert) {
		this.oListBox.setBusyIndicatorDelay(0);
		var oBusySection = jQuery(this.oListBox.getDomRef(this.oListBox._sBusySection));
		var aChildrenBefore = oBusySection.parent()[0].childNodes;

		assert.equal(aChildrenBefore.length, 1, 'No busy spans inserted');
		this.oListBox.setBusy(true);
		assert.equal(this.oListBox.getBusy(), true, 'ListBox is busy');
		assert.equal(aChildrenBefore.length, 3, 'busy spans inserted');
		this.oListBox.setBusy(true);
		assert.equal(aChildrenBefore.length, 3, 'busy spans inserted only once');
		this.oListBox.setBusy(false);
		assert.equal(aChildrenBefore.length, 1, 'No busy spans inserted');
		this.oListBox.setBusy(false);
		this.oListBox.setBusy(false);
		assert.equal(aChildrenBefore.length, 1, 'No busy spans inserted');
		this.oListBox.setBusy(true);
		assert.equal(aChildrenBefore.length, 3, 'busy spans inserted only once');
		this.oListBox.setBusy(false);
	});

	QUnit.module("Delay", {
		beforeEach : function() {
			this.iDelay = 500;
			this.oButton = new Button({
				busy : true,
				busyIndicatorDelay : this.iDelay,
				text : "Delayed BusyIndicator"
			});
		},

		afterEach : function() {
			delete this.iDelay;
			this.oButton.destroy();
		}
	});

	QUnit.test("OnBeforeRendering", function(assert) {
		var done = assert.async();

		this.oButton.setBusyIndicatorDelay(0);

		this.oButton.placeAt("target1");
		this.oButton.setBusy(true);

		sap.ui.getCore().applyChanges();

		this.oButton.addDelegate({
			onBeforeRendering: function() {
				var oControl = this.getDomRef();
				var oBusyIndicator = this.getDomRef("busyIndicator");

				assert.equal(oControl.previousElementSibling.nodeName.toLowerCase(), "span", "<span> before is available.");
				assert.equal(oControl.previousElementSibling.getAttribute("tabindex"), 0, "Previous <span> has tabindex 0.");
				assert.ok(oBusyIndicator, "BusyIndicator DOM is still available.");
				assert.equal(oControl.nextElementSibling.nodeName.toLowerCase(), "span", "<span> after is available.");
				assert.equal(oControl.previousElementSibling.getAttribute("tabindex"), 0, "Next <span> has tabindex 0.");
			}
		}, true, this.oButton);

		this.oButton.addDelegate({
			onBeforeRendering: function() {
				var oControl = this.getDomRef();
				var oBusyIndicator = this.getDomRef("busyIndicator");

				// check if prev & next sibilings are either not existant or not a <span tabindex='0'> element
				var oTabSpan = oControl.previousElementSibling;
				assert.ok(oTabSpan === null || (oTabSpan.getAttribute("tabindex") !== "0" && oTabSpan.nodeName !== "SPAN"), "Previous tabbable span shouldn't be available.");

				assert.notOk(oBusyIndicator, "BusyIndicator DOM is now removed");

				oTabSpan = oControl.nextElementSibling;
				assert.ok(oTabSpan === null || (oTabSpan.getAttribute("tabindex") !== "0" && oTabSpan.nodeName !== "SPAN"), "Previous tabbable span shouldn't be available.");

				done();
			}
		}, false, this.oButton);

		this.oButton.rerender();
	});

	QUnit.test("OnAfterRendering", function(assert) {
		var done = assert.async();
		assert.expect(4);
		this.oButton.placeAt("target1");
		sap.ui.getCore().applyChanges();
		var that = this;

		setTimeout(function() {
			// set busy after rendering but no animation shown
			assert.ok(that.oButton.getBusy(), "Button is set to busy");
			var $BusyIndicator = that.oButton.$("busyIndicator");
			assert.ok(!$BusyIndicator.length, "BusyIndicator isn't shown yet");

			setTimeout(function() {
				// set busy and animation shown
				assert.ok(that.oButton.getBusy(), "Button still set to busy");
				$BusyIndicator = that.oButton.$("busyIndicator");
				assert.ok($BusyIndicator.length, "BusyIndicator is shown after delay");

				done();
			}, that.iDelay);
		}, 200);
	});

	QUnit.test("Ensuring DelayedCall Only Used Once", function(assert) {
		var done = assert.async();
		assert.expect(2);

		var iFirstDelayedCallId,
			iSecondDelayedCallId;
		var oOnAfterRenderingDelegate = {
			onAfterRendering : function() {
				if (!iFirstDelayedCallId) {
					// first rendering will call delegate
					iFirstDelayedCallId = this.oButton._busyIndicatorDelayedCallId;
				} else if (!iSecondDelayedCallId) {
					// second call will happen when the text of the button is being changed
					iSecondDelayedCallId = this.oButton._busyIndicatorDelayedCallId;
				}
			}
		};
		this.oButton.addDelegate(oOnAfterRenderingDelegate, false, this);
		this.oButton.placeAt("target1");
		sap.ui.getCore().applyChanges();
		var that = this;

		setTimeout(function() {
			assert.ok(iFirstDelayedCallId && !iSecondDelayedCallId, "Delayed call started in afterRendering of control");

			// Force a re-rendering while waiting for the delay
			// (possible for example if a binding changes properties asynchronously)
			that.oButton.setText("Changed Text");

			setTimeout(function() {
				// set busy and animation shown
				assert.ok(iFirstDelayedCallId === iSecondDelayedCallId, "Delayed call not overwritten by rerendering");

				done();
			}, that.iDelay);
		}, 20);
	});

	QUnit.module("Busy Animation");

	QUnit.test("Check if small Animation is used", function(assert) {
		var done = assert.async();

		this.oBtn = new Button({
			text : "Blub",
			width : "45px",
			busyIndicatorSize : 'Small',
			busy : true,
			busyIndicatorDelay : 0
		}).placeAt("target1");

		this.oDelegate = {
			onAfterRendering : function(oEvent) {}
		};
		this.oBtn.addDelegate(this.oDelegate);
		this.oSpy = sinon.spy(this.oDelegate, "onAfterRendering");

		sap.ui.getCore().applyChanges();

		setTimeout(function() {
			var $Animation = jQuery(".sapUiLocalBusyIndicatorAnimation");
			assert.ok($Animation.length, "Animation exists");
			assert.ok($Animation.hasClass("sapUiLocalBusyIndicatorAnimSmall"), "Correct CSS class set to DOM");

			assert.equal(this.oSpy.callCount, 1, "Icon should be rendered once");

			this.oSpy.restore();
			delete this.oSpy;
			this.oBtn.removeDelegate(this.oDelegate);
			delete this.oDelegate;
			this.oBtn.destroy();

			done();
		}.bind(this), 50);
	});

	QUnit.test("Check if small Animation is used", function(assert) {
		var done = assert.async();

		this.oBtn = new Button({
			text : "Blub",
			width : "45px",
			busyIndicatorSize : 'Auto',
			busy : true,
			busyIndicatorDelay : 0
		}).placeAt("target1");

		this.oDelegate = {
			onAfterRendering : function(oEvent) {}
		};
		this.oBtn.addDelegate(this.oDelegate);
		this.oSpy = sinon.spy(this.oDelegate, "onAfterRendering");

		sap.ui.getCore().applyChanges();

		setTimeout(function() {
			var $Animation = jQuery(".sapUiLocalBusyIndicatorAnimation");
			assert.ok($Animation.length, "Animation exists");
			assert.ok($Animation.hasClass("sapUiLocalBusyIndicatorAnimSmall"), "Correct CSS class set to DOM");

			assert.equal(this.oSpy.callCount, 1, "Icon should be rendered once");

			this.oSpy.restore();
			delete this.oSpy;
			this.oBtn.removeDelegate(this.oDelegate);
			delete this.oDelegate;
			this.oBtn.destroy();

			done();
		}.bind(this), 50);
	});

	QUnit.test("Check if animations are stacked", function(assert) {
		var done = assert.async();
		this.oVBox = new VBox({
			items : [
				new List({
					busyIndicatorDelay : 0,
					busy : true
				}),
				new List({
					busyIndicatorDelay : 0,
					busy : true
				})
			],
			busyIndicatorDelay : 0,
			busy : true
		}).placeAt("target3");

		sap.ui.getCore().applyChanges();

		setTimeout(function() {
			var $Animation = jQuery(".sapUiLocalBusyIndicatorAnimation");

			assert.equal($Animation.length, 3, "3 animations should be in DOM");
			assert.ok(!jQuery($Animation.get(0)).is(":visible"), "List1's animation is hidden");
			assert.ok(!jQuery($Animation.get(1)).is(":visible"), "List2's animation is hidden");
			assert.ok(jQuery($Animation.get(2)).is(":visible"), "VBox's animation is visible");

			this.oVBox.destroy();
			done();
		}.bind(this), 50);
	});

	QUnit.module("setBusy with rendering delegate", {
		beforeEach: function() {
			this.oButton = new Button({
				text: "Rendering Delegate"
			});

			this.oButton.setBusyIndicatorDelay(0);

			this.testClickEventOn = function (oControl, assert) {
				var oDomRef = oControl.getDomRef(),
					fnEventListener = sinon.spy();

				if (oDomRef) {
					oDomRef.addEventListener("click", fnEventListener);
					qutils.triggerEvent("click", oDomRef);
					assert.equal(fnEventListener.callCount, 1, "click event can be triggered correctly");
					oDomRef.removeEventListener("click", fnEventListener);
				} else {
					assert.ok(false, "The given control doesn't have DOM reference");
				}
			};
		},
		afterEach: function() {
			this.oButton.destroy();
		}
	});

	QUnit.test("on control which is migrated with the new renderer mechanism", function(assert) {
		// add one event delegate which set the busy state before the control is rerendered
		this.oButton.addEventDelegate({
			onBeforeRendering: function() {
				this.setBusy(true);
			}
		}, this.oButton);

		this.oButton.placeAt("target1");
		sap.ui.getCore().applyChanges();
		this.oButton.setBusy(false);
		// after reset the busy state, the control should be able to react to click event
		this.testClickEventOn(this.oButton, assert);

		// rerender the control to activate the busy state
		this.oButton.rerender();
		this.oButton.setBusy(false);
		// after reset the busy state, the control should be able to react to click event
		this.testClickEventOn(this.oButton, assert);
	});

	QUnit.module("Legacy", {
		beforeEach: function(assert) {
			var Log = sap.ui.require("sap/base/Log");
			assert.ok(Log, "Log module should be available");
			this.oLogSpy = sinon.spy(Log, "error");
		},
		afterEach: function() {
			this.oLogSpy.restore();
		}
	});

	/**
	 * @deprecated Since 1.15
	 */
	QUnit.test("LocalBusyIndicatorSupport", function(assert) {

		assert.equal(typeof Control.prototype.setDelay, "undefined", "Control#setDelay should not be available by default");

		// apply deprecated LocalBusyIndicatorSupport to Control prototype to make "setDelay" method available
		LocalBusyIndicatorSupport.apply(Control.prototype);

		assert.equal(Control.prototype.setDelay, Control.prototype.setBusyIndicatorDelay,
			"Control#setDelay should be available and a reference to #setBusyIndicatorDelay after applying legacy support");

		assert.ok(this.oLogSpy.notCalled, "No error should be logged");

	});

	/**
	 * @deprecated Since 1.15
	 */
	QUnit.test("LocalBusyIndicatorSupport (error handling)", function(assert) {

		// apply deprecated LocalBusyIndicatorSupport to a specific control
		LocalBusyIndicatorSupport.apply(Button.prototype);

		// LocalBusyIndicatorSupport should log an error when applying on a specific control
		sinon.assert.calledWithExactly(this.oLogSpy, "Only controls can use the LocalBusyIndicator", Button.prototype);

	});

});


text:
@implementation SDPlaylist

@end


text:
<META http-equiv="content-type" content="text/html;charset=iso-8859-9"/><meta name="viewport" content="width=device-width, initial-scale=1"><title>ac</title> <link rel="stylesheet"  href="css/jquery.mobile-1.2.0.css" />

ALÝ GAV SULTAN

Geri

On birinci asýrda yaþamýþ gâzi ve mücâhid þeyhlerden. Doðum ve vefât târihleri
bilinmemektedir.

Türkler, on birinci asrýn baþlarýndan îtibâren Anadolu'ya yoðun bir þekilde akýnlar yapmaya
baþlamýþlardý. Bu akýnlar Malazgirt Zaferinin ön hazýrlýklarý mâhiyetinde idi. Mücâhid
gâziler ve þeyhler önderliðinde harekete geçen Selçuklu Türkleri, gönül verdikleri Ýslâm
dînini yaymaða ve çoðalan nüfûsa yeni yerleþim yerleri aramaya çalýþýyorlardý. Bilhassa
Afþin Bey idâresindeki Türklerin yiðitlik, alplik, mertlik, cesâret ve muhâripliðinin yanýsýra,
Ýslâmýn cihâd rûhu ve emri ile hareket etmeleri, Rumlarý müthiþ bir bozguna uðrattý.

Bu cihat hareketi esnâsýnda Afþin Beyin kuvvetleri arasýnda dikkati çeken bir kiþi vardý;
Derviþ Ali. Bu zât, Afþin Bey kumandasý altýndaki kuvvetlerin mânevî komutaný ve fetihlerin
mânevî fâtihidir. Hiç bir ânýný boþa geçirmek istemez, her nefesini, Allahü teâlânýn dînini
yaymak için sarfederdi. Gâzileri devamlý cihâd etmeðe ve Ýslâmiyeti yaymaða teþvik ederdi.
Fýrsat buldukça da Ýslâmiyetin emir ve yasaklarýný öðretmekle meþgûl olurdu.

Gönülleri cihâd aþký ile tutuþan gâziler, Gaziantep, Haleb ve Antakya bölgesinde uðramadýk
yer býrakmadýlar. Nihâyet 1068 yýlýnda Konya kuþatma altýna alýndý. Günlerce süren
muhâsaraya raðmen þehir, bir türlü düþürülemedi. Ordu komutaný
þehri kuþatan duvarlarý
savaþ yoluyla aþamayacaðýný anlayýnca, harp meclisini toplayarak ne yapýlmasý gerektiðini
sordu. Bu gibi durumlarda gâzi þeyhlerin sözlerine çok îtibâr edilirdi. Meclistekiler, Þeyh
Ali'ye bakarak onun konuþmasýný beklediler. Þeyh Ali kýsa bir murâkabeye, düþünceye
daldýktan sonra;

"Ordumuz kuþatmayý kaldýrýyormuþ gibi geri çekilsin ve gizlenelim, sonra gizlice kaleye
girmenin çâresini araþtýrýrýz." dedi. Bu teklif, emirler tarafýndan beðenildi. Selçuklu
kuvvetleri daðýnýk bir þekilde çekilmeye baþladýlar.

Selçuklularýn çevreden tamâmiyle uzaklaþtýklarýný gören ve günlerce süren muhasaraya
raðmen teslim olmadan kuþatmayý atlatmanýn sevincine kapýlan þehir halký, birkaç gün sonra
normal yaþantýlarýna baþladý. Kapýlar açýldý. Çarþý ve pazarda faâliyetler normal seyrine
döndü.

Halk þehir içinde olduðu gibi, þehir dýþýnda da bað, bahçe ve yaylak iþleriyle uðraþmaða
baþlamýþtý. Bir gece þehre dönmeye baþlayan sýðýr sürülerinin arasýna bir öküz postuna
bürünmüþ bulunan Þeyh Ali de karýþtý ve böylece kimseye belli etmeden þehre girmeye
muvaffak oldu. Þehirde, akþam karanlýðýnda kimseye görünmemeyi baþararak bir yere
gizlendi. Herkesin yorgunluktan derin uykuya daldýðý bir saatte yavaþça gidip, þehri kuþatan
duvarlarýn kapýsýný açtý ve o gece yakýnlara kadar gelerek bekleþen askerlere kararlaþtýrdýklarý

iþâreti verdi. Þeyh Ali'nin her türlü tehlikeyi göze alarak açmayý baþardýðý kapýdan þehre akan
askerler, nöbetçileri de tesirsiz hâle getirdikten sonra þehre hâkim olmakta gecikmediler.

Ýþte þehrin ele geçirilmesi sýrasýnda bu gâzi þeyhe, öküz postuna bürünmesinden dolayý Ali
Gav Sultan denildi. Gav, Farsçada öküz demektir. Yine Konya'da bulunan Ali Gav mahallesi
bâzý târihî kayýtlarda Mahalle-i Post-pûþþeklinde geçmektedir. Böyle olunca bu mahallenin
adý "Posta bürünenin, post örtünenin mahallesi" mânâsýna gelmektedir.

Vefâtý hakkýnda kaynaklarda bir bilgi bulunmayan Ali Gav Sultan, Konya'da Akýncý
mahallesi Tolaltý sokaðýndaki zâviyesinde medfundur.

1) Konya Velîleri; s.139-141

2) Konya Târihi, Ý.H.Konyalý; s.912-913

3) Mevlânâ Þehri Konya; s.168-169

4) Ýslâm Târihi Ansiklopedisi; c.1, s.194


text:
#include "OOCVoxelManager.h"
#include "CommonOptions.h"
#include <io.h>
#include <process.h>
#include <algorithm>
#include "Photon.h"
#include "PhotonOctree.h"
#include <map>
#include <stopwatch.h>
#include "OpenIRT.h"
#include "Renderer.h"

#ifndef fminf
#define fminf(a,b) (((a) < (b)) ? (a) : (b))
#endif

#ifndef fmaxf
#define fmaxf(a,b) (((a) > (b)) ? (a) : (b))
#endif

#include "CUDA/CUDADataStructures.cuh"

using namespace irt;

OOCVoxelManager::OOCVoxelManager(Octree *highOctree, const char *fileBase, int oriNumVoxels, const Vector3 &thresholdSize, int allowedMemMB)
{
#	ifndef USE_OOCVOXEL
	return;
#	endif
	m_highOctree = highOctree;

	m_oriNumVoxels = oriNumVoxels;
	m_allowedMem = allowedMemMB * 1024 * 1024;
	m_freeMem.insert(FreeMem(0, m_allowedMem/sizeof(Voxel)));
	m_thresholdSize = thresholdSize;

	char fileName[256];
	FILE *fp;

	m_exit = true;

	// read header
	sprintf_s(fileName, 255, "%s_OOCVoxel.hdr", fileBase);
	fopen_s(&fp, fileName, "rb");
	if(!fp)
	{
		printf("Cannot find %s\n", fileName);
		return;
	}

	int numOOCVoxels = (int)_filelength(_fileno(fp)) / sizeof(OOCVoxel);
	for(int i=0;i<numOOCVoxels;i++)
	{
		OOCVoxel buf;
		fread(&buf, sizeof(OOCVoxel), 1, fp);
		m_oocVoxelList.push_back(buf);

		(*m_highOctree)[buf.rootChildIndex].setLink2Low(i);
	}
	fclose(fp);

	m_requestCountListSize = numOOCVoxels;
	m_requestCountList = new float[m_requestCountListSize];

	BY_HANDLE_FILE_INFORMATION fileInfo;
	// map voxel file
	sprintf_s(fileName, 255, "%s_OOCVoxel.ooc", fileBase);
	m_hVoxelFile = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS, NULL);
	if(!m_hVoxelFile)
	{
		printf("Cannot find %s\n", fileName);
		return;
	}
	GetFileInformationByHandle(m_hVoxelFile, &fileInfo);
	m_hVoxelMap = CreateFileMapping(m_hVoxelFile, NULL, PAGE_READONLY, fileInfo.nFileSizeHigh, fileInfo.nFileSizeLow, NULL);
	m_voxelFile = (Voxel*)MapViewOfFile(m_hVoxelMap, FILE_MAP_READ, 0, 0, 0);

	// map photon voxel file

	sprintf_s(fileName, 255, "%s_photonVoxel.ooc", fileBase);
	m_hPhotonVoxelFile = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS, NULL);
	if(!m_hPhotonVoxelFile)
	{
		printf("Cannot find %s\n", fileName);
		return;
	}
	GetFileInformationByHandle(m_hPhotonVoxelFile, &fileInfo);
	m_hPhotonVoxelMap = CreateFileMapping(m_hPhotonVoxelFile, NULL, PAGE_READONLY, fileInfo.nFileSizeHigh, fileInfo.nFileSizeLow, NULL);
	m_photonVoxelFile = (PhotonVoxel*)MapViewOfFile(m_hPhotonVoxelMap, FILE_MAP_READ, 0, 0, 0);

	m_in = new int[numOOCVoxels*2];
	m_out = new int[numOOCVoxels*4];

	m_hQNotEmpty = CreateEvent(NULL, TRUE, FALSE, NULL);
	m_hEnoughMem = CreateEvent(NULL, TRUE, TRUE, NULL);
	m_exit = false;
	m_enabled = true;
	m_hLoadingThread = (HANDLE)_beginthreadex(NULL, 0, loadingThread, this, 0, NULL);
}

OOCVoxelManager::~OOCVoxelManager()
{
	m_exit = true;

	SetEvent(m_hQNotEmpty);
	SetEvent(m_hEnoughMem);

	if(m_hLoadingThread)
	{
		WaitForSingleObject(m_hLoadingThread, INFINITE);
		CloseHandle(m_hLoadingThread);
		m_hLoadingThread = NULL;
	}

	UnmapViewOfFile(m_voxelFile);
	CloseHandle(m_hVoxelMap);
	CloseHandle(m_hVoxelFile);

	UnmapViewOfFile(m_photonVoxelFile);
	CloseHandle(m_hPhotonVoxelMap);
	CloseHandle(m_hPhotonVoxelFile);
	delete[] m_in;
	delete[] m_out;
	delete[] m_requestCountList;

	CloseHandle(m_hQNotEmpty);
	CloseHandle(m_hEnoughMem);
}

int OOCVoxelManager::allocMem(int count)
{
	int offset = -1;
	m_lockMem.lock();

	/*
	printf("before alloc: ");
	for(std::set<FreeMem, FreeMemCountLess>::iterator it=m_freeMem.begin();it!=m_freeMem.end();it++)
	{
		printf("(%d, %d) ", it->offset, it->count);
	}
	printf("\n");
	*/

	for(std::set<FreeMem, FreeMemCountLess>::iterator it=m_freeMem.begin();it!=m_freeMem.end();it++)
	{
		if(it->count >= count)
		{
			offset = it->offset;
			if(it->count > count)
				m_freeMem.insert(FreeMem(it->offset+count, it->count - count));
			m_freeMem.erase(it);
			break;
		}
	}

	/*
	if(offset >= 0)
	{
		printf("alloc (%d, %d)\n", offset, count);
		printf("after alloc: ");
		for(std::set<FreeMem, FreeMemCountLess>::iterator it=m_freeMem.begin();it!=m_freeMem.end();it++)
		{
			printf("(%d, %d) ", it->offset, it->count);
		}
		printf("\n");
	}
	else
		printf("not enough memory\n");
	*/

	m_lockMem.unlock();

	if(offset < 0 && packMem())
		offset = allocMem(count);

	return offset;
}

void OOCVoxelManager::freeMem(int offset, int count)
{
	m_lockMem.lock();
	m_freeMem.insert(FreeMem(offset, count));
	m_lockMem.unlock();
}

bool OOCVoxelManager::packMem()
{
	bool packed = false;
	std::vector<FreeMem> list;

	m_lockMem.lock();
	for(std::set<FreeMem, FreeMemCountLess>::iterator it=m_freeMem.begin();it!=m_freeMem.end();it++)
		list.push_back(*it);
	std::sort(list.begin(), list.end(), FreeMemOffsetLess());
	for(int i=0;i<(int)list.size()-1;i++)
	{
		if(list[i].offset + list[i].count == list[i+1].offset)
		{
			list[i+1].offset = list[i].offset;
			list[i+1].count += list[i].count;
			list[i].count = 0;
			packed = true;
		}
	}
	m_freeMem.clear();
	for(int i=0;i<(int)list.size();i++)
	{
		if(list[i].count > 0)
			m_freeMem.insert(list[i]);
	}

	m_lockMem.unlock();
	return packed;
}

Vector3 g_camPos;
std::vector<OOCVoxelManager::OOCVoxel> *g_oocVoxelList = NULL;
float *g_requestCountList = NULL;
extern "C" void loadVoxelsAPI(int count, const CUDA::Voxel *voxels, int oocVoxelIdx, int offset, int ttt);
extern "C" void loadPhotonVoxelsAPI(int count, const CUDA::PhotonVoxel *voxels, int oocVoxelIdx, int offset);
extern "C" int tracePhotonsAPI();
extern "C" int tracePhotonsToOOCVoxelAPI(int oocVoxelIdx);
unsigned __stdcall OOCVoxelManager::loadingThread(void* arg)
{
#	ifndef USE_OOCVOXEL
	return 0;
#	endif
	OOCVoxelManager *m = (OOCVoxelManager*)arg;
	while(!m->m_exit)
	{
		WaitForSingleObject(m->m_hQNotEmpty, INFINITE);
		if(m->m_exit) break;

#		if VOXEL_PRIORITY_POLICY == 1
		if(!g_oocVoxelList)
#		endif
#		if VOXEL_PRIORITY_POLICY == 2
		if(!g_requestCountList)
#		endif
		{
			Sleep(10);
			continue;
		}

		int voxel;
		m->m_lockQNeeded.lock();
		if(m->m_voxelNeeded.empty())
		{
			m->m_lockQNeeded.unlock();
			continue;
		}
		voxel = m->m_voxelNeeded.front();
		m->m_lockQNeeded.unlock();

		//printf("Loading... %d\n", voxel);

		int gpuOffset = -1;
		const OOCVoxel &oocVoxel = m->m_oocVoxelList[voxel];
		int fileOffset = oocVoxel.offset;
		int numVoxels = oocVoxel.numVoxels;
		m->m_lockSet.lock();
		bool isIn = m->m_activeVoxels.find(voxel) != m->m_activeVoxels.end();
		m->m_lockSet.unlock();
		if(!isIn)
		{
			//while((gpuOffset = m->allocMem(numVoxels)) < 0)
			while(!m->m_exit)
			{
				m->m_lockSet.lock();
				//printf("alloc for voxel[%d] with %d\n", voxel, numVoxels);
				gpuOffset = m->allocMem(numVoxels);
				if(gpuOffset >= 0)
				{
					m->m_activeVoxels[voxel] = gpuOffset;
					//printf("<- %d\n", voxel);
					m->m_lockSet.unlock();
					break;
				}
				//printf("failed wait...removeing...");

				ResetEvent(m->m_hEnoughMem);
				// if requested voxel has lower priority than all active voxels then ignore the request
				if(VOXEL_COMPARE()(m->m_activeVoxels.rbegin()->first, voxel))
				{
					m->m_lockQNeeded.lock();
					m->m_voxelNeeded.clear();
					ResetEvent(m->m_hQNotEmpty);
					m->m_lockQNeeded.unlock();
					m->m_lockSet.unlock();

					//tracePhotonsAPI();
					goto END_OF_LOOP;
				}
				m->m_lockQOut.lock();
				int targetSpace = m->m_allowedMem / 10;
				for(ActiveVoxelMap::reverse_iterator it=m->m_activeVoxels.rbegin();it!=m->m_activeVoxels.rend();it++)
				{
					const OOCVoxel &voxel = m->m_oocVoxelList[it->first];

					bool isIn = false;
					for(int i=0;i<m->m_voxelOut.size();i++)
					{
						//printf("[%d, %d] ", it->first, m->m_voxelOut[i].voxel);
						if(m->m_voxelOut[i].voxel == it->first)
						{
							isIn = true;
							break;
						}
					}
					if(!isIn) m->m_voxelOut.push_back(VoxelOutElem(it->first, voxel.rootChildIndex, it->second, voxel.numVoxels));

					targetSpace -= voxel.numVoxels * sizeof(Voxel);

					//printf("(%d) ", it->first);

					if(targetSpace < 0) break;
				}
				//printf("\n");
				m->m_lockQOut.unlock();
				m->m_lockSet.unlock();
				WaitForSingleObject(m->m_hEnoughMem, INFINITE);
				if(m->m_exit) break;
			}

			//m->m_lockSet.lock();
			//m->m_activeVoxels[voxel] = gpuOffset;
			//m->m_lockSet.unlock();
		}

		m->m_lockQNeeded.lock();
		if(!m->m_voxelNeeded.empty())
			m->m_voxelNeeded.pop_front();
		m->m_lockQNeeded.unlock();

		if(gpuOffset >= 0)
		{
			Voxel *tempVoxels = new Voxel[numVoxels];
			//memcpy(tempVoxels, &m->m_voxelFile[fileOffset], sizeof(Voxel)*numVoxels);
			for(int i=0;i<numVoxels;i++)
			{
				Voxel &voxel = tempVoxels[i];
				voxel = m->m_voxelFile[fileOffset+i];
				if(voxel.hasChild())
					voxel.setChildIndex(voxel.getChildIndex() + (m->m_oriNumVoxels + gpuOffset)/8);
			}
			//loadVoxelsAPI(numVoxels, (CUDA::Voxel*)&m->m_voxelFile[fileOffset], gpuOffset);
			loadVoxelsAPI(numVoxels, (CUDA::Voxel*)tempVoxels, voxel, gpuOffset, oocVoxel.rootChildIndex);
			loadPhotonVoxelsAPI(numVoxels, (CUDA::PhotonVoxel*)&(m->m_photonVoxelFile[fileOffset]), voxel, gpuOffset);
			//tracePhotonsToOOCVoxelAPI(voxel);
			//printf("<- %d\n", voxel);
			delete[] tempVoxels;
			m->m_lockQLoaded.lock();
			m->m_voxelLoaded.push_back(VoxelLoadedElem(oocVoxel.rootChildIndex, gpuOffset));
			m->m_lockQLoaded.unlock();
		}

END_OF_LOOP:
		if(m->m_voxelNeeded.empty())
			if(!m->m_exit) ResetEvent(m->m_hQNotEmpty);

	}
	_endthreadex(0);
	return 0;
}

void OOCVoxelManager::moveCamera(Camera &camera)
{
	static bool s_moving = false;
	if(!m_enabled)
	{
		//printf("disabled\n");
		return;
	}
	if(s_moving)
	{
		//printf("moving\n");
		return;
	}

	static Vector3 prevPos;
	const Vector3 &pos = camera.getEye();
	if(m_exit || pos == prevPos)
	{
		//if(m_exit) printf("exit\n");
		//if(pos == prevPos) printf("same pos\n");
		return;
	}

	s_moving = true;
	prevPos = pos;

	m_lockQNeeded.lock();
	m_voxelNeeded.clear();
	ResetEvent(m_hQNotEmpty);
	m_lockQNeeded.unlock();

	int numOOCVoxels = (int)m_oocVoxelList.size();

	std::vector<int> voxelDistList;
	for(int i=0;i<numOOCVoxels;i++)
		voxelDistList.push_back(i);

	// sort voxels w.r.t distance from camera position
	g_camPos = pos;
	g_oocVoxelList = &m_oocVoxelList;
	std::sort(voxelDistList.begin(), voxelDistList.end(), VoxelDistLess());

	m_lockSet.lock();

	// rearrange sorted map
	std::vector<std::pair<int, int> > tempList;
	for(ActiveVoxelMap::iterator it=m_activeVoxels.begin();it!=m_activeVoxels.end();it++)
		tempList.push_back(*it);

	m_activeVoxels.clear();
	for(int i=0;i<(int)tempList.size();i++)
		m_activeVoxels[tempList[i].first] = tempList[i].second;

#	if 0
	printf("ActiveVoxels = ");
	int usedMem = 0;
	for(ActiveVoxelMap::iterator it=m_activeVoxels.begin();it!=m_activeVoxels.end();it++)
	{
		printf("%d ", it->first);
		usedMem += m_oocVoxelList[it->first].numVoxels * 32;
	}
	printf("\n");
	printf("%d bytes used\n", usedMem);
	int freeMem = 0;
	for(std::set<FreeMem, FreeMemCountLess>::iterator it=m_freeMem.begin();it!=m_freeMem.end();it++)
	{
		freeMem += it->count*32;
	}
	printf("%d/%d bytes available\n", freeMem, m_allowedMem);
	if(usedMem + freeMem != m_allowedMem)
	{
		printf("Memory Error! %d != %d\n", usedMem + freeMem, m_allowedMem);
		/*
		printf("free mem: ");
		for(std::set<FreeMem, FreeMemCountLess>::iterator it=m_freeMem.begin();it!=m_freeMem.end();it++)
		{
			printf("(%d, %d) ", it->offset, it->count);
		}
		printf("\n ActiveVoxels: ");
		for(ActiveVoxelMap::iterator it=m_activeVoxels.begin();it!=m_activeVoxels.end();it++)
		{
			printf("(%d, %d) ", m_oocVoxelList[it->first].offset, m_oocVoxelList[it->first].numVoxels);
		}
		printf("\n");
		*/
		//exit(1);
	}
#	endif

	//printf("NeededVoxels = ");
	float diag = m_thresholdSize.length();
	int scrWidth = OpenIRT::getSingletonPtr()->getRenderer()->getWidth();
	float ratio = (camera.getScaledRight().length() / scrWidth) / camera.getZNear();
	for(int i=0;i<numOOCVoxels;i++)
	{
		int voxelIdx = voxelDistList[i];
		const OOCVoxel &voxel = m_oocVoxelList[voxelIdx];

		float dist = (0.5f*(voxel.rootBB.min + voxel.rootBB.max) - pos).length() - (0.5f*(voxel.rootBB.max - voxel.rootBB.min)).length();

		if(dist > 0 && ratio > diag / dist)
			break;

		if(m_activeVoxels.find(voxelIdx) == m_activeVoxels.end())
		{
			m_lockQNeeded.lock();
			m_voxelNeeded.push_back(voxelIdx);
			//printf("%d ", voxelIdx);
			m_lockQNeeded.unlock();
			SetEvent(m_hQNotEmpty);
		}
	}
	//printf("++\n");
	m_lockSet.unlock();

	s_moving = false;
}

void OOCVoxelManager::updateVoxelList()
{
	m_lockQNeeded.lock();
	m_voxelNeeded.clear();
	ResetEvent(m_hQNotEmpty);
	m_lockQNeeded.unlock();

	int numOOCVoxels = (int)m_oocVoxelList.size();

	/*
	printf("------------------------------------------------\n");
	for(int i=0;i<numOOCVoxels;i++)
	{
		if(m_requestCountList[i] >= 1.0f)
			printf("[%d] %f, ", i, m_requestCountList[i]);
	}
	printf("\n================================================\n");
	*/

	std::vector<int> voxelRequestCountList;
	for(int i=0;i<numOOCVoxels;i++)
		voxelRequestCountList.push_back(i);

	// sort voxels w.r.t request count from GPU
	g_requestCountList = m_requestCountList;
	std::sort(voxelRequestCountList.begin(), voxelRequestCountList.end(), VoxelRequestedGreater());

	m_lockSet.lock();

	// rearrange sorted map
	std::vector<std::pair<int, int> > tempList;
	for(ActiveVoxelMap::iterator it=m_activeVoxels.begin();it!=m_activeVoxels.end();it++)
		tempList.push_back(*it);

	m_activeVoxels.clear();
	for(int i=0;i<(int)tempList.size();i++)
		m_activeVoxels[tempList[i].first] = tempList[i].second;

	/*
	printf("ActiveVoxels = ");
	int usedMem = 0;
	for(ActiveVoxelMap::iterator it=m_activeVoxels.begin();it!=m_activeVoxels.end();it++)
	{
		printf("%d ", it->first);
		usedMem += m_oocVoxelList[it->first].numVoxels * 32;
	}
	printf("\n");
	printf("%d bytes used\n", usedMem);
	int freeMem = 0;
	for(std::set<FreeMem, FreeMemCountLess>::iterator it=m_freeMem.begin();it!=m_freeMem.end();it++)
	{
		freeMem += it->count*32;
	}
	printf("%d/%d bytes available\n", freeMem, m_allowedMem);
	if(usedMem + freeMem != m_allowedMem)
	{
		printf("Memory Error! %d != %d\n", usedMem + freeMem, m_allowedMem);
		exit(1);
	}
	*/

	//printf("NeededVoxels = ");
	for(int i=0;i<numOOCVoxels;i++)
	{
		int voxelIdx = voxelRequestCountList[i];
		const OOCVoxel &voxel = m_oocVoxelList[voxelIdx];

		if(m_requestCountList[voxelIdx] < 1.0f)
			break;

		if(m_activeVoxels.find(voxelIdx) == m_activeVoxels.end())
		{
			m_lockQNeeded.lock();
			m_voxelNeeded.push_back(voxelIdx);
			//printf("%d ", voxelIdx);
			m_lockQNeeded.unlock();
			SetEvent(m_hQNotEmpty);
		}
	}
	//printf("++\n");
	m_lockSet.unlock();
}

/*
int g_ttt = 0;
float g_fff = 0;
FILE *g_fpfp = 0;
*/
extern "C" void OnVoxelChangedAPI(int numIn, int *in, int numOut, int *out);
void OOCVoxelManager::update()
{
	if(!m_enabled) return;
	if(m_exit) return;

	m_lockQLoaded.lock();
	int numIn = (int)m_voxelLoaded.size();
	for(int i=0;i<numIn;i++)
	{
		const VoxelLoadedElem &e = m_voxelLoaded.front();
		m_in[i*2+0] = e.rootIndex;
		m_in[i*2+1] = e.gpuOffset;
		m_voxelLoaded.pop_front();
	}
	m_lockQLoaded.unlock();

	m_lockQOut.lock();
	int numOut = (int)m_voxelOut.size();
	for(int i=0;i<numOut;i++)
	{
		const VoxelOutElem &e = m_voxelOut.front();
		m_out[i*2+0] = e.rootIndex;
		m_out[i*2+1] = e.gpuOffset;
		m_out[2*numOut+i*2+0] = e.voxel;
		m_out[2*numOut+i*2+1] = e.numVoxels;
		m_voxelOut.pop_front();
	}
	m_lockQOut.unlock();

	/*
	int timer = StopWatch::create();
	StopWatch::get(timer).start();
	*/

	OnVoxelChangedAPI(numIn, m_in, numOut, m_out);

	/*
	StopWatch::get(timer).stop();
	g_fff += StopWatch::get(timer).getTime();
	g_ttt += numIn;
	if(numIn > 0)
	{
		printf("numin = %d, update time = %f ms, summed[%d] = %f ms\n", numIn, StopWatch::get(timer).getTime(), g_ttt, g_fff);
		fprintf_s(g_fpfp, "%d %f\n", numIn, StopWatch::get(timer).getTime());
		fflush(g_fpfp);
	}
	StopWatch::destroy(timer);
	*/

	m_lockSet.lock();
	for(int i=0;i<numOut;i++)
	{
		int voxel = m_out[2*numOut+i*2+0];
		int gpuOffset = m_out[i*2+1];
		int numVoxels = m_out[2*numOut+i*2+1];

		ActiveVoxelMap::iterator it = m_activeVoxels.find(voxel);
		if(it != m_activeVoxels.end())
		{
			if(gpuOffset != it->second)
			{
				printf("offset error! %d != %d\n", gpuOffset, it->second);
				exit(-1);
			}
			m_activeVoxels.erase(it);
			//printf("-> %d\n", voxel);
			freeMem(gpuOffset, numVoxels);
		}
		/*
		m_activeVoxels.erase(m_out[2*numOut+i*2+0]);
		//printf("-> %d\n", m_out[2*numOut+i*2+0]);
		freeMem(m_out[i*2+1], m_out[2*numOut+i*2+1]);
		*/
	}
	m_lockSet.unlock();

	if(numOut > 0) SetEvent(m_hEnoughMem);
}


text:
S2I builder images normally include [`assemble` and `run` scripts](https://docs.okd.io/latest/creating_images/s2i.html#s2i-scripts), but the default behavior of those scripts may not be suitable for all users. This topic covers a few approaches for customizing the behavior of an S2I builder that includes default scripts.

## Invoking scripts embedded in an image

Typically, builder images provide their own version of the [S2I scripts](builder_image.md#s2i-scripts) that cover the most common use-cases. If these scripts do not fulfill your needs, S2I provides a way of overriding them by adding custom ones in the `.s2i/bin` directory. However, by doing this you are [completely replacing the standard scripts](https://docs.okd.io/latest/creating_images/s2i.html#s2i-scripts). In some cases this is acceptable, but in other scenarios you may prefer to execute a few commands before (or after) the scripts while retaining the logic of the script provided in the image. In this case, it is possible to create a wrapper script that executes custom logic and delegates further work to the default script in the image.

To determine the location of the scripts inside of the builder image, look at the value of `io.openshift.s2i.scripts-url` label. Use `docker inspect`:

```console
$ docker inspect --format='{{ index .Config.Labels "io.openshift.s2i.scripts-url" }}' openshift/wildfly-100-centos7
image:///usr/libexec/s2i
```

You inspected the `openshift/wildfly-100-centos7` builder image and found out that the scripts are in the `/usr/libexec/s2i` directory.

With this knowledge, invoke any of these scripts from your own by wrapping its invocation.

Example of `.s2i/bin/assemble` script:
```bash
#!/bin/bash
echo "Before assembling"

/usr/libexec/s2i/assemble
rc=$?

if [ $rc -eq 0 ]; then
    echo "After successful assembling"
else
    echo "After failed assembling"
fi

exit $rc
```

The example shows a custom `assemble` script that prints the message, executes standard `assemble` script from the image and prints another message depending on the exit code of the `assemble` script.

When wrapping the `run` script, you must [use `exec` for invoking it](https://docs.okd.io/latest/creating_images/guidelines.html#general-docker-guidelines) to ensure signals are handled properly. Unfortunately, the use of `exec` also precludes the ability to run additional commands after invoking the default image run script.

Example of `.s2i/bin/run` script:
```bash
#!/bin/bash
echo "Before running application"
exec /usr/libexec/s2i/run
```


text:
^ don't know -> know
be patient, resilient

---

## Failure
# is just getting from "draft" to "more finished"

^ forgive yourself the horrors of your early draft

---

## Failure
# developers maturity

^ confidence,
knowing it will be okay anyway

---

## Failure
# is often not as bad as we think

^ be a praiseworthy pilot
being prepared takes some of the sting out of it

---

# Evolution,
# not revolution

---

# Get better in small steps

^ easier to do
more sustainable
revise, repeat


text:
import com.sun.org.apache.xerces.internal.impl.xpath.regex.Match;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExtractHyperlinks {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        StringBuilder text = new StringBuilder();

        Pattern pattern = Pattern.compile("<a\\s+([^>]+)?href\\s*=\\s*('([^']*)'|(\"([^\"]*)\")|([^\\s>]+))");

        String line = scanner.nextLine();

        while (!line.equals("END")){
            text.append(line);

            line = scanner.nextLine();
        }

        Matcher matcher = pattern.matcher(text);

        while (matcher.find()){
            for (int i = 5; i >= 0 ; i--) {
                String result = matcher.group(i);
                if (result != null){
                    System.out.println(result);
                    break;
                }
            }
        }
    }
}


text:
#include "config.h"
#include "core/dom/shadow/DistributedNodes.h"

#include "core/dom/shadow/InsertionPoint.h"

namespace blink {

void DistributedNodes::swap(DistributedNodes& other)
{
    m_nodes.swap(other.m_nodes);
    m_indices.swap(other.m_indices);
}

void DistributedNodes::append(PassRefPtrWillBeRawPtr<Node> node)
{
    ASSERT(node);
    ASSERT(!isActiveInsertionPoint(*node));
    size_t size = m_nodes.size();
    m_indices.set(node.get(), size);
    m_nodes.append(node);
}

size_t DistributedNodes::find(const Node* node) const
{
    WillBeHeapHashMap<RawPtrWillBeMember<const Node>, size_t>::const_iterator it = m_indices.find(node);
    if (it == m_indices.end())
        return kNotFound;

    return it.get()->value;
}

Node* DistributedNodes::nextTo(const Node* node) const
{
    size_t index = find(node);
    if (index == kNotFound || index + 1 == size())
        return 0;
    return at(index + 1).get();
}

Node* DistributedNodes::previousTo(const Node* node) const
{
    size_t index = find(node);
    if (index == kNotFound || !index)
        return 0;
    return at(index - 1).get();
}

DEFINE_TRACE(DistributedNodes)
{
#if ENABLE(OILPAN)
    visitor->trace(m_nodes);
    visitor->trace(m_indices);
#endif
}

} // namespace blink


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.SiteRecovery.Models;

namespace Microsoft.WindowsAzure.Management.SiteRecovery.Models
{
    /// <summary>
    /// The response model for the list Vm Group operation.
    /// </summary>
    public partial class VirtualMachineGroupListResponse : OperationResponse, IEnumerable<VirtualMachineGroup>
    {
        private IList<VirtualMachineGroup> _vmGroups;

        /// <summary>
        /// Optional. The list of Vm groups under given protection Container.
        /// </summary>
        public IList<VirtualMachineGroup> VmGroups
        {
            get { return this._vmGroups; }
            set { this._vmGroups = value; }
        }

        /// <summary>
        /// Initializes a new instance of the VirtualMachineGroupListResponse
        /// class.
        /// </summary>
        public VirtualMachineGroupListResponse()
        {
            this.VmGroups = new LazyList<VirtualMachineGroup>();
        }

        /// <summary>
        /// Gets the sequence of VmGroups.
        /// </summary>
        public IEnumerator<VirtualMachineGroup> GetEnumerator()
        {
            return this.VmGroups.GetEnumerator();
        }

        /// <summary>
        /// Gets the sequence of VmGroups.
        /// </summary>
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
}


text:
package com.google.errorprone.refaster.testdata;

/**
 * Test data for {@code VariableDeclTemplate}.
 *
 * @author lowasser@google.com (Louis Wasserman)
 */
public class VariableDeclTemplateExample {
  @SuppressWarnings("unused")
  public void example() {
    int a = Integer.parseInt("3");
    Integer b = Integer.valueOf("3");
    final int c = Integer.parseInt("3");
  }
}


text:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Cargo } from '../../models/cargo';
import { HttpHelper } from "../../http/http-helper/http.helper";
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class CargoListService {

    // Injecting the http client into the service
    constructor(private http: Http, private routerHelper: HttpHelper) { }

    private getServiceURL() : string {
      return this.routerHelper.getHaulierBookingUrl();
    }

    // Method retrieve all the cargos
    getCargos(): Observable<Cargo[]> {
        return this.http.get(this.getServiceURL())
            .map(this.parseData)
            .catch(this.handleError);
    }

    // Method confirm the haulier booking
    confirmHaulierBooking(bookingId: string): Observable<Cargo> {
        return this.http.post(`${this.getServiceURL()}/${bookingId}/confirm`, {})
            .map((response: Response) => <Cargo>response.json())
            .catch(this.handleError);
    }

    // Method decline the haulier booking
    declineHaulierBooking(bookingId: string): Observable<Cargo> {
        return this.http.post(`${this.getServiceURL()}/${bookingId}/reject`, {})
            .map((response: Response) => <Cargo>response.json())
            .catch(this.handleError);
    }

    // Method for picked up cargo
    pickedUpCargo(bookingId: string): Observable<Cargo> {
        return this.http.post(`${this.getServiceURL()}/${bookingId}/pickedup`, {})
            .map((response: Response) => <Cargo>response.json())
            .catch(this.handleError);
    }

    // Method for picked up cargo
    deliveredCargo(bookingId: string): Observable<Cargo> {
        return this.http.post(`${this.getServiceURL()}/${bookingId}/delivered`, {})
            .map((response: Response) => <Cargo>response.json())
            .catch(this.handleError);
    }

    // This method parses the data to JSON
    private parseData(res: Response) {
        return res.json() || [];
    }

    // Displays the error message
    private handleError(error: Response | any) {
        let errorMessage: string;

        errorMessage = error.message ? error.message : error.toString();

        // This returns another Observable for the observer to subscribe to
        return Observable.throw(errorMessage);
    }
}


text:
package logging

import (
	"encoding/json"
	"io/ioutil"
	"log/syslog"
	"os"

	"github.com/Shopify/sarama"
	"github.com/mailgun/kafka-pixy/config"
	"github.com/pkg/errors"
	"github.com/samuel/go-zookeeper/zk"
	log "github.com/sirupsen/logrus"
	syslogrus "github.com/sirupsen/logrus/hooks/syslog"
)

// Init initializes sirupsen/logrus hooks from the JSON config string. It also
// sets the sirupsen/logrus as a logger for 3rd party libraries.
func Init(jsonCfg string, cfg *config.App) error {
	var formatter log.Formatter
	var loggingCfg []config.LoggerCfg

	if len(jsonCfg) != 0 {
		if err := json.Unmarshal([]byte(jsonCfg), &loggingCfg); err != nil {
			return errors.Wrap(err, "failed to parse logger config")
		}
	}

	// Prefer the command line logging config over the config file
	if loggingCfg == nil {
		loggingCfg = cfg.Logging
	}

	// Default to plain text formatter
	formatter = &textFormatter{}
	log.SetFormatter(formatter)
	log.StandardLogger().Out = ioutil.Discard

	var hooks []log.Hook
	for _, loggerCfg := range loggingCfg {
		switch loggerCfg.Name {
		case "console":
			log.StandardLogger().Out = os.Stdout
		case "syslog":
			h, err := syslogrus.NewSyslogHook("udp", "127.0.0.1:514", syslog.LOG_INFO|syslog.LOG_MAIL, "kafka-pixy")
			if err != nil {
				continue
			}
			hooks = append(hooks, newLevelFilter(h, loggerCfg.Level()))
		case "json":
			formatter = newJSONFormatter()
			log.SetFormatter(formatter)
			log.StandardLogger().Out = os.Stdout
		}
	}

	// samuel/go-zookeeper/zk is using the standard logger.
	zk.DefaultLogger = log.WithField("category", "zk")

	// Shopify/sarama formatter removes trailing `\n` from log entries
	saramaLogger := log.New()
	saramaLogger.Out = log.StandardLogger().Out
	saramaLogger.Formatter = &saramaFormatter{formatter}
	sarama.Logger = saramaLogger.WithField("category", "sarama")

	for _, hook := range hooks {
		saramaLogger.Hooks.Add(hook)
		log.StandardLogger().Hooks.Add(hook)
	}

	return nil
}

// saramaFormatter is a sirupsen/logrus formatter that strips trailing new
// lines from the log lines.
type saramaFormatter struct {
	parentFormatter log.Formatter
}

func (f *saramaFormatter) Format(entry *log.Entry) ([]byte, error) {
	lastByteIdx := len(entry.Message) - 1
	if lastByteIdx >= 0 && entry.Message[lastByteIdx] == '\n' {
		entry.Message = entry.Message[:lastByteIdx]
	}
	return f.parentFormatter.Format(entry)
}


text:
define(function () {
    function PhoneNumberValidator(fieldName) {
        var digitRegex = /^\d{1,10}$/;
        this.validate = function (value) {
            if (digitRegex.test(value)) {
                return null;
            } else {
                return fieldName +
                    " must contain only digits and cannot exceed 10 digits.";
            }
        };

        this.rulesAsString = function () {
            return "Only digits and must not exceed 10 digits.";
        };
    }

    return PhoneNumberValidator;
});


text:
define(["exports"], function (exports) {
  "use strict";

  var test = exports.test = 2;
  test = exports.test = 5;
  test = exports.test += 1;

  (function () {
    var test = 2;
    test = 3;
    test++;
  })();
  Object.defineProperty(exports, "__esModule", {
    value: true
  });
});


text:
The ssl.match_hostname() function from Python 3.5
=================================================

The Secure Sockets Layer is only actually *secure*
if you check the hostname in the certificate returned
by the server to which you are connecting,
and verify that it matches to hostname
that you are trying to reach.

But the matching logic, defined in `RFC2818`_,
can be a bit tricky to implement on your own.
So the ``ssl`` package in the Standard Library of Python 3.2
and greater now includes a ``match_hostname()`` function
for performing this check instead of requiring every application
to implement the check separately.

This backport brings ``match_hostname()`` to users
of earlier versions of Python.
Simply make this distribution a dependency of your package,
and then use it like this::

    from backports.ssl_match_hostname import match_hostname, CertificateError
    [...]
    sslsock = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_SSLv23,
                              cert_reqs=ssl.CERT_REQUIRED, ca_certs=...)
    try:
        match_hostname(sslsock.getpeercert(), hostname)
    except CertificateError, ce:
        ...

Brandon Craig Rhodes is merely the packager of this distribution;
the actual code inside comes from Python 3.5 with small changes for
portability.

Requirements
------------

* If you want to verify hosts match with certificates via ServerAltname
  IPAddress fields, you need to install the `ipaddress module`_.
  backports.ssl_match_hostname will continue to work without ipaddress but
  will only be able to handle ServerAltName DNSName fields, not IPAddress.
  System packagers (Linux distributions, et al) are encouraged to add
  this as a hard dependency in their packages.

* If you need to use this on Python versions earlier than 2.6 you will need to
  install the `ssl module`_.  From Python 2.6 upwards ``ssl`` is included in
  the Python Standard Library so you do not need to install it separately.

.. _`ipaddress module`:: https://pypi.python.org/pypi/ipaddress
.. _`ssl module`:: https://pypi.python.org/pypi/ssl

History
-------

* This function was introduced in python-3.2
* It was updated for python-3.4a1 for a CVE
  (backports-ssl_match_hostname-3.4.0.1)
* It was updated from RFC2818 to RFC 6125 compliance in order to fix another
  security flaw for python-3.3.3 and python-3.4a5
  (backports-ssl_match_hostname-3.4.0.2)
* It was updated in python-3.5 to handle IPAddresses in ServerAltName fields
  (something that backports.ssl_match_hostname will do if you also install the
  ipaddress library from pypi).

.. _RFC2818: http://tools.ietf.org/html/rfc2818.html


text:
<?php

declare(strict_types=1);

namespace OpenTelemetry\Example\Unit\SDK\Common\Configuration\Resolver;

use OpenTelemetry\SDK\Common\Configuration\Resolver\PhpIniAccessor;
use OpenTelemetry\SDK\Common\Configuration\Resolver\PhpIniResolver;
use PHPUnit\Framework\TestCase;

/**
 * @covers \OpenTelemetry\SDK\Common\Configuration\Resolver\PhpIniResolver
 * @psalm-suppress UndefinedMethod
 */
class PhpIniResolverTest extends TestCase
{
    private PhpIniAccessor $accessor;
    private PhpIniResolver $resolver;

    public function setUp(): void
    {
        $this->accessor = $this->createMock(PhpIniAccessor::class);
        $this->resolver = new PhpIniResolver($this->accessor);
    }

    public function test_retrieve_array(): void
    {
        $this->accessor->expects($this->once())->method('get')->willReturn(['foo', 'bar', 'baz']);
        $this->assertSame('foo,bar,baz', $this->resolver->retrieveValue('OTEL_FOO'));
    }

    public function test_retrieve_string(): void
    {
        $this->accessor->expects($this->once())->method('get')->willReturn('foo');
        $this->assertSame('foo', $this->resolver->retrieveValue('OTEL_FOO'));
    }

    /**
     * @dataProvider hasVariableProvider
     */
    public function test_has_variable($value, bool $expected): void
    {
        $this->accessor->method('get')->willReturn($value);
        $this->assertSame($expected, $this->resolver->hasVariable('OTEL_FOO'));
    }

    public function hasVariableProvider(): array
    {
        return [
            'string' => ['foo', true],
            'array' => [['foo'], true],
            'empty string' => ['', false],
            'null' => [null, false],
            'empty array' => [[], false],
        ];
    }
}


text:
package io.github.davepkennedy.bark

import java.util.concurrent.TimeUnit

import akka.actor.{Actor, Props, ActorRef, ActorSystem}
import io.github.davepkennedy.bark.state._
import io.github.davepkennedy.bark.ui.{Displayable, Display}
import org.apache.log4j.BasicConfigurator

import scala.concurrent.Await
import scala.concurrent.duration.{Duration, FiniteDuration}
import scala.util.Random

object BarkStateManager {
  def props(id: Int, display: ActorRef) = Props(classOf[BarkStateManager], id, display)

  case class Bootstrap (peers: Map[Int,ActorRef])
}

class BarkStateManager (val id: Int, display: ActorRef) extends Candidate with Follower with Leader with Displayable with SystemTime {
  import BarkStateManager._
  import context._

  override def display(id: Int,
                       name: String,
                       leader: Boolean,
                       currentTerm: Int,
                       commitIndex: Int,
                       votedFor: Option[Int],
                       votes: Int, heartbeat: Long): Unit = {
    display ! Display.PeerState (id, name, leader, currentTerm, commitIndex, votedFor, votes, heartbeat)
  }

  override def shouldRetire: Boolean = chance(1)

  startWith(BootState, FollowerData (now))

  when (BootState) {
    case Event (Bootstrap (peers), data: FollowerData) =>
      goto (FollowerState) using data.copy(peers = peers)
  }

  def scheduleTick (): Unit = {
    system.scheduler.scheduleOnce(randomInterval) {
      self ! Tick
      scheduleTick()
    }
  }

  scheduleTick()
}

object BarkApplication {
  val actorCount = 27
  val actorSystem = ActorSystem ("bark")

  def main (args: Array[String]): Unit = {
    BasicConfigurator.configure()

    val display = actorSystem.actorOf(Display.props)

    val peers = (for (i <- 0 until actorCount) yield (i -> actorSystem.actorOf(BarkStateManager.props(i, display), s"Actor-$i"))).toMap
    peers foreach {
      case (id, peer) => peer ! BarkStateManager.Bootstrap (peers)
    }

    Await.result(actorSystem.whenTerminated, Duration.Inf)
  }
}


text:
package org.dbflute.intro.app.logic.dfprop.schemapolicy;

import java.util.Arrays;
import java.util.List;

/**
 * The logic for definition of Schema Policy.

 * Subjectのリストなど、schemaPolicyMap.dfpropの定義を扱う。

 * schemaPolicyMap: http://dbflute.seasar.org/ja/manual/reference/dfprop/schemapolicy/index.html
 * @author jflute
 * @author prprmurakami
 * @since 0.5.0 split from DfpropSchemaPolicyReadLogic (2021/12/25 Saturday at urayasu)
 */
public class DfpropSchemaPolicyDefLogic {

    // ===================================================================================
    //                                                                        Subject List
    //                                                                        ============
    /**
     * if の主語 (of table) のリストを取得する。(e.g. tableName, alias, ...)

     * http://dbflute.seasar.org/ja/manual/reference/dfprop/schemapolicy/index.html#tablestatementifsubject
     * @return The read-only list of subject object. (NotNull, NotEmpty)
     */
    public List<TableMapSubject> getStatementTableMapSubjectList() {
        // Create subject list here because contents does not change frequently
        return Arrays.asList(TableMapSubject.values());
    }

    /**
     * if の主語 (of column) のリストを取得する。(e.g. columnName, dbType, ...)

     * http://dbflute.seasar.org/ja/manual/reference/dfprop/schemapolicy/index.html#columnstatementifsubject
     * @return The read-only list of subject object. (NotNull, NotEmpty)
     */
    public List<ColumnMapSubject> getStatementColumnMapSubjectList() {
        // Create subject list here because contents does not change frequently
        return Arrays.asList(ColumnMapSubject.values());
    }

    // 以下のページの内容と一致しており、項目が増えた場合は追加する。 by prprmurakami (2021/05/27)
    // http://dbflute.seasar.org/ja/manual/reference/dfprop/schemapolicy/index.html#tablestatement
    public enum TableMapSubject {
        TABLE_NAME("tableName"), //
        ALIAS("alias"), //
        FIRST_DATE("firstDate"), //
        PK_COLUMN_NAME("pk_columnName"), //
        PK_DB_TYPE("pk_dbType"), //
        PK_SIZE("pk_size"), //
        PK_DB_TYPE_WITH_SIZE("pk_dbType_with_size"); //

        private final String title;

        private TableMapSubject(String title) {
            this.title = title;
        }

        public String getTitle() {
            return title;
        }
    }

    // 以下のページの内容と一致しており、項目が増えた場合は追加する。 by prprmurakami (2021/05/27)
    // http://dbflute.seasar.org/ja/manual/reference/dfprop/schemapolicy/index.html#columnstatement
    public enum ColumnMapSubject {
        TABLE_NAME("tableName"), //
        ALIAS("alias"), //
        FIRST_DATE("firstDate"), //
        COLUMN("column"), //
        COLUMN_NAME("columnName"), //
        TABLE_COLUMN_NAME("tableColumnName"), //
        DB_TYPE_WITH_SIZE("dbType_with_size"), //
        SIZE("size"), //
        DB_TYPE("dbType");

        private final String title;

        private ColumnMapSubject(String title) {
            this.title = title;
        }

        public String getTitle() {
            return title;
        }
    }
}


text: My attempt at tackling http://cryptopals.com


text:
@echo off

rem
rem Extra installation script
rem
rem See CK LICENSE.txt for licensing details.
rem See CK Copyright.txt for copyright details.
rem
rem Developer(s): Grigori Fursin, 2016-2017
rem

set CK_CMAKE_EXTRA=%CK_CMAKE_EXTRA% ^
 -DBoost_ADDITIONAL_VERSIONS="1.62" ^
 -DBoost_NO_SYSTEM_PATHS=ON ^
 -DBOOST_ROOT="%CK_ENV_LIB_BOOST%" ^
 -DBOOST_INCLUDEDIR="%CK_ENV_LIB_BOOST_INCLUDE%" ^
 -DBOOST_LIBRARYDIR="%CK_ENV_LIB_BOOST_LIB%" ^
 -DBoost_INCLUDE_DIR="%CK_ENV_LIB_BOOST_INCLUDE%" ^
 -DBoost_LIBRARY_DIR="%CK_ENV_LIB_BOOST_LIB%" ^
 -DCMAKE_C_COMPILER="%CK_CC_PATH_FOR_CMAKE%" ^
 -DCMAKE_CXX_COMPILER="%CK_CXX_PATH_FOR_CMAKE%" ^
 -DCMAKE_C_FLAGS="%CK_CXX_FLAGS_FOR_CMAKE%" ^
 -DCMAKE_CXX_FLAGS="%CK_CXX_FLAGS_FOR_CMAKE%" ^
 -DOPENCL_ROOT="%CK_ENV_LIB_OPENCL%"

exit /b 0


text:
============
Uninstalling
============

While we'd always recommend using your automated deployment system to
reinstall systems from scratch, sometimes you do need to remove
OpenStack from a system the hard way. Here's how:

* Remove all packages.
* Remove remaining files.
* Remove databases.

These steps depend on your underlying distribution, but in general you
should be looking for :command:`purge` commands in your package manager, like
:command:`aptitude purge ~c $package`. Following this, you can look for
orphaned files in the directories referenced throughout this guide. To
uninstall the database properly, refer to the manual appropriate for the
product in use.


text:
/**
 * Basic interfaces API
 * @externs
 */

/**
 * @interface
 */
var _Comparable = function () {
};

/**
 * Object equality method.
 *
 * @param {Object} obj passed object.
 * @return {boolean} true - in case given object equals to current,
 *                   false - otherwise
 * @public
 */
_Comparable.prototype.equals = function (obj) {
};

/**
 * Comparing given object to the current one.
 *
 * @param {!Object} obj usually object of the same class current.
 * @return {number} 1 - in case passed object is bigger,
 *                  0 - if they are equal,
 *                  -1 - otherwise.
 * @throws {Error} may throw an error if object is not of the same class, or comparison is impossible.
 * @public
 */
_Comparable.prototype.compareTo = function (obj) {
};


text:
package thirdparty.fr.inria.optimization.cmaes;

import java.util.Properties;

/** Simple container of (mostly generic) options for the
 * optimization, like the maximum number of objective
 * function evaluations, see class fields.  No explicit setting of
 * options is needed to
 * initialize the CMA-ES ({@link CMAEvolutionStrategy#init()})
 * and options of the CMA-ES can be set
 * and changed any time, either via a property file and the method
 * {@link CMAEvolutionStrategy#readProperties()}, or new values can simply be
 * assigned to the fields of the public opts field of
 * the class CMAEvolutionStrategy (yeah, I know, not exactly Java style).
 *
 */
public class CMAOptions implements java.io.Serializable {
        // needs to be public to make sure that a using class can excess Options.
        // Therefore, if not nested, needs to move into a separate file

	private static final long serialVersionUID = 2255162105325585121L;

    /** number of initial iterations with diagonal covariance matrix, where
     * 1 means always. Default is
     * diagonalCovarianceMatrix=0, but this will presumably change in future.
     * As long as iterations<=diagonalCovarianceMatrix
     * the internal time complexity is linear in the search space dimensionality
     * (memory requirements remain quadratic).
     */
    public long diagonalCovarianceMatrix = 0; // -1;

	/** lower bound for standard deviations (step sizes). The
         * Array can be of any length. The i-th entry corresponds to
         * the i-th variable. If length<dim the last entry is recycled for
         * all remaining variables. Zero entries mean, naturally, no
         * lower bound.
CAVE: there is an interference with stopTolX (and stopTolXFactor):
         * if lowerStdDev is larger than stopTolX, the termination criterion
         * can never be satisfied.

         *
Example:
         *
 CMAEvolutionStrategy es = new CMAEvolutionStrategy();
         * es.options.lowerStandardDeviations = new double[]{1e-4,1e-8}; // 1e-8 for all but first variable
         *

         * @see #stopTolX
         * @see #stopTolXFactor
         * */
        public double[] lowerStandardDeviations;
        /** upper bound for standard deviations (step lengths).
         * Zero entries mean no upper
         * bound. Be aware of the interference with option stopTolUpXFactor.
         * @see #lowerStandardDeviations
         * @see #stopTolUpXFactor
         * */
        public double[] upperStandardDeviations;

        /** stop if function value drops below the target
         * function value stopFitness. Default = Double.MIN_VALUE */
        public double stopFitness = Double.MIN_VALUE;
        /** stop if the
         *  maximum function value difference of all iteration-best
         * solutions of the last 10 +
         * 30*N/lambda iterations
         * and all solutions of the recent iteration
         * become <= stopTolFun. Default = 1e-12.
         * */
        public double stopTolFun = 1e-12;
        /** stop if the maximum function value difference of all iteration-best
         * solutions of the last 10 +
         * 30*N/lambda iterations become smaller than
         * stopTolFunHist. Default = 1e-13. The measured objective
         * function value differences do not include repair
         * penalties. */
        public double stopTolFunHist = 1e-13; // used if non-null
        /** stop if search steps become smaller than stopTolX. Default = 0 */
        public double stopTolX = 0.0;
        /** stop if search steps become smaller than stopTolXFactor * initial step size.
         * Default = 1e-11. */
        public double stopTolXFactor = 1e-11; // used if TolX is null
        /** stop if search steps become larger than stopTolUpXFactor
         * * initial step size. Default = 1e3. When this termination
         * criterion applies on a static objective function, the initial
         * step-size was chosen far too
         * small (or divergent behavior is observed). */
        public double stopTolUpXFactor = 1e3; // multiplier for initial sigma
        /** stop if the number of objective function evaluations exceed stopMaxFunEvals */
        public long stopMaxFunEvals = Long.MAX_VALUE; // it is not straight forward to set a dimension dependent
        											  // default as the user can first set stopMaxFunEvals
        										      // and afterwards the dimension
        /** stop if the number of iterations (generations) exceed stopMaxIter */
        public long stopMaxIter = Long.MAX_VALUE;
        /** if true stopping message "Manual:..." is generated */
        public boolean stopnow = false;

        /** flag used by methods iterate(), whether to write output to files.
         * Methods write an output file if flgWriteFile>0.
         */

        /** determines whether CMA says hello after initialization.
         * @see CMAEvolutionStrategy#helloWorld()
         *  */
        public int verbosity = 1;
        /** Output files written will have the names outputFileNamesPrefix*.dat */
        public String outputFileNamesPrefix = "outcmaes";
        /** if chosen > 0 the console output from functions print... is saved
         * additionally into a file, by default <tt>outcmaesdisp.dat</tt> */
        public int writeDisplayToFile = 1;

        /** only for >= 1 results are always exactly reproducible, as otherwise the update of the
         * eigensystem is conducted depending on time measurements, defaut is 0.2 */
        public double maxTimeFractionForEigendecomposition = 0.2;
        /** default is 0.1
         */
        public double maxTimeFractionForWriteToDefaultFiles = 0.1;

        /** checks eigendecomposition mainly for debugging purpose, default is 0==no-check;
         * the function checkEigenSystem requires O(N^3) operations.
         */
        public int checkEigenSystem = 0;

        /** This is the only place where the reading of a new option needs to be declared
         *
         * @param properties
         */
        void setOptions(Properties properties) {
            String s;
            diagonalCovarianceMatrix = getFirstToken(properties.getProperty("diagonalCovarianceMatrix"), diagonalCovarianceMatrix);
            if((s = properties.getProperty("stopFitness")) != null)
                stopFitness = Double.valueOf(getFirstToken(s));
            stopTolFun = getFirstToken(properties.getProperty("stopTolFun"), stopTolFun);
            stopTolFunHist = getFirstToken(properties.getProperty("stopTolFunHist"), stopTolFunHist);
            stopTolX = getFirstToken(properties.getProperty("stopTolX"), stopTolX);
            stopTolXFactor = getFirstToken(properties.getProperty("stopTolXFactor"), stopTolXFactor);
            stopTolUpXFactor = getFirstToken(properties.getProperty("stopTolUpXFactor"), stopTolUpXFactor);
            stopMaxFunEvals = getFirstToken(properties.getProperty("stopMaxFunEvals"), stopMaxFunEvals);
            stopMaxIter = getFirstToken(properties.getProperty("stopMaxIter"), stopMaxIter);
            if ((s = properties.getProperty("upperStandardDeviations")) != null && !s.equals(""))
                upperStandardDeviations = parseDouble(getAllToken(s));
            if ((s = properties.getProperty("lowerStandardDeviations")) != null && !s.equals(""))
                lowerStandardDeviations = parseDouble(getAllToken(s));
            outputFileNamesPrefix = properties.getProperty("outputFileNamesPrefix", outputFileNamesPrefix).split("\\s")[0];
            maxTimeFractionForEigendecomposition =
                getFirstToken(properties.getProperty("maxTimeFractionForEigendecomposition"),
                        maxTimeFractionForEigendecomposition);
            maxTimeFractionForWriteToDefaultFiles =
                getFirstToken(properties.getProperty("maxTimeFractionForWriteToDefaultFiles"),
                        maxTimeFractionForWriteToDefaultFiles);
            stopnow = "now".equals(getFirstToken(properties.getProperty("stop")));
            writeDisplayToFile = getFirstToken(properties.getProperty("writeDisplayToFile"), writeDisplayToFile);
            checkEigenSystem = getFirstToken(properties.getProperty("checkEigenSystem"), checkEigenSystem);
        }

		/** Returns the double value of the first token of a string s or the default,
		 *  if the string is null or empty. This method should become generic with respect to the
		 *  type of second argument.
		 *  @param s string where the first token is read from
		 *  @param def double default value, in case the string is empty*/
		public Double getFirstToken(String s, Double def) {
		    if (s == null)
		        return def;
		    String[] ar = s.split("\\s+");
		    if (ar[0].equals(""))
		        return def;
		    return Double.valueOf(ar[0]);
		}

		/** should become generic with type argument?  */
		public String getFirstToken(String s) {
		    if (s == null)
		        return "";
		    String[] ar = s.split(new String("\\s+"));
		    return ar[0];
		}

		/** Returns the Integer value of the first token of a string s or the default,
		 *  if the string is null or empty. This method should become generic with respect to the
		 *  type of second argument.
		 *  @param s string where the first token is read from
		 *  @param def Integer default value, in case the string is empty*/
		public Integer getFirstToken(String s, Integer def) {
		    if (s == null)
		        return def;
		    String[] ar = s.split("\\s+");
		    if (ar[0].equals(""))
		        return def;
		    return Integer.valueOf(ar[0]);
		}

		//    public <T> T getFirstToken(String s, T def) {
		//        if (s == null)
		//            return def;
		//        String[] ar = s.split("\\s+");
		//        if (ar[0].equals(""))
		//            return def;
		//        return (T)(ar[0]); /* this fails */
		//    }

		    private String removeComments(String s) {
		        int i;
		        // remove trailing comments
		        i = s.indexOf("#");
		        if (i >= 0)
		            s = s.substring(0,i);
		        i = s.indexOf("!");
		        if (i >= 0)
		            s = s.substring(0,i);
		        i = s.indexOf("%");
		        if (i >= 0)
		            s = s.substring(0,i);
		        i = s.indexOf("//");
		        if (i >= 0)
		            s = s.substring(0,i);
		        return s;
		    }

		/** Returns def if s==null or empty, code dublicate, should become generic */
		private Long getFirstToken(String s, Long def) {
		    if (s == null)
		        return def;
		    String[] ar = removeComments(s).split("\\s+");
		    if (ar[0].equals(""))
		        return def;
		    return Long.valueOf(ar[0]);
		}

		String[] getAllToken(String s) {
		    // split w.r.t. white spaces regexp \s+
		    return removeComments(s).split("\\s+");
		}

		double[] parseDouble(String[] ars) {
		    double[] ard = new double[ars.length];
		    for(int i = 0; i < ars.length; ++i) {
		        ard[i] = Double.parseDouble(ars[i]);
		    }
		    return ard;
		}
    }