text:
import * as nls from 'vs/nls';
import * as types from 'vs/base/common/types';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { TextCompareEditorVisibleContext, EditorInput, IEditorIdentifier, IEditorCommandsContext, ActiveEditorGroupEmptyContext, MultipleEditorGroupsContext, CloseDirection, IEditorInput, IVisibleEditorPane } from 'vs/workbench/common/editor';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { TextDiffEditor } from 'vs/workbench/browser/parts/editor/textDiffEditor';
import { KeyMod, KeyCode, KeyChord } from 'vs/base/common/keyCodes';
import { URI } from 'vs/base/common/uri';
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
import { IListService } from 'vs/platform/list/browser/listService';
import { List } from 'vs/base/browser/ui/list/listWidget';
import { distinct, coalesce } from 'vs/base/common/arrays';
import { IEditorGroupsService, IEditorGroup, GroupDirection, GroupLocation, GroupsOrder, preferredSideBySideGroupDirection, EditorGroupLayout } from 'vs/workbench/services/editor/common/editorGroupsService';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
import { CommandsRegistry, ICommandHandler } from 'vs/platform/commands/common/commands';
import { MenuRegistry, MenuId } from 'vs/platform/actions/common/actions';
import { ActiveGroupEditorsByMostRecentlyUsedQuickAccess } from 'vs/workbench/browser/parts/editor/editorQuickAccess';

export const CLOSE_SAVED_EDITORS_COMMAND_ID = 'workbench.action.closeUnmodifiedEditors';
export const CLOSE_EDITORS_IN_GROUP_COMMAND_ID = 'workbench.action.closeEditorsInGroup';
export const CLOSE_EDITORS_AND_GROUP_COMMAND_ID = 'workbench.action.closeEditorsAndGroup';
export const CLOSE_EDITORS_TO_THE_RIGHT_COMMAND_ID = 'workbench.action.closeEditorsToTheRight';
export const CLOSE_EDITOR_COMMAND_ID = 'workbench.action.closeActiveEditor';
export const CLOSE_EDITOR_GROUP_COMMAND_ID = 'workbench.action.closeGroup';
export const CLOSE_OTHER_EDITORS_IN_GROUP_COMMAND_ID = 'workbench.action.closeOtherEditors';

export const MOVE_ACTIVE_EDITOR_COMMAND_ID = 'moveActiveEditor';
export const LAYOUT_EDITOR_GROUPS_COMMAND_ID = 'layoutEditorGroups';
export const KEEP_EDITOR_COMMAND_ID = 'workbench.action.keepEditor';
export const SHOW_EDITORS_IN_GROUP = 'workbench.action.showEditorsInGroup';

export const TOGGLE_DIFF_SIDE_BY_SIDE = 'toggle.diff.renderSideBySide';
export const GOTO_NEXT_CHANGE = 'workbench.action.compareEditor.nextChange';
export const GOTO_PREVIOUS_CHANGE = 'workbench.action.compareEditor.previousChange';
export const TOGGLE_DIFF_IGNORE_TRIM_WHITESPACE = 'toggle.diff.ignoreTrimWhitespace';

export const SPLIT_EDITOR_UP = 'workbench.action.splitEditorUp';
export const SPLIT_EDITOR_DOWN = 'workbench.action.splitEditorDown';
export const SPLIT_EDITOR_LEFT = 'workbench.action.splitEditorLeft';
export const SPLIT_EDITOR_RIGHT = 'workbench.action.splitEditorRight';

export const OPEN_EDITOR_AT_INDEX_COMMAND_ID = 'workbench.action.openEditorAtIndex';

export interface ActiveEditorMoveArguments {
	to: 'first' | 'last' | 'left' | 'right' | 'up' | 'down' | 'center' | 'position' | 'previous' | 'next';
	by: 'tab' | 'group';
	value: number;
}

const isActiveEditorMoveArg = function (arg: ActiveEditorMoveArguments): boolean {
	if (!types.isObject(arg)) {
		return false;
	}

	if (!types.isString(arg.to)) {
		return false;
	}

	if (!types.isUndefined(arg.by) && !types.isString(arg.by)) {
		return false;
	}

	if (!types.isUndefined(arg.value) && !types.isNumber(arg.value)) {
		return false;
	}

	return true;
};

function registerActiveEditorMoveCommand(): void {
	KeybindingsRegistry.registerCommandAndKeybindingRule({
		id: MOVE_ACTIVE_EDITOR_COMMAND_ID,
		weight: KeybindingWeight.WorkbenchContrib,
		when: EditorContextKeys.editorTextFocus,
		primary: 0,
		handler: (accessor, args) => moveActiveEditor(args, accessor),
		description: {
			description: nls.localize('editorCommand.activeEditorMove.description', "Move the active editor by tabs or groups"),
			args: [
				{
					name: nls.localize('editorCommand.activeEditorMove.arg.name', "Active editor move argument"),
					description: nls.localize('editorCommand.activeEditorMove.arg.description', "Argument Properties:\n\t* 'to': String value providing where to move.\n\t* 'by': String value providing the unit for move (by tab or by group).\n\t* 'value': Number value providing how many positions or an absolute position to move."),
					constraint: isActiveEditorMoveArg,
					schema: {
						'type': 'object',
						'required': ['to'],
						'properties': {
							'to': {
								'type': 'string',
								'enum': ['left', 'right']
							},
							'by': {
								'type': 'string',
								'enum': ['tab', 'group']
							},
							'value': {
								'type': 'number'
							}
						},
					}
				}
			]
		}
	});
}

function moveActiveEditor(args: ActiveEditorMoveArguments = Object.create(null), accessor: ServicesAccessor): void {
	args.to = args.to || 'right';
	args.by = args.by || 'tab';
	args.value = typeof args.value === 'number' ? args.value : 1;

	const activeEditorPane = accessor.get(IEditorService).activeEditorPane;
	if (activeEditorPane) {
		switch (args.by) {
			case 'tab':
				return moveActiveTab(args, activeEditorPane, accessor);
			case 'group':
				return moveActiveEditorToGroup(args, activeEditorPane, accessor);
		}
	}
}

function moveActiveTab(args: ActiveEditorMoveArguments, control: IVisibleEditorPane, accessor: ServicesAccessor): void {
	const group = control.group;
	let index = group.getIndexOfEditor(control.input);
	switch (args.to) {
		case 'first':
			index = 0;
			break;
		case 'last':
			index = group.count - 1;
			break;
		case 'left':
			index = index - args.value;
			break;
		case 'right':
			index = index + args.value;
			break;
		case 'center':
			index = Math.round(group.count / 2) - 1;
			break;
		case 'position':
			index = args.value - 1;
			break;
	}

	index = index < 0 ? 0 : index >= group.count ? group.count - 1 : index;
	group.moveEditor(control.input, group, { index });
}

function moveActiveEditorToGroup(args: ActiveEditorMoveArguments, control: IVisibleEditorPane, accessor: ServicesAccessor): void {
	const editorGroupService = accessor.get(IEditorGroupsService);
	const configurationService = accessor.get(IConfigurationService);

	const sourceGroup = control.group;
	let targetGroup: IEditorGroup | undefined;

	switch (args.to) {
		case 'left':
			targetGroup = editorGroupService.findGroup({ direction: GroupDirection.LEFT }, sourceGroup);
			if (!targetGroup) {
				targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.LEFT);
			}
			break;
		case 'right':
			targetGroup = editorGroupService.findGroup({ direction: GroupDirection.RIGHT }, sourceGroup);
			if (!targetGroup) {
				targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.RIGHT);
			}
			break;
		case 'up':
			targetGroup = editorGroupService.findGroup({ direction: GroupDirection.UP }, sourceGroup);
			if (!targetGroup) {
				targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.UP);
			}
			break;
		case 'down':
			targetGroup = editorGroupService.findGroup({ direction: GroupDirection.DOWN }, sourceGroup);
			if (!targetGroup) {
				targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.DOWN);
			}
			break;
		case 'first':
			targetGroup = editorGroupService.findGroup({ location: GroupLocation.FIRST }, sourceGroup);
			break;
		case 'last':
			targetGroup = editorGroupService.findGroup({ location: GroupLocation.LAST }, sourceGroup);
			break;
		case 'previous':
			targetGroup = editorGroupService.findGroup({ location: GroupLocation.PREVIOUS }, sourceGroup);
			break;
		case 'next':
			targetGroup = editorGroupService.findGroup({ location: GroupLocation.NEXT }, sourceGroup);
			if (!targetGroup) {
				targetGroup = editorGroupService.addGroup(sourceGroup, preferredSideBySideGroupDirection(configurationService));
			}
			break;
		case 'center':
			targetGroup = editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE)[(editorGroupService.count / 2) - 1];
			break;
		case 'position':
			targetGroup = editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE)[args.value - 1];
			break;
	}

	if (targetGroup) {
		sourceGroup.moveEditor(control.input, targetGroup);
		targetGroup.focus();
	}
}

function registerEditorGroupsLayoutCommand(): void {
	CommandsRegistry.registerCommand(LAYOUT_EDITOR_GROUPS_COMMAND_ID, (accessor: ServicesAccessor, args: EditorGroupLayout) => {
		if (!args || typeof args !== 'object') {
			return;
		}

		const editorGroupService = accessor.get(IEditorGroupsService);
		editorGroupService.applyLayout(args);
	});
}

export function mergeAllGroups(editorGroupService: IEditorGroupsService): void {
	const target = editorGroupService.activeGroup;
	editorGroupService.getGroups(GroupsOrder.MOST_RECENTLY_ACTIVE).forEach(group => {
		if (group === target) {
			return; // keep target
		}

		editorGroupService.mergeGroup(group, target);
	});
}

function registerDiffEditorCommands(): void {
	KeybindingsRegistry.registerCommandAndKeybindingRule({
		id: GOTO_NEXT_CHANGE,
		weight: KeybindingWeight.WorkbenchContrib,
		when: TextCompareEditorVisibleContext,
		primary: KeyMod.Alt | KeyCode.F5,
		handler: accessor => navigateInDiffEditor(accessor, true)
	});

	KeybindingsRegistry.registerCommandAndKeybindingRule({
		id: GOTO_PREVIOUS_CHANGE,
		weight: KeybindingWeight.WorkbenchContrib,
		when: TextCompareEditorVisibleContext,
		primary: KeyMod.Alt | KeyMod.Shift | KeyCode.F5,
		handler: accessor => navigateInDiffEditor(accessor, false)
	});

	function navigateInDiffEditor(accessor: ServicesAccessor, next: boolean): void {
		const editorService = accessor.get(IEditorService);
		const candidates = [editorService.activeEditorPane, ...editorService.visibleEditorPanes].filter(e => e instanceof TextDiffEditor);

		if (candidates.length > 0) {
			const navigator = (<TextDiffEditor>candidates[0]).getDiffNavigator();
			if (navigator) {
				next ? navigator.next() : navigator.previous();
			}
		}
	}

	function toggleDiffSideBySide(accessor: ServicesAccessor): void {
		const configurationService = accessor.get(IConfigurationService);

		const newValue = !configurationService.getValue<boolean>('diffEditor.renderSideBySide');
		configurationService.updateValue('diffEditor.renderSideBySide', newValue, ConfigurationTarget.USER);
	}

	function toggleDiffIgnoreTrimWhitespace(accessor: ServicesAccessor): void {
		const configurationService = accessor.get(IConfigurationService);

		const newValue = !configurationService.getValue<boolean>('diffEditor.ignoreTrimWhitespace');
		configurationService.updateValue('diffEditor.ignoreTrimWhitespace', newValue, ConfigurationTarget.USER);
	}

	KeybindingsRegistry.registerCommandAndKeybindingRule({
		id: TOGGLE_DIFF_SIDE_BY_SIDE,
		weight: KeybindingWeight.WorkbenchContrib,
		when: undefined,
		primary: undefined,
		handler: accessor => toggleDiffSideBySide(accessor)
	});

	MenuRegistry.appendMenuItem(MenuId.CommandPalette, {
		command: {
			id: TOGGLE_DIFF_SIDE_BY_SIDE,
			title: {
				value: nls.localize('toggleInlineView', "Toggle Inline View"),
				original: 'Compare: Toggle Inline View'
			},
			category: nls.localize('compare', "Compare")
		},
		when: ContextKeyExpr.has('textCompareEditorActive')
	});

	KeybindingsRegistry.registerCommandAndKeybindingRule({
		id: TOGGLE_DIFF_IGNORE_TRIM_WHITESPACE,
		weight: KeybindingWeight.WorkbenchContrib,
		when: undefined,
		primary: undefined,
		handler: accessor => toggleDiffIgnoreTrimWhitespace(accessor)
	});
}

function registerOpenEditorAtIndexCommands(): void {
	const openEditorAtIndex: ICommandHandler = (accessor: ServicesAccessor, editorIndex: number): void => {
		const editorService = accessor.get(IEditorService);
		const activeEditorPane = editorService.activeEditorPane;
		if (activeEditorPane) {
			const editor = activeEditorPane.group.getEditorByIndex(editorIndex);
			if (editor) {
				editorService.openEditor(editor);
			}
		}
	};

	// This command takes in the editor index number to open as an argument
	CommandsRegistry.registerCommand({
		id: OPEN_EDITOR_AT_INDEX_COMMAND_ID,
		handler: openEditorAtIndex
	});

	// Keybindings to focus a specific index in the tab folder if tabs are enabled
	for (let i = 0; i < 9; i++) {
		const editorIndex = i;
		const visibleIndex = i + 1;

		KeybindingsRegistry.registerCommandAndKeybindingRule({
			id: OPEN_EDITOR_AT_INDEX_COMMAND_ID + visibleIndex,
			weight: KeybindingWeight.WorkbenchContrib,
			when: undefined,
			primary: KeyMod.Alt | toKeyCode(visibleIndex),
			mac: { primary: KeyMod.WinCtrl | toKeyCode(visibleIndex) },
			handler: accessor => openEditorAtIndex(accessor, editorIndex)
		});
	}

	function toKeyCode(index: number): KeyCode {
		switch (index) {
			case 0: return KeyCode.KEY_0;
			case 1: return KeyCode.KEY_1;
			case 2: return KeyCode.KEY_2;
			case 3: return KeyCode.KEY_3;
			case 4: return KeyCode.KEY_4;
			case 5: return KeyCode.KEY_5;
			case 6: return KeyCode.KEY_6;
			case 7: return KeyCode.KEY_7;
			case 8: return KeyCode.KEY_8;
			case 9: return KeyCode.KEY_9;
		}

		throw new Error('invalid index');
	}
}

function registerFocusEditorGroupAtIndexCommands(): void {

	// Keybindings to focus a specific group (2-8) in the editor area
	for (let groupIndex = 1; groupIndex < 8; groupIndex++) {
		KeybindingsRegistry.registerCommandAndKeybindingRule({
			id: toCommandId(groupIndex),
			weight: KeybindingWeight.WorkbenchContrib,
			when: undefined,
			primary: KeyMod.CtrlCmd | toKeyCode(groupIndex),
			handler: accessor => {
				const editorGroupService = accessor.get(IEditorGroupsService);
				const configurationService = accessor.get(IConfigurationService);

				// To keep backwards compatibility (pre-grid), allow to focus a group
				// that does not exist as long as it is the next group after the last
				// opened group. Otherwise we return.
				if (groupIndex > editorGroupService.count) {
					return;
				}

				// Group exists: just focus
				const groups = editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE);
				if (groups[groupIndex]) {
					return groups[groupIndex].focus();
				}

				// Group does not exist: create new by splitting the active one of the last group
				const direction = preferredSideBySideGroupDirection(configurationService);
				const lastGroup = editorGroupService.findGroup({ location: GroupLocation.LAST });
				const newGroup = editorGroupService.addGroup(lastGroup, direction);

				// Focus
				newGroup.focus();
			}
		});
	}

	function toCommandId(index: number): string {
		switch (index) {
			case 1: return 'workbench.action.focusSecondEditorGroup';
			case 2: return 'workbench.action.focusThirdEditorGroup';
			case 3: return 'workbench.action.focusFourthEditorGroup';
			case 4: return 'workbench.action.focusFifthEditorGroup';
			case 5: return 'workbench.action.focusSixthEditorGroup';
			case 6: return 'workbench.action.focusSeventhEditorGroup';
			case 7: return 'workbench.action.focusEighthEditorGroup';
		}

		throw new Error('Invalid index');
	}

	function toKeyCode(index: number): KeyCode {
		switch (index) {
			case 1: return KeyCode.KEY_2;
			case 2: return KeyCode.KEY_3;
			case 3: return KeyCode.KEY_4;
			case 4: return KeyCode.KEY_5;
			case 5: return KeyCode.KEY_6;
			case 6: return KeyCode.KEY_7;
			case 7: return KeyCode.KEY_8;
		}

		throw new Error('Invalid index');
	}
}

export function splitEditor(editorGroupService: IEditorGroupsService, direction: GroupDirection, context?: IEditorCommandsContext): void {
	let sourceGroup: IEditorGroup | undefined;
	if (context && typeof context.groupId === 'number') {
		sourceGroup = editorGroupService.getGroup(context.groupId);
	} else {
		sourceGroup = editorGroupService.activeGroup;
	}

	if (!sourceGroup) {
		return;
	}

	// Add group
	const newGroup = editorGroupService.addGroup(sourceGroup, direction);

	// Split editor (if it can be split)
	let editorToCopy: IEditorInput | undefined;
	if (context && typeof context.editorIndex === 'number') {
		editorToCopy = sourceGroup.getEditorByIndex(context.editorIndex);
	} else {
		editorToCopy = types.withNullAsUndefined(sourceGroup.activeEditor);
	}

	if (editorToCopy && (editorToCopy as EditorInput).supportsSplitEditor()) {
		sourceGroup.copyEditor(editorToCopy, newGroup);
	}

	// Focus
	newGroup.focus();
}

function registerSplitEditorCommands() {
	[
		{ id: SPLIT_EDITOR_UP, direction: GroupDirection.UP },
		{ id: SPLIT_EDITOR_DOWN, direction: GroupDirection.DOWN },
		{ id: SPLIT_EDITOR_LEFT, direction: GroupDirection.LEFT },
		{ id: SPLIT_EDITOR_RIGHT, direction: GroupDirection.RIGHT }
	].forEach(({ id, direction }) => {
		CommandsRegistry.registerCommand(id, function (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) {
			splitEditor(accessor.get(IEditorGroupsService), direction, getCommandsContext(resourceOrContext, context));
		});
	});
}

function registerCloseEditorCommands() {

	KeybindingsRegistry.registerCommandAndKeybindingRule({
		id: CLOSE_SAVED_EDITORS_COMMAND_ID,
		weight: KeybindingWeight.WorkbenchContrib,
		when: undefined,
		primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.KEY_U),
		handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
			const editorGroupService = accessor.get(IEditorGroupsService);
			const contexts = getMultiSelectedEditorContexts(getCommandsContext(resourceOrContext, context), accessor.get(IListService), editorGroupService);

			const activeGroup = editorGroupService.activeGroup;
			if (contexts.length === 0) {
				contexts.push({ groupId: activeGroup.id }); // active group as fallback
			}

			return Promise.all(distinct(contexts.map(c => c.groupId)).map(async groupId => {
				const group = editorGroupService.getGroup(groupId);
				if (group) {
					return group.closeEditors({ savedOnly: true });
				}
			}));
		}
	});

	KeybindingsRegistry.registerCommandAndKeybindingRule({
		id: CLOSE_EDITORS_IN_GROUP_COMMAND_ID,
		weight: KeybindingWeight.WorkbenchContrib,
		when: undefined,
		primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.KEY_W),
		handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
			const editorGroupService = accessor.get(IEditorGroupsService);
			const contexts = getMultiSelectedEditorContexts(getCommandsContext(resourceOrContext, context), accessor.get(IListService), editorGroupService);
			const distinctGroupIds = distinct(contexts.map(c => c.groupId));

			if (distinctGroupIds.length === 0) {
				distinctGroupIds.push(editorGroupService.activeGroup.id);
			}

			return Promise.all(distinctGroupIds.map(async groupId => {
				const group = editorGroupService.getGroup(groupId);
				if (group) {
					return group.closeAllEditors();
				}
			}));
		}
	});

	KeybindingsRegistry.registerCommandAndKeybindingRule({
		id: CLOSE_EDITOR_COMMAND_ID,
		weight: KeybindingWeight.WorkbenchContrib,
		when: undefined,
		primary: KeyMod.CtrlCmd | KeyCode.KEY_W,
		win: { primary: KeyMod.CtrlCmd | KeyCode.F4, secondary: [KeyMod.CtrlCmd | KeyCode.KEY_W] },
		handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
			const editorGroupService = accessor.get(IEditorGroupsService);
			const contexts = getMultiSelectedEditorContexts(getCommandsContext(resourceOrContext, context), accessor.get(IListService), editorGroupService);

			const activeGroup = editorGroupService.activeGroup;
			if (contexts.length === 0 && activeGroup.activeEditor) {
				contexts.push({ groupId: activeGroup.id, editorIndex: activeGroup.getIndexOfEditor(activeGroup.activeEditor) });  // active editor as fallback
			}

			const groupIds = distinct(contexts.map(context => context.groupId));

			return Promise.all(groupIds.map(async groupId => {
				const group = editorGroupService.getGroup(groupId);
				if (group) {
					const editors = coalesce(contexts
						.filter(context => context.groupId === groupId)
						.map(context => typeof context.editorIndex === 'number' ? group.getEditorByIndex(context.editorIndex) : group.activeEditor));

					return group.closeEditors(editors);
				}
			}));
		}
	});

	KeybindingsRegistry.registerCommandAndKeybindingRule({
		id: CLOSE_EDITOR_GROUP_COMMAND_ID,
		weight: KeybindingWeight.WorkbenchContrib,
		when: ContextKeyExpr.and(ActiveEditorGroupEmptyContext, MultipleEditorGroupsContext),
		primary: KeyMod.CtrlCmd | KeyCode.KEY_W,
		win: { primary: KeyMod.CtrlCmd | KeyCode.F4, secondary: [KeyMod.CtrlCmd | KeyCode.KEY_W] },
		handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
			const editorGroupService = accessor.get(IEditorGroupsService);
			const commandsContext = getCommandsContext(resourceOrContext, context);

			let group: IEditorGroup | undefined;
			if (commandsContext && typeof commandsContext.groupId === 'number') {
				group = editorGroupService.getGroup(commandsContext.groupId);
			} else {
				group = editorGroupService.activeGroup;
			}

			if (group) {
				editorGroupService.removeGroup(group);
			}
		}
	});

	KeybindingsRegistry.registerCommandAndKeybindingRule({
		id: CLOSE_OTHER_EDITORS_IN_GROUP_COMMAND_ID,
		weight: KeybindingWeight.WorkbenchContrib,
		when: undefined,
		primary: undefined,
		mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_T },
		handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
			const editorGroupService = accessor.get(IEditorGroupsService);
			const contexts = getMultiSelectedEditorContexts(getCommandsContext(resourceOrContext, context), accessor.get(IListService), editorGroupService);

			const activeGroup = editorGroupService.activeGroup;
			if (contexts.length === 0 && activeGroup.activeEditor) {
				contexts.push({ groupId: activeGroup.id, editorIndex: activeGroup.getIndexOfEditor(activeGroup.activeEditor) });  // active editor as fallback
			}

			const groupIds = distinct(contexts.map(context => context.groupId));

			return Promise.all(groupIds.map(async groupId => {
				const group = editorGroupService.getGroup(groupId);
				if (group) {
					const editors = contexts
						.filter(context => context.groupId === groupId)
						.map(context => typeof context.editorIndex === 'number' ? group.getEditorByIndex(context.editorIndex) : group.activeEditor);
					const editorsToClose = group.editors.filter(e => editors.indexOf(e) === -1);

					if (group.activeEditor) {
						group.pinEditor(group.activeEditor);
					}

					return group.closeEditors(editorsToClose);
				}
			}));
		}
	});

	KeybindingsRegistry.registerCommandAndKeybindingRule({
		id: CLOSE_EDITORS_TO_THE_RIGHT_COMMAND_ID,
		weight: KeybindingWeight.WorkbenchContrib,
		when: undefined,
		primary: undefined,
		handler: async (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
			const editorGroupService = accessor.get(IEditorGroupsService);

			const { group, editor } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context));
			if (group && editor) {
				if (group.activeEditor) {
					group.pinEditor(group.activeEditor);
				}

				return group.closeEditors({ direction: CloseDirection.RIGHT, except: editor });
			}
		}
	});

	KeybindingsRegistry.registerCommandAndKeybindingRule({
		id: KEEP_EDITOR_COMMAND_ID,
		weight: KeybindingWeight.WorkbenchContrib,
		when: undefined,
		primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.Enter),
		handler: async (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
			const editorGroupService = accessor.get(IEditorGroupsService);

			const { group, editor } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context));
			if (group && editor) {
				return group.pinEditor(editor);
			}
		}
	});

	KeybindingsRegistry.registerCommandAndKeybindingRule({
		id: SHOW_EDITORS_IN_GROUP,
		weight: KeybindingWeight.WorkbenchContrib,
		when: undefined,
		primary: undefined,
		handler: (accessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
			const editorGroupService = accessor.get(IEditorGroupsService);
			const quickInputService = accessor.get(IQuickInputService);

			const commandsContext = getCommandsContext(resourceOrContext, context);
			if (commandsContext && typeof commandsContext.groupId === 'number') {
				const group = editorGroupService.getGroup(commandsContext.groupId);
				if (group) {
					editorGroupService.activateGroup(group); // we need the group to be active
				}
			}

			return quickInputService.quickAccess.show(ActiveGroupEditorsByMostRecentlyUsedQuickAccess.PREFIX);
		}
	});

	CommandsRegistry.registerCommand(CLOSE_EDITORS_AND_GROUP_COMMAND_ID, async (accessor: ServicesAccessor, resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
		const editorGroupService = accessor.get(IEditorGroupsService);

		const { group } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context));
		if (group) {
			await group.closeAllEditors();

			if (group.count === 0 && editorGroupService.getGroup(group.id) /* could be gone by now */) {
				editorGroupService.removeGroup(group); // only remove group if it is now empty
			}
		}
	});
}

function getCommandsContext(resourceOrContext: URI | IEditorCommandsContext, context?: IEditorCommandsContext): IEditorCommandsContext | undefined {
	if (URI.isUri(resourceOrContext)) {
		return context;
	}

	if (resourceOrContext && typeof resourceOrContext.groupId === 'number') {
		return resourceOrContext;
	}

	if (context && typeof context.groupId === 'number') {
		return context;
	}

	return undefined;
}

function resolveCommandsContext(editorGroupService: IEditorGroupsService, context?: IEditorCommandsContext): { group: IEditorGroup, editor?: IEditorInput } {

	// Resolve from context
	let group = context && typeof context.groupId === 'number' ? editorGroupService.getGroup(context.groupId) : undefined;
	let editor = group && context && typeof context.editorIndex === 'number' ? types.withNullAsUndefined(group.getEditorByIndex(context.editorIndex)) : undefined;

	// Fallback to active group as needed
	if (!group) {
		group = editorGroupService.activeGroup;
		editor = <EditorInput>group.activeEditor;
	}

	return { group, editor };
}

export function getMultiSelectedEditorContexts(editorContext: IEditorCommandsContext | undefined, listService: IListService, editorGroupService: IEditorGroupsService): IEditorCommandsContext[] {

	// First check for a focused list to return the selected items from
	const list = listService.lastFocusedList;
	if (list instanceof List && list.getHTMLElement() === document.activeElement) {
		const elementToContext = (element: IEditorIdentifier | IEditorGroup) => {
			if (isEditorGroup(element)) {
				return { groupId: element.id, editorIndex: undefined };
			}

			const group = editorGroupService.getGroup(element.groupId);

			return { groupId: element.groupId, editorIndex: group ? group.getIndexOfEditor(element.editor) : -1 };
		};

		const onlyEditorGroupAndEditor = (e: IEditorIdentifier | IEditorGroup) => isEditorGroup(e) || isEditorIdentifier(e);

		const focusedElements: Array<IEditorIdentifier | IEditorGroup> = list.getFocusedElements().filter(onlyEditorGroupAndEditor);
		const focus = editorContext ? editorContext : focusedElements.length ? focusedElements.map(elementToContext)[0] : undefined; // need to take into account when editor context is { group: group }

		if (focus) {
			const selection: Array<IEditorIdentifier | IEditorGroup> = list.getSelectedElements().filter(onlyEditorGroupAndEditor);

			// Only respect selection if it contains focused element
			if (selection?.some(s => {
				if (isEditorGroup(s)) {
					return s.id === focus.groupId;
				}

				const group = editorGroupService.getGroup(s.groupId);
				return s.groupId === focus.groupId && (group ? group.getIndexOfEditor(s.editor) : -1) === focus.editorIndex;
			})) {
				return selection.map(elementToContext);
			}

			return [focus];
		}
	}

	// Otherwise go with passed in context
	return !!editorContext ? [editorContext] : [];
}

function isEditorGroup(thing: unknown): thing is IEditorGroup {
	const group = thing as IEditorGroup;

	return group && typeof group.id === 'number' && Array.isArray(group.editors);
}

function isEditorIdentifier(thing: unknown): thing is IEditorIdentifier {
	const identifier = thing as IEditorIdentifier;

	return identifier && typeof identifier.groupId === 'number';
}

export function setup(): void {
	registerActiveEditorMoveCommand();
	registerEditorGroupsLayoutCommand();
	registerDiffEditorCommands();
	registerOpenEditorAtIndexCommands();
	registerCloseEditorCommands();
	registerFocusEditorGroupAtIndexCommands();
	registerSplitEditorCommands();
}


text:
//
// Copyright 2019 ZetaSQL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#include "zetasql/public/id_string.h"

#include "zetasql/base/logging.h"
#include "zetasql/base/case.h"
#include "absl/synchronization/mutex.h"
#include "zetasql/base/map_util.h"

namespace zetasql {

#ifndef NDEBUG

absl::Mutex IdStringPool::global_mutex_;

// Initialize lazily in IdStringPool::AllocatePoolId when first pool is created.
std::unordered_set<int64_t>* IdStringPool::live_pool_ids_ = nullptr;

int64_t IdStringPool::max_pool_id_ = 0;

// static
void IdStringPool::CheckPoolIdAlive(int64_t pool_id) {
  absl::MutexLock l(&global_mutex_);
  DCHECK(live_pool_ids_ != nullptr);
  if (!zetasql_base::ContainsKey(*live_pool_ids_, pool_id)) {
    LOG(FATAL) << "IdString was accessed after its IdStringPool ("
               << pool_id << ") was destructed";
  }
}
#endif

IdStringPool::IdStringPool()
#ifndef NDEBUG
    : arena_(std::make_shared<zetasql_base::UnsafeArena>(/*block_size=*/1024)),
      pool_id_(AllocatePoolId()) {
  VLOG(1) << "Allocated IdStringPool " << pool_id_;
#else
    : arena_(std::make_shared<zetasql_base::UnsafeArena>(/*block_size=*/1024)) {
#endif
}

IdStringPool::IdStringPool(const std::shared_ptr<zetasql_base::UnsafeArena>& arena)
#ifndef NDEBUG
    : arena_(arena), pool_id_(AllocatePoolId()) {
  VLOG(1) << "Allocated IdStringPool " << pool_id_;
#else
    : arena_(arena) {
#endif
}

IdStringPool::~IdStringPool() {
#ifndef NDEBUG
  VLOG(1) << "Deleting IdStringPool " << pool_id_;
  absl::MutexLock l(&global_mutex_);
  CHECK_EQ(1, live_pool_ids_->erase(pool_id_));
#endif
}

#ifndef NDEBUG
int64_t IdStringPool::AllocatePoolId() {
  absl::MutexLock l(&global_mutex_);
  if (live_pool_ids_ == nullptr) live_pool_ids_ = new std::unordered_set<int64_t>;
  int64_t pool_id = ++max_pool_id_;
  zetasql_base::InsertOrDie(live_pool_ids_, pool_id);
  return pool_id;
}
#endif

// We want to keep one global empty string constant so that we can implement
// the default constructor and clear() as assignment, without allocating
// a new Shared object.
const IdString* const IdString::kEmptyString =
    new IdString(IdString::MakeGlobal(""));

IdString IdString::ToLower(IdStringPool* pool) const {
  return pool->Make(absl::AsciiStrToLower(ToStringView()));
}

}  // namespace zetasql

redpajama_set_name: RedPajamaGithub


text:
import { IBag, IVoxaEvent } from "./VoxaEvent";

export interface IVoxaReply {
  hasMessages: boolean;
  hasDirectives: boolean;
  hasTerminated: boolean;

  /**
   * empty the reply
   */
  clear: () => void;

  /**
   * end the conversation
   */
  terminate: () => void;

  /**
   * will return the ssml
   */
  speech: string;
  reprompt?: string;

  /**
   * should return plain text for platforms that support it,
   * for example microsoft bot framework chat, dialog flow
   */
  plain?: string;

  /**
   * adds an SSML or plain statement
   */
  addStatement: (statement: string, isPlain?: boolean) => void;

  /**
   * adds an SSML or plain statement
   */
  addReprompt: (statement: string) => void;

  hasDirective: (type: string | RegExp) => boolean;

  /**
   *  saveSession should store the attributes object into a storage that is scoped to the session.
   *  Attributes stored to the session should be made available in the platform's subsequent event
   *  under `event.session.attributes`. In this way, devs can use the session carry data forward
   *  through the conversation.
   */
  saveSession: (attributes: IBag, event: IVoxaEvent) => Promise<void>;
}

export function addToSSML(ssml: string|undefined, statement: string): string {
  ssml = ssml || "";
  const base = ssml.replace(/^<speak>([\s\S]*)<\/speak>$/g, "$1");
  if (!base) {
    return `<speak>${statement}</speak>`;
  }

  return `<speak>${base}\n${statement}</speak>`;
}

export function addToText(text: string|undefined, statement: string): string {
  if (!text) {
    return statement;
  }

  return `${text} ${statement}`;
}


text:
package com.flying.promotion.nio.server;

import static com.flying.promotion.socket.Commons.DEFAULT_MESSAGE_CHARSET;
import static com.flying.promotion.socket.Commons.closeStreams;
import static com.flying.promotion.socket.Commons.logInfo;

import java.io.IOException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class SelectionKeyProcessor {

	private SelectionKey selectionKey;

	private Selector selector;

	public SelectionKeyProcessor(SelectionKey selectionKey, Selector selector) {
		this.selectionKey = selectionKey;
		this.selector = selector;
	}

	public void processKey() throws IOException {
		try {
			if (selectionKey.isAcceptable()) {//接收
				processAccept();
			} else if (selectionKey.isReadable()) {//读取
				processRead();
			} else if (selectionKey.isWritable()) {//写
				processWrite();
			}
		}catch(IOException e) {//IO异常需要关闭,否则会导致无限制地报错,因为通道没结束,就会一直被检测
			SelectableChannel channel = selectionKey.channel();
			if(channel instanceof SocketChannel) {
				DownloadFileProcessor downloadFileProcessor = (DownloadFileProcessor)selectionKey.attachment();
				closeStreams(downloadFileProcessor , channel);
				logInfo("下载由于IO异常,结束.....");
			}
		}
	}

	private void processAccept() throws IOException {
		//System.out.println("一个新的连接................");
		ServerSocketChannel server = (ServerSocketChannel) selectionKey.channel();//这里获取到Server打开的通道
		SocketChannel channel = server.accept();//接受一个请求的Channel的通道
		channel.configureBlocking(false);//将接受请求的通道配置为非阻塞模式
		//System.out.println(channel.socket().getSendBufferSize());
		//channel.socket().setSendBufferSize(16 * 1024);
		channel.register(selector, SelectionKey.OP_READ);//将这个通道注册一个读取事件
	}

	private void processRead() throws IOException {
		SocketChannel channel = (SocketChannel)selectionKey.channel();//此时取出的为processAccept()注册了的通道
		channel.read(NIOServer.CLIENT_BYTE_BUFFER);
		//以下转换字符集过程也可以自己使用转换器:CharsetDecoder来完成
		byte[]bytes = new byte[NIOServer.CLIENT_BYTE_BUFFER.position()];
		NIOServer.CLIENT_BYTE_BUFFER.flip();//将指针重新偏移,才能得到准确的数据
		NIOServer.CLIENT_BYTE_BUFFER.get(bytes);//读取到Byte中
		NIOServer.CLIENT_BYTE_BUFFER.clear();
		logInfo("客户端消息 >>" + new String(bytes , DEFAULT_MESSAGE_CHARSET));//转换输出字符集

		SelectionKey writeSelectionKey = channel.register(selector , SelectionKey.OP_WRITE);//注册一个写的选择器
		writeSelectionKey.attach(new DownloadFileProcessor());//这里可以绑定一个对象到selectionKey当中,触发相应事件的时候,可以将其取出
	}

	private void processWrite() throws IOException {
		//System.out.println("处理写操作");
		SocketChannel channel = (SocketChannel)selectionKey.channel();
		DownloadFileProcessor downloadFileProcessor = (DownloadFileProcessor)selectionKey.attachment();//获取注册WRITE事件的对象
		int count = downloadFileProcessor.read();
		if(count <= 0) {
			closeStreams(downloadFileProcessor , channel);
			logInfo("下载结束.....");
		}else {
			channel.write(downloadFileProcessor.getFileByteBuffer());
		}
	}

}


text: indexModule = angular.module('index', ['angularGrid', 'fileBrowser', 'basic', 'account']);


text:
/*
 *  Default Template feature
 *  @name    Feature
 *  @package Scaffold
 */
function TemplateFeature(element, template)
{
	var feature = this,
		value;

	/**
	 *  Initializer function, bootstrapping the feature
	 *  @name    init
	 *  @type    function
	 *  @access  internal
	 *  @return  void
	 */
	function init()
	{
		var i;

		value = '';
		for (i = 0; i < element.childNodes.length; ++i)
			value += element.childNodes[i].nodeValue;
	}

	/**
	 *  Access attributes of the associated DOMElement
	 *  @name    attribute
	 *  @type    method
	 *  @access  public
	 *  @param   string name [optional, default null - return all attributes in an object]
	 *  @param   string value [optional, default null - do not set the attribute value]
	 *  @return  mixed  value (one of: object containing all attributes, the value for the given name)
	 */
	feature.attribute = function(name, value)
	{
		var all, i;

		if (name && value)
			element.setAttribute(name, value);
		if (name)
			return element.getAttribute(name);

		all = {};

		for (i = 0; i < element.attributes.length; ++i)
			all[element.attributes[i].nodeName] = element.attributes[i].nodeValue;

		return all;
	};

	/**
	 *  Obtain the original value of the DOMElement associated with the feature
	 *  @name    value
	 *  @type    method
	 *  @access  public
	 *  @return  string value
	 */
	feature.value = function()
	{
		return value || '';
	};

	/**
	 *  Obtain the DOMElement associated with the feature
	 *  @name    node
	 *  @type    method
	 *  @access  public
	 *  @return  DOMElement element
	 */
	feature.node = function()
	{
		return element;
	};

	/**
	 *  Obtain the DOMDocument in which the DOMElement resides
	 *  @name    dom
	 *  @type    method
	 *  @access  public
	 *  @return  DOMDocument document
	 */
	feature.dom = function()
	{
		return element.ownerDocument;
	};

	/**
	 *  Remove the feature node from the document
	 *  @name    clean
	 *  @type    method
	 *  @access  public
	 *  @return  void
	 *  @note    this method is automatically called by the Template instance that constructed the feature
	 */
	feature.clean = function(done)
	{
		if (element.parentNode)
			element.parentNode.removeChild(element);

		if (done)
			done(null, feature);
	};

	/**
	 *  Prepare the feature
	 *  @name    prepare
	 *  @type    method
	 *  @access  public
	 *  @return  void
	 *  @note    this method is automatically called by the Template instance that constructed the feature
	 */
	feature.prepare = function(done)
	{
		if (done)
			done(null, feature);
	};

	/**
	 *  The feature should be rendered as the template is rendering itself
	 *  @name    render
	 *  @type    method
	 *  @access  public
	 *  @return  void
	 *  @note    this method is automatically called by the Template instance that constructed the feature
	 */
	feature.render = function(done)
	{
		if (done)
			done(null, feature);
	};

	init();
}

module.exports = TemplateFeature;


text:
(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory(require("https"), require("querystring"));
	else if(typeof define === 'function' && define.amd)
		define("google-trends-api", ["https", "querystring"], factory);
	else if(typeof exports === 'object')
		exports["google-trends-api"] = factory(require("https"), require("querystring"));
	else
		root["google-trends-api"] = factory(root["https"], root["querystring"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_4__, __WEBPACK_EXTERNAL_MODULE_5__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;
/******/
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	Object.defineProperty(exports, "__esModule", {
	  value: true
	});

	var _api = __webpack_require__(1);

	var _api2 = _interopRequireDefault(_api);

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

	exports.default = {
	  interestByRegion: (0, _api2.default)('interest by region'),
	  interestOverTime: (0, _api2.default)('interest over time'),
	  relatedQueries: (0, _api2.default)('related queries'),
	  relatedTopics: (0, _api2.default)('related topics')
	};
	module.exports = exports['default'];

/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	Object.defineProperty(exports, "__esModule", {
	  value: true
	});

	var _utilities = __webpack_require__(2);

	exports.default = function (searchType) {
	  return function (reqObj, cb) {
	    var _constructObj = (0, _utilities.constructObj)(reqObj, cb),
	        cbFunc = _constructObj.cbFunc,
	        obj = _constructObj.obj;

	    if (obj instanceof Error) return Promise.reject(cbFunc(obj));

	    return (0, _utilities.getResults)(searchType, obj).then(function (res) {
	      return cbFunc(null, res);
	    }).catch(function (err) {
	      return Promise.reject(cbFunc(err));
	    });
	  };
	};

	module.exports = exports['default'];

/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	Object.defineProperty(exports, "__esModule", {
	  value: true
	});

	var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

	exports.isLessThan7Days = isLessThan7Days;
	exports.convertDateToString = convertDateToString;
	exports.formatTime = formatTime;
	exports.constructObj = constructObj;
	exports.formatResolution = formatResolution;
	exports.getResults = getResults;

	var _request = __webpack_require__(3);

	var _request2 = _interopRequireDefault(_request);

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

	function isLessThan7Days(date1, date2) {
	  return Math.abs(date2 - date1) / (24 * 60 * 60 * 1000) < 7;
	};

	function convertDateToString(d, shouldIncludeTime) {
	  var month = (d.getUTCMonth() + 1).toString();

	  month = month.length < 2 ? '0' + month : month;
	  var day = d.getUTCDate().toString();
	  var year = d.getUTCFullYear().toString();
	  var hour = d.getUTCHours();
	  var minute = d.getUTCMinutes();

	  if (shouldIncludeTime) {
	    return year + '-' + month + '-' + day + 'T' + hour + '\\:' + minute + '\\:00';
	  }

	  return year + '-' + month + '-' + day;
	};

	function formatTime(obj) {
	  if (obj.startTime && !(obj.startTime instanceof Date)) {
	    return new Error('startTime must be a Date object');
	  }
	  if (obj.endTime && !(obj.endTime instanceof Date)) {
	    return new Error('endTime must be a Date object');
	  }

	  if (obj.startTime && obj.endTime && obj.startTime > obj.endTime) {
	    var temp = obj.startTime;

	    obj.startTime = obj.endTime;
	    obj.endTime = temp;
	  }

	  if (!obj.endTime) obj.endTime = new Date();
	  if (!obj.startTime) obj.startTime = new Date('2004-01-01');

	  var shouldIncludeTime = isLessThan7Days(obj.startTime, obj.endTime);

	  var startTime = convertDateToString(obj.startTime, shouldIncludeTime);
	  var endTime = convertDateToString(obj.endTime, shouldIncludeTime);

	  obj.time = startTime + ' ' + endTime;
	  return obj;
	};

	function constructObj(obj, cbFunc) {
	  if (typeof obj === 'function') cbFunc = obj;

	  if (!obj || !!obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) !== 'object' || Array.isArray(obj)) {
	    obj = new Error('Must supply an object');
	  } else if (!obj.keyword) obj = new Error('Must have a keyword field');

	  if (!!cbFunc && typeof cbFunc !== 'function') {
	    obj = new Error('Callback function must be a function');
	  }

	  if (!obj.hl) obj.hl = 'en-US';

	  if (!cbFunc) {
	    cbFunc = function cbFunc(err, res) {
	      if (err) return err;
	      return res;
	    };
	  }

	  obj = formatTime(obj);

	  return {
	    cbFunc: cbFunc,
	    obj: obj
	  };
	};

	function formatResolution() {
	  var resolution = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';

	  var resolutions = ['COUNTRY', 'REGION', 'CITY', 'DMA'];
	  var isResValid = resolutions.some(function (res) {
	    return res === resolution.toUpperCase();
	  });

	  if (isResValid) return resolution.toUpperCase();
	  return '';
	}

	function getResults(searchType, obj) {
	  var map = {
	    'interest over time': {
	      path: '/trends/api/widgetdata/multiline',
	      pos: 0
	    },
	    'interest by region': {
	      path: '/trends/api/widgetdata/comparedgeo',
	      pos: 1,
	      resolution: formatResolution(obj.resolution)
	    },
	    'related topics': {
	      path: '/trends/api/widgetdata/relatedsearches',
	      pos: 2
	    },
	    'related queries': {
	      path: '/trends/api/widgetdata/relatedsearches',
	      pos: 3
	    }
	  };

	  var options = {
	    method: 'GET',
	    host: 'trends.google.com',
	    path: '/trends/api/explore',
	    qs: {
	      hl: obj.hl,
	      req: JSON.stringify({ comparisonItem: [obj], cat: 0 }),
	      tz: 300
	    }
	  };

	  var _map$searchType = map[searchType],
	      pos = _map$searchType.pos,
	      path = _map$searchType.path,
	      resolution = _map$searchType.resolution;

	  return (0, _request2.default)(options).then(function (results) {
	    var parsedResults = JSON.parse(results.slice(4)).widgets;
	    var req = parsedResults[pos].request;

	    if (resolution) req.resolution = resolution;
	    req = JSON.stringify(req);
	    var token = parsedResults[pos].token;
	    var nextOptions = {
	      path: path,
	      method: 'GET',
	      host: 'trends.google.com',
	      qs: {
	        hl: obj.hl,
	        req: req,
	        token: token,
	        tz: 300
	      }
	    };

	    return (0, _request2.default)(nextOptions);
	  }).then(function (res) {
	    return res.slice(5);
	  });
	};

/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	Object.defineProperty(exports, "__esModule", {
	  value: true
	});
	exports.default = request;

	var _https = __webpack_require__(4);

	var _https2 = _interopRequireDefault(_https);

	var _querystring = __webpack_require__(5);

	var _querystring2 = _interopRequireDefault(_querystring);

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

	function request(_ref) {
	  var method = _ref.method,
	      host = _ref.host,
	      path = _ref.path,
	      qs = _ref.qs;

	  var options = {
	    host: host,
	    method: method,
	    path: path + '?' + _querystring2.default.stringify(qs)
	  };

	  return new Promise(function (resolve, reject) {
	    var req = _https2.default.request(options, function (res) {
	      var chunk = '';

	      res.on('data', function (data) {
	        chunk += data;
	      });

	      res.on('end', function () {
	        resolve(chunk.toString('utf8'));
	      });
	    });

	    req.on('error', function (e) {
	      reject(e);
	    });

	    req.end();
	  });
	};
	module.exports = exports['default'];

/***/ },
/* 4 */
/***/ function(module, exports) {

	module.exports = require("https");

/***/ },
/* 5 */
/***/ function(module, exports) {

	module.exports = require("querystring");

/***/ }
/******/ ])
});
;
//# sourceMappingURL=google-trends-api.js.map


text:
var columnDefs = [
    {
        headerName: 'Group 1',
        headerClass: 'blue',
        groupId: 'Group1',
        children: [
            { field: 'athlete', pinned: true, width: 100 },
            { field: 'age', pinned: true, columnGroupShow: 'open', width: 100 },
            { field: 'country', width: 100 },
            { field: 'year', columnGroupShow: 'open', width: 100 },
            { field: 'date', width: 100 },
            { field: 'sport', columnGroupShow: 'open', width: 100 },
            { field: 'date', width: 100 },
            { field: 'sport', columnGroupShow: 'open', width: 100 }
        ]
    },
    {
        headerName: 'Group 2',
        headerClass: 'green',
        groupId: 'Group2',
        children: [
            { field: 'athlete', pinned: true, width: 100 },
            { field: 'age', pinned: true, columnGroupShow: 'open', width: 100 },
            { field: 'country', width: 100 },
            { field: 'year', columnGroupShow: 'open', width: 100 },
            { field: 'date', width: 100 },
            { field: 'sport', columnGroupShow: 'open', width: 100 },
            { field: 'date', width: 100 },
            { field: 'sport', columnGroupShow: 'open', width: 100 }
        ]
    }
];

// this is the grid options for the top grid
var gridOptionsTop = {
    defaultColDef: {
        editable: true,
        sortable: true,
        resizable: true,
        filter: true,
        flex: 1,
        minWidth: 100
    },
    columnDefs: columnDefs,
    rowData: null,
    debug: true,
    alignedGrids: []
};

// this is the grid options for the bottom grid
var gridOptionsBottom = {
    defaultColDef: {
        editable: true,
        sortable: true,
        resizable: true,
        filter: true,
        flex: 1,
        minWidth: 100
    },
    columnDefs: columnDefs,
    rowData: null,
    debug: true,
    alignedGrids: []
};

gridOptionsTop.alignedGrids.push(gridOptionsBottom);
gridOptionsBottom.alignedGrids.push(gridOptionsTop);

function setData(rowData) {
    gridOptionsTop.api.setRowData(rowData);
    gridOptionsBottom.api.setRowData(rowData);
    gridOptionsTop.api.sizeColumnsToFit();

    // mix up some columns
    gridOptionsTop.columnApi.moveColumnByIndex(11, 4);
    gridOptionsTop.columnApi.moveColumnByIndex(11, 4);
}

// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function() {
    var gridDivTop = document.querySelector('#myGridTop');
    new agGrid.Grid(gridDivTop, gridOptionsTop);

    var gridDivBottom = document.querySelector('#myGridBottom');
    new agGrid.Grid(gridDivBottom, gridOptionsBottom);

    agGrid.simpleHttpRequest({ url: 'https://www.ag-grid.com/example-assets/olympic-winners.json' })
        .then(function(data) {
            setData(data);
        });
});


text:
<?php

namespace Miquel\SiteBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class SiteController extends Controller
{

    public function indexAction()
    {
        return $this->render('MiquelSiteBundle::base.html.twig');
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <gradient
                android:angle="0"
                android:startColor="#dfdfdf"
                android:endColor="#aeaeae"
                android:type="linear" />
        </shape>
    </item>
</selector>


text:
layout: page
title: About
permalink: /about/
---

Kaya Stechly

Currently an intern at the [Machine Intelligence Research Institute](http://www.intelligence.org).

### Contact me

[rot13'd:](http://www.rot13.com/)
xnlnfgrpuyl@tznvy.pbz


text:
import entity
from symlib.terminal import ITERM

class PB_NO(entity.CodedSymbol):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def generate(self):
        return [
            ITERM(right=False),
            entity.Line(start=entity.Point(10, -10), end=entity.Point(50, -10)),
            entity.Line(start=entity.Point(30, -10), end=entity.Point(30, 10)),
            ITERM(left=False).translate(xoff=40, yoff=0)
        ]

class PB_NC(entity.CodedSymbol):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def generate(self):
        return [
            ITERM(right=False),
            entity.Line(start=entity.Point(10, -5), end=entity.Point(50, -5)),
            entity.Line(start=entity.Point(30, -5), end=entity.Point(30, 10)),
            ITERM(left=False).translate(xoff=40, yoff=0)
        ]


text:
class CreateTimesheets < ActiveRecord::Migration
  def change
    create_table :timesheets do |t|
      t.date :date
      t.belongs_to :employee, index: true, foreign_key: true
      t.belongs_to :activity, index: true, foreign_key: true
      t.belongs_to :day, index: true, foreign_key: true
      t.belongs_to :workstream, index: true, foreign_key: true
      t.string :notes

      t.timestamps null: false
    end
  end
end


text:
package net.sourceforge.rules.resource.spi;

/**
 * TODO
 *
 * @version $Revision$ $Date$
 * @author Rainer Langbehn
 */
public final class RuleConstants
{
	// Constants -------------------------------------------------------------

	/**
	 * TODO
	 */
	public static final String USERNAME_PROPERTY_KEY =
		"javax.security.auth.login.name";

	/**
	 * TODO
	 */
	public static final String PASSWORD_PROPERTY_KEY =
		"javax.security.auth.login.password";

	// Attributes ------------------------------------------------------------

	// Static ----------------------------------------------------------------

	// Constructors ----------------------------------------------------------

	/**
	 * Private default ctor to prevent instantiation.
	 */
	private RuleConstants() {
	}

	// Public ----------------------------------------------------------------

	// Package protected -----------------------------------------------------

	// Protected -------------------------------------------------------------

	// Private ---------------------------------------------------------------

	// Inner classes ---------------------------------------------------------
}


text:
package ch.idsia.tools;

import ch.idsia.benchmark.mario.engine.GlobalOptions;
import ch.idsia.benchmark.mario.engine.MarioVisualComponent;

import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

/**
 * Created by IntelliJ IDEA.
 * User: Sergey Karakovskiy
 * Date: Mar 29, 2009
 * Time: 3:34:13 PM
 * Package: .Tools
 */

public class GameViewer extends JFrame {
    public TextField Console = new TextField();
    public Label LabelConsole = new Label("TextFieldConsole:");
    public Checkbox ShowLevelMapObservation = new Checkbox("Show Level Map Observation", true);
    public Checkbox ShowEnemiesObservation = new Checkbox("Show Enemies Observation");
    public Checkbox ShowMergedObservation = new Checkbox("Show Merged Observation");
    public Button btnUpdate = new Button("Update");
    public Checkbox ContinuousUpdates = new Checkbox("Continuous Updates", false);
    Dimension defaultSize = new Dimension(1900, 1800);
    Point defaultLocation = new Point(350, 10);
    //    Thread animator;
//    int frame;
    int delay;
    int FPS = 5;
    GameViewerView gameViewerViewPanel = new GameViewerView();
    CheckboxGroup ZLevelMap = new CheckboxGroup();
    Checkbox Z0_Map = new Checkbox("Z0_Map", ZLevelMap, true);
    Checkbox Z1_Map = new Checkbox("Z1_Map", ZLevelMap, false);
    Checkbox Z2_Map = new Checkbox("Z2_Map", ZLevelMap, false);
    CheckboxGroup ZLevelEnemies = new CheckboxGroup();
    Checkbox Z0_Enemies = new Checkbox("Z0_Enemies", ZLevelEnemies, true);
    Checkbox Z1_Enemies = new Checkbox("Z1_Enemies", ZLevelEnemies, false);
    Checkbox Z2_Enemies = new Checkbox("Z2_Enemies", ZLevelEnemies, false);
    private MarioVisualComponent marioVisualComponent;
    private ToolsConfigurator toolsConfigurator = null;
    private int ZLevelMapValue = 0;
    private int ZLevelEnemiesValue = 0;
    public GameViewer(MarioAIOptions marioAIOptions) {
        super(GlobalOptions.getBenchmarkName() + " Game Viewer");
        Dimension size = null;
        Point location = null;

        setSize((size == null) ? defaultSize : size);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        defaultLocation.setLocation(screenSize.getWidth() - defaultSize.getWidth(), 0);

        setLocation((location == null) ? defaultLocation : location);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        GameViewerActions gameViewerActions = new GameViewerActions();
        ShowEnemiesObservation.addItemListener(gameViewerActions);
        Console.addActionListener(gameViewerActions);
        ShowLevelMapObservation.addItemListener(gameViewerActions);
        ShowMergedObservation.addItemListener(gameViewerActions);
        btnUpdate.addActionListener(gameViewerActions);
        ContinuousUpdates.addItemListener(gameViewerActions);
        Z0_Map.addItemListener(gameViewerActions);
        Z1_Map.addItemListener(gameViewerActions);
        Z2_Map.addItemListener(gameViewerActions);
        Z0_Enemies.addItemListener(gameViewerActions);
        Z1_Enemies.addItemListener(gameViewerActions);
        Z2_Enemies.addItemListener(gameViewerActions);

        JPanel GameViewerOptionsPanel = new JPanel(new GridLayout(0, 3));
        GameViewerOptionsPanel.add(Z0_Map);
        GameViewerOptionsPanel.add(Z0_Enemies);
        GameViewerOptionsPanel.add(LabelConsole);
        GameViewerOptionsPanel.add(Z1_Map);
        GameViewerOptionsPanel.add(Z1_Enemies);
        GameViewerOptionsPanel.add(Console);
        GameViewerOptionsPanel.add(Z2_Map);
        GameViewerOptionsPanel.add(Z2_Enemies);
        GameViewerOptionsPanel.add(btnUpdate);
        GameViewerOptionsPanel.add(ShowLevelMapObservation);
        GameViewerOptionsPanel.add(ShowEnemiesObservation);
        GameViewerOptionsPanel.add(ShowMergedObservation);
        GameViewerOptionsPanel.add(ContinuousUpdates);
        ContinuousUpdates.setState(marioAIOptions.isGameViewerContinuousUpdates());

        GameViewerOptionsPanel.setBorder(new TitledBorder(new EtchedBorder(), "Mario AI Game Viewer Options"));

        Dimension sizeOfView = new Dimension(1600, 960);
        gameViewerViewPanel.setPreferredSize(sizeOfView);
        gameViewerViewPanel.setMinimumSize(sizeOfView);
        gameViewerViewPanel.setMaximumSize(sizeOfView);
        gameViewerViewPanel.setBorder(new TitledBorder(new EtchedBorder(), "Game Viewer View"));

//        JPanel lowerPanel = new JPanel(new GridLayout(0, 1));
//        lowerPanel.add(GameViewerOptionsPanel);
//        lowerPanel.add(new JScrollPane(gameViewerViewPanel));

        JPanel borderPanel = new JPanel(new BorderLayout());
//        levelEditView = new LevelEditView(tilePicker);
//        borderPanel.add(BorderLayout.CENTER, new JScrollPane(levelEditView));
        borderPanel.add(BorderLayout.NORTH, GameViewerOptionsPanel);
        borderPanel.add(BorderLayout.CENTER, new JScrollPane(gameViewerViewPanel));
        setContentPane(borderPanel);

        GlobalOptions.registerGameViewer(this);
    }

    public void AdjustFPS() {
        int fps = FPS; // GlobalOptions.FPS;
        delay = (fps > 0) ? (fps >= GlobalOptions.MaxFPS) ? 0 : (1000 / fps) : 100;
        System.out.println("Game Viewer animator delay: " + delay);
    }

    public void setMarioVisualComponent(MarioVisualComponent marioVisualComponent) {
        this.marioVisualComponent = marioVisualComponent;
    }

    public void tick() {
        if (GlobalOptions.isGameplayStopped)
            return;
        gameViewerViewPanel.repaint();
    }

    public void setToolsConfigurator(ToolsConfigurator toolsConfigurator) {
        this.toolsConfigurator = toolsConfigurator;
    }

    public void setConsoleText(String text) {
        LabelConsole.setText("TextFieldConsole got message:");
        Console.setText(text);
    }

    public boolean getContinuousUpdatesState() {
        return ContinuousUpdates.getState();
    }

    private class GameViewerView extends JPanel implements Runnable {
        Thread animator;
//        private MarioVisualComponent marioVisualComponent;

        public void start() {
            animator = new Thread(this);
            animator.start();
        }

        public void stop() {
            animator = null;
        }

        public void paint(Graphics g) {
            g.fillRect(0, 0, getWidth(), getHeight());
            g.setColor(Color.YELLOW);
            int y_dump = 0;
            g.drawString("Current GAME STATE: ", 320, y_dump += 11);
            g.setColor(Color.GREEN);
            if (this.getMarioVisualComponent() != null) {
                for (String s : this.getMarioVisualComponent().getTextObservation(
                        ShowEnemiesObservation.getState(),
                        ShowLevelMapObservation.getState(),
                        ShowMergedObservation.getState(),
                        ZLevelMapValue,
                        ZLevelEnemiesValue)) {
                    g.setColor((s.charAt(0) == '~') ? Color.YELLOW : Color.GREEN);
                    g.drawString(s, 0, y_dump += 11);
                }

            }

        }

        public void run() {
            // Remember the starting time
            long tm = System.currentTimeMillis();
            while (Thread.currentThread() == animator) {
                // Display the next frame of animation.
                repaint();

                // Delay depending on how far we are behind.
                try {
                    tm += delay;
                    Thread.sleep(Math.max(0, tm - System.currentTimeMillis()));
                } catch (InterruptedException e) {
                    break;
                }

                // Advance the frame
//                frame++;
            }
        }

        public MarioVisualComponent getMarioVisualComponent() {
            return marioVisualComponent;
        }
    }

    public class GameViewerActions implements ActionListener, ItemListener {
        public void actionPerformed(ActionEvent ae) {
            Object ob = ae.getSource();
            if (ob == Console) {
                LabelConsole.setText("TextFieldConsole sent message:");
                toolsConfigurator.setConsoleText(Console.getText());
            } else if (ob == btnUpdate) {
                System.out.println("ob = " + ob);
                gameViewerViewPanel.repaint();
            }
//            else
//            {
//                iw.setVisible(false);
//                b.setLabel("Show");
//            }
        }

        public void itemStateChanged(ItemEvent ie) {
            Object ob = ie.getSource();
            if (ob == ShowEnemiesObservation) {
                Console.setText("Enemies " + (ShowEnemiesObservation.getState() ? "Shown" : "Hidden"));
                gameViewerViewPanel.repaint();
            } else if (ob == ShowLevelMapObservation) {
                Console.setText("Level Map " + (ShowLevelMapObservation.getState() ? "Shown" : "Hidden"));
                gameViewerViewPanel.repaint();
            } else if (ob == ShowMergedObservation) {
                Console.setText("Merged Observation " + (ShowMergedObservation.getState() ? "Shown" : "Hidden"));
                gameViewerViewPanel.repaint();
            } else if (ob == ContinuousUpdates) {
                Console.setText("Continuous Updates " + (ContinuousUpdates.getState() ? "On" : "Off"));
            } else if (ob == Z0_Map) {
                if (Z0_Map.getState())
                    ZLevelMapValue = 0;
                Console.setText("Zoom Level Map: Z" + ZLevelMapValue);
                gameViewerViewPanel.repaint();
            } else if (ob == Z1_Map) {
                if (Z1_Map.getState())
                    ZLevelMapValue = 1;
                Console.setText("Zoom Level Map: Z" + ZLevelMapValue);
                gameViewerViewPanel.repaint();
            } else if (ob == Z2_Map) {
                if (Z2_Map.getState())
                    ZLevelMapValue = 2;
                Console.setText("Zoom Level Map: Z" + ZLevelMapValue);
                gameViewerViewPanel.repaint();
            } else if (ob == Z0_Enemies) {
                if (Z0_Enemies.getState())
                    ZLevelEnemiesValue = 0;
                Console.setText("Zoom Level Enemies: Z" + ZLevelEnemiesValue);
                gameViewerViewPanel.repaint();
            } else if (ob == Z1_Enemies) {
                if (Z1_Enemies.getState())
                    ZLevelEnemiesValue = 1;
                Console.setText("Zoom Level Enemies: Z" + ZLevelEnemiesValue);
                gameViewerViewPanel.repaint();
            } else if (ob == Z2_Enemies) {
                if (Z2_Enemies.getState())
                    ZLevelEnemiesValue = 2;
                Console.setText("Zoom Level Enemies: Z" + ZLevelEnemiesValue);
                gameViewerViewPanel.repaint();
            }
        }
    }
}


text:
//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_MPEG4_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Multiple/File_Mpeg4_TimeCode.h"
#include "MediaInfo/TimeCode.h"
#include "MediaInfo/MediaInfo_Config_MediaInfo.h"
#include <limits>
using namespace std;
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
File_Mpeg4_TimeCode::File_Mpeg4_TimeCode()
:File__Analyze()
{
    //Out
    Pos=numeric_limits<int64s>::max();

    FirstEditOffset=0;
    FirstEditDuration=(int64u)-1;
    NumberOfFrames=0;
    FrameMultiplier=1;
    DropFrame=false;
    NegativeTimes=false;
    tkhd_Duration=0;
    mvhd_Duration_TimeScale=0;

    //Temp
    FrameMultiplier_Pos=0;
}

//***************************************************************************
// Streams management
//***************************************************************************

//---------------------------------------------------------------------------
void File_Mpeg4_TimeCode::Streams_Accept()
{
    Stream_Prepare(Stream_Other);
    Fill(Stream_Other, StreamPos_Last, Other_Type, "Time code");
}

//---------------------------------------------------------------------------
void File_Mpeg4_TimeCode::Streams_Fill()
{
    if (Pos!=numeric_limits<int64s>::max())
    {
        float64 FrameRate_WithDF;
        if (tmcd_Duration && tmcd_Duration_TimeScale)
        {
            FrameRate_WithDF=(float64)tmcd_Duration_TimeScale/(float64)tmcd_Duration;
            if (!NumberOfFrames)
                NumberOfFrames=(int8u)float64_int64s(FrameRate_WithDF)/FrameMultiplier;
        }
        else
        {
            FrameRate_WithDF=NumberOfFrames;
            if (DropFrame)
            {
                int FramesToRemove=0;
                int NumberOfFramesMultiplier=0;
                while (NumberOfFrames>NumberOfFramesMultiplier)
                {
                    FramesToRemove+=108;
                    NumberOfFramesMultiplier+=30;
                }
                float64 FramesPerHour_NDF=FrameRate_WithDF*60*60;
                FrameRate_WithDF*=(FramesPerHour_NDF-FramesToRemove)/FramesPerHour_NDF;
            }

        }
        Fill(Stream_General, 0, "Delay", Pos*FrameMultiplier*1000/FrameRate_WithDF, 0);
    }
}

//---------------------------------------------------------------------------
void File_Mpeg4_TimeCode::Streams_Finish()
{
    if (Pos!=numeric_limits<int64s>::max())
    {
        float64 FrameRate_WithDF;
        if (tmcd_Duration && tmcd_Duration_TimeScale)
        {
            FrameRate_WithDF=(float64)tmcd_Duration_TimeScale/(float64)tmcd_Duration;
            if (!NumberOfFrames)
                NumberOfFrames=(int8u)float64_int64s(FrameRate_WithDF)/FrameMultiplier;
        }
        else
        {
            FrameRate_WithDF=NumberOfFrames;
            if (DropFrame)
            {
                int FramesToRemove=0;
                int NumberOfFramesMultiplier=0;
                while (NumberOfFrames>NumberOfFramesMultiplier)
                {
                    FramesToRemove+=108;
                    NumberOfFramesMultiplier+=30;
                }
                float64 FramesPerHour_NDF=FrameRate_WithDF*60*60;
                FrameRate_WithDF*=(FramesPerHour_NDF-FramesToRemove)/FramesPerHour_NDF;
            }

        }

        TimeCode TC(Pos, NumberOfFrames-1, DropFrame);
        if (FrameMultiplier>1)
        {
            int64s Frames=TC.GetFrames();
            TC-=TC.GetFrames();
            TC=TimeCode(TC.ToFrames()*FrameMultiplier, NumberOfFrames*FrameMultiplier-1, DropFrame);
            TC+=Frames*FrameMultiplier;
        }
        Fill(Stream_Other, StreamPos_Last, Other_TimeCode_FirstFrame, TC.ToString().c_str());
        int64s FrameCount;
        if (NumberOfFrames==mdhd_Duration_TimeScale) // Prioritize mdhd or edit list for in case there are drop frame and integer frame rate
        {
            if (FirstEditDuration!=(int64u)-1)
            {
                float64 FrameCountF=(float64)FirstEditDuration/mvhd_Duration_TimeScale*FrameRate_WithDF*FrameMultiplier;
                FrameCount=(int64u)float64_int64s(FrameCountF);
                if (FrameCountF-FrameCount>0.01) // TODO: avoid rouding issues and better way to manage partial frames
                    FrameCount++;
            }
            else
                FrameCount=mdhd_Duration-FirstEditOffset;
        }
        else
        {
            float64 FrameCountF=(float64)tkhd_Duration/mvhd_Duration_TimeScale*FrameRate_WithDF*FrameMultiplier;
            FrameCount=(int64u)float64_int64s(FrameCountF);
            if (FrameCountF-FrameCount>0.01) // TODO: avoid rouding issues and better way to manage partial frames
                FrameCount++;
        }
        Fill(Stream_Other, StreamPos_Last, Other_FrameCount, FrameCount);
        if (Frame_Count==1)
        {
            Fill(Stream_Other, StreamPos_Last, Other_TimeCode_Stripped, "Yes");
            if (FrameCount)
                Fill(Stream_Other, StreamPos_Last, Other_TimeCode_LastFrame, (TC+(FrameCount-1)).ToString().c_str());
        }
        else
        {
            Fill(Stream_Other, StreamPos_Last, Other_TimeCode_Stripped, "No");
            TimeCode TC_Last(Pos_Last, NumberOfFrames-1, DropFrame);
            if (FrameMultiplier>1)
            {
                int64s Frames=TC_Last.GetFrames();
                TC_Last-=TC_Last.GetFrames();
                TC_Last=TimeCode(TC_Last.ToFrames()*FrameMultiplier, NumberOfFrames*FrameMultiplier-1, DropFrame);
                TC_Last+=Frames*FrameMultiplier+(Config->ParseSpeed<=0.5?(FrameMultiplier-1):FrameMultiplier_Pos);
            }
            Fill(Stream_Other, StreamPos_Last, Other_TimeCode_LastFrame, TC_Last.ToString().c_str());
        }
    }
}

//***************************************************************************
// Buffer - Global
//***************************************************************************

//---------------------------------------------------------------------------
void File_Mpeg4_TimeCode::Read_Buffer_Init()
{
    ZtringListList Map=Config->File_ForceParser_Config_Get();
    if (!Map.empty())
    {
        NumberOfFrames=Map(__T("NumberOfFrames")).To_int8u();
        DropFrame=Map(__T("DropFrame")).To_int8u()?true:false;
        NegativeTimes=Map(__T("NegativeTimes")).To_int8u()?true:false;
    }
}

//---------------------------------------------------------------------------
void File_Mpeg4_TimeCode::Read_Buffer_Continue()
{
    //Parsing
    while (Element_Offset<Element_Size)
    {
        int32u Position=0;
        Get_B4 (Position,                                       "Position");
        int64s Pos_Last_Temp;
        if (NegativeTimes)
            Pos_Last_Temp=(int32s)Position;
        else
            Pos_Last_Temp=Position;
        Pos_Last_Temp+=FirstEditOffset;
        if (Pos==numeric_limits<int64s>::max()) //First time code
        {
            Pos=Pos_Last_Temp;
            if (Config->ParseSpeed<=0.5 && Element_Offset!=Element_Size)
                Skip_XX(Element_Size-Element_Offset,            "Other positions");
        }
        else if (Config->ParseSpeed>0.5)
        {
            FrameMultiplier_Pos++;
            if (FrameMultiplier_Pos>=FrameMultiplier)
            {
                FrameMultiplier_Pos=0;
                Pos_Last++;
            }
            if (Pos_Last!=Pos_Last_Temp)
            {
                const Ztring& Discontinuities=Retrieve_Const(Stream_Other, 0, "Discontinuities");
                if (Discontinuities.size()>25*10)
                {
                    if (Discontinuities[Discontinuities.size()-1]!=']')
                        Fill(Stream_Other, 0, "Discontinuities", "[...]");
                }
                else
                {
                    Pos_Last--;
                    TimeCode TC_Last1(Pos_Last, NumberOfFrames-1, DropFrame);
                    if (FrameMultiplier>1)
                    {
                        int64s Frames=TC_Last1.GetFrames();
                        TC_Last1-=TC_Last1.GetFrames();
                        TC_Last1=TimeCode(TC_Last1.ToFrames()*FrameMultiplier, NumberOfFrames*FrameMultiplier-1, DropFrame);
                        TC_Last1+=Frames*FrameMultiplier;
                    }
                    string Discontinuity=TC_Last1.ToString();
                    TimeCode TC_Last2(Pos_Last_Temp, NumberOfFrames-1, DropFrame);
                    if (FrameMultiplier>1)
                    {
                        int64s Frames=TC_Last2.GetFrames();
                        TC_Last2-=TC_Last2.GetFrames();
                        TC_Last2=TimeCode(TC_Last2.ToFrames()*FrameMultiplier, NumberOfFrames*FrameMultiplier-1, DropFrame);
                        TC_Last2+=(Frames+1)*FrameMultiplier-1;
                    }
                    Discontinuity+='-';
                    Discontinuity+=TC_Last2.ToString();
                    Fill(Stream_Other, 0, "Discontinuities", Discontinuity);
                }
            }
        }
        Pos_Last=Pos_Last_Temp;
    }

    FILLING_BEGIN();
        Frame_Count+=Element_Size/4;

        if (!Status[IsAccepted])
        {
            Accept("TimeCode");
            Fill("TimeCode");
        }
    FILLING_END();
}

}

#endif //MEDIAINFO_MPEG4_YES


text:
KISSY.add('hilo/loader/ScriptLoader', function(S, Class){

/**
 * @language=en
 * @private
 * @class javascript or JSONP loader
 * @module hilo/loader/ScriptLoader
 * @requires hilo/core/Class
 */
var ScriptLoader = Class.create({
    load: function(data){
        var me = this, src = data.src, isJSONP = data.type == 'jsonp';

        if(isJSONP){
            var callbackName = data.callbackName || 'callback';
            var callback = data.callback || 'jsonp' + (++ScriptLoader._count);
            var win = window;

            if(!win[callback]){
                win[callback] = function(result){
                    delete win[callback];
                };
            }

            src += (src.indexOf('?') == -1 ? '?' : '&') + callbackName + '=' + callback;
        }

        if(data.noCache) src += (src.indexOf('?') == -1 ? '?' : '&') + 't=' + (+new Date());

        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.async = true;
        script.onload = me.onLoad.bind(me);
        script.onerror = me.onError.bind(me);
        script.src = src;
        if(data.id) script.id = data.id;
        document.getElementsByTagName('head')[0].appendChild(script);
    },

    onLoad: function(e){
        var script = e.target;
        script.onload = script.onerror = null;
        return script;
    },

    onError: function(e){
        var script = e.target;
        script.onload = script.onerror = null;
        return e;
    },

    Statics: {
        _count: 0
    }

});

return ScriptLoader;

}, {
    requires: ['hilo/core/Class']
});


text:
package org.apache.log4j.examples;

import org.apache.log4j.Category;
import org.apache.log4j.NDC;

/**
   Example code for log4j to viewed in conjunction with the {@link
   org.apache.log4j.examples.Sort Sort} class.

SortAlgo uses the bubble sort algorithm to sort an integer
   array. See also its source
   code.

   @author Ceki Gülcü
*/
public class SortAlgo {

  final static String className = SortAlgo.class.getName();
  final static Category CAT = Category.getInstance(className);
  final static Category OUTER = Category.getInstance(className + ".OUTER");
  final static Category INNER = Category.getInstance(className + ".INNER");
  final static Category DUMP = Category.getInstance(className + ".DUMP");
  final static Category SWAP = Category.getInstance(className + ".SWAP");

  int[] intArray;

  SortAlgo(int[] intArray) {
    this.intArray = intArray;
  }

  void bubbleSort() {
    CAT.info( "Entered the sort method.");

    for(int i = intArray.length -1; i >= 0  ; i--) {
      NDC.push("i=" + i);
      OUTER.debug("in outer loop.");
      for(int j = 0; j  intArray[j+1])
	   swap(j, j+1);
	NDC.pop();
      }
      NDC.pop();
    }
  }

  void dump() {
    if(! (this.intArray instanceof int[])) {
      DUMP.error( "Tried to dump an uninitialized array.");
      return;
    }
    DUMP.info( "Dump of integer array:");
    for(int i = 0; i < this.intArray.length; i++) {
      DUMP.info( "Element [" + i + "]=" + this.intArray[i]);
    }
  }

  void swap(int l, int r) {
    // It is poor practice to ship code with log staments in tight
    // loops or code called potentially millions of times.
    SWAP.debug( "Swapping intArray["+l+"]=" + intArray[l] +
	                     " and intArray["+r+"]=" + intArray[r]);
    int temp = this.intArray[l];
    this.intArray[l] = this.intArray[r];
    this.intArray[r] = temp;
  }
}


text:
import Ember from 'ember';
import layout from './template';

/**
  Widget that provides the ability to manually deserialize the current canvas to
  JSON, or to load fabric JSON to the current canvas.

  ### Example

  ```htmlbars
  \{{#embric-editor as |editor| }}
    \{{embric-json-loader editor=editor  }}
  \{{/embric-editor}}
  ```

  @element embric-json-loader
  @public
*/
export default Ember.Component.extend({
  layout,
  /**
    The name of the widget (rendered as a ```<label>``` in the default template)

    @attribute name
    @default "JSON Loader"
    @type String
    @public
  */
  name: 'JSON Loader',
  classNames: ['embric-control', 'embric-control-json-loader'],
  actions: {
    getJSON() {
      let json = this.get('editor').currentCanvasJSON();
      this.set('json', json);
    }
  }
});


text:
'''
Functions used in improvisor
'''
import numpy as np

def yinpitch(signal, fs, w_size=6000, tau_max=3000):
    '''
    This algorithm was developed by A. de Cheveigné and H. Kawahara and
    published in:

    de Cheveigné, A., Kawahara, H. (2002) "YIN, a fundamental frequency
    estimator for speech and music", J. Acoust. Soc. Am. 111, 1917-1930.

    see http://recherche.ircam.fr/equipes/pcm/pub/people/cheveign.html

    ARGS:
        signal:                 - Input signal
        fs                      - Sampling frequency
        w_size                  - Window size
        tau_max                 - Lag used to calculate autocorrelation
    '''

    # discrete fourier transform
    data = np.fft.fft(signal)

    # Calculate auto-correlation
    r = np.zeros(tau_max)
    for i in range(tau_max):
        s = 0.0
        for j in range(w_size):
            s += (data[j] - data[j+i]) * (data[j] - data[j+i])
        r[i] = s

    # Get the normalized difference function
    d = np.zeros(tau_max)
    s = r[0]
    for i in range(1, tau_max):
        s += r[i]
        d[i] = r[i] / ((1 / i) * s)

    # Select frequencies
    freqs = []
    for i in range(tau_max):
        if d[i] > 0.5:
            continue
        if d[i-1] > d[i] < d[i+1]:
            freq = fs / i
            freqs.append(freq)

    # Map pitches to the input signal
    to_pad = 0 if len(signal) % tau_max == 0 else tau_max - (len(signal) % tau_max)
    extended_signal = np.resize(signal, len(signal) + to_pad)
    signal_2d = extended_signal.reshape(len(extended_signal) // tau_max, tau_max)
    mapped = zip(freqs, signal_2d)
    return mapped


text:
package com.ifmo.ml.knn.metrics;

import com.ifmo.ml.knn.Precedent;

@FunctionalInterface
public interface Metric {
    double countMetric(Precedent p1, Precedent p2);
}


text:
package com.microsoft.mimickeralarm.mimics;

/**
 * Mimic fragment classes should implement this interface to allow the MimicStateManager class
 * to control audio/image capture and also to allow the class to take the appropriate action
 * based on the following state changes: Mimic timeout, failure and success
 */
public interface IMimicImplementation {
    void initializeCapture();
    void startCapture();
    void stopCapture();

    void onCountDownTimerExpired();
    void onSucceeded();
    void onFailed();
    void onInternalError();
}


text:
package org.jgroups.tests;

import org.jgroups.Global;
import org.jgroups.JChannel;
import org.jgroups.ViewId;
import org.jgroups.jmx.JmxConfigurator;
import org.jgroups.logging.Log;
import org.jgroups.logging.LogFactory;
import org.jgroups.protocols.*;
import org.jgroups.protocols.pbcast.GMS;
import org.jgroups.protocols.pbcast.NAKACK2;
import org.jgroups.protocols.pbcast.STABLE;
import org.jgroups.stack.DiagnosticsHandler;
import org.jgroups.stack.ProtocolStack;
import org.jgroups.util.*;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import javax.management.MBeanServer;
import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Tests merging with a large number of members
 * @author Bela Ban
 */
@Test(groups=Global.FUNCTIONAL,sequential=true)
public class LargeMergeTest {
    static final int NUM=50; // number of members
    static final int MAX_PARTICIPANTS_IN_MERGE=NUM / 3;

    protected final JChannel[]     channels=new JChannel[NUM];
    protected MyDiagnosticsHandler handler;
    protected ThreadPoolExecutor   oob_thread_pool;
    protected ThreadPoolExecutor   thread_pool;

    @BeforeMethod
    void setUp() throws Exception {
        handler=new MyDiagnosticsHandler(InetAddress.getByName("224.0.75.75"), 7500,
                                         LogFactory.getLog(DiagnosticsHandler.class),
                                         new DefaultSocketFactory(),
                                         new DefaultThreadFactory("", false));
        handler.start();

        TimeScheduler timer=new TimeScheduler2(new DefaultThreadFactory("Timer", true, true),
                                               5,20,
                                               3000, 5000, "abort");

        oob_thread_pool=new ThreadPoolExecutor(5, Math.max(5, NUM/4), 3000, TimeUnit.MILLISECONDS,
                                                                  new ArrayBlockingQueue<Runnable>(NUM * NUM));
        oob_thread_pool.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());

        thread_pool=new ThreadPoolExecutor(5, Math.max(5, NUM/4), 3000, TimeUnit.MILLISECONDS,
                                                              new ArrayBlockingQueue<Runnable>(NUM * NUM));
        thread_pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        MBeanServer server=Util.getMBeanServer();

        System.out.print("Connecting channels: ");
        for(int i=0; i < NUM; i++) {
            SHARED_LOOPBACK shared_loopback=(SHARED_LOOPBACK)new SHARED_LOOPBACK().setValue("enable_bundling", false);
            // UDP shared_loopback=(UDP)new UDP().setValue("enable_bundling", false);
            shared_loopback.setLoopback(false);
            shared_loopback.setTimer(timer);
            shared_loopback.setOOBThreadPool(oob_thread_pool);
            shared_loopback.setDefaultThreadPool(thread_pool);
            shared_loopback.setDiagnosticsHandler(handler);

            channels[i]=Util.createChannel(shared_loopback,
                                           new DISCARD().setValue("discard_all",true),
                                           new PING().setValue("timeout",1).setValue("num_initial_members",50)
                                             .setValue("force_sending_discovery_rsps", true),
                                           new MERGE3().setValue("min_interval",1000)
                                             .setValue("max_interval",5000)
                                             .setValue("max_participants_in_merge", MAX_PARTICIPANTS_IN_MERGE),
                                           new NAKACK2().setValue("use_mcast_xmit",false)
                                             .setValue("discard_delivered_msgs",true)
                                             .setValue("log_discard_msgs",false).setValue("log_not_found_msgs",false)
                                             .setValue("xmit_table_num_rows",5)
                                             .setValue("xmit_table_msgs_per_row",10),
                                           new UNICAST3().setValue("xmit_table_num_rows",5)
                                             .setValue("xmit_table_msgs_per_row",10)
                                             .setValue("conn_expiry_timeout", 10000),
                                           new STABLE().setValue("max_bytes",500000),
                                           new GMS().setValue("print_local_addr",false)
                                             .setValue("leave_timeout",100)
                                             .setValue("log_view_warnings",false)
                                             .setValue("view_ack_collection_timeout",2000)
                                             .setValue("log_collect_msgs",false));
            channels[i].setName(String.valueOf((i + 1)));

            JmxConfigurator.registerChannel(channels[i], server, "channel-" + (i+1), "LargeMergeTest", true);
            channels[i].connect("LargeMergeTest");
            System.out.print(i + 1 + " ");
        }
        System.out.println("");
    }

    @AfterMethod
    void tearDown() throws Exception {
        for(int i=NUM-1; i >= 0; i--) {
            ProtocolStack stack=channels[i].getProtocolStack();
            String cluster_name=channels[i].getClusterName();
            stack.stopStack(cluster_name);
            stack.destroy();
        }
        handler.destroy();
    }

    public void testClusterFormationAfterMerge() {
        System.out.println("\nEnabling message traffic between members to start the merge");
        for(JChannel ch: channels) {
            Discovery ping=(Discovery)ch.getProtocolStack().findProtocol(PING.class);
            ping.setTimeout(3000);
            DISCARD discard=(DISCARD)ch.getProtocolStack().findProtocol(DISCARD.class);
            discard.setDiscardAll(false);
        }

        boolean merge_completed=true;
        for(int i=0; i < NUM; i++) {
            merge_completed=true;
            System.out.println();

            Map<ViewId,Integer> views=new HashMap<ViewId,Integer>();

            for(JChannel ch: channels) {
                ViewId view_id=ch.getView().getViewId();
                Integer val=views.get(view_id);
                if(val == null) {
                    views.put(view_id, 1);
                }
                else {
                    views.put(view_id, val +1);
                }

                int size=ch.getView().size();
                if(size != NUM)
                    merge_completed=false;
            }

            if(i++ > 0) {
                int num_singleton_views=0;
                for(Map.Entry<ViewId,Integer> entry: views.entrySet()) {
                    if(entry.getValue() == 1)
                        num_singleton_views++;
                    else {
                        System.out.println("==> " + entry.getKey() + ": " + entry.getValue() + " members");
                    }
                }
                if(num_singleton_views > 0)
                    System.out.println("==> " + num_singleton_views + " singleton views");

                System.out.println("------------------\n" + getStats());
            }

            if(merge_completed)
                break;
            Util.sleep(5000);
        }

        if(!merge_completed) {
            System.out.println("\nFinal cluster:");
            for(JChannel ch: channels) {
                int size=ch.getView().size();
                System.out.println(ch.getAddress() + ": " + size + " members - " + (size == NUM? "OK" : "FAIL"));
            }
        }
        for(JChannel ch: channels) {
            int size=ch.getView().size();
            assert size == NUM : "Channel has " + size + " members, but should have " + NUM;
        }
    }

    protected String getStats() {
        StringBuilder sb=new StringBuilder();
        int merge_task_running=0;
        int merge_canceller_running=0;
        int merge_in_progress=0;
        int gms_merge_task_running=0;

        for(JChannel ch:  channels) {
            MERGE2 merge=(MERGE2)ch.getProtocolStack().findProtocol(MERGE2.class);
            if(merge != null && merge.isMergeTaskRunning())
                merge_task_running++;

            MERGE3 merge3=(MERGE3)ch.getProtocolStack().findProtocol(MERGE3.class);
            if(merge3 != null && merge3.isMergeTaskRunning())
                merge_task_running++;

            GMS gms=(GMS)ch.getProtocolStack().findProtocol(GMS.class);
            if(gms.isMergeKillerRunning())
                merge_canceller_running++;
            if(gms.isMergeInProgress())
                merge_in_progress++;
            if(gms.isMergeTaskRunning())
                gms_merge_task_running++;
        }
        sb.append("merge tasks running: " + merge_task_running).append("\n");
        sb.append("merge killers running: " + merge_canceller_running).append("\n");
        sb.append("merge in progress: " + merge_in_progress).append("\n");
        sb.append("gms.merge tasks running: " + gms_merge_task_running).append("\n");
        sb.append("thread_pool: threads=" + thread_pool.getPoolSize() + ", queue=" + thread_pool.getQueue().size() +
                    ", largest threads=" + thread_pool.getLargestPoolSize() + "\n");
        sb.append("oob_thread_pool: threads=" + oob_thread_pool.getPoolSize() + ", queue=" + oob_thread_pool.getQueue().size() +
                    ", largest threads=" + oob_thread_pool.getLargestPoolSize() + "\n");
        return sb.toString();
    }

    protected static class MyDiagnosticsHandler extends DiagnosticsHandler {

        protected MyDiagnosticsHandler(InetAddress diagnostics_addr, int diagnostics_port, Log log, SocketFactory socket_factory, ThreadFactory thread_factory) {
            super(diagnostics_addr,diagnostics_port,log,socket_factory,thread_factory);
        }

        public void start() throws IOException {
            super.start();
        }

        public void stop() {
        }

        public void destroy() {
            super.stop();
        }
    }

    @Test(enabled=false)
    public static void main(String args[]) throws Exception {
        LargeMergeTest test=new LargeMergeTest();
        test.setUp();
        test.testClusterFormationAfterMerge();
        test.tearDown();
    }
}


text:
package yk.jcommon.collections;

public interface Function_T_int<T> {
    T apply(int i);
}


text:
---
title: dot-location - Rules
layout: doc
---
<!-- Note: No pull requests accepted for this file. See README.md in the root directory for details. -->

# Enforce newline before and after dot (dot-location)

(fixable) The `--fix` option on the [command line](../user-guide/command-line-interface#fix) can automatically fix some of the problems reported by this rule.

JavaScript allows you to place newlines before or after a dot in a member expression.

Consistency in placing a newline before or after the dot can greatly increase readability.

```js
var a = universe.
        galaxy;

var b = universe
       .galaxy;
```

## Rule Details

This rule aims to enforce newline consistency in member expressions. This rule prevents the use of mixed newlines around the dot in a member expression.

## Options

The rule takes one option, a string:

* If it is `"object"`, the dot in a member expression should be on the same line as the object portion. The default is `"object"`.
* If it is `"property"`, the dot in a member expression should be on the same line as the property portion.

### object

The default `"object"` option requires the dot to be on the same line as the object.

Examples of **incorrect** code for the default `"object"` option:

```js
/*eslint dot-location: ["error", "object"]*/

var foo = object
.property;
```

Examples of **correct** code for the default `"object"` option:

```js
/*eslint dot-location: ["error", "object"]*/

var foo = object.
property;
var bar = object.property;
```

### property

The `"property"` option requires the dot to be on the same line as the property.

Examples of **incorrect** code for the `"property"` option:

```js
/*eslint dot-location: ["error", "property"]*/

var foo = object.
property;
```

Examples of **correct** code for the `"property"` option:

```js
/*eslint dot-location: ["error", "property"]*/

var foo = object
.property;
var bar = object.property;
```

## When Not To Use It

You can turn this rule off if you are not concerned with the consistency of newlines before or after dots in member expressions.

## Related Rules

* [newline-after-var](newline-after-var)
* [dot-notation](dot-notation)

## Version

This rule was introduced in ESLint 0.21.0.

## Resources

* [Rule source](https://github.com/eslint/eslint/tree/master/lib/rules/dot-location.js)
* [Documentation source](https://github.com/eslint/eslint/tree/master/docs/rules/dot-location.md)