text:
import * as dom from 'vs/base/browser/dom';
import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode';
import { ContentWidgetPositionPreference, IContentWidget } from 'vs/editor/browser/editorBrowser';
import { ViewPart, PartFingerprint, PartFingerprints } from 'vs/editor/browser/view/viewPart';
import { ViewContext } from 'vs/editor/common/view/viewContext';
import { RenderingContext, RestrictedRenderingContext } from 'vs/editor/common/view/renderingContext';
import { Position, IPosition } from 'vs/editor/common/core/position';
import { Range, IRange } from 'vs/editor/common/core/range';
import * as viewEvents from 'vs/editor/common/view/viewEvents';
import { ViewportData } from 'vs/editor/common/viewLayout/viewLinesViewportData';
import { Constants } from 'vs/editor/common/core/uint';

class Coordinate {
	_coordinateBrand: void;

	public readonly top: number;
	public readonly left: number;

	constructor(top: number, left: number) {
		this.top = top;
		this.left = left;
	}
}

export class ViewContentWidgets extends ViewPart {

	private _viewDomNode: FastDomNode<HTMLElement>;
	private _widgets: { [key: string]: Widget; };

	public domNode: FastDomNode<HTMLElement>;
	public overflowingContentWidgetsDomNode: FastDomNode<HTMLElement>;

	constructor(context: ViewContext, viewDomNode: FastDomNode<HTMLElement>) {
		super(context);
		this._viewDomNode = viewDomNode;
		this._widgets = {};

		this.domNode = createFastDomNode(document.createElement('div'));
		PartFingerprints.write(this.domNode, PartFingerprint.ContentWidgets);
		this.domNode.setClassName('contentWidgets');
		this.domNode.setPosition('absolute');
		this.domNode.setTop(0);

		this.overflowingContentWidgetsDomNode = createFastDomNode(document.createElement('div'));
		PartFingerprints.write(this.overflowingContentWidgetsDomNode, PartFingerprint.OverflowingContentWidgets);
		this.overflowingContentWidgetsDomNode.setClassName('overflowingContentWidgets');
	}

	public dispose(): void {
		super.dispose();
		this._widgets = {};
	}

	// --- begin event handlers

	public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean {
		let keys = Object.keys(this._widgets);
		for (let i = 0, len = keys.length; i < len; i++) {
			const widgetId = keys[i];
			this._widgets[widgetId].onConfigurationChanged(e);
		}
		return true;
	}
	public onDecorationsChanged(e: viewEvents.ViewDecorationsChangedEvent): boolean {
		// true for inline decorations that can end up relayouting text
		return true;
	}
	public onFlushed(e: viewEvents.ViewFlushedEvent): boolean {
		return true;
	}
	public onLineMappingChanged(e: viewEvents.ViewLineMappingChangedEvent): boolean {
		let keys = Object.keys(this._widgets);
		for (let i = 0, len = keys.length; i < len; i++) {
			const widgetId = keys[i];
			this._widgets[widgetId].onLineMappingChanged(e);
		}
		return true;
	}
	public onLinesChanged(e: viewEvents.ViewLinesChangedEvent): boolean {
		return true;
	}
	public onLinesDeleted(e: viewEvents.ViewLinesDeletedEvent): boolean {
		return true;
	}
	public onLinesInserted(e: viewEvents.ViewLinesInsertedEvent): boolean {
		return true;
	}
	public onScrollChanged(e: viewEvents.ViewScrollChangedEvent): boolean {
		return true;
	}
	public onZonesChanged(e: viewEvents.ViewZonesChangedEvent): boolean {
		return true;
	}

	// ---- end view event handlers

	public addWidget(_widget: IContentWidget): void {
		const myWidget = new Widget(this._context, this._viewDomNode, _widget);
		this._widgets[myWidget.id] = myWidget;

		if (myWidget.allowEditorOverflow) {
			this.overflowingContentWidgetsDomNode.appendChild(myWidget.domNode);
		} else {
			this.domNode.appendChild(myWidget.domNode);
		}

		this.setShouldRender();
	}

	public setWidgetPosition(widget: IContentWidget, position: IPosition | null | undefined, range: IRange | null | undefined, preference: ContentWidgetPositionPreference[] | null | undefined): void {
		const myWidget = this._widgets[widget.getId()];
		myWidget.setPosition(position, range, preference);

		this.setShouldRender();
	}

	public removeWidget(widget: IContentWidget): void {
		const widgetId = widget.getId();
		if (this._widgets.hasOwnProperty(widgetId)) {
			const myWidget = this._widgets[widgetId];
			delete this._widgets[widgetId];

			const domNode = myWidget.domNode.domNode;
			domNode.parentNode!.removeChild(domNode);
			domNode.removeAttribute('monaco-visible-content-widget');

			this.setShouldRender();
		}
	}

	public shouldSuppressMouseDownOnWidget(widgetId: string): boolean {
		if (this._widgets.hasOwnProperty(widgetId)) {
			return this._widgets[widgetId].suppressMouseDown;
		}
		return false;
	}

	public onBeforeRender(viewportData: ViewportData): void {
		let keys = Object.keys(this._widgets);
		for (let i = 0, len = keys.length; i < len; i++) {
			const widgetId = keys[i];
			this._widgets[widgetId].onBeforeRender(viewportData);
		}
	}

	public prepareRender(ctx: RenderingContext): void {
		let keys = Object.keys(this._widgets);
		for (let i = 0, len = keys.length; i < len; i++) {
			const widgetId = keys[i];
			this._widgets[widgetId].prepareRender(ctx);
		}
	}

	public render(ctx: RestrictedRenderingContext): void {
		let keys = Object.keys(this._widgets);
		for (let i = 0, len = keys.length; i < len; i++) {
			const widgetId = keys[i];
			this._widgets[widgetId].render(ctx);
		}
	}
}

interface IBoxLayoutResult {
	fitsAbove: boolean;
	aboveTop: number;
	aboveLeft: number;

	fitsBelow: boolean;
	belowTop: number;
	belowLeft: number;
}

class Widget {
	private readonly _context: ViewContext;
	private readonly _viewDomNode: FastDomNode<HTMLElement>;
	private readonly _actual: IContentWidget;

	public readonly domNode: FastDomNode<HTMLElement>;
	public readonly id: string;
	public readonly allowEditorOverflow: boolean;
	public readonly suppressMouseDown: boolean;

	private _fixedOverflowWidgets: boolean;
	private _contentWidth: number;
	private _contentLeft: number;
	private _lineHeight: number;

	private _position: IPosition | null;
	private _viewPosition: Position | null;
	private _range: IRange | null;
	private _viewRange: Range | null;
	private _preference: ContentWidgetPositionPreference[] | null;
	private _cachedDomNodeClientWidth: number;
	private _cachedDomNodeClientHeight: number;
	private _maxWidth: number;
	private _isVisible: boolean;

	private _renderData: Coordinate | null;

	constructor(context: ViewContext, viewDomNode: FastDomNode<HTMLElement>, actual: IContentWidget) {
		this._context = context;
		this._viewDomNode = viewDomNode;
		this._actual = actual;
		this.domNode = createFastDomNode(this._actual.getDomNode());

		this.id = this._actual.getId();
		this.allowEditorOverflow = this._actual.allowEditorOverflow || false;
		this.suppressMouseDown = this._actual.suppressMouseDown || false;

		this._fixedOverflowWidgets = this._context.configuration.editor.viewInfo.fixedOverflowWidgets;
		this._contentWidth = this._context.configuration.editor.layoutInfo.contentWidth;
		this._contentLeft = this._context.configuration.editor.layoutInfo.contentLeft;
		this._lineHeight = this._context.configuration.editor.lineHeight;

		this._setPosition(null, null);
		this._preference = [];
		this._cachedDomNodeClientWidth = -1;
		this._cachedDomNodeClientHeight = -1;
		this._maxWidth = this._getMaxWidth();
		this._isVisible = false;
		this._renderData = null;

		this.domNode.setPosition((this._fixedOverflowWidgets && this.allowEditorOverflow) ? 'fixed' : 'absolute');
		this.domNode.setVisibility('hidden');
		this.domNode.setAttribute('widgetId', this.id);
		this.domNode.setMaxWidth(this._maxWidth);
	}

	public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): void {
		if (e.lineHeight) {
			this._lineHeight = this._context.configuration.editor.lineHeight;
		}
		if (e.layoutInfo) {
			this._contentLeft = this._context.configuration.editor.layoutInfo.contentLeft;
			this._contentWidth = this._context.configuration.editor.layoutInfo.contentWidth;
			this._maxWidth = this._getMaxWidth();
		}
	}

	public onLineMappingChanged(e: viewEvents.ViewLineMappingChangedEvent): void {
		this._setPosition(this._position, this._range);
	}

	private _setPosition(position: IPosition | null | undefined, range: IRange | null | undefined): void {
		this._position = position || null;
		this._range = range || null;
		this._viewPosition = null;
		this._viewRange = null;

		if (this._position) {
			// Do not trust that widgets give a valid position
			const validModelPosition = this._context.model.validateModelPosition(this._position);
			if (this._context.model.coordinatesConverter.modelPositionIsVisible(validModelPosition)) {
				this._viewPosition = this._context.model.coordinatesConverter.convertModelPositionToViewPosition(validModelPosition);
			}
		}
		if (this._range) {
			// Do not trust that widgets give a valid position
			const validModelRange = this._context.model.validateModelRange(this._range);
			this._viewRange = this._context.model.coordinatesConverter.convertModelRangeToViewRange(validModelRange);
		}
	}

	private _getMaxWidth(): number {
		return (
			this.allowEditorOverflow
				? window.innerWidth || document.documentElement!.clientWidth || document.body.clientWidth
				: this._contentWidth
		);
	}

	public setPosition(position: IPosition | null | undefined, range: IRange | null | undefined, preference: ContentWidgetPositionPreference[] | null | undefined): void {
		this._setPosition(position, range);
		this._preference = preference || null;
		this._cachedDomNodeClientWidth = -1;
		this._cachedDomNodeClientHeight = -1;
	}

	private _layoutBoxInViewport(topLeft: Coordinate, bottomLeft: Coordinate, width: number, height: number, ctx: RenderingContext): IBoxLayoutResult {
		// Our visible box is split horizontally by the current line => 2 boxes

		// a) the box above the line
		let aboveLineTop = topLeft.top;
		let heightAboveLine = aboveLineTop;

		// b) the box under the line
		let underLineTop = bottomLeft.top + this._lineHeight;
		let heightUnderLine = ctx.viewportHeight - underLineTop;

		let aboveTop = aboveLineTop - height;
		let fitsAbove = (heightAboveLine >= height);
		let belowTop = underLineTop;
		let fitsBelow = (heightUnderLine >= height);

		// And its left
		let actualAboveLeft = topLeft.left;
		let actualBelowLeft = bottomLeft.left;
		if (actualAboveLeft + width > ctx.scrollLeft + ctx.viewportWidth) {
			actualAboveLeft = ctx.scrollLeft + ctx.viewportWidth - width;
		}
		if (actualBelowLeft + width > ctx.scrollLeft + ctx.viewportWidth) {
			actualBelowLeft = ctx.scrollLeft + ctx.viewportWidth - width;
		}
		if (actualAboveLeft < ctx.scrollLeft) {
			actualAboveLeft = ctx.scrollLeft;
		}
		if (actualBelowLeft < ctx.scrollLeft) {
			actualBelowLeft = ctx.scrollLeft;
		}

		return {
			fitsAbove: fitsAbove,
			aboveTop: aboveTop,
			aboveLeft: actualAboveLeft,

			fitsBelow: fitsBelow,
			belowTop: belowTop,
			belowLeft: actualBelowLeft,
		};
	}

	private _layoutBoxInPage(topLeft: Coordinate, bottomLeft: Coordinate, width: number, height: number, ctx: RenderingContext): IBoxLayoutResult | null {
		let aboveLeft0 = topLeft.left - ctx.scrollLeft;
		let belowLeft0 = bottomLeft.left - ctx.scrollLeft;

		if (aboveLeft0 < 0 || aboveLeft0 > this._contentWidth) {
			// Don't render if position is scrolled outside viewport
			return null;
		}

		let aboveTop = topLeft.top - height;
		let belowTop = bottomLeft.top + this._lineHeight;
		let aboveLeft = aboveLeft0 + this._contentLeft;
		let belowLeft = belowLeft0 + this._contentLeft;

		let domNodePosition = dom.getDomNodePagePosition(this._viewDomNode.domNode);
		let absoluteAboveTop = domNodePosition.top + aboveTop - dom.StandardWindow.scrollY;
		let absoluteBelowTop = domNodePosition.top + belowTop - dom.StandardWindow.scrollY;
		let absoluteAboveLeft = domNodePosition.left + aboveLeft - dom.StandardWindow.scrollX;
		let absoluteBelowLeft = domNodePosition.left + belowLeft - dom.StandardWindow.scrollX;

		let INNER_WIDTH = window.innerWidth || document.documentElement!.clientWidth || document.body.clientWidth;
		let INNER_HEIGHT = window.innerHeight || document.documentElement!.clientHeight || document.body.clientHeight;

		// Leave some clearance to the bottom
		let TOP_PADDING = 22;
		let BOTTOM_PADDING = 22;

		let fitsAbove = (absoluteAboveTop >= TOP_PADDING),
			fitsBelow = (absoluteBelowTop + height <= INNER_HEIGHT - BOTTOM_PADDING);

		if (absoluteAboveLeft + width + 20 > INNER_WIDTH) {
			let delta = absoluteAboveLeft - (INNER_WIDTH - width - 20);
			absoluteAboveLeft -= delta;
			aboveLeft -= delta;
		}
		if (absoluteBelowLeft + width + 20 > INNER_WIDTH) {
			let delta = absoluteBelowLeft - (INNER_WIDTH - width - 20);
			absoluteBelowLeft -= delta;
			belowLeft -= delta;
		}
		if (absoluteAboveLeft < 0) {
			let delta = absoluteAboveLeft;
			absoluteAboveLeft -= delta;
			aboveLeft -= delta;
		}
		if (absoluteBelowLeft < 0) {
			let delta = absoluteBelowLeft;
			absoluteBelowLeft -= delta;
			belowLeft -= delta;
		}

		if (this._fixedOverflowWidgets) {
			aboveTop = absoluteAboveTop;
			belowTop = absoluteBelowTop;
			aboveLeft = absoluteAboveLeft;
			belowLeft = absoluteBelowLeft;
		}

		return { fitsAbove, aboveTop, aboveLeft, fitsBelow, belowTop, belowLeft };
	}

	private _prepareRenderWidgetAtExactPositionOverflowing(topLeft: Coordinate): Coordinate {
		return new Coordinate(topLeft.top, topLeft.left + this._contentLeft);
	}

	/**
	 * Compute `this._topLeft`
	 */
	private _getTopAndBottomLeft(ctx: RenderingContext): [Coordinate, Coordinate] | [null, null] {
		if (!this._viewPosition) {
			return [null, null];
		}

		const visibleRangeForPosition = ctx.visibleRangeForPosition(this._viewPosition);
		if (!visibleRangeForPosition) {
			return [null, null];
		}

		const topForPosition = ctx.getVerticalOffsetForLineNumber(this._viewPosition.lineNumber) - ctx.scrollTop;
		const topLeft = new Coordinate(topForPosition, visibleRangeForPosition.left);

		let largestLineNumber = this._viewPosition.lineNumber;
		let smallestLeft = visibleRangeForPosition.left;

		if (this._viewRange) {
			const visibleRangesForRange = ctx.linesVisibleRangesForRange(this._viewRange, false);
			if (visibleRangesForRange && visibleRangesForRange.length > 0) {
				for (let i = visibleRangesForRange.length - 1; i >= 0; i--) {
					const visibleRangesForLine = visibleRangesForRange[i];
					if (visibleRangesForLine.lineNumber >= largestLineNumber) {
						if (visibleRangesForLine.lineNumber > largestLineNumber) {
							largestLineNumber = visibleRangesForLine.lineNumber;
							smallestLeft = Constants.MAX_SAFE_SMALL_INTEGER;
						}
						for (let j = 0, lenJ = visibleRangesForLine.ranges.length; j < lenJ; j++) {
							const visibleRange = visibleRangesForLine.ranges[j];

							if (visibleRange.left < smallestLeft) {
								smallestLeft = visibleRange.left;
							}
						}
					}
				}
			}
		}

		const topForBottomLine = ctx.getVerticalOffsetForLineNumber(largestLineNumber) - ctx.scrollTop;
		const bottomLeft = new Coordinate(topForBottomLine, smallestLeft);

		return [topLeft, bottomLeft];
	}

	private _prepareRenderWidget(ctx: RenderingContext): Coordinate | null {
		const [topLeft, bottomLeft] = this._getTopAndBottomLeft(ctx);
		if (!topLeft || !bottomLeft) {
			return null;
		}

		if (this._cachedDomNodeClientWidth === -1 || this._cachedDomNodeClientHeight === -1) {
			const domNode = this.domNode.domNode;
			this._cachedDomNodeClientWidth = domNode.clientWidth;
			this._cachedDomNodeClientHeight = domNode.clientHeight;
		}

		let placement: IBoxLayoutResult | null;
		if (this.allowEditorOverflow) {
			placement = this._layoutBoxInPage(topLeft, bottomLeft, this._cachedDomNodeClientWidth, this._cachedDomNodeClientHeight, ctx);
		} else {
			placement = this._layoutBoxInViewport(topLeft, bottomLeft, this._cachedDomNodeClientWidth, this._cachedDomNodeClientHeight, ctx);
		}

		// Do two passes, first for perfect fit, second picks first option
		if (this._preference) {
			for (let pass = 1; pass <= 2; pass++) {
				for (let i = 0; i < this._preference.length; i++) {
					// placement
					let pref = this._preference[i];
					if (pref === ContentWidgetPositionPreference.ABOVE) {
						if (!placement) {
							// Widget outside of viewport
							return null;
						}
						if (pass === 2 || placement.fitsAbove) {
							return new Coordinate(placement.aboveTop, placement.aboveLeft);
						}
					} else if (pref === ContentWidgetPositionPreference.BELOW) {
						if (!placement) {
							// Widget outside of viewport
							return null;
						}
						if (pass === 2 || placement.fitsBelow) {
							return new Coordinate(placement.belowTop, placement.belowLeft);
						}
					} else {
						if (this.allowEditorOverflow) {
							return this._prepareRenderWidgetAtExactPositionOverflowing(topLeft);
						} else {
							return topLeft;
						}
					}
				}
			}
		}
		return null;
	}

	/**
	 * On this first pass, we ensure that the content widget (if it is in the viewport) has the max width set correctly.
	 */
	public onBeforeRender(viewportData: ViewportData): void {
		if (!this._viewPosition || !this._preference) {
			return;
		}

		if (this._viewPosition.lineNumber < viewportData.startLineNumber || this._viewPosition.lineNumber > viewportData.endLineNumber) {
			// Outside of viewport
			return;
		}

		this.domNode.setMaxWidth(this._maxWidth);
	}

	public prepareRender(ctx: RenderingContext): void {
		this._renderData = this._prepareRenderWidget(ctx);
	}

	public render(ctx: RestrictedRenderingContext): void {
		if (!this._renderData) {
			// This widget should be invisible
			if (this._isVisible) {
				this.domNode.removeAttribute('monaco-visible-content-widget');
				this._isVisible = false;
				this.domNode.setVisibility('hidden');
			}
			return;
		}

		// This widget should be visible
		if (this.allowEditorOverflow) {
			this.domNode.setTop(this._renderData.top);
			this.domNode.setLeft(this._renderData.left);
		} else {
			this.domNode.setTop(this._renderData.top + ctx.scrollTop - ctx.bigNumbersDelta);
			this.domNode.setLeft(this._renderData.left);
		}

		if (!this._isVisible) {
			this.domNode.setVisibility('inherit');
			this.domNode.setAttribute('monaco-visible-content-widget', 'true');
			this._isVisible = true;
		}
	}
}


text:
package com.eventprogramming.gui.components;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import com.eventprogramming.client.ClientGUI.STATE;
import com.eventprogramming.gui.logic.DefaultSelectionListener;
import com.eventprogramming.gui.logic.PageMediator;

public class RegisterPageComposite extends PageComposite {

	public RegisterPageComposite(Composite parent, int style, PageMediator mediator) {
		super(parent, style, mediator);
		buildComposite();
	}

	protected void buildComposite() {
		Group mainGroup = new Group(this, SWT.NONE);
		mainGroup.setLayout(new GridLayout(2, true));
		mainGroup.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));

		Label userLabel = new Label(mainGroup, SWT.NONE);
		userLabel.setText("User name:");
		userLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
		Text userText = new Text(mainGroup, SWT.SINGLE | SWT.BORDER);
		userText.setText("");
		userText.setTextLimit(100);
		userText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		fMediator.registerControl(userText, "userText");

		Label passLabel = new Label(mainGroup, SWT.NONE);
		passLabel.setText("Password:");
		passLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
		Text passText = new Text(mainGroup, SWT.SINGLE | SWT.BORDER);
		passText.setText("");
		passText.setTextLimit(100);
		passText.setEchoChar('*');
		passText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		fMediator.registerControl(passText, "passText");

		Label emailLabel = new Label(mainGroup, SWT.NONE);
		emailLabel.setText("Email:");
		emailLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
		Text emailText = new Text(mainGroup, SWT.SINGLE | SWT.BORDER);
		emailText.setText("");
		emailText.setTextLimit(100);
		emailText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		fMediator.registerControl(emailText, "emailText");

		Button buttonRegister = new Button(this, SWT.PUSH);
		buttonRegister.setText("Register");
		buttonRegister.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
		fMediator.registerControl(buttonRegister, "buttonRegister");
		buttonRegister.addSelectionListener(new DefaultSelectionListener(fMediator, buttonRegister));
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.canoo.dp.impl.server.event;

import com.canoo.dp.impl.platform.core.Assert;
import com.canoo.platform.remoting.server.event.MessageEventContext;
import com.canoo.platform.remoting.server.event.Topic;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.StreamSerializer;
import org.apiguardian.api.API;

import java.io.IOException;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;

import static com.canoo.dp.impl.server.event.DistributedEventConstants.CONTEXT_PARAM;
import static com.canoo.dp.impl.server.event.DistributedEventConstants.DATA_PARAM;
import static com.canoo.dp.impl.server.event.DistributedEventConstants.METADATA_KEY_PARAM;
import static com.canoo.dp.impl.server.event.DistributedEventConstants.METADATA_PARAM;
import static com.canoo.dp.impl.server.event.DistributedEventConstants.METADATA_VALUE_PARAM;
import static com.canoo.dp.impl.server.event.DistributedEventConstants.SPEC_1_0;
import static com.canoo.dp.impl.server.event.DistributedEventConstants.SPEC_VERSION_PARAM;
import static com.canoo.dp.impl.server.event.DistributedEventConstants.TIMESTAMP_PARAM;
import static com.canoo.dp.impl.server.event.DistributedEventConstants.TOPIC_PARAM;
import static com.canoo.dp.impl.server.event.DistributedEventConstants.TYPE_ID;
import static org.apiguardian.api.API.Status.INTERNAL;

@API(since = "1.0.0.RC1", status = INTERNAL)
public class EventStreamSerializer implements StreamSerializer<DolphinEvent<?>> {

    private final Gson gson;

    private EventStreamSerializer(final Gson gson) {
        this.gson = Assert.requireNonNull(gson, "gson");
    }

    public EventStreamSerializer() {
        this(new GsonBuilder().serializeNulls().create());
    }

    @Override
    public void write(final ObjectDataOutput out, final DolphinEvent<?> event) throws IOException {
        out.writeUTF(gson.toJson(convertToJson(event)));
    }

    private JsonObject convertToJson(final DolphinEvent<?> event) throws IOException {
        final JsonObject root = new JsonObject();

        root.addProperty(SPEC_VERSION_PARAM, SPEC_1_0);

        final Serializable data = event.getData();
        if (data != null) {
            root.addProperty(DATA_PARAM, Base64Utils.toBase64(data));
        } else {
            root.add(DATA_PARAM, JsonNull.INSTANCE);
        }

        root.add(CONTEXT_PARAM, convertToJson(event.getMessageEventContext()));

        return root;
    }

    private JsonObject convertToJson(final MessageEventContext<?> eventContext) throws IOException {
        final JsonObject root = new JsonObject();
        root.addProperty(TOPIC_PARAM, eventContext.getTopic().getName());
        root.addProperty(TIMESTAMP_PARAM, eventContext.getTimestamp());

        final JsonArray metadataArray = new JsonArray();
        for (final Map.Entry<String, Serializable> entry : eventContext.getMetadata().entrySet()) {
            final String key = entry.getKey();
            final Serializable data = entry.getValue();
            final JsonObject metadataEntry = new JsonObject();
            metadataEntry.addProperty(METADATA_KEY_PARAM, key);
            if (data != null) {
                metadataEntry.addProperty(METADATA_VALUE_PARAM, Base64Utils.toBase64(data));
            } else {
                metadataEntry.add(METADATA_VALUE_PARAM, JsonNull.INSTANCE);
            }
            metadataArray.add(metadataEntry);
        }
        root.add(METADATA_PARAM, metadataArray);
        return root;
    }

    @Override
    public DolphinEvent<?> read(final ObjectDataInput in) throws IOException {
        final JsonElement root = new JsonParser().parse(in.readUTF());
        if (!root.isJsonObject()) {
            throw new IllegalArgumentException("Input can not be parsed!");
        }
        if (!root.getAsJsonObject().has(CONTEXT_PARAM)) {
            throw new IllegalArgumentException("Input can not be parsed! No event context found");
        }

        if (!root.getAsJsonObject().has(SPEC_VERSION_PARAM) &&
                !root.getAsJsonObject().get(SPEC_VERSION_PARAM).isJsonPrimitive() &&
                !root.getAsJsonObject().get(SPEC_VERSION_PARAM).getAsJsonPrimitive().isString() &&
                !root.getAsJsonObject().get(SPEC_VERSION_PARAM).getAsJsonPrimitive().getAsString().equals(SPEC_1_0)) {
            throw new IllegalArgumentException("Input can not be parsed! Unknown Spec");
        }

        final JsonElement contextElement = root.getAsJsonObject().get(CONTEXT_PARAM);
        if (!contextElement.isJsonObject()) {
            throw new IllegalArgumentException("Input can not be parsed! event context not parseable");
        }

        if (!contextElement.getAsJsonObject().has(TOPIC_PARAM) &&
                !contextElement.getAsJsonObject().get(TOPIC_PARAM).isJsonPrimitive() &&
                !contextElement.getAsJsonObject().get(TOPIC_PARAM).getAsJsonPrimitive().isString()) {
            throw new IllegalArgumentException("Input can not be parsed! No topic found");
        }
        final Topic<?> topic = new Topic<>(contextElement.getAsJsonObject().getAsJsonPrimitive(TOPIC_PARAM).getAsString());

        if (!contextElement.getAsJsonObject().has(TIMESTAMP_PARAM) &&
                !contextElement.getAsJsonObject().get(TIMESTAMP_PARAM).isJsonPrimitive() &&
                !contextElement.getAsJsonObject().get(TIMESTAMP_PARAM).getAsJsonPrimitive().isNumber()) {
            throw new IllegalArgumentException("Input can not be parsed! No timestamp found");
        }
        final long timestamp = contextElement.getAsJsonObject().getAsJsonPrimitive(TIMESTAMP_PARAM).getAsLong();

        if (!root.getAsJsonObject().has(DATA_PARAM)) {
            throw new IllegalArgumentException("Input can not be parsed! No data found");
        }
        final JsonElement dataElement = root.getAsJsonObject().get(DATA_PARAM);
        Serializable data;
        if (dataElement.isJsonNull()) {
            data = null;
        } else if (dataElement.isJsonPrimitive() && dataElement.getAsJsonPrimitive().isString()) {
            try {
                data = Base64Utils.fromBase64(dataElement.getAsJsonPrimitive().getAsString());
            } catch (ClassNotFoundException e) {
                throw new IllegalArgumentException("Input can not be parsed! Data can not be parsed");
            }
        } else {
            throw new IllegalArgumentException("Input can not be parsed! Data can not be parsed");
        }

        final DolphinEvent event = new DolphinEvent(topic, timestamp, data);

        if (!contextElement.getAsJsonObject().has(METADATA_PARAM)) {
            throw new IllegalArgumentException("Input can not be parsed! No metadata found");
        }
        final JsonElement metadataArrayElement = contextElement.getAsJsonObject().get(METADATA_PARAM);
        if (!metadataArrayElement.isJsonArray()) {
            throw new IllegalArgumentException("Input can not be parsed! metadata can not be parsed");
        }
        final Iterator<JsonElement> metadataIterator = metadataArrayElement.getAsJsonArray().iterator();
        while (metadataIterator.hasNext()) {
            final JsonElement metadataElement = metadataIterator.next();
            if (!metadataElement.isJsonObject()) {
                throw new IllegalArgumentException("Input can not be parsed! metadata can not be parsed");
            }
            if (!metadataElement.getAsJsonObject().has(METADATA_KEY_PARAM) &&
                    !metadataElement.getAsJsonObject().get(METADATA_KEY_PARAM).isJsonPrimitive() &&
                    !metadataElement.getAsJsonObject().get(METADATA_KEY_PARAM).getAsJsonPrimitive().isString()) {
                throw new IllegalArgumentException("Input can not be parsed! metadata can not be parsed");
            }
            final String metadataKey = metadataElement.getAsJsonObject().get(METADATA_KEY_PARAM).getAsJsonPrimitive().getAsString();

            if (!metadataElement.getAsJsonObject().has(METADATA_VALUE_PARAM) &&
                    ((metadataElement.getAsJsonObject().get(METADATA_VALUE_PARAM).isJsonPrimitive() &&
                            metadataElement.getAsJsonObject().get(METADATA_VALUE_PARAM).getAsJsonPrimitive().isString()) || metadataElement.getAsJsonObject().get(METADATA_VALUE_PARAM).isJsonNull())) {
                throw new IllegalArgumentException("Input can not be parsed! metadata for key '" + metadataKey + "' can not be parsed");
            }
            if (metadataElement.getAsJsonObject().get(METADATA_VALUE_PARAM).isJsonNull()) {
                event.addMetadata(metadataKey, null);
            } else {
                try {
                    event.addMetadata(metadataKey, Base64Utils.fromBase64(metadataElement.getAsJsonObject().get(METADATA_VALUE_PARAM).getAsJsonPrimitive().getAsString()));
                } catch (final ClassNotFoundException e) {
                    throw new IllegalArgumentException("Input can not be parsed! metadata for key '" + metadataKey + "' can not be parsed");
                }
            }
        }
        return event;
    }

    @Override
    public int getTypeId() {
        return TYPE_ID;
    }

    @Override
    public void destroy() {

    }
}


text:
/*
 * BP.h
 *
 *  Created on: 14/01/2010
 *      Author: jorge
 */

#ifndef BP_H_
#define BP_H_

#include <string>
#include "NeuralNet.h"
#include "Data.h"

class BP {

public:

	BP();

	virtual ~BP();

	double learn(NeuralNet* net, Data** data, int numberOfData, Data* validate, Data* test, int cycles, double initalLearning, double finalLearning, std::string netOutputFile);

private:

	double test(NeuralNet* net, Data** data, int numberOfData, double* netOutput);

};

#endif /* BP_H_ */


text:
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;

namespace osu.Game.Screens
{
    public class OsuScreenDependencies : DependencyContainer
    {
        public Bindable<WorkingBeatmap> Beatmap { get; }

        public Bindable<RulesetInfo> Ruleset { get; }

        public Bindable<IReadOnlyList<Mod>> Mods { get; }

        public OsuScreenDependencies(bool requireLease, IReadOnlyDependencyContainer parent)
            : base(parent)
        {
            if (requireLease)
            {
                Beatmap = parent.Get<LeasedBindable<WorkingBeatmap>>()?.GetBoundCopy();

                if (Beatmap == null)
                {
                    Cache(Beatmap = parent.Get<Bindable<WorkingBeatmap>>().BeginLease(false));
                    CacheAs(Beatmap);
                }

                Ruleset = parent.Get<LeasedBindable<RulesetInfo>>()?.GetBoundCopy();

                if (Ruleset == null)
                {
                    Cache(Ruleset = parent.Get<Bindable<RulesetInfo>>().BeginLease(true));
                    CacheAs(Ruleset);
                }

                Mods = parent.Get<LeasedBindable<IReadOnlyList<Mod>>>()?.GetBoundCopy();

                if (Mods == null)
                {
                    Cache(Mods = parent.Get<Bindable<IReadOnlyList<Mod>>>().BeginLease(true));
                    CacheAs(Mods);
                }
            }
            else
            {
                Beatmap = (parent.Get<LeasedBindable<WorkingBeatmap>>() ?? parent.Get<Bindable<WorkingBeatmap>>()).GetBoundCopy();
                Ruleset = (parent.Get<LeasedBindable<RulesetInfo>>() ?? parent.Get<Bindable<RulesetInfo>>()).GetBoundCopy();
                Mods = (parent.Get<LeasedBindable<IReadOnlyList<Mod>>>() ?? parent.Get<Bindable<IReadOnlyList<Mod>>>()).GetBoundCopy();
            }
        }
    }
}


text:
from __future__ import absolute_import

from django.conf import settings
from django.conf.urls import url
from wagtail.wagtailimages.views.serve import ServeView

from .api import router
from .views import image

urlpatterns = [
    url(r'^api/v1/', router.urls),
    url('^images/(?P<pk>\d+)/(?P<specs>.+)$', image, name='image'),
    url(r'^images/([^/]*)/(\d*)/([^/]*)/[^/]*$', ServeView.as_view(), name='wagtailimages_serve'),
]

if settings.DEBUG:
    from django.views.generic import TemplateView

    # Add views for testing 404 and 500 templates
    urlpatterns += [
        url(r'^404/$', TemplateView.as_view(template_name='404.html')),
        url(r'^500/$', TemplateView.as_view(template_name='500.html')),
    ]


text:
/* $Id$ */

package org.apache.fop.layoutmgr;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * An iterator over {@link Position} instances, that is wrapped around
 * another 'parent' {@link Iterator}. The parent can be either another
 * {@code PositionIterator}, or an iterator over {@link KnuthElement}s,
 * for example.

 * The {@link #next()} method always returns a {@link Position}. The
 * {@link #getPos(Object)} method can be overridden in subclasses
 * to take care of obtaining the {@link LayoutManager} or {@link Position}
 * from the object returned by the parent iterator's {@code next()} method.
 */
public class PositionIterator implements Iterator<Position> {

    private Iterator parentIter;
    private Object nextObj;
    private LayoutManager childLM;
    private boolean hasNext;

    /**
     * Construct position iterator.
     * @param parentIter an iterator to use as parent
     */
    public PositionIterator(Iterator parentIter) {
        this.parentIter = parentIter;
        lookAhead();
        //checkNext();
    }

    /** @return layout manager of next child layout manager or null */
    public LayoutManager getNextChildLM() {
        // Move to next "segment" of iterator, ie: new childLM
        if (childLM == null && nextObj != null) {
            childLM = getLM(nextObj);
            hasNext = true;
        }
        return childLM;
    }

    /**
     * @param nextObj next object from which to obtain position
     * @return layout manager
     */
    protected LayoutManager getLM(Object nextObj) {
        return getPos(nextObj).getLM();
    }

    /**
     * Default implementation assumes that the passed
     * {@code nextObj} is itself a {@link Position}, and just returns it.
     * Subclasses for which this is not the case, must provide a
     * suitable override this method.
     * @param nextObj next object from which to obtain position
     * @return position of next object.
     */
    protected Position getPos(Object nextObj) {
        if (nextObj instanceof Position) {
            return (Position)nextObj;
        }
        throw new IllegalArgumentException(
                "Cannot obtain Position from the given object.");
    }

    private void lookAhead() {
        if (parentIter.hasNext()) {
            hasNext = true;
            nextObj = parentIter.next();
        } else {
            endIter();
        }
    }

    /** @return true if not at end of sub-sequence with same child layout manager */
    protected boolean checkNext() {
        LayoutManager lm = getLM(nextObj);
        if (childLM == null) {
            childLM = lm;
        } else if (childLM != lm && lm != null) {
            // End of this sub-sequence with same child LM
            hasNext = false;
            childLM = null;
            return false;
        }
        return true;
    }

    /** end (reset) iterator */
    protected void endIter() {
        hasNext = false;
        nextObj = null;
        childLM = null;
    }

    /** {@inheritDoc} */
    public boolean hasNext() {
        return (hasNext && checkNext());
    }

    /** {@inheritDoc} */
    public Position next() throws NoSuchElementException {
        if (hasNext) {
            Position retPos = getPos(nextObj);
            lookAhead();
            return retPos;
        } else {
            throw new NoSuchElementException("PosIter");
        }
    }

    /** @return peek at next object */
    public Object peekNext() {
        return nextObj;
    }

    /** {@inheritDoc} */
    public void remove() throws UnsupportedOperationException {
        throw new UnsupportedOperationException("PositionIterator doesn't support remove");
    }
}


text:
package de.gurkenlabs.litiengine;

import de.gurkenlabs.litiengine.util.MathUtilities;
import jakarta.xml.bind.annotation.XmlEnum;
import jakarta.xml.bind.annotation.XmlEnumValue;

/** The enum {@code Valign} defines a range of vertical alignments. */
@XmlEnum
public enum Valign {
  @XmlEnumValue("DOWN")
  DOWN(1f),
  @XmlEnumValue("MIDDLE")
  MIDDLE(0.5f),
  @XmlEnumValue("TOP")
  TOP(0f),
  @XmlEnumValue("MIDDLE_TOP")
  MIDDLE_TOP(0.25f),
  @XmlEnumValue("MIDDLE_DOWN")
  MIDDLE_DOWN(0.75f);

  private final float portion;

  Valign(float portion) {
    this.portion = portion;
  }

  /**
   * Gets the vertical align enumeration value for the specified string.
   *
   * @param valignString
   *          The string representing the enum value.
   * @return The enum value represented by the specified string or {@link Valign#DOWN} if the specified string is invalid.
   */
  public static Valign get(final String valignString) {
    if (valignString == null || valignString.isEmpty()) {
      return Valign.DOWN;
    }

    try {
      return Valign.valueOf(valignString.toUpperCase());
    } catch (final IllegalArgumentException iae) {
      return Valign.DOWN;
    }
  }

  /**
   * Gets the proportional value of this instance.
   *
   * @param height
   *          The height to calculate the relative value from.
   * @return The proportional value for the specified height.
   */
  public float getValue(float height) {
    return height * this.portion;
  }

  /**
   * Gets the proportional value of this instance.
   *
   * @param height
   *          The height to calculate the relative value from.
   * @return The proportional value for the specified height.
   */
  public double getValue(double height) {
    return height * this.portion;
  }

  /**
   * Gets the proportional value of this instance.
   *
   * @param height
   *          The height to calculate the relative value from.
   * @return The proportional value for the specified height.
   */
  public int getValue(int height) {
    return (int) (height * this.portion);
  }

  /**
   * Gets the location for the specified object height to be vertically aligned within the bounds of the specified height.
   *
   * @param height
   *          The height, limiting the vertical alignment.
   * @param objectHeight
   *          The height of the object for which to calculate the vertically aligned location.
   * @return The y-coordinate for the location of the object with the specified height.
   */
  public double getLocation(final double height, final double objectHeight) {
    double value = this.getValue(height);
    double location = value - objectHeight / 2.0;

    if (objectHeight > height) {
      return location;
    }

    return MathUtilities.clamp(location, 0, height - objectHeight);
  }
}


text:
import sys
import random

read_file = open("data/user_profile.txt", 'r')
write_file = open("data/mini_user_profile.txt", 'w')
number_of_lines = int(sys.argv[1])
number_of_items = int(sys.argv[2])

#record number of lines
count = 0
random_num_list = []
# loop through the file to get number of lines in the file
for line in read_file:
    count += 1

print "generating random numbers"
# generating a list of random lines to read from
for i in range(0, number_of_lines):
    random_num_list.append(random.randint(0, count))

#get rid of any duplicates
no_duplicate_list = list(set(random_num_list))

#sort the list
no_duplicate_list.sort()
#print no_duplicate_list

#go to file begining
read_file.seek(0)
count = 0
index = 0
user_id_list = []
print "getting lines from user_profile"
for line in read_file:
    if count == no_duplicate_list[index]:
        write_file.write(line)
        index += 1
        user_id_list.append(int(line.split()[0]))
        if index == len(no_duplicate_list):
            break
    count += 1

#user_id_list is sorted

user_id_list = map(str, user_id_list)
user_id_list.sort()
#print user_id_list
print "user_id finished"

print "getting lines from item"
read_file = open("data/item.txt", 'r')
write_file = open("data/mini_item.txt", 'w')
count = 0
random_num_list = []
for line in read_file:
    count += 1

for i in range(0, number_of_items):
    random_num_list.append(random.randint(0, count))

#no duplicate
random_num_list = list(set(random_num_list))

random_num_list.sort()

read_file.seek(0)
count = 0
index = 0
item_id_list = []
for line in read_file:
    if count == random_num_list[index]:
        write_file.write(line)
        index += 1
        item_id_list.append(int(line.split()[0]))
        if index == len(random_num_list):
            break
    count += 1
print "item finished"

print "getting mini user_key_word"
read_file = open("data/user_key_word.txt", 'r')
write_file = open("data/mini_user_key_word.txt", 'w')

#record number of lines
count = 0
index = 0
# loop through the file to get number of lines in the file
for line in read_file:
    if line.split()[0] == user_id_list[index]:
        write_file.write(line)
        index += 1
        if index == len(user_id_list):
            #print "break"
            break
print "user keyword finished"
#go to file begining
#getting the user_sns_small

print "getting user sns"
#print user_id_list
read_file = open("data/user_sns.txt", 'r')

#write_file = open("data/mini_user_sns_small.txt", 'w')
user_sns_list = []
index = 0
met = False
count = 0
for line in read_file:
    count += 1
    #print count
    #Same user multiple following
    if met:
        if line.split()[0] != user_id_list[index]:
            index += 1
            met = False
            if index == len(user_id_list):
                break
    if line.split()[0] == user_id_list[index]:
        #print "here"
        user_sns_list.append(line)
        met = True
    # if the current line's user is greater than the user list, that means
    # the user doesn't follow or are following, then we move to next user
    if line.split()[0] > user_id_list[index]:
        index += 1
        if index == len(user_id_list):
            break

#print user_sns_list
write_file = open("data/mini_user_sns.txt",'w')
for line in user_sns_list:
    for user_id in user_id_list:
        if line.split()[1] == user_id:
            write_file.write(line)
            break
print "sns got"

print "getting user action"
#for line in write_file:
read_file = open("data/user_action.txt", 'r')
user_action_list = []
index = 0
met = False
count = 0
for line in read_file:
    count += 1
    #print count
    if met:
        if line.split()[0] != user_id_list[index]:
            index += 1
            met = False
            if index == len(user_id_list):
                break
    if line.split()[0] == user_id_list[index]:
        #print "here"
        user_action_list.append(line)
        met = True
    if line.split()[0] > user_id_list[index]:
        index += 1
        if index == len(user_id_list):
            break
#print user_action_list
write_file = open("data/mini_user_action.txt",'w')
for line in user_action_list:
    for user_id in user_id_list:
        if line.split()[1] == user_id:
            write_file.write(line)
            break
print "user action got"

print "getting rec_log_train"
user_set = set(user_id_list)
item_set = set(item_id_list)
read_file = open("data/rec_log_train.txt", 'r')
write_file = open("data/mini_rec_log_train.txt",'w')
count = 0
#for item in item_set:
#    print type(item)
#for user in user_set:
#    print type(user)
for line in read_file:
    words = line.split()
#    if words[0] in user_set and (words[1] in user_set or words[1] in item_set):
    if words[0] in user_set and words[1] in item_set:
        write_file.write(line)
    print count
    count += 1

print "Done"


text:
package com.netflix.spectator.ipc;

import com.netflix.spectator.api.BasicTag;
import com.netflix.spectator.api.Tag;

/**
 * Standard dimensions used for IPC metrics.
 */
public enum IpcTagKey {

  /** The library that produced the metric. */
  owner("owner"),

  /**
   * Indicates whether or not the request was successful. See {@link IpcResult}
   * for permitted values.
   */
  result("ipc.result"),

  /**
   * Dimension indicating a high level status for the request. These values are the same
   * for all implementations to make it easier to query across services. See {@link IpcStatus}
   * for permitted values.
   */
  status("ipc.status"),

  /**
   * Optional dimension indicating a more detailed status. The values for this are
   * implementation specific. For example with HTTP, the status code would be a likely
   * value used here.
   */
  statusDetail("ipc.status.detail"),

  /**
   * Dimension indicating a high level cause for the request failure. These groups
   * are the same for all implementations to make it easier to query across all
   * services and client implementations. See {@link IpcErrorGroup} for permitted
   * values.
   *
   * @deprecated Use {@link #status} instead. This value is scheduled for removal
   * in a future release.
   */
  @Deprecated
  errorGroup("ipc.error.group"),

  /**
   * Implementation specific error code.
   *
   * @deprecated Use {@link #statusDetail} instead. This value is scheduled for removal
   * in a future release.
   */
  @Deprecated
  errorReason("ipc.error.reason"),

  /**
   * Indicates the attempt number for the request.
   */
  attempt("ipc.attempt"),

  /**
   * Indicates if this is the final attempt for the request. For example, if the client
   * is configured to allow 1 retry, then the second attempt would be final. Acceptable
   * values are {@code true} and {@code false}.
   */
  attemptFinal("ipc.attempt.final"),

  /**
   * Identifier for the client instance making the request. This is typically the name used
   * to see the associated configuration settings for the client.
   */
  id("id"),

  /**
   * Eureka VIP used to select the server. If there are multiple vips in the list, then it
   * should be the first vip that caused the server to get selected.
   */
  vip("ipc.vip"),

  /**
   * The server side endpoint that is being requested. This should be a bounded set that
   * will have a small cardinality. Do not pass in the unsanitized path value for a
   * URI.
   */
  endpoint("ipc.endpoint"),

  /**
   * Protocol used for the request. For example {@code http_1} or {@code http_2}.
   */
  protocol("ipc.protocol"),

  /**
   * Region where the client is located.
   *
   * @deprecated Not included in the spec. Common IPC tags should bias towards consistency
   * across integrations and only use tags that are part of the spec. This value is scheduled
   * for removal in a future release.
   */
  @Deprecated
  clientRegion("ipc.client.region"),

  /**
   * Availability zone where the client is located.
   *
   * @deprecated Not included in the spec. Common IPC tags should bias towards consistency
   * across integrations and only use tags that are part of the spec. This value is scheduled
   * for removal in a future release.
   */
  @Deprecated
  clientZone("ipc.client.zone"),

  /**
   * Application that is running the client.
   */
  clientApp("ipc.client.app"),

  /**
   * Cluster that is running the client.
   */
  clientCluster("ipc.client.cluster"),

  /**
   * Server group that is running the client.
   */
  clientAsg("ipc.client.asg"),

  /**
   * Region where the server is located.
   *
   * @deprecated Not included in the spec. Common IPC tags should bias towards consistency
   * across integrations and only use tags that are part of the spec. This value is scheduled
   * for removal in a future release.
   */
  @Deprecated
  serverRegion("ipc.server.region"),

  /**
   * Availability zone where the server is located.
   *
   * @deprecated Not included in the spec. Common IPC tags should bias towards consistency
   * across integrations and only use tags that are part of the spec. This value is scheduled
   * for removal in a future release.
   */
  @Deprecated
  serverZone("ipc.server.zone"),

  /**
   * Application name for the server.
   */
  serverApp("ipc.server.app"),

  /**
   * Cluster name for the server.
   */
  serverCluster("ipc.server.cluster"),

  /**
   * Server group name for the server.
   */
  serverAsg("ipc.server.asg"),

  /**
   * Instance id for the server. Do not use this unless you know it will not
   * cause a metrics explosion. If there is any doubt, then do not enable it.
   *
   * @deprecated Not included in the spec. Common IPC tags should bias towards consistency
   * across integrations and only use tags that are part of the spec. This value is scheduled
   * for removal in a future release.
   */
  @Deprecated
  serverNode("ipc.server.node"),

  /**
   * The port number connected to on the server.
   *
   * @deprecated Not included in the spec. Common IPC tags should bias towards consistency
   * across integrations and only use tags that are part of the spec. This value is scheduled
   * for removal in a future release.
   */
  @Deprecated
  serverPort("ipc.server.port"),

  /**
   * Indicates that an artificial failure was injected into the request processing for testing
   * purposes. The outcome of that failure will be reflected in the other error tags.
   * See {@link IpcFailureInjection} for permitted values.
   */
  failureInjected("ipc.failure.injected"),

  /**
   * HTTP status code. In most cases it is preferred to use {@link #statusDetail} instead.
   * This tag key is optionally used to include the HTTP status code when the status detail
   * is overridden with application specific values.
   */
  httpStatus("http.status"),

  /**
   * HTTP method such as GET, PUT, or POST.
   */
  httpMethod("http.method");

  private final String key;

  /** Create a new instance. */
  IpcTagKey(String key) {
    this.key = key;
  }

  /** String to use as the tag key. */
  public String key() {
    return key;
  }

  /** Create a new tag with the specified value and this key. */
  public Tag tag(String value) {
    return new BasicTag(key, value);
  }
}


text:
class Board {

  config() {
    return {
      id: 'board',
      hook: window.document.body,
      autoBind: false,
      isToolBar: false,
      isSolved: false,
      cols: 8,
      rows: 8,
      css: {
        base: 'container-fluid'
      }
    }
  }

  constructor(config) {
    this._docElement = window.document.createElement('div');
    this._toolBar = null;
    this._id = config && config.hasOwnProperty('id') ? config.id : this.config().id;
    this._isSolved = config && config.hasOwnProperty('isSolved') ? config.isSolved : this.config().isSolved;
    this._isToolBar = config && config.hasOwnProperty('isToolBar') ? config.isToolBar : this.config().isToolBar;
    this._hook = config && config.hasOwnProperty('hook') ? config.hook : this.config().hook;
    this._autoBind = config && config.hasOwnProperty('autoBind') ? config.autoBind : this.config().autoBind;
    this._cols = config && config.hasOwnProperty('cols') ? config.cols : this.config().cols;
    this._rows = config && config.hasOwnProperty('rows') ? config.rows : this.config().rows;
    this._css = config && config.hasOwnProperty('css') ? config.css : this.config().css;
    this.init();
  }

  get id() {
    return this._id;
  }

  get isToolBar() {
    return this._isToolBar;
  }

  get isBoard() {
    return true;
  }

  get isSolved() {
    return this._isSolved;
  }

  get docElement() {
    return this._docElement;
  }

  get toolBar() {
    return this._toolBar;
  }

  get hook() {
    return this._hook;
  }

  get autoBind() {
    return this._autoBind;
  }

  get store() {
    return this._store;
  }

  get css() {
    return this._css;
  }

  get cols() {
    return this._cols;
  }

  get rows() {
    return this._rows;
  }

  onHelpClick() {
    let link = document.createElement('a');
    link.setAttribute('href', window.app.metadata.helpUrl);
    link.setAttribute('target', '_blank');
    link.click();
  }

  onRightClick(row) {
    row.store.shiftRight();
  }

  onLeftClick(row) {
    row.store.shiftLeft();
  }

  onSquareClick(square) {

    let row = square.parent,
        board = row ? row.parent : null,
        store = board ? board.store : null,
        squareA = square,
        squareB = store.emptySquare;

    if (!squareA.isEmpty && Util.isValidMove(squareA, squareB)) {
      Util.swap(squareA, squareB);
      if (window.document.activeElement !== window.document.body) {
        window.document.activeElement.blur();
      }
    } else if (squareA.row === squareB.row) {
        if (squareA.col < squareB.col) {
          row.store.shiftLeft();
        } else {
          row.store.shiftRight();
        }
    }

  }

  onResetClick() {
    this.store.reset();
  }

  bind() {
    this.hook.appendChild(this.docElement);
  }

  init() {
    this.docElement.setAttribute('class', this.css.base);
    this.docElement.setAttribute('id', this.id);

    this._store = new Rows({
      rows: this.rows,
      cols: this.cols,
      parent: this,
      hook: this.docElement,
      autoBind: true,
      isSolved: this.isSolved,
      listeners: {
        squareclick: this.onSquareClick,
        leftclick: this.onLeftClick,
        rightclick: this.onRightClick
      }
    });

    if (this.isToolBar) {
      this._toolBar = new Toolbar({
        hook: this.docElement,
        autoBind: true,
        listeners: {
          reset: this.onResetClick,
          help: this.onHelpClick
        }
      });
    }

    if (this.autoBind) {
      this.bind();
    }

  }

  solve() {
    this.store.solve();
  }

  play() {
    this.store.play();
  }

  toggle(el) {
    if(el.innerHTML === 'play') {
      this.play();
      el.innerHTML = 'solve';
      el.setAttribute('title', 'Solve the puzzle');

    } else {
      this.solve();
      el.innerHTML = 'play';
      el.setAttribute('title', 'Begin the game');
    }
  }

}


text:
use std::collections::HashMap;

use crate::errors::Result;
use crate::request::{get, put};
use crate::Client;

#[derive(Clone, Default, Eq, PartialEq, Serialize, Deserialize, Debug)]
#[serde(default)]
pub struct AgentCheck {
    pub Node: String,
    pub CheckID: String,
    pub Name: String,
    pub Status: String,
    pub Notes: String,
    pub Output: String,
    pub ServiceID: String,
    pub ServiceName: String,
}

#[derive(Clone, Default, Eq, PartialEq, Serialize, Deserialize, Debug)]
#[serde(default)]
pub struct AgentMember {
    pub Name: String,
    pub Addr: String,
    pub Port: u16,
    pub Tags: HashMap<String, String>,
    pub pubStatus: usize,
    pub ProtocolMin: u8,
    pub ProtocolMax: u8,
    pub ProtocolCur: u8,
    pub DelegateMin: u8,
    pub DelegateMax: u8,
    pub DelegateCur: u8,
}

#[derive(Eq, Default, PartialEq, Serialize, Deserialize, Debug)]
#[serde(default)]
pub struct AgentService {
    pub ID: String,
    pub Service: String,
    pub Tags: Option<Vec<String>>,
    pub Port: u16,
    pub Address: String,
    pub EnableTagOverride: bool,
    pub CreateIndex: u64,
    pub ModifyIndex: u64,
}

//I haven't implemetned https://www.consul.io/api/agent.html#read-configuration
//I haven't implemetned https://www.consul.io/api/agent.html#stream-logs
pub trait Agent {
    fn checks(&self) -> Result<HashMap<String, AgentCheck>>;
    fn members(&self, wan: bool) -> Result<AgentMember>;
    fn reload(&self) -> Result<()>;
    fn maintenance_mode(&self, enable: bool, reason: Option<&str>) -> Result<()>;
    fn join(&self, address: &str, wan: bool) -> Result<()>;
    fn leave(&self) -> Result<()>;
    fn force_leave(&self) -> Result<()>;
}

impl Agent for Client {
    /// https://www.consul.io/api/agent/check.html#list-checks
    fn checks(&self) -> Result<HashMap<String, AgentCheck>> {
        get("/v1/agent/checks", &self.config, HashMap::new(), None).map(|x| x.0)
    }
    /// https://www.consul.io/api/agent.html#list-members
    fn members(&self, wan: bool) -> Result<AgentMember> {
        let mut params = HashMap::new();
        if wan {
            params.insert(String::from("wan"), String::from("1"));
        }
        get("/v1/agent/members", &self.config, params, None).map(|x| x.0)
    }
    /// https://www.consul.io/api/agent.html#reload-agent
    fn reload(&self) -> Result<()> {
        put(
            "/v1/agent/reload",
            None as Option<&()>,
            &self.config,
            HashMap::new(),
            None,
        )
        .map(|x| x.0)
    }

    /// https://www.consul.io/api/agent.html#reload-agent
    fn maintenance_mode(&self, enable: bool, reason: Option<&str>) -> Result<()> {
        let mut params = HashMap::new();
        let enable_str = if enable {
            String::from("true")
        } else {
            String::from("false")
        };
        params.insert(String::from("enabled"), enable_str);
        if let Some(r) = reason {
            params.insert(String::from("reason"), r.to_owned());
        }
        put(
            "/v1/agent/maintenance",
            None as Option<&()>,
            &self.config,
            params,
            None,
        )
        .map(|x| x.0)
    }
    ///https://www.consul.io/api/agent.html#join-agent
    fn join(&self, address: &str, wan: bool) -> Result<()> {
        let mut params = HashMap::new();

        if wan {
            params.insert(String::from("wan"), String::from("true"));
        }
        let path = format!("/v1/agent/join/{}", address);
        put(&path, None as Option<&()>, &self.config, params, None).map(|x| x.0)
    }

    /// https://www.consul.io/api/agent.html#graceful-leave-and-shutdown
    fn leave(&self) -> Result<()> {
        put(
            "/v1/agent/leave",
            None as Option<&()>,
            &self.config,
            HashMap::new(),
            None,
        )
        .map(|x| x.0)
    }

    ///https://www.consul.io/api/agent.html#force-leave-and-shutdown
    fn force_leave(&self) -> Result<()> {
        put(
            "/v1/agent/force-leave",
            None as Option<&()>,
            &self.config,
            HashMap::new(),
            None,
        )
        .map(|x| x.0)
    }
}