text:
/* Droppable */
+function($, window, document, Math)
{
    "use strict";

    var Droppable = function(element, options)
    {
        this.$         = $(element);
        this.options   = this.getOptions(options);

        this.init();
    };

    Droppable.DEFAULTS = {container: 'body', flex: false, deviation: 5, sensorOffsetX: 0, sensorOffsetY: 0, nested: false};

    Droppable.prototype.getOptions = function (options)
    {
        options = $.extend({}, Droppable.DEFAULTS, this.$.data(), options);
        return options;
    };

    Droppable.prototype.callEvent = function(name, params)
    {
        return $.callEvent(this.options[name], params, this);
    }

    Droppable.prototype.init = function()
    {
        this.handleMouseEvents();
    }

    Droppable.prototype.handleMouseEvents = function()
    {
        var $e      = this.$,
            self    = this,
            setting = this.options;

        this.$triggerTarget = (setting.trigger ? ($.isFunction(setting.trigger) ? setting.trigger($e) : $e.find(setting.trigger)).first() : $e);

        this.$triggerTarget.on('mousedown', function(event)
        {
            if(setting.hasOwnProperty('before') && $.isFunction(setting['before']))
            {
                var isSure = setting['before']({event: event, element: $e});
                if (isSure != undefined && (!isSure)) return;
            }

            var $targets         = $.isFunction(setting.target) ? setting.target($e): $(setting.target),
                target           = null,
                shadow           = null,
                $container       = $(setting.container).first(),
                isIn             = false,
                isSelf           = true,
                oldCssPosition,
                startOffset      = $e.offset(),
                startMouseOffset = {left: event.pageX, top: event.pageY};
            var containerOffset  = $container.offset();
            var startPosition    = {left: startOffset.left - containerOffset.left, top: startOffset.top - containerOffset.top};
            var clickOffset      = {left: startMouseOffset.left - startOffset.left, top: startMouseOffset.top - startOffset.top};
            var lastMouseOffset  = {left: startMouseOffset.left, top: startMouseOffset.top};

            $e.addClass('drag-from');
            $(document).bind('mousemove',mouseMove).bind('mouseup',mouseUp);
            event.preventDefault();

            function mouseMove(event)
            {
                var mouseOffset = {left: event.pageX, top: event.pageY};

                // ignore small move
                if(Math.abs(mouseOffset.left - startMouseOffset.left) < setting.deviation && Math.abs(mouseOffset.top - startMouseOffset.top) < setting.deviation ) return;

                if(shadow == null) // create shadow
                {
                    var cssPosition = $container.css('position');
                    if(cssPosition != 'absolute' && cssPosition != 'relative' && cssPosition != 'fixed')
                    {
                        oldCssPosition = cssPosition;
                        $container.css('position', 'relative');
                    }

                    shadow = $e.clone().removeClass('drag-from').addClass('drag-shadow').css(
                    {
                        position: 'absolute',
                        width: $e.outerWidth(),
                        transition: 'none'
                    }).appendTo($container);
                    $e.addClass('dragging');

                    self.callEvent('start', {event: event, element: $e});
                }

                var offset = {left: mouseOffset.left - clickOffset.left, top: mouseOffset.top - clickOffset.top};
                var position = {left: offset.left - containerOffset.left, top: offset.top - containerOffset.top};
                shadow.css(position);
                var moveOffset = {left: mouseOffset.left - lastMouseOffset.left, top: mouseOffset.top - lastMouseOffset.top};
                lastMouseOffset.left = mouseOffset.left;
                lastMouseOffset.top = mouseOffset.top;

                var isNew = false; isIn = false;

                if(!setting.flex)
                {
                    $targets.removeClass('drop-to');
                }

                var newTarget = null;
                $targets.each(function(index)
                {
                    var t = $(this);
                    var tPos = t.offset();
                    var tW = t.width(),
                        tH = t.height(),
                        tX = tPos.left + setting.sensorOffsetX,
                        tY = tPos.top + setting.sensorOffsetY;

                    if(mouseOffset.left > tX && mouseOffset.top > tY && mouseOffset.left < (tX + tW) && mouseOffset.top < (tY + tH))
                    {
                        if(newTarget) newTarget.removeClass('drop-to');
                        newTarget = t;
                        if(!setting.nested) return false;
                    }
                });

                if(newTarget)
                {
                    isIn = true;
                    var id = newTarget.data('id');
                    if($e.data('id') != id) isSelf = false;
                    if(target == null || (target.data('id') != id && (!isSelf))) isNew = true;
                    target = newTarget;
                    if(setting.flex)
                    {
                        $targets.removeClass('drop-to');
                    }
                    target.addClass('drop-to');
                }

                if(!setting.flex)
                {
                    $e.toggleClass('drop-in', isIn);
                    shadow.toggleClass('drop-in', isIn);
                }
                else if(target != null && target.length)
                {
                    isIn = true;
                }

                self.callEvent('drag',
                {
                    event: event,
                    isIn: isIn,
                    target: target,
                    element: $e,
                    isNew: isNew,
                    selfTarget: isSelf,
                    clickOffset: clickOffset,
                    offset: offset,
                    position: {left: offset.left - containerOffset.left, top: offset.top - containerOffset.top},
                    mouseOffset: mouseOffset
                });
            }

            function mouseUp(event)
            {
                if(oldCssPosition)
                {
                    $container.css('position', oldCssPosition);
                }

                if(shadow == null)
                {
                    $e.removeClass('drag-from');
                    $(document).unbind('mousemove', mouseMove).unbind('mouseup', mouseUp);
                    return;
                }

                if(!isIn) target = null;
                var isSure = true,
                    mouseOffset = {left: event.pageX, top: event.pageY};
                var offset = {left: mouseOffset.left - clickOffset.left, top: mouseOffset.top - clickOffset.top};
                var moveOffset = {left: mouseOffset.left - lastMouseOffset.left, top: mouseOffset.top - lastMouseOffset.top};
                lastMouseOffset.left = mouseOffset.left;
                lastMouseOffset.top = mouseOffset.top;
                var eventOptions =
                {
                    event: event,
                    isIn: isIn,
                    target: target,
                    element: $e,
                    isNew: (!isSelf) && target != null,
                    selfTarget: isSelf,
                    offset: offset,
                    mouseOffset: mouseOffset,
                    position: {left: offset.left - containerOffset.left, top: offset.top - containerOffset.top},
                    lastMouseOffset: lastMouseOffset,
                    moveOffset: moveOffset
                };

                isSure = self.callEvent('beforeDrop',eventOptions);

                if(isSure && isIn)
                {
                    self.callEvent('drop', eventOptions);
                }

                $(document).unbind('mousemove', mouseMove).unbind('mouseup', mouseUp);
                $targets.removeClass('drop-to');
                $e.removeClass('dragging').removeClass('drag-from');
                shadow.remove();

                self.callEvent('finish', eventOptions);

                event.preventDefault();
            }
        });

    };

    Droppable.prototype.reset = function()
    {
        this.$triggerTarget.off('mousedown');
        this.handleMouseEvents();
    };

    $.fn.droppable = function(option)
    {
        return this.each(function()
        {
            var $this   = $(this);
            var data    = $this.data('zui.droppable');
            var options = typeof option == 'object' && option;

            if (!data) $this.data('zui.droppable', (data = new Droppable(this, options)));

            if (typeof option == 'string') data[option]();
        })
    };

    $.fn.droppable.Constructor = Droppable;
}(jQuery,window,document,Math);


text:
package grogers.message.data;

import org.bson.types.ObjectId;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.code.morphia.annotations.Embedded;

/**
 * An embedded reference to a collection persisted bean.
 *
 * Contains id and name so that object reference can be presented
 * to users without the need to load the object itself. The type
 * of object is assumed to be know to the referencer by context.
 *
 */
@Embedded
public class NamedReference extends BaseBean {
    String name;

    public NamedReference() {
        super();
    }
    public NamedReference(NamedReference other) {
        super(other);
        this.name = other.name;
    }
    public NamedReference(ObjectId id, String name) {
        setId(id);
        setName(name);
    }
    public NamedReference(JSONObject json) throws JSONException {
        setId(new ObjectId(json.getString("id")));
        setName(json.getString("name"));
    }

    public NamedReference(UserBean user) {
        this(user.getId(), user.getLoginName());
    }
    public NamedReference(GroupBean group) {
        this(group.getId(), group.getName());
    }

    /** hash based on the hash of the id.
     */
    public int hashCode() {
        if (getId() != null) {
            return getId().toString().hashCode();
        }
        return super.hashCode();
    };

    /** References to the same object (by Id) are considered equal.
     */
    public boolean equals(Object obj) {
        if(obj instanceof NamedReference) {
            return getId() != null && getId().equals(((NamedReference) obj).getId());
        }
        return false;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public JSONObject toJson() throws JSONException {
        JSONObject json = super.toJson();
        json.put("name", getName());
        return json;
    }
    public void fromJson(JSONObject json) throws JSONException {
        super.fromJson(json);
        if (json.has("name")) {
            setName(json.getString("name"));
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
namespace System.Windows.Forms {

    using System.Diagnostics;

    /// <include file='doc\ErrorIconAlignment.uex' path='docs/doc[@for="ErrorIconAlignment"]/*' />
    /// <devdoc>
    ///     Describes the set of locations that an error icon can appear in
    ///     relation to the control with the error.
    /// </devdoc>
    public enum ErrorIconAlignment {

        /// <include file='doc\ErrorIconAlignment.uex' path='docs/doc[@for="ErrorIconAlignment.TopLeft"]/*' />
        /// <devdoc>
        ///     The icon appears aligned with the top of the control, and to
        ///     the left of the control.
        /// </devdoc>
        TopLeft,

        /// <include file='doc\ErrorIconAlignment.uex' path='docs/doc[@for="ErrorIconAlignment.TopRight"]/*' />
        /// <devdoc>
        ///     The icon appears aligned with the top of the control, and to
        ///     the right of the control.
        /// </devdoc>
        TopRight,

        /// <include file='doc\ErrorIconAlignment.uex' path='docs/doc[@for="ErrorIconAlignment.MiddleLeft"]/*' />
        /// <devdoc>
        ///     The icon appears aligned with the middle of the control, and
        ///     the left of the control.
        /// </devdoc>
        MiddleLeft,

        /// <include file='doc\ErrorIconAlignment.uex' path='docs/doc[@for="ErrorIconAlignment.MiddleRight"]/*' />
        /// <devdoc>
        ///     The icon appears aligned with the middle of the control, and
        ///     the right of the control.
        /// </devdoc>
        MiddleRight,

        /// <include file='doc\ErrorIconAlignment.uex' path='docs/doc[@for="ErrorIconAlignment.BottomLeft"]/*' />
        /// <devdoc>
        ///     The icon appears aligned with the bottom of the control, and
        ///     the left of the control.
        /// </devdoc>
        BottomLeft,

        /// <include file='doc\ErrorIconAlignment.uex' path='docs/doc[@for="ErrorIconAlignment.BottomRight"]/*' />
        /// <devdoc>
        ///     The icon appears aligned with the bottom of the control, and
        ///     the right of the control.
        /// </devdoc>
        BottomRight
    }

}


text:
from nose.tools import assert_equals, assert_raises, assert_in, assert_not_in
from nose.tools import assert_not_equals

from nettool.logging_facility import LoggingFacility

class TestLoggingFacility(object):

    def setup(self):
        self.log = LoggingFacility()
        self.invalid_values = (-1, 'super emergency')
        self.invalid_types = (True, list(), tuple())

    def test_initialization_default(self):
        assert_equals(self.log.level, None)
        assert_equals(self.log.name, 'none')

    def test_initialization(self):
        for index, name in enumerate(LoggingFacility._level_names):
            assert_equals(LoggingFacility(name).level, index)
        for index, name in enumerate(LoggingFacility._level_names):
            assert_equals(LoggingFacility(index).level, index)

    def test_level_invalid(self):
        for value in self.invalid_values:
            assert_raises(ValueError, setattr, self.log, 'level', value)
        for value in self.invalid_types:
            assert_raises(TypeError, setattr, self.log, 'level', value)

    def test_number_getter(self):
        for index, name in enumerate(LoggingFacility._level_names):
            assert_equals(LoggingFacility(name).number, index)

    def test_name_getter(self):
        for index, name in enumerate(LoggingFacility._level_names):
            assert_equals(LoggingFacility(index).name, name)

    def test_contains(self):
        log01 = LoggingFacility(2)
        log02 = LoggingFacility(7)
        assert_in(log01, log02)
        log01 = LoggingFacility(7)
        assert_in(log01, log02)
        assert_in(LoggingFacility(), LoggingFacility())

    def test_not_contains(self):
        log01 = LoggingFacility(2)
        log02 = LoggingFacility(7)
        assert_not_in(log02, log01)
        assert_not_in(LoggingFacility(), log01)

    def test_contains_invalid(self):
        for value in self.invalid_values:
            assert_raises(ValueError, self.log.__contains__, value)
        for value in self.invalid_types:
            assert_raises(TypeError, self.log.__contains__, value)

    def test_equality(self):
        assert_equals(LoggingFacility(2), LoggingFacility(2))
        assert_equals('critical', LoggingFacility(2))

    def test_equality_invalid(self):
        for value in self.invalid_values:
            assert_raises(ValueError, self.log.__eq__, value)
        for value in self.invalid_types:
            assert_raises(TypeError, self.log.__eq__, value)

    def test_inequality(self):
        assert_not_equals(LoggingFacility(2), LoggingFacility(3))
        assert_not_equals(2, LoggingFacility(3))
        assert_not_equals('error', LoggingFacility(3))

    def test_from_string(self):
        from_string = LoggingFacility.from_string
        for index, name in enumerate(LoggingFacility._level_names):
            assert_equals(from_string(index).level, index)
            assert_equals(from_string(str(index)).level, index)
            assert_equals(from_string(name).level, index)
        assert_equals(LoggingFacility.from_string('WARNING  ').level, 4)

    def test_from_string_invalid(self):
        from_string = LoggingFacility.from_string
        for value in self.invalid_values:
            assert_raises(ValueError, from_string, value)
        for value in self.invalid_types:
            assert_raises(TypeError, from_string, value)

    def test_repr(self):
        assert_equals(self.log.__repr__(), '<LoggingFacility none>')
        self.log.level = 'warning'
        assert_equals(self.log.__repr__(), '<LoggingFacility warning>')


text:
require("Menu/MainMenu/mainMenuStyle.lua")
--this = SceneNode()
InfoScreen = {}
function InfoScreen.new(camera)
	local self = {}
	local mainForm
	local isVisible = false
	local labelTab = {}
	local client
	local otherClientConnectionIssue = {}
	local startTime = Core.getTime()

	local players = {}

	function self.update()
		mainForm:update()
		--update clients
		for clientId,tab in pairs(players) do
			if client:isClientConnected(clientId)==true then
				if Core.getTime()-players[clientId].lastUpdated>3.0 then
					if Core.getTime()-startTime<=30.0 then
						--User is probably in loading screen
						local labels = labelTab[tab.listPos]
						labels.icon:setUvCoord(Vec2(0.5,0.625),Vec2(0.62,0.75))
						labels.ping:setText("Loading")
					else
						--user is losing connection
						local labels = labelTab[tab.listPos]
						labels.icon:setUvCoord(Vec2(0.375,0.625),Vec2(0.5,0.75))
						labels.ping:setText(tostring(math.floor(Core.getTime()-players[clientId].lastUpdated)).."s" )
					end
				end
			else
				local labels = labelTab[tab.listPos]
				labels.icon:setUvCoord(Vec2(0.5,0.625),Vec2(0.62,0.75))
				labels.name:setText(tab.name)
				labels.gold:setText("-")
				labels.kills:setText("-")
				labels.totalDamage:setText("-")
				labels.damage:setText("-")
				labels.speed:setText("-")
				labels.ping:setText("-")
				labels.name:setTextColor(Vec4(1,1,1,0.2))
				labels.gold:setTextColor(Vec4(1,1,1,0.2))
				labels.kills:setTextColor(Vec4(1,1,1,0.2))
				labels.totalDamage:setTextColor(Vec4(1,1,1,0.2))
				labels.damage:setTextColor(Vec4(1,1,1,0.2))
				labels.speed:setTextColor(Vec4(1,1,1,0.2))
				labels.ping:setTextColor(Vec4(1,1,1,0.2))
			end
		end
	end
	function self.manageConnectionIssues()
		if self.isAnyClientLosingConnection() and not(client and client:isConnected() and client:isLosingConnection()) then
			--another user has lost connection to the server
			if not otherClientConnectionIssue.speed then
				otherClientConnectionIssue.speed = Core.getBillboard("stats"):getInt("speed")
				Core.getNetworkClient():writeSafe("CMD-GameSpeed:0")
			end
			if self.isVisible()==false then
				self.togleVisible()
			end
		else
			if otherClientConnectionIssue.speed then
				--it has returned to normal, after someone was losing connection
				if self.isVisible()==true then
					self.togleVisible()
				end
				Core.getNetworkClient():writeSafe("CMD-GameSpeed:"..otherClientConnectionIssue.speed)
				--
				otherClientConnectionIssue = {}
			end
		end
	end
	function self.isAnyClientLosingConnection()
		if Core.getTime()-startTime>30.0 then
			for clientId,tab in pairs(players) do
				if client:getClientId()~=clientId and client:isClientConnected(clientId)==true then
					if Core.getTime()-players[clientId].lastUpdated>3.0 then
						return true
					end
				end
			end
		end
		return false
	end
	function self.isVisible()
		return isVisible
	end
	function self.togleVisible()
		if self.isAnyClientLosingConnection() then
			isVisible = true
		else
			isVisible = not isVisible
		end
		mainForm:setVisible(isVisible)
	end
	local function updateConnectedUsers()
		local tab = client:getConnected()
		local index = 1
		while tab[index] do
			players[tab[index].clientId] = {ping=tab[index].ping, totalDamage=0.0, damage=0.0, gold=0.0, speed=0, name=tab[index].name, playerId=tab[index].playerId}
			index = index + 1
		end
	end
	local function setDefaultLineColor(label,mNum)
		if mNum%2 == 0 then
			label:setBackground(Sprite(Vec4(1,1,1,0.05)))
		else
			label:setBackground(Sprite(Vec4(0)))
		end
	end
	function self.updateClientInfo(param)
		local name,clientId,gold,totalDamage,speed,ping,averageDamage,kills = string.match(param,"(.*);(.*);(.*);(.*);(.*);(.*);(.*);(.*)")

		--update client damage info
		if players[tonumber(clientId)] then
			local labels = labelTab[players[tonumber(clientId)].listPos]
			labels.averageDamage = tonumber(averageDamage)
			labels.totalDamageValue = tonumber(totalDamage)
		end

		--get sum of total damage and sum of average damage
		local sumTotalAverageDamage = 1
		local sumTotalDamage = 1
		for clientId,tab in pairs(players) do
			local labels = labelTab[tab.listPos]
			sumTotalAverageDamage = sumTotalAverageDamage + labels.averageDamage
			sumTotalDamage = sumTotalDamage + labels.totalDamageValue
		end

		print("\n\n")
		print("sumTotalAverageDamage: "..sumTotalAverageDamage)
		print("sumTotalDamage: "..sumTotalDamage)

		if players[tonumber(clientId)] then
			players[tonumber(clientId)].lastUpdated = Core.getTime()
			local labels = labelTab[players[tonumber(clientId)].listPos]
			labels.icon:setUvCoord(Vec2(0.375,0.75),Vec2(0.5,0.875))
			labels.name:setText(name)
			labels.gold:setText(gold)
			labels.kills:setText(kills)

			print("------------------------")
			print("totalDamage: "..totalDamage)
			print("averageDamage: "..averageDamage)
			print("------------------------\n")

			labels.totalDamage:setText(tostring( math.round(tonumber(totalDamage)/sumTotalDamage*100.0)).."%")
			labels.damage:setText(tostring( math.round(tonumber(averageDamage)/sumTotalAverageDamage*100.0)).."%")
			labels.speed:setText(speed)
			labels.ping:setText(ping)
		else
--			local pList = players
--			error("ClientId not used")
--			abort()
		end
	end
	local function init()
		client = Core.getNetworkClient()

		local weight = {-0.35}
		for i=1, 6 do
			weight[i+1] = -1.0/(7-i)
		end
		weight[5] = weight[5] * 1.4

		updateConnectedUsers()

		mainForm = Form( camera, PanelSize(Vec2(-0.7,-0.45), Vec2(5,2.5)), Alignment.MIDDLE_CENTER);
		mainForm:setName("InfoScreen form")
		mainForm:setLayout(FallLayout( Alignment.TOP_CENTER, PanelSize(Vec2(0,0.01))));
		mainForm:setRenderLevel(11)
		mainForm:setBackground(Gradient(MainMenuStyle.backgroundTopColor, MainMenuStyle.backgroundDownColor))
		mainForm:setBorder(Border(BorderSize(Vec4(MainMenuStyle.borderSize)), MainMenuStyle.borderColor))
		mainForm:setVisible(isVisible)

		mainPanel = mainForm:add(Panel(PanelSize(Vec2(-1))))
		mainPanel:setLayout(FallLayout(Alignment.TOP_CENTER, PanelSize(Vec2(0,0.01))))

		mainPanel:add(Panel(PanelSize(Vec2(-1, -0.05))))

		local contentPanel = mainPanel:add(Panel(PanelSize(Vec2(-0.9, -0.9474))))--95%
		--
		contentPanel:setBackground(Gradient(Vec4(1,1,1,0.01), Vec4(1,1,1,0.025)))

		local headerPanel = contentPanel:add(Panel(PanelSize(Vec2(-1, 0.035))))
		headerPanel:setBackground(Gradient(Vec4(1,1,1,0.05), Vec4(1,1,1,0.1)))

		headerPanel:add(Panel(PanelSize(Vec2(-1),Vec2(1))))
		local namePanel = headerPanel:add(Panel(PanelSize(Vec2(weight[1], -1))))
--		namePanel:add(Panel(PanelSize(Vec2(-0.1, -1))))
		namePanel:add(Label(PanelSize(Vec2(-1.0)), language:getText("name"), Vec4(0.95)))
		--
		local killsPanel = headerPanel:add(Panel(PanelSize(Vec2(weight[2], -1))))--language:getText("Total damage")
		local icon = killsPanel:add(Image(PanelSize(Vec2(-1), Vec2(1)), Text("icon_table.tga") ))
		icon:setUvCoord(Vec2(0.625,0.4375),Vec2(0.75,0.5))
		icon:setToolTip(Text("Kills"))
		--
		local totalDamagePanel = headerPanel:add(Panel(PanelSize(Vec2(weight[3], -1))))--language:getText("Total damage")
		local icon = totalDamagePanel:add(Image(PanelSize(Vec2(-1), Vec2(1)), Text("icon_table.tga") ))
		icon:setUvCoord(Vec2(0.125,0),Vec2(0.25,0.0625))
		icon:setToolTip(Text("Total damage"))
		--
		local damagePanel = headerPanel:add(Panel(PanelSize(Vec2(weight[4], -1))))--language:getText("Average damage")
		local icon = damagePanel:add(Image(PanelSize(Vec2(-1), Vec2(1)), Text("icon_table.tga") ))
		icon:setUvCoord(Vec2(0.125,0),Vec2(0.25,0.0625))
		icon:setToolTip(Text("Average damge per wave"))
		--
		local goldPanel = headerPanel:add(Panel(PanelSize(Vec2(weight[5], -1))))--language:getText("gold")
		local icon = goldPanel:add(Image(PanelSize(Vec2(-1), Vec2(1)), Text("icon_table.tga") ))
		icon:setUvCoord(Vec2(0,0),Vec2(0.125,0.0625))
		--
		local speedPanel = headerPanel:add(Panel(PanelSize(Vec2(weight[6], -1))))
		local icon = speedPanel:add(Image(PanelSize(Vec2(-1), Vec2(1)), Text("icon_table.tga") ))
		icon:setUvCoord(Vec2(0.125,0.25),Vec2(0.25,0.3125))
		--
		local pingPanel = headerPanel:add(Panel(PanelSize(Vec2(weight[7], -1))))--language:getText("ping")
		local icon = pingPanel:add(Image(PanelSize(Vec2(-1), Vec2(1)), Text("icon_table.tga") ))
		icon:setUvCoord(Vec2(0.125,0.375),Vec2(0.25,0.4375))
		--
		--
		--
		local listPanel = contentPanel:add(Panel(PanelSize(Vec2(-1, -1))))
		for clientId,tab in pairs(players) do
			local line = listPanel:add(Panel(PanelSize(Vec2(-1,0.03))))
			local icon = Image(PanelSize(Vec2(-1), Vec2(1)), Text("icon_table.tga") )
			setDefaultLineColor(line,1)
			line:setLayout(FlowLayout(Alignment.TOP_LEFT))
			tab.lastUpdated = Core.getTime()
			tab.listPos = #labelTab+1
			labelTab[tab.listPos] = {}
			local labels = labelTab[tab.listPos]
			labels.averageDamage = 0
			labels.totalDamageValue = 0

			labels.icon = 		line:add(icon)
			labels.name = 		line:add(Label(PanelSize(Vec2(weight[1], -1)), tab.name, Vec4(0.95)))
			labels.kills =		line:add(Label(PanelSize(Vec2(weight[2], -1)), "0", Vec3(0.95)))--language:getText("score")
			labels.totalDamage =line:add(Label(PanelSize(Vec2(weight[3], -1)), "0%", Vec3(0.95)))--language:getText("score")
			labels.damage = 	line:add(Label(PanelSize(Vec2(weight[4], -1)), "0%", Vec3(0.95)))--language:getText("score")
			labels.gold = 		line:add(Label(PanelSize(Vec2(weight[5], -1)), tostring(tab.gold), Vec3(0.95)))--language:getText("gold")
			labels.speed = 		line:add(Label(PanelSize(Vec2(weight[6], -1)), tostring(tab.speed), Vec3(0.95)))
			labels.ping = 		line:add(Label(PanelSize(Vec2(weight[7], -1)), tostring(tab.ping), Vec3(0.95)))--language:getText("ping")
		end
	end
	init()

	return self
end


text:
/**
 * This Script is licensed under the MIT license. Use and adapt according to your needs.
 *
 * Disclamer: This script is developed as a way for me to crawl and create static versions of my Ember.js applications.
 * The static versions are then later used in order to provide an SEO friendly version of the website, as well
 * as being able to provide a version of the site to users without JavaScript enabled in their browsers.
 */

/**
 * Helper functions added to the String prototype to check if a String starts or ends with
 * another String.
 */
if (typeof String.prototype.endsWith != 'function') {
    // see below for better implementation!
    String.prototype.endsWith = function (suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
}

if (typeof String.prototype.startsWith != 'function') {
    // see below for better implementation!
    String.prototype.startsWith = function (str) {
        return this.indexOf(str) == 0;
    };
}

(function (host) {

    function Crawler() {
        //A hash of all visited URLs
        this.visitedURLs = {};
        //The remaining URLs to visit
        this.urlsToVisit = [];
        //The intervalId of the main script interval
        this.intervalId = null;
        //The number of pages that are currently processing
        this.currentlyProcessing = 0;
    };

    //We need to both interact with the webpage and the filesystem
    Crawler.webpage = require('webpage');
    var fs = require('fs');

    /**
     * Helper function tht will strip away any <script> and <noscript> tags from a HTML document.
     *
     * @param doc
     * @returns {*}
     */
    Crawler.stripScriptTags = function(doc) {
        if (doc) {
            var SCRIPT_REGEX = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
            while (SCRIPT_REGEX.test(doc)) {
                doc = doc.replace(SCRIPT_REGEX, "");
            }

            SCRIPT_REGEX = /<noscript\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/noscript>/gi;
            while (SCRIPT_REGEX.test(doc)) {
                doc = doc.replace(SCRIPT_REGEX, "");
            }
        }

        return doc;
    };

    /**
     * Helper function that will replace the occurrence of the find variable with the
     * replace variable in the passed in str variable.
     *
     * Returns the new string after
     *
     * @param find
     * @param replace
     * @param str
     * @returns {*}
     */
    Crawler.replaceAll = function(find, replace, str) {
        if (find && replace && str) {
            return str.replace(new RegExp(find, 'g'), replace);
        }

        return str;
    };

    /**
     * The crawl function will go through all of the URLs that are currently found as part of the website.
     * The Crawler will only fetch 8 pages simultaneously, as to not run out of resources on the system that
     * performs the crawling.
     *
     * Once there are no more URLs to visit, the crawl function will output the final sitemap XML file to the
     * file specified to the script.
     *
     * Some servers are unable to access the public domain of the website, and must crawl via http://localhost:port
     * For these situations, the script will replace any occurance of parameter 5 with parameter 6, which can be used to
     * replace localhost:port with the actual domain name inside the Sitemap.xml file.
     *
     *Once the Sitemap.xml file is written, the script will exit with a status code of 0
     *
     * @param url
     * @param depth
     * @param onSuccess
     * @param onFailure
     */
    Crawler.prototype.crawl = function (url, depth, onSuccess, onFailure) {
        var self = this;
        if (!self.intervalId) {
            self.intervalId = setInterval(function () {
                if (self.currentlyProcessing < 8) {
                    if (self.urlsToVisit.length === 0 && self.currentlyProcessing == 0) {
                        var sitemapContent = '<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">\n';

                        for (var key in self.visitedURLs) {
                            var outputKey = key;

                            if (localurl && replaceurl) {
                                outputKey = Crawler.replaceAll(localurl, replaceurl, key);
                            }
                            outputKey = Crawler.replaceAll("&", "&", outputKey);

                            sitemapContent += '<url><loc>' + outputKey + "</loc></url>\n";
                        }

                        //Write the Sitemap.xml file
                        if (sitemapTarget) {
                            fs.write(sitemapTarget, sitemapContent + '</urlset>', 'w', "utf8");
                        }

                        console.log('Site crawled');
                        phantom.exit(0);

                    } else if (self.urlsToVisit.length > 0) {
                        self.doCrawl(self.urlsToVisit.shift());
                    }
                }
            }, 10);
        }

        if (depth > 0 && !this.isVisited(url) && url.indexOf(urlToCrawl) === 0) {
            self.urlsToVisit.push(url);
        }
    };

    /**
     * This is the function that performs the actual crawling of a URL.
     *
     * It will only crawl one URL once, and it will keep a record of all previously
     * crawled URLs. The function will only crawl URLs that originate from the same
     * domain that is currently being crawled (read: the URL starts with param 1)
     *
     * The function opens the URL, extracts all links adds these links to the list of URLs to crawl
     *
     * The function will also render a static HTML version of the website and write the contents into
     * the directory specified in the scripts third parameter. If the URL ends with a directory, the
     * script will append .html to the file, in order to be able to store nested URLs. You need to handle
     * this fact when you are serving the static content for your webapp.
     *
     * If your URLs use the hash-sign (#), it will also replace all instances of # with the path "/static".
     *
     * The version of the HTML page that is stored is a static version. Any <script> tags are therefore
     * removed from the version written to disk
     * @param url
     */
    Crawler.prototype.doCrawl = function (url) {
        //Only crawl a URL once, and only crawl URLS that originate from the correct domain
        if (!this.visitedURLs[url] && url.indexOf(urlToCrawl) === 0) {
            this.currentlyProcessing++;
            this.visitedURLs[url] = true;

            var self = this;
            var page = Crawler.webpage.create();

            page.open(url, function (status) {
                //console.log('opening page: ' + url);

                if ('success' === status) {
                    setTimeout(function () {

                        //Extract all links on the page
                        var pageUrls = page.evaluate(function () {
                            if (document.body && document.body.innerHTML) {
                                return Array.prototype.slice.call(document.querySelectorAll("a"), 0)
                                    .map(function (link) {
                                        return link.getAttribute("href");
                                    });
                            } else {
                                return [];
                            }
                        });

                        //Extract the static HTML version of the site
                        var documentBody = page.evaluate(function() {
                            if (document.body && document.body.innerHTML) {
                                return document.body.innerHTML;
                            }
                        });

                        var title = page.evaluate(function() {
                            if (document.title) {
                                return document.title;
                            }
                        });

                        console.log('title: ' + title);

                        //Schedule all links to be crawled
                        self.crawlURLs(pageUrls);

                        //Remove the protocol and domain name from the URL (i.e. http://domain.com
                        var pageUrl = url;
                        if (pageUrl.indexOf(urlToCrawl) == 0) {
                            pageUrl = pageUrl.slice(urlToCrawl.length, pageUrl.length);
                        }

                        //Remove /#/ if the URL starts with it
                        if (pageUrl.indexOf("/#/") == 0) {
                            pageUrl = pageUrl.slice(3, pageUrl.length);
                        }

                        //If there is anything left in the URL, store it in the designated target directory, and append .html
                        //Also remove any script tags, so that a true static version will be served
                        if (pageUrl.length > 0) {
                            fs.write(target + "/" + pageUrl + ".html", Crawler.replaceAll('#', '/static', Crawler.stripScriptTags(page.content)), 'w', "utf8");
                        } else {
                            //If there is nothign left in the URL, we are indexing http://domain.com. Store this as index.html
                            fs.write(target + "/index.html", Crawler.replaceAll('#', '/static', Crawler.stripScriptTags(page.content)), 'w', "utf8");
                        }

                    }, maxPageLoad * 1000); //Wait for maxPageLoad seconds before fetching the contents
                }

                //Once the page have been crawled and stored on the filesystem, close the file handle
                setTimeout(function (p) {
                    return function () {
                        //console.log('closing page: ' + url);
                        self.currentlyProcessing--;
                        p.close();
                    };
                }(page), maxPageLoad * 1100); //Wait for just a bit longer than the above timeout before closing the file handle
            });
        }
    };

    /**
     * Helper function that will determine if a URL has already been crawled
     * @param url
     * @returns {boolean}
     */
    Crawler.prototype.isVisited = function (url) {
        var visited = false;

        if (this.visitedURLs[url]) {
            visited = true;
        }

        return visited;
    };

    /**
     * The crawlUrls function will build up the correct URL for the passed in URL. Mostly adding trailing slash-es
     * to ensure that the resst of the script wont have to deal with possible trailing slashes to the URL
     *
     * If the URL has not been visited before, its added to the urlsToVisit array
     *
     * @param urls
     */
    Crawler.prototype.crawlURLs = function (urls) {
        var self = this;
        urls.forEach(function (url) {
            var useUrl = url;

            if (Crawler.isTopLevelURL(url)) {
                useUrl = url;
            } else if (!urlToCrawl.endsWith("/") && !url.startsWith("/")) {
                useUrl = urlToCrawl + "/" + url;
            } else if (urlToCrawl.endsWith("/") || url.startsWith("/")) {
                useUrl = urlToCrawl + url;
            }

            if (!self.visitedURLs[useUrl]) {
                self.urlsToVisit.push(useUrl);
            }
        });
    };

    /**
     * Helper function to check if the URL is absolute or if it is relative to the current path
     * @param url
     * @returns {boolean}
     */
    Crawler.isTopLevelURL = function (url) {
        return 0 == url.indexOf("http");
    };

    host.Crawler = Crawler;
})(phantom);

/*
 The script expects 7 arguments

 Example:

 phantomjs http://localhost:8085 1 /srv/website/static /srv/website/Sitemap.xml localhost:8085 domain.com 6

 The above example will:

 - Crawl the URL http://localhost:8085 (parameter 1) and traverse into any links until it reaches a depth of 6 (parameter 7)
 - The script will wait 1 second (parameter 2) for each page in order to render the full JavaScript. Heavy JS sites might need longer
 - Each of the crawled pages will be stored inside /src/website/static (parameter 3)
 - The final Sitemap.xml file will be stored at /srv/website/Sitemap.xml (parameter 4)
 - When writing the Sitemap.xml, replace any occurence of localhost:8085 (parameter 5) with domain.com (parameter 6)

 */
var args = phantom.args;
if (args.length != 7) {
    console.log('Param 1: URL to crawl\n' +
        'param2: seconds to wait for page load\n' +
        'param3: target dir for static folders\n' +
        'param4: path to Sitemap.xml\n' +
        'param5: part of url to replace (typically localhost:port)\n' +
        'param6: String to replace param5 with\n' +
        'param7: The maximum depth of the crawl');
    phantom.exit(-1);
}

var urlToCrawl = args[0];
var maxPageLoad = args[1];
var target = args[2];
var sitemapTarget = args[3];
var localurl = args[4];
var replaceurl = args[5];
var maxDepth = args[6]

//Start the crawler
var crawler = new phantom.Crawler().crawl(urlToCrawl, maxDepth,
    function onSuccess(page) {
        //console.log(page.url);
    },
    function onFailure(page) {
        //console.log("Could not load page. URL = " +  page.url);
    }
);


text:
namespace oakvr
{
namespace core
{
namespace io
{
	// --------------------------------------------------------------------------------
	struct File::FileImpl
	{
		FILE *pFileHandle;
	};

	// --------------------------------------------------------------------------------
	File::File(const oakvr::core::io::path::PathType &filepath)
		: m_bFileOpened(false) , m_eFileOpenMode(FileOpenMode::unknown), m_filePath(filepath)
	{
		m_pImpl = std::make_unique<FileImpl>();
		m_bFileOpened = false;
	}

	File::File(File &&file)
	{
		m_pImpl = std::move(file.m_pImpl);
		m_bFileOpened = std::move(file.m_bFileOpened);
		m_filePath = std::move(file.m_filePath);
	}

	// --------------------------------------------------------------------------------
	File::~File()
	{
		if(m_bFileOpened)
			Close();
	}

	// --------------------------------------------------------------------------------
	auto File::Exists(const oakvr::core::io::path::PathType &filepath) -> bool
	{
		struct stat st;
		if(stat(filepath.c_str(), &st ))
		{
			Log::Error("stat(%s, %p) error code(errno) %d", filepath.c_str(), &st, errno);
			return false;
		}
		return st.st_size != 0;
	}

	// --------------------------------------------------------------------------------
	auto File::Size(const oakvr::core::io::path::PathType &filepath) -> OffsetType
	{
		struct stat st;
		if(stat(filepath.c_str(), &st ))
		{
			Log::Error("stat(%s, %p) error code(errno) %d.\n", filepath.c_str(), &st, errno);
			return false;
		}

		return st.st_size;
	}

	// --------------------------------------------------------------------------------
	auto File::Size() -> OffsetType
	{
		return Size(m_filePath);
	}

	// --------------------------------------------------------------------------------
	auto File::Open(FileOpenMode eFileOpenMode) -> void
	{
		m_eFileOpenMode = eFileOpenMode;
		char mode[4];
		switch(eFileOpenMode)
		{
		case FileOpenMode::read:
			strcpy(mode, "rb");
			break;
		case FileOpenMode::write:
			strcpy(mode, "wb");
			break;
		case FileOpenMode::append:
			strcpy(mode, "ab");
			break;
		case FileOpenMode::readAndWrite:
			strcpy(mode, "r+b");
			break;
		default:
			strcpy(mode, "rb");
			m_eFileOpenMode = FileOpenMode::read;
			break;
		}

		errno_t err = fopen_s(&m_pImpl->pFileHandle, m_filePath.c_str(), mode);
		if(!m_pImpl->pFileHandle)
			Log::Error("File could not be opened (%s). Errno is %d.", m_filePath.c_str(), err);
		m_bFileOpened = m_pImpl->pFileHandle != nullptr;
	}

	// --------------------------------------------------------------------------------
	auto File::Close() -> void
	{
		if(fclose(m_pImpl->pFileHandle))
			Log::Error("File could not be closed (%s). Errno is %d.", m_filePath.c_str(), errno );

		m_eFileOpenMode = FileOpenMode::unknown;
		m_pImpl->pFileHandle = nullptr;
		m_bFileOpened = false;
	}

	// --------------------------------------------------------------------------------
	auto File::Read(uint8_t *buffer, OffsetType bufferSize, OffsetType bytesToRead, OffsetType offset) -> OffsetType
	{
		if(offset + bytesToRead > bufferSize)
		{
			Log::Error("Reading from %s; attempt to read past buffer limit!\n", m_filePath.c_str());
			return 0;
		}

		OffsetType fileSize = Size();

		if(bytesToRead == 0)
			return fread(buffer + offset, 1, fileSize - offset, m_pImpl->pFileHandle);

		if(bytesToRead > fileSize)
		{
			Log::Error("Reading from %s; attempt to read more than the file size!\n", m_filePath.c_str());
			return 0;
		}

		return fread(buffer + offset, 1, bytesToRead, m_pImpl->pFileHandle);
	}

	// --------------------------------------------------------------------------------
	auto File::Write(uint8_t *buffer, OffsetType bufferSize, OffsetType bytesToWrite, OffsetType offset) -> OffsetType
	{
		if(offset + bytesToWrite > bufferSize)
		{
			Log::Error("Writing to %s; attempt to write past buffer limit!\n", m_filePath.c_str());
			exit(1);
		}

		return fwrite(buffer + offset, bytesToWrite, 1, m_pImpl->pFileHandle);
	}

}	// namespace io
}	// namespace core
}	// namespace oakvr


text:
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'datetimewidget',
    'bootstrap3',
    'djangobower',
    'rest_framework',
    'rest_framework.authtoken',
    'corsheaders',
    'catalogue',
    'playlist',
    'session',
)


text:
require 'finals-framework/game'

describe FinalsFramework::Game do
  context "creation" do
    it "should have no players" do
      game = FinalsFramework::Game.new
      game.players.should be_empty
    end

    it "should be in the 'initiating' state" do
      game = FinalsFramework::Game.new
      game.state.should == 'initiating'
    end
  end
end


text:
package jme3test.opencl;

import com.jme3.app.SimpleApplication;
import com.jme3.niftygui.NiftyJmeDisplay;
import com.jme3.opencl.*;
import com.jme3.system.AppSettings;
import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.NiftyEventSubscriber;
import de.lessvoid.nifty.controls.*;
import de.lessvoid.nifty.screen.Screen;
import de.lessvoid.nifty.screen.ScreenController;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Sebastian Weiss
 */
public class TestContextSwitching extends SimpleApplication implements ScreenController {
    private static final Logger LOG = Logger.getLogger(TestContextSwitching.class.getName());

    private Nifty nifty;
    private Label infoLabel;
    private Button applyButton;
    private ListBox<String> platformListBox;
    private ListBox<String> deviceListBox;

    private static String selectedPlatform;
    private static String selectedDevice;
    private Context clContext;
    private static List<? extends Platform> availabePlatforms;
    private Buffer testBuffer;
    private boolean bufferCreated;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new TestContextSwitching().start();
    }

    public TestContextSwitching() {
        AppSettings settings = new AppSettings(true);
        settings.setOpenCLSupport(true);
        settings.setVSync(true);
        settings.setWidth(800);
        settings.setHeight(600);
        settings.setOpenCLPlatformChooser(CustomPlatformChooser.class);
        //settings.setRenderer(AppSettings.JOGL_OPENGL_FORWARD_COMPATIBLE);

        setSettings(settings);
        setShowSettings(false);
    }

    @Override
    public void simpleInitApp() {

        clContext = null;

        NiftyJmeDisplay niftyDisplay = NiftyJmeDisplay.newNiftyJmeDisplay(
                assetManager,
                inputManager,
                audioRenderer,
                guiViewPort);
        nifty = niftyDisplay.getNifty();
        nifty.fromXml("jme3test/opencl/ContextSwitchingScreen.xml", "Screen", this);
        guiViewPort.addProcessor(niftyDisplay);
        inputManager.setCursorVisible(true);
        flyCam.setEnabled(false);
    }

    @Override
    public void simpleUpdate(float tpf) {
        if (applyButton != null) {
            updateInfos();
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public void bind(Nifty nifty, Screen screen) {
        applyButton = screen.findNiftyControl("ApplyButton", Button.class);
        platformListBox = screen.findNiftyControl("PlatformListBox", ListBox.class);
        deviceListBox = screen.findNiftyControl("DeviceListBox", ListBox.class);
        infoLabel = screen.findNiftyControl("InfoLabel", Label.class);

        updateInfos();

        platformListBox.clear();
        for (Platform p : availabePlatforms) {
            platformListBox.addItem(p.getName());
        }
        platformListBox.selectItem(selectedPlatform);
        changePlatform(selectedPlatform);
    }

    private void updateInfos() {

        if (testBuffer == null && clContext != null && !bufferCreated) {
            try {
                testBuffer = clContext.createBuffer(1024);
                testBuffer.register();
                LOG.info("Test buffer created");
            } catch (OpenCLException ex) {
                LOG.log(Level.SEVERE, "Unable to create buffer", ex);
            }
            bufferCreated = true;
        }

        Context c = context.getOpenCLContext();
        if (c == clContext) {
            return;
        }
        clContext = c;
        LOG.info("context changed");
        testBuffer = null;
        bufferCreated = false;
        StringBuilder text = new StringBuilder();
        text.append("Current context:\n");
        text.append("  Platform: ").append(clContext.getDevices().get(0).getPlatform().getName()).append("\n");
        text.append("  Device: ").append(clContext.getDevices().get(0).getName()).append("\n");
        text.append("  Profile: ").append(clContext.getDevices().get(0).getProfile()).append("\n");
        text.append("  Memory: ").append(clContext.getDevices().get(0).getGlobalMemorySize()).append(" B\n");
        text.append("  Compute Units: ").append(clContext.getDevices().get(0).getComputeUnits()).append("\n");
        infoLabel.setText(text.toString());
    }

    @NiftyEventSubscriber(id="ApplyButton")
    public void onButton(String id, ButtonClickedEvent event) {
        LOG.log(Level.INFO, "Change context: platorm={0}, device={1}", new Object[]{selectedPlatform, selectedDevice});
        restart();
    }

    private void changePlatform(String platform) {
        selectedPlatform = platform;
        Platform p = null;
        for (Platform p2 : availabePlatforms) {
            if (p2.getName().equals(selectedPlatform)) {
                p = p2;
                break;
            }
        }
        deviceListBox.clear();
        if (p == null) {
            return;
        }
        for (Device d : p.getDevices()) {
            deviceListBox.addItem(d.getName());
        }
        deviceListBox.selectItem(selectedDevice);
    }

    @NiftyEventSubscriber(id="PlatformListBox")
    public void onPlatformChanged(String id, ListBoxSelectionChangedEvent<String> event) {
        String p = event.getSelection().isEmpty() ? null : event.getSelection().get(0);
        LOG.log(Level.INFO, "Selected platform changed to {0}", p);
        selectedPlatform = p;
        changePlatform(p);
    }

    @NiftyEventSubscriber(id="DeviceListBox")
    public void onDeviceChanged(String id, ListBoxSelectionChangedEvent<String> event) {
        String d = event.getSelection().isEmpty() ? null : event.getSelection().get(0);
        LOG.log(Level.INFO, "Selected device changed to {0}", d);
        selectedDevice = d;
    }

    @Override
    public void onStartScreen() {

    }

    @Override
    public void onEndScreen() {

    }

    public static class CustomPlatformChooser implements PlatformChooser {

        public CustomPlatformChooser() {}

        @Override
        public List<? extends Device> chooseDevices(List<? extends Platform> platforms) {
            availabePlatforms = platforms;

            Platform platform = null;
            for (Platform p : platforms) {
                if (p.getName().equals(selectedPlatform)) {
                    platform = p;
                    break;
                }
            }
            if (platform == null) {
                platform = platforms.get(0);
            }
            selectedPlatform = platform.getName();

            Device device = null;
            for (Device d : platform.getDevices()) {
                if (d.getName().equals(selectedDevice)) {
                    device = d;
                    break;
                }
            }
            if (device == null) {
                for (Device d : platform.getDevices()) {
                    if (d.getDeviceType() == Device.DeviceType.GPU) {
                        device = d;
                        break;
                    }
                }
            }
            if (device == null) {
                device = platform.getDevices().get(0);
            }
            selectedDevice = device.getName();

            return Collections.singletonList(device);
        }

    }
}


text:
#region License

#endregion

#region Authors
/*
 * Authors:
 *   Gonzalo Paniagua Javier <gonzalo@novell.com>
 */
#endregion

using System;
using System.IO;

namespace WebSocketSharp.Net
{
  internal class RequestStream : Stream
  {
    #region Private Fields

    private byte [] _buffer;
    private bool    _disposed;
    private int     _length;
    private int     _offset;
    private long    _remainingBody;
    private Stream  _stream;

    #endregion

    #region Internal Constructors

    internal RequestStream (
      Stream stream, byte [] buffer, int offset, int length)
      : this (stream, buffer, offset, length, -1)
    {
    }

    internal RequestStream (
      Stream stream, byte [] buffer, int offset, int length, long contentlength)
    {
      _stream = stream;
      _buffer = buffer;
      _offset = offset;
      _length = length;
      _remainingBody = contentlength;
    }

    #endregion

    #region Public Properties

    public override bool CanRead {
      get {
        return true;
      }
    }

    public override bool CanSeek {
      get {
        return false;
      }
    }

    public override bool CanWrite {
      get {
        return false;
      }
    }

    public override long Length {
      get {
        throw new NotSupportedException ();
      }
    }

    public override long Position {
      get {
        throw new NotSupportedException ();
      }

      set {
        throw new NotSupportedException ();
      }
    }

    #endregion

    #region Private Methods

    // Returns 0 if we can keep reading from the base stream,
    // > 0 if we read something from the buffer.
    // -1 if we had a content length set and we finished reading that many bytes.
    private int fillFromBuffer (byte [] buffer, int offset, int count)
    {
      if (buffer == null)
        throw new ArgumentNullException ("buffer");

      if (offset < 0)
        throw new ArgumentOutOfRangeException ("offset", "Less than zero.");

      if (count < 0)
        throw new ArgumentOutOfRangeException ("count", "Less than zero.");

      var len = buffer.Length;
      if (offset > len)
        throw new ArgumentException ("'offset' is greater than 'buffer' size.");

      if (offset > len - count)
        throw new ArgumentException ("Reading would overrun 'buffer'.");

      if (_remainingBody == 0)
        return -1;

      if (_length == 0)
        return 0;

      var size = _length < count ? _length : count;
      if (_remainingBody > 0 && _remainingBody < size)
        size = (int) _remainingBody;

      var remainingBuffer = _buffer.Length - _offset;
      if (remainingBuffer < size)
        size = remainingBuffer;

      if (size == 0)
        return 0;

      Buffer.BlockCopy (_buffer, _offset, buffer, offset, size);
      _offset += size;
      _length -= size;
      if (_remainingBody > 0)
        _remainingBody -= size;

      return size;
    }

    #endregion

    #region Public Methods

    public override IAsyncResult BeginRead (
      byte [] buffer,
      int offset,
      int count,
      AsyncCallback callback,
      object state)
    {
      if (_disposed)
        throw new ObjectDisposedException (GetType ().ToString ());

      var read = fillFromBuffer (buffer, offset, count);
      if (read > 0 || read == -1) {
        var ares = new HttpStreamAsyncResult ();
        ares.Buffer = buffer;
        ares.Offset = offset;
        ares.Count = count;
        ares.Callback = callback;
        ares.State = state;
        ares.SyncRead = read;
        ares.Complete ();

        return ares;
      }

      // Avoid reading past the end of the request to allow for HTTP pipelining.
      if (_remainingBody >= 0 && _remainingBody < count)
        count = (int) _remainingBody;

      return _stream.BeginRead (buffer, offset, count, callback, state);
    }

    public override IAsyncResult BeginWrite (
      byte [] buffer, int offset, int count, AsyncCallback callback, object state)
    {
      throw new NotSupportedException ();
    }

    public override void Close ()
    {
      _disposed = true;
    }

    public override int EndRead (IAsyncResult asyncResult)
    {
      if (_disposed)
        throw new ObjectDisposedException (GetType ().ToString ());

      if (asyncResult == null)
        throw new ArgumentNullException ("asyncResult");

      if (asyncResult is HttpStreamAsyncResult) {
        var ares = (HttpStreamAsyncResult) asyncResult;
        if (!ares.IsCompleted)
          ares.AsyncWaitHandle.WaitOne ();

        return ares.SyncRead;
      }

      // Close on exception?
      var read = _stream.EndRead (asyncResult);
      if (read > 0 && _remainingBody > 0)
        _remainingBody -= read;

      return read;
    }

    public override void EndWrite (IAsyncResult asyncResult)
    {
      throw new NotSupportedException ();
    }

    public override void Flush ()
    {
    }

    public override int Read (byte [] buffer, int offset, int count)
    {
      if (_disposed)
        throw new ObjectDisposedException (GetType ().ToString ());

      // Call fillFromBuffer to check for buffer boundaries even when
      // _remainingBody is 0.
      var read = fillFromBuffer (buffer, offset, count);
      if (read == -1) // No more bytes available (Content-Length).
        return 0;
      else if (read > 0)
        return read;

      read = _stream.Read (buffer, offset, count);
      if (read > 0 && _remainingBody > 0)
        _remainingBody -= read;

      return read;
    }

    public override long Seek (long offset, SeekOrigin origin)
    {
      throw new NotSupportedException ();
    }

    public override void SetLength (long value)
    {
      throw new NotSupportedException ();
    }

    public override void Write (byte [] buffer, int offset, int count)
    {
      throw new NotSupportedException ();
    }

    #endregion
  }
}


text:
<?php

class LoginPage {

	function show(&$page) {

		$page->data->formurl = 'index.php?page=login&action=login';

	}

	function login(&$page) {

		// jednoduche prihlasenie s napevno nastvenym menom a heslom (md5 hash)

		if ($page->from->post('username') == 'admin' && md5($page->from->post('password')) == md5('admin')){

			//logon ok, setup session
			$page->session->set('kiss_loged', 1);

			$page->redirect('/');
			//header('Location: ');
			//exit();

		} else {
			//logon wrong, prepare message for display
			$page->data->error = 'Zlé meno alebo heslo!';
		}

		/*
		// vzor prihlásenia cez databazu s tabulkou users

		$query = "SELECT * FROM users WHERE username='".$page->r->post['username']."' AND password='".md5($page->r->post['password'])."' LIMIT 1";
		$page->data->onlineuser = $page->db->query($query);

		if ($page->from->post('username')->val() == $page->data->onlineuser->row->username && md5($page->from->post('password')->val()) == $page->data->onlineuser->row->password) {

			//logon ok, setup session
			$page->session->set('kiss_loged', 1);
			$page->session->set('kiss_userid', $page->data->onlineuser->row->user_id);

			header('Location: index.php');
			exit();

		} else {
			//logon wrong, prepare message
			$page->data->error = 'Zlé meno alebo heslo!';
		}
		*/

	}

	function logout(&$page) {
		$page->session->set('kiss_loged', null);
	}

}

?>


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="@color/white_bg"
    android:layout_height="match_parent"
    android:paddingTop="20dp"
    android:paddingBottom="20dp"
    android:paddingLeft="80dp"
    android:paddingRight="80dp"
    android:orientation="vertical"
    android:gravity="center">

    <TextView
        android:id="@+id/game_over"
        android:layout_width="wrap_content"
        android:text="@string/game_over"
        android:layout_gravity="center_horizontal"
        android:textSize="35sp"
        android:textColor="@color/blue_gray"
        android:layout_height="wrap_content" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:layout_marginBottom="20dp"
        android:layout_marginTop="20dp"
        android:background="@android:color/darker_gray"/>

    <TextView
        android:id="@+id/level_indicator"
        android:text="Level 1"
        android:textSize="20sp"
        android:textColor="@color/dark_gray"
        android:layout_gravity="center_horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/points_box"
        android:layout_marginTop="20dp"
        android:textSize="36sp"
        android:background="@color/blue_gray"
        android:text="124"
        android:textColor="@color/yellow"
        android:layout_gravity="center_horizontal"
        android:padding="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:text="@string/highscore"
        android:textColor="@color/red"
        android:id="@+id/highscore_txt"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:background="@drawable/border"
        android:layout_marginTop="20dp"
        android:orientation="vertical"
        android:padding="10dp"
        android:layout_gravity="center_horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/best_label"
            android:text="@string/best_label"
            android:layout_gravity="center_horizontal"
            android:textColor="@color/blue_gray"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/best_box"
            android:textSize="36sp"
            android:text="176"
            android:textColor="@color/red"
            android:layout_gravity="center_horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        </LinearLayout>

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:layout_marginBottom="20dp"
        android:layout_marginTop="20dp"
        android:background="@android:color/darker_gray"/>

    <Button
        android:id="@+id/replay_btn"
        android:layout_width="180dp"
        android:layout_gravity="center_horizontal"
        android:text="@string/retry_game"
        android:textSize="15sp"
        android:background="@drawable/replay_button"
        android:onClick="playGame"
        android:layout_height="wrap_content" />

</LinearLayout>


text:
int boot_modules = 0;

typedef struct {
	int test;
} module_raw_t;

list_t * modules;

void module_add_raw(module_raw_t * module)
{
	list_insert(modules, module);
}

void modloader_init()
{
	klog(LOG_INFO,"modloader_init","Initialising...\n");
	modules = list_create();
}


text:
      Farm Place

        <form class="navbar-form navbar-left" role="search">

            <input type="text" class="form-control nav-search-form" size="30" ng-model="term.title" placeholder="Job Title">

          <button ng-click="navsearch()" class="btn nav-button signup">Search</button>
        </form>


text:
package action

import (
	"context"
	"flag"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"testing"

	dockerauth "github.com/deislabs/oras/pkg/auth/docker"
	fakeclientset "k8s.io/client-go/kubernetes/fake"

	"helm.sh/helm/v3/internal/experimental/registry"
	"helm.sh/helm/v3/pkg/chart"
	"helm.sh/helm/v3/pkg/chartutil"
	kubefake "helm.sh/helm/v3/pkg/kube/fake"
	"helm.sh/helm/v3/pkg/release"
	"helm.sh/helm/v3/pkg/storage"
	"helm.sh/helm/v3/pkg/storage/driver"
	"helm.sh/helm/v3/pkg/time"
)

var verbose = flag.Bool("test.log", false, "enable test logging")

func actionConfigFixture(t *testing.T) *Configuration {
	t.Helper()

	client, err := dockerauth.NewClient()
	if err != nil {
		t.Fatal(err)
	}

	resolver, err := client.Resolver(context.Background(), http.DefaultClient, false)
	if err != nil {
		t.Fatal(err)
	}

	tdir, err := ioutil.TempDir("", "helm-action-test")
	if err != nil {
		t.Fatal(err)
	}

	t.Cleanup(func() { os.RemoveAll(tdir) })

	cache, err := registry.NewCache(
		registry.CacheOptDebug(true),
		registry.CacheOptRoot(filepath.Join(tdir, registry.CacheRootDir)),
	)
	if err != nil {
		t.Fatal(err)
	}

	registryClient, err := registry.NewClient(
		registry.ClientOptAuthorizer(&registry.Authorizer{
			Client: client,
		}),
		registry.ClientOptResolver(&registry.Resolver{
			Resolver: resolver,
		}),
		registry.ClientOptCache(cache),
	)
	if err != nil {
		t.Fatal(err)
	}

	return &Configuration{
		Releases:       storage.Init(driver.NewMemory()),
		KubeClient:     &kubefake.FailingKubeClient{PrintingKubeClient: kubefake.PrintingKubeClient{Out: ioutil.Discard}},
		Capabilities:   chartutil.DefaultCapabilities,
		RegistryClient: registryClient,
		Log: func(format string, v ...interface{}) {
			t.Helper()
			if *verbose {
				t.Logf(format, v...)
			}
		},
	}
}

var manifestWithHook = `kind: ConfigMap
metadata:
  name: test-cm
  annotations:
    "helm.sh/hook": post-install,pre-delete,post-upgrade
data:
  name: value`

var manifestWithTestHook = `kind: Pod
  metadata:
	name: finding-nemo,
	annotations:
	  "helm.sh/hook": test
  spec:
	containers:
	- name: nemo-test
	  image: fake-image
	  cmd: fake-command
  `

var rbacManifests = `apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: schedule-agents
rules:
- apiGroups: [""]
  resources: ["pods", "pods/exec", "pods/log"]
  verbs: ["*"]

---

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: schedule-agents
  namespace: {{ default .Release.Namespace}}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: schedule-agents
subjects:
- kind: ServiceAccount
  name: schedule-agents
  namespace: {{ .Release.Namespace }}
`

type chartOptions struct {
	*chart.Chart
}

type chartOption func(*chartOptions)

func buildChart(opts ...chartOption) *chart.Chart {
	c := &chartOptions{
		Chart: &chart.Chart{
			// TODO: This should be more complete.
			Metadata: &chart.Metadata{
				APIVersion: "v1",
				Name:       "hello",
				Version:    "0.1.0",
			},
			// This adds a basic template and hooks.
			Templates: []*chart.File{
				{Name: "templates/hello", Data: []byte("hello: world")},
				{Name: "templates/hooks", Data: []byte(manifestWithHook)},
			},
		},
	}

	for _, opt := range opts {
		opt(c)
	}

	return c.Chart
}

func withName(name string) chartOption {
	return func(opts *chartOptions) {
		opts.Metadata.Name = name
	}
}

func withSampleValues() chartOption {
	values := map[string]interface{}{
		"someKey": "someValue",
		"nestedKey": map[string]interface{}{
			"simpleKey": "simpleValue",
			"anotherNestedKey": map[string]interface{}{
				"yetAnotherNestedKey": map[string]interface{}{
					"youReadyForAnotherNestedKey": "No",
				},
			},
		},
	}
	return func(opts *chartOptions) {
		opts.Values = values
	}
}

func withValues(values map[string]interface{}) chartOption {
	return func(opts *chartOptions) {
		opts.Values = values
	}
}

func withNotes(notes string) chartOption {
	return func(opts *chartOptions) {
		opts.Templates = append(opts.Templates, &chart.File{
			Name: "templates/NOTES.txt",
			Data: []byte(notes),
		})
	}
}

func withDependency(dependencyOpts ...chartOption) chartOption {
	return func(opts *chartOptions) {
		opts.AddDependency(buildChart(dependencyOpts...))
	}
}

func withMetadataDependency(dependency chart.Dependency) chartOption {
	return func(opts *chartOptions) {
		opts.Metadata.Dependencies = append(opts.Metadata.Dependencies, &dependency)
	}
}

func withSampleTemplates() chartOption {
	return func(opts *chartOptions) {
		sampleTemplates := []*chart.File{
			// This adds basic templates and partials.
			{Name: "templates/goodbye", Data: []byte("goodbye: world")},
			{Name: "templates/empty", Data: []byte("")},
			{Name: "templates/with-partials", Data: []byte(`hello: {{ template "_planet" . }}`)},
			{Name: "templates/partials/_planet", Data: []byte(`{{define "_planet"}}Earth{{end}}`)},
		}
		opts.Templates = append(opts.Templates, sampleTemplates...)
	}
}

func withSampleIncludingIncorrectTemplates() chartOption {
	return func(opts *chartOptions) {
		sampleTemplates := []*chart.File{
			// This adds basic templates and partials.
			{Name: "templates/goodbye", Data: []byte("goodbye: world")},
			{Name: "templates/empty", Data: []byte("")},
			{Name: "templates/incorrect", Data: []byte("{{ .Values.bad.doh }}")},
			{Name: "templates/with-partials", Data: []byte(`hello: {{ template "_planet" . }}`)},
			{Name: "templates/partials/_planet", Data: []byte(`{{define "_planet"}}Earth{{end}}`)},
		}
		opts.Templates = append(opts.Templates, sampleTemplates...)
	}
}

func withMultipleManifestTemplate() chartOption {
	return func(opts *chartOptions) {
		sampleTemplates := []*chart.File{
			{Name: "templates/rbac", Data: []byte(rbacManifests)},
		}
		opts.Templates = append(opts.Templates, sampleTemplates...)
	}
}

func withKube(version string) chartOption {
	return func(opts *chartOptions) {
		opts.Metadata.KubeVersion = version
	}
}

// releaseStub creates a release stub, complete with the chartStub as its chart.
func releaseStub() *release.Release {
	return namedReleaseStub("angry-panda", release.StatusDeployed)
}

func namedReleaseStub(name string, status release.Status) *release.Release {
	now := time.Now()
	return &release.Release{
		Name: name,
		Info: &release.Info{
			FirstDeployed: now,
			LastDeployed:  now,
			Status:        status,
			Description:   "Named Release Stub",
		},
		Chart:   buildChart(withSampleTemplates()),
		Config:  map[string]interface{}{"name": "value"},
		Version: 1,
		Hooks: []*release.Hook{
			{
				Name:     "test-cm",
				Kind:     "ConfigMap",
				Path:     "test-cm",
				Manifest: manifestWithHook,
				Events: []release.HookEvent{
					release.HookPostInstall,
					release.HookPreDelete,
				},
			},
			{
				Name:     "finding-nemo",
				Kind:     "Pod",
				Path:     "finding-nemo",
				Manifest: manifestWithTestHook,
				Events: []release.HookEvent{
					release.HookTest,
				},
			},
		},
	}
}

func TestGetVersionSet(t *testing.T) {
	client := fakeclientset.NewSimpleClientset()

	vs, err := GetVersionSet(client.Discovery())
	if err != nil {
		t.Error(err)
	}

	if !vs.Has("v1") {
		t.Errorf("Expected supported versions to at least include v1.")
	}
	if vs.Has("nosuchversion/v1") {
		t.Error("Non-existent version is reported found.")
	}
}


text:
    <form action="<?= site_url('/').$access ?>" method="post" enctype="multipart/form-data" accept-charset="utf-8" class="form-horizontal martop" id="block-validate">

                Nama Wilayah

                    <input type="hidden" name="kode" value="<?=$kode?>"/>
                    <input type="text" class="form-control" placeholder="Example: Yogyakarta, Tegal dll" name="wilayah" value="<?=$wilayah?>"/>

                 	<input type="submit" value="<?=$submit?>" class="btn btn-primary">
                    <?php if($form=='edit'){ ?>
                       <a href="<?=site_url('wm_ad')?>" class="btn btn-warning">Cancel
                    <?php } ?>

    </form>


text:
layout: default
title: Site Builder.
section_id: home
---

      Slogan Here

        simple.
        minimal.
        useful.
        profitable.
        delightful.

        Card Title

I am a very simple card. I am good at containing small bits of information.

        This is a link

        Card Title

I am a very simple card. I am good at containing small bits of information
.

        This is a link
        This is a link

        Card Title

I am a very simple card. I am good at containing small bits of information.

        This is a link
        This is a link

This is our big Tagline!

Here's our small slogan.

Left Aligned Caption

Here's our small slogan.

Right Aligned Caption

Here's our small slogan.

This is our big Tagline!

Here's our small slogan.

Our Customers:

This is a link

        Card Title

Here is some more information about this product that is only revealed once clicked on.

This is a link

        Card Title

Here is some more information about this product that is only revealed once clicked on.

This is a link

        Card Title

Here is some more information about this product that is only revealed once clicked on.

This is a link

        Card Title

Here is some more information about this product that is only revealed once clicked on.

Testimonials:

        Someone said this.
        Someone said this.
        Someone said this.
        Someone said this.

        Someone said this.
        Someone said this.
        Someone said this.
        Someone said this.

        Someone said this.
        Someone said this.
        Someone said this.
        Someone said this.

In The Press:

This is a link

        Card Title

Here is some more information about this product that is only revealed once clicked on.

This is a link

        Card Title

Here is some more information about this product that is only revealed once clicked on.

This is a link

        Card Title

Here is some more information about this product that is only revealed once clicked on.

This is a link

        Card Title

Here is some more information about this product that is only revealed once clicked on.

Authorized Partners:

        Card Title

I am a very simple card. I am good at containing small bits of information.

        This is a link
        This is a link

        Card Title

I am a very simple card. I am good at containing small bits of information
.

        This is a link
        This is a link

        Card Title

I am a very simple card. I am good at containing small bits of information.

        This is a link
        This is a link

Featured Case Studies:

Title of case study

I am a very simple card. I am good at containing small bits of information.
        I am a very simple card. I am good at containing small bits of information.
        I am a very simple card. I am good at containing small bits of information.
        I am a very simple card. I am good at containing small bits of information.

        This is a link
        This is a link

Title of case study

I am a very simple card. I am good at containing small bits of information.
        I am a very simple card. I am good at containing small bits of information.
        I am a very simple card. I am good at containing small bits of information.
        I am a very simple card. I am good at containing small bits of information.

        This is a link
        This is a link

Title of case study

I am a very simple card. I am good at containing small bits of information.
        I am a very simple card. I am good at containing small bits of information.
        I am a very simple card. I am good at containing small bits of information.
        I am a very simple card. I am good at containing small bits of information.

        This is a link
        This is a link


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

namespace System.Tests
{
    public partial class BooleanTests
    {
        [Fact]
        public void TrueString_Get_ReturnsTrue()
        {
            Assert.Equal("True", bool.TrueString);
        }

        [Fact]
        public void FalseString_Get_ReturnsFalse()
        {
            Assert.Equal("False", bool.FalseString);
        }

        public static IEnumerable<object[]> Parse_Valid_TestData()
        {
            yield return new object[] { "True", true };
            yield return new object[] { "true", true };
            yield return new object[] { "TRUE", true };
            yield return new object[] { "tRuE", true };
            yield return new object[] { "  True  ", true };
            yield return new object[] { "True\0", true };
            yield return new object[] { " \0 \0  True   \0 ", true };
            yield return new object[] { "False", false };
            yield return new object[] { "false", false };
            yield return new object[] { "FALSE", false };
            yield return new object[] { "fAlSe", false };
            yield return new object[] { "False  ", false };
            yield return new object[] { "False\0", false };
            yield return new object[] { "  False \0\0\0  ", false };
        }

        [Theory]
        [MemberData(nameof(Parse_Valid_TestData))]
        public void Parse_ValidValue_ReturnsExpected(string value, bool expected)
        {
            Assert.True(bool.TryParse(value, out bool result));
            Assert.Equal(expected, result);

            Assert.Equal(expected, bool.Parse(value));
        }

        public static IEnumerable<object[]> Parse_Invalid_TestData()
        {
            yield return new object[] { null, typeof(ArgumentNullException) };
            yield return new object[] { "", typeof(FormatException) };
            yield return new object[] { " ", typeof(FormatException) };
            yield return new object[] { "Garbage", typeof(FormatException) };
            yield return new object[] { "True\0Garbage", typeof(FormatException) };
            yield return new object[] { "True\0True", typeof(FormatException) };
            yield return new object[] { "True True", typeof(FormatException) };
            yield return new object[] { "True False", typeof(FormatException) };
            yield return new object[] { "False True", typeof(FormatException) };
            yield return new object[] { "Fa lse", typeof(FormatException) };
            yield return new object[] { "T", typeof(FormatException) };
            yield return new object[] { "0", typeof(FormatException) };
            yield return new object[] { "1", typeof(FormatException) };
    }

        [Theory]
        [MemberData(nameof(Parse_Invalid_TestData))]
        public void Parse_InvalidValue_ThrowsException(string value, Type exceptionType)
        {
            Assert.Throws(exceptionType, () => bool.Parse(value));

            Assert.False(bool.TryParse(value, out bool result));
            Assert.False(result);
        }

        [Theory]
        [InlineData(true, "True")]
        [InlineData(false, "False")]
        public void ToString_Invoke_ReturnsExpected(bool value, string expected)
        {
            Assert.Equal(expected, value.ToString());
        }

        [Theory]
        [InlineData(true, true, 0)]
        [InlineData(true, false, 1)]
        [InlineData(true, null, 1)]
        [InlineData(false, false, 0)]
        [InlineData(false, true, -1)]
        [InlineData(false, null, 1)]
        public void CompareTo_Other_ReturnsExpected(bool b, object obj, int expected)
        {
            if (obj is bool boolValue)
            {
                Assert.Equal(expected, Math.Sign(b.CompareTo(boolValue)));
            }

            Assert.Equal(expected, Math.Sign(b.CompareTo(obj)));
        }

        [Theory]
        [InlineData(true, 1)]
        [InlineData(true, "true")]
        [InlineData(false, 0)]
        [InlineData(false, "false")]
        public void CompareTo_ObjectNotBool_ThrowsArgumentException(bool b, object obj)
        {
            AssertExtensions.Throws<ArgumentException>(null, () => b.CompareTo(obj));
        }

        [Theory]
        [InlineData(true, true, true)]
        [InlineData(true, false, false)]
        [InlineData(true, "1", false)]
        [InlineData(true, "True", false)]
        [InlineData(true, null, false)]
        [InlineData(false, false, true)]
        [InlineData(false, true, false)]
        [InlineData(false, "0", false)]
        [InlineData(false, "False", false)]
        [InlineData(false, null, false)]
        public void Equals_Other_ReturnsExpected(bool b1, object obj, bool expected)
        {
            if (obj is bool boolValue)
            {
                Assert.Equal(expected, b1.Equals(boolValue));
                Assert.Equal(expected, b1.GetHashCode().Equals(obj.GetHashCode()));
            }

            Assert.Equal(expected, b1.Equals(obj));
        }

        [Theory]
        [InlineData(true, 1)]
        [InlineData(false, 0)]
        public void GetHashCode_Invoke_ReturnsExpected(bool value, int expected)
        {
            Assert.Equal(expected, value.GetHashCode());
        }

        [Fact]
        public void GetTypeCode_Invoke_ReturnsBoolean()
        {
            Assert.Equal(TypeCode.Boolean, true.GetTypeCode());
        }

        public static IEnumerable<object[]> Parse_ValidWithOffsetCount_TestData()
        {
            foreach (object[] inputs in Parse_Valid_TestData())
            {
                yield return new object[] { inputs[0], 0, ((string)inputs[0]).Length, inputs[1] };
            }

            yield return new object[] { " \0 \0  TrueFalse   \0 ", 6, 4, true };
            yield return new object[] { " \0 \0  TrueFalse   \0 ", 10, 5, false };
        }

        [Theory]
        [MemberData(nameof(Parse_ValidWithOffsetCount_TestData))]
        public static void Parse_Span_Valid(string value, int offset, int count, bool expected)
        {
            Assert.Equal(expected, bool.Parse(value.AsSpan(offset, count)));

            Assert.True(bool.TryParse(value.AsSpan(offset, count), out bool result));
            Assert.Equal(expected, result);
        }

        [Theory]
        [MemberData(nameof(Parse_Invalid_TestData))]
        public static void Parse_Span_Invalid(string value, Type exceptionType)
        {
            if (value != null)
            {
                Assert.Throws(exceptionType, () => bool.Parse(value.AsSpan()));

                Assert.False(bool.TryParse(value.AsSpan(), out bool result));
                Assert.False(result);
            }
        }

        [Theory]
        [InlineData(true, "True")]
        [InlineData(false, "False")]
        public static void TryFormat(bool i, string expected)
        {
            char[] actual;
            int charsWritten;

            // Just right
            actual = new char[expected.Length];
            Assert.True(i.TryFormat(actual.AsSpan(), out charsWritten));
            Assert.Equal(expected.Length, charsWritten);
            Assert.Equal(expected, new string(actual));

            // Longer than needed
            actual = new char[expected.Length + 1];
            Assert.True(i.TryFormat(actual.AsSpan(), out charsWritten));
            Assert.Equal(expected.Length, charsWritten);
            Assert.Equal(expected, new string(actual, 0, charsWritten));

            // Too short
            if (expected.Length > 0)
            {
                actual = new char[expected.Length - 1];
                Assert.False(i.TryFormat(actual.AsSpan(), out charsWritten));
                Assert.Equal(0, charsWritten);
            }
        }
    }
}


text:
Puts stands for 'put string'.  The method returns prints the output to the console and ads a new blank line.

##What is an integer? What is a float?
An integer is any real, whole number. Said more simply, it's any number without a decimal point. Numbers with decimials are called floats.

##What's the difference between float and integer division?  (Explain it to a non programmer)
Float division is like using a calculator -- it returns remainders.  Integer division does not return remainders.  Instead, it returns the number of times something can be divided without a remainder. For example:  10/3 = 3.

##Hours in Years Ruby Program:
puts 1*365.242*24

##Minutes in a decade Ruby Program:
puts 1*10*365.242*24*60

##Addition, subration, multiplication, and division in Ruby
These all work just like a calculator, except for division. As explained above, there are two types of division:  intger and float divsion.  Float returns the remainder, integer does not.

##What are strings?  Why and when would you use them?
A group of letters in a program. They are mainly used to write words and sentences.  They can be stored as variables.  You can mutiply and add stringss.  Strings would be used in programs to communiate with users.

##What are local variables? Why and when would you use them?
A variable is when you assign a short string (starting with a lowercase letter) to some other object.  You can point your variable to a string or integer or any object.  You can also reasign variables.  You use varaibles so you don't have to keep typing the same thing over and over again.

##How was the challenge
This challenge was pretty easy.  The content was fairly basic and it's review from what we had to learn to appply to DBC.


text:
package com.tonybeltramelli.mobile.lib.intent;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

/**
 *
 * @author Tony Beltramelli www.tonybeltramelli.com
 *
 */
public class UIntent {
	public static boolean isIntentAvailable(Context context, String action) {
	    final PackageManager packageManager = context.getPackageManager();
	    final Intent intent = new Intent(action);
	    List<ResolveInfo> list =  packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
	    return list.size() > 0;
	}
}


text:
<?php

namespace johnitvn\userplus\basic\actions;

use Yii;
use johnitvn\userplus\base\Action;
use johnitvn\userplus\base\traits\AjaxValidationTrait;

/**
 * Recovery action handler user reset password request
 * @author John Martin <john.itvn@gmail.com>
 * @since 1.0.0
 */
class RecoveryPasswordAction extends Action {

    use AjaxValidationTrait;

    /**
     * @var string the view file to be rendered. If not set, it will take the value of [[id]].
     * That means, if you name the action as "error" in "SiteController", then the view name
     * would be "error", and the corresponding view file would be "views/site/error.php".
     */
    public $view;

    /**
     * Runs the reset password action
     *
     * @return string result content
     */
    public function run() {
        $model = $this->userPlusModule->createModelInstance('RecoveryForm');

        $this->performAjaxValidation($model);
        $view = $this->view == null ? $this->id : $this->view;

        if ($model->load(Yii::$app->request->post()) && $model->recovery()) {
            return $this->controller->render($view, [
                        'alert' => true,
                        'model' => $model,
            ]);
        } else {
            return $this->controller->render($view, [
                        'alert' => false,
                        'model' => $model,
            ]);
        }
    }

}


text:
package org.dcache.nfs.v3.xdr;
import org.dcache.xdr.*;
import java.io.IOException;

public class SETATTR3args implements XdrAble {
    public nfs_fh3 object;
    public sattr3 new_attributes;
    public sattrguard3 guard;

    public SETATTR3args() {
    }

    public SETATTR3args(XdrDecodingStream xdr)
           throws OncRpcException, IOException {
        xdrDecode(xdr);
    }

    public void xdrEncode(XdrEncodingStream xdr)
           throws OncRpcException, IOException {
        object.xdrEncode(xdr);
        new_attributes.xdrEncode(xdr);
        guard.xdrEncode(xdr);
    }

    public void xdrDecode(XdrDecodingStream xdr)
           throws OncRpcException, IOException {
        object = new nfs_fh3(xdr);
        new_attributes = new sattr3(xdr);
        guard = new sattrguard3(xdr);
    }

}
// End of SETATTR3args.java


text:
package akka.contrib.persistence.mongodb

import akka.actor.{Actor, ExtendedActorSystem, Props}
import akka.persistence.query._
import akka.persistence.query.scaladsl.{CurrentEventsByPersistenceIdQuery, CurrentPersistenceIdsQuery}
import akka.persistence.query.javadsl.{CurrentEventsByPersistenceIdQuery => JCEBP, CurrentPersistenceIdsQuery => JCP}
import akka.stream.actor.{ActorPublisher, ActorPublisherMessage}
import akka.stream.scaladsl.Source
import akka.stream.javadsl.{Source => JSource}

object MongoReadJournal {
  val Identifier = "akka-contrib-mongodb-persistence-readjournal"
}

class MongoReadJournal(system: ExtendedActorSystem) extends ReadJournalProvider {

  private[this] val impl = MongoPersistenceExtension(system).readJournal

  override def scaladslReadJournal(): scaladsl.ReadJournal = new ScalaDslMongoReadJournal(impl)

  override def javadslReadJournal(): javadsl.ReadJournal = new JavaDslMongoReadJournal(new ScalaDslMongoReadJournal(impl))
}

class ScalaDslMongoReadJournal(impl: MongoPersistenceReadJournallingApi) extends scaladsl.ReadJournal with CurrentPersistenceIdsQuery with CurrentEventsByPersistenceIdQuery {

  def allEvents(): Source[EventEnvelope,Unit] =
    Source.actorPublisher[EventEnvelope](impl.allEvents)
      .mapMaterializedValue(_ => ())

  override def currentPersistenceIds(): Source[String, Unit] =
    Source.actorPublisher[String](impl.allPersistenceIds)
      .mapMaterializedValue(_ => ())

  override def currentEventsByPersistenceId(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long): Source[EventEnvelope, Unit] =
    Source.actorPublisher[EventEnvelope](impl.eventsByPersistenceId(persistenceId,fromSequenceNr,toSequenceNr))
      .mapMaterializedValue(_ => ())
}

class JavaDslMongoReadJournal(rj: ScalaDslMongoReadJournal) extends javadsl.ReadJournal with JCP with JCEBP {
  def allEvents(): JSource[EventEnvelope, Unit] = rj.allEvents().asJava

  override def currentPersistenceIds(): JSource[String, Unit] = rj.currentPersistenceIds().asJava

  override def currentEventsByPersistenceId(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long): JSource[EventEnvelope, Unit] =
    rj.currentEventsByPersistenceId(persistenceId,fromSequenceNr,toSequenceNr).asJava
}

trait MongoPersistenceReadJournallingApi {
  def allPersistenceIds: Props
  def allEvents: Props
  def eventsByPersistenceId(persistenceId: String, fromSeq: Long, toSeq: Long): Props
}

trait SyncActorPublisher[A,Cursor] extends ActorPublisher[A] {
  import ActorPublisherMessage._

  override def preStart() = {
    context.become(streaming(initialCursor, 0))
    super.preStart()
  }

  protected def driver: MongoPersistenceDriver

  protected def initialCursor: Cursor

  protected def next(c: Cursor, atMost: Long): (Vector[A], Cursor)

  protected def isCompleted(c: Cursor): Boolean

  protected def discard(c: Cursor): Unit

  def receive = Actor.emptyBehavior

  def streaming(cursor: Cursor, offset: Long): Receive = {
    case _: Cancel | SubscriptionTimeoutExceeded =>
      discard(cursor)
      context.stop(self)
    case Request(_) =>
      val (filled,remaining) = next(cursor, totalDemand)
      filled foreach onNext
      if (isCompleted(remaining))
        onCompleteThenStop()
      else
        context.become(streaming(remaining, offset + filled.size))
  }
}


text:
  #include <mitkNavigationToolStorage.h>
  #include <mitkIOUtil.h>
  #include "mitkNavigationToolStorageTestHelper.h"

mitk::NavigationToolStorage::Pointer mitk::NavigationToolStorageTestHelper::CreateTestData_SimpleStorage()
    {
    //create Tool Storage
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();
    //first tool
    mitk::NavigationTool::Pointer myTool1 = mitk::NavigationTool::New();
    myTool1->SetIdentifier("001");
    myStorage->AddTool(myTool1);
    //second tool
    mitk::NavigationTool::Pointer myTool2 = mitk::NavigationTool::New();
    myTool2->SetIdentifier("002");
    myStorage->AddTool(myTool2);
    //third tool
    mitk::NavigationTool::Pointer myTool3 = mitk::NavigationTool::New();
    myTool3->SetIdentifier("003");
    myStorage->AddTool(myTool3);

    return myStorage;
    }

  mitk::NavigationToolStorage::Pointer mitk::NavigationToolStorageTestHelper::CreateTestData_StorageWithOneTool()
    {
    //create Tool Storage
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();

    //first tool
    mitk::NavigationTool::Pointer myTool1 = mitk::NavigationTool::New();
    myTool1->SetIdentifier("001");
    mitk::PointSet::Pointer CalLandmarks1 = mitk::PointSet::New();
    mitk::Point3D testPt1;
    mitk::FillVector3D(testPt1,1,2,3);
    CalLandmarks1->SetPoint(0,testPt1);
    mitk::PointSet::Pointer RegLandmarks1 = mitk::PointSet::New();
    mitk::Point3D testPt2;
    mitk::FillVector3D(testPt2,4,5,6);
    RegLandmarks1->SetPoint(5,testPt2);
    myTool1->SetToolCalibrationLandmarks(CalLandmarks1);
    myTool1->SetToolRegistrationLandmarks(RegLandmarks1);
    mitk::Point3D toolTipPos;
    mitk::FillVector3D(toolTipPos,1.3423,2.323,4.332);
    mitk::Quaternion toolTipRot = mitk::Quaternion(0.1,0.2,0.3,0.4);
    myTool1->SetToolTipPosition(toolTipPos);
    myTool1->SetToolTipOrientation(toolTipRot);
    myStorage->AddTool(myTool1);

    return myStorage;
    }

  mitk::NavigationToolStorage::Pointer mitk::NavigationToolStorageTestHelper::CreateTestData_ComplexStorage(std::string toolFilePath, std::string toolSurfacePath1, std::string toolSurfacePath2)
    {
    //create first tool
    mitk::NavigationTool::Pointer myNavigationTool = mitk::NavigationTool::New();
    myNavigationTool->SetCalibrationFile(toolFilePath);
    mitk::DataNode::Pointer myNode = mitk::DataNode::New();
    myNode->SetName("ClaronTool");
    myNode->SetData(mitk::IOUtil::LoadSurface(toolSurfacePath1)); //load an stl File
    myNavigationTool->SetDataNode(myNode);
    myNavigationTool->SetIdentifier("ClaronTool#1");
    myNavigationTool->SetSerialNumber("0815");
    myNavigationTool->SetTrackingDeviceType(mitk::ClaronMicron);
    myNavigationTool->SetType(mitk::NavigationTool::Fiducial);

    //create second tool
    mitk::NavigationTool::Pointer myNavigationTool2 = mitk::NavigationTool::New();
    mitk::Surface::Pointer testSurface2;

    mitk::DataNode::Pointer myNode2 = mitk::DataNode::New();
    myNode2->SetName("AuroraTool");

    //load an stl File
    testSurface2 = mitk::IOUtil::LoadSurface(toolSurfacePath2);
    myNode2->SetData(testSurface2);

    myNavigationTool2->SetDataNode(myNode2);
    myNavigationTool2->SetIdentifier("AuroraTool#1");
    myNavigationTool2->SetSerialNumber("0816");
    myNavigationTool2->SetTrackingDeviceType(mitk::NDIAurora);
    myNavigationTool2->SetType(mitk::NavigationTool::Instrument);

    //create navigation tool storage
    mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();
    myStorage->AddTool(myNavigationTool);
    myStorage->AddTool(myNavigationTool2);

    return myStorage;
    }


text:
This inspection reports any instances of labeled statements.

  Powered by InspectionGadgets


text:
<?xml version="1.0" encoding="UTF-8"?>
<tei xmlns="http://www.tei-c.org/ns/1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:mml="http://www.w3.org/1998/Math/MathML">
	<teiHeader>
		<fileDesc>
			<sourceDesc>
				<biblStruct>
					<analytic>
						<author>

						<affiliation>
							<orgName type="department">Department of Pathology, Anatomy and Cell Biology</orgName>,
							<orgName type="institution">Jefferson Medical College</orgName>,
							<lb/>
							<orgName type="institution">Thomas Jefferson University</orgName>,
							<address>
								<settlement>Philadelphia</settlement>,
								<country>Pennsylvania</country>
							</address>
						</affiliation>
						<affiliation>
							<marker>2</marker>
							<orgName type="institution">Sbarro Institute for Cancer Research and Molecular Medicine</orgName>,
							<orgName type="institution">Jefferson Medical College</orgName>,
							<lb/>
							<orgName type="institution">Thomas Jefferson University</orgName>,
							<address>
								<settlement>Philadelphia</settlement>,
								<region>Pennsylvania</region>
							</address>
						</affiliation>

						</author>
					</analytic>
				</biblStruct>
			</sourceDesc>
		</fileDesc>
	</teiHeader>
</tei>


text:
//===-- ThreadingTests.cpp --------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "support/Threading.h"
#include "gtest/gtest.h"
#include <mutex>

namespace clang {
namespace clangd {
class ThreadingTest : public ::testing::Test {};

TEST_F(ThreadingTest, TaskRunner) {
  const int TasksCnt = 100;
  // This should be const, but MSVC does not allow to use const vars in lambdas
  // without capture. On the other hand, clang gives a warning that capture of
  // const var is not required.
  // Making it non-const makes both compilers happy.
  int IncrementsPerTask = 1000;

  std::mutex Mutex;
  int Counter(0); /* GUARDED_BY(Mutex) */
  {
    AsyncTaskRunner Tasks;
    auto scheduleIncrements = [&]() {
      for (int TaskI = 0; TaskI < TasksCnt; ++TaskI) {
        Tasks.runAsync("task", [&Counter, &Mutex, IncrementsPerTask]() {
          for (int Increment = 0; Increment < IncrementsPerTask; ++Increment) {
            std::lock_guard<std::mutex> Lock(Mutex);
            ++Counter;
          }
        });
      }
    };

    {
      // Make sure runAsync is not running tasks synchronously on the same
      // thread by locking the Mutex used for increments.
      std::lock_guard<std::mutex> Lock(Mutex);
      scheduleIncrements();
    }

    Tasks.wait();
    {
      std::lock_guard<std::mutex> Lock(Mutex);
      ASSERT_EQ(Counter, TasksCnt * IncrementsPerTask);
    }

    {
      std::lock_guard<std::mutex> Lock(Mutex);
      Counter = 0;
      scheduleIncrements();
    }
  }
  // Check that destructor has waited for tasks to finish.
  std::lock_guard<std::mutex> Lock(Mutex);
  ASSERT_EQ(Counter, TasksCnt * IncrementsPerTask);
}
} // namespace clangd
} // namespace clang