text:
package pl.garciapl.currencyfair.controller.json;

import com.wordnik.swagger.annotations.ApiModel;
import com.wordnik.swagger.annotations.ApiModelProperty;
import org.springframework.format.annotation.NumberFormat;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * Created by lukasz on 17.05.15.
 */
@ApiModel(value = "Request", description = "CurrencyFair Request")
public class Request {

    @ApiModelProperty(value = "userId", required = true, position = 0)
    private String userId;

    @ApiModelProperty(value = "currencyFrom", required = true, notes = "ISO 4217", position = 1)
    private String currencyFrom;

    @ApiModelProperty(value = "currencyTo", required = true, notes = "ISO 4217", position = 2)
    private String currencyTo;

    @ApiModelProperty(value = "amountSell", required = true, dataType = "java.math.BigDecimal", position = 3)
    @NumberFormat(style = NumberFormat.Style.CURRENCY)
    private BigDecimal amountSell;

    @ApiModelProperty(value = "amountBuy", required = true, dataType = "java.math.BigDecimal", position = 4)
    @NumberFormat(style = NumberFormat.Style.CURRENCY)
    private BigDecimal amountBuy;

    @ApiModelProperty(value = "rate", required = true, dataType = "java.lang.Double", position = 5)
    private Double rate;

    @ApiModelProperty(value = "timePlaced", required = false, notes = "DD-MMM-YY HH:MM:SS", position = 6)
    private String timePlaced;

    @ApiModelProperty(value = "originatingCountry", required = true, notes = "ISO 3166-1", position = 7)
    private String originatingCountry;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getCurrencyFrom() {
        return currencyFrom;
    }

    public void setCurrencyFrom(String currencyFrom) {
        this.currencyFrom = currencyFrom;
    }

    public String getCurrencyTo() {
        return currencyTo;
    }

    public void setCurrencyTo(String currencyTo) {
        this.currencyTo = currencyTo;
    }

    public BigDecimal getAmountSell() {
        return round(amountSell);
    }

    public void setAmountSell(BigDecimal amountSell) {
        this.amountSell = round(amountSell);
    }

    public BigDecimal getAmountBuy() {
        return round(amountBuy);
    }

    public void setAmountBuy(BigDecimal amountBuy) {
        this.amountBuy = round(amountBuy);
    }

    public Double getRate() {
        return rate;
    }

    public void setRate(Double rate) {
        this.rate = rate;
    }

    public String getTimePlaced() {
        return timePlaced;
    }

    public void setTimePlaced(String timePlaced) {
        this.timePlaced = timePlaced;
    }

    public String getOriginatingCountry() {
        return originatingCountry;
    }

    public void setOriginatingCountry(String originatingCountry) {
        this.originatingCountry = originatingCountry;
    }

    private BigDecimal round(BigDecimal decimal) {
        return (decimal != null) ? decimal.setScale(2, RoundingMode.CEILING) : null;
    }

    @Override
    public String toString() {
        return "Request{" +
                "userId=" + userId +
                ", currencyFrom='" + currencyFrom + '\'' +
                ", currencyTo='" + currencyTo + '\'' +
                ", amountSell=" + ((amountSell != null) ? amountSell.setScale(2, RoundingMode.CEILING) : null) +
                ", amountBuy=" + ((amountBuy != null) ? amountBuy.setScale(2, RoundingMode.CEILING) : null) +
                ", rate=" + rate +
                ", timePlaced='" + timePlaced + '\'' +
                ", originatingCountry='" + originatingCountry + '\'' +
                '}';
    }
}


text:
package org.pf4j;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.pf4j.test.PluginZip;
import org.pf4j.util.FileUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class LoadPluginsFromMultipleRootsTest {

    private DefaultPluginManager pluginManager;

    Path pluginsPath1;
    Path pluginsPath2;

    @BeforeEach
    public void setUp() throws IOException {
        pluginsPath1 = Files.createTempDirectory("junit-pf4j-");
        pluginsPath2 = Files.createTempDirectory("junit-pf4j-");
        pluginManager = new DefaultPluginManager(pluginsPath1, pluginsPath2);
    }

    @AfterEach
    public void tearDown() throws IOException {
        FileUtils.delete(pluginsPath1);
        FileUtils.delete(pluginsPath2);
    }

    @Test
    public void load() throws Exception {
        PluginZip pluginZip1 = new PluginZip.Builder(pluginsPath1.resolve("my-plugin-1.2.3.zip"), "myPlugin")
            .pluginVersion("1.2.3")
            .build();

        PluginZip pluginZip2 = new PluginZip.Builder(pluginsPath2.resolve("my-other-plugin-4.5.6.zip"), "myOtherPlugin")
            .pluginVersion("4.5.6")
            .build();

        assertTrue(Files.exists(pluginZip1.path()));
        assertEquals(0, pluginManager.getPlugins().size());

        pluginManager.loadPlugins();

        assertTrue(Files.exists(pluginZip1.path()));
        assertTrue(Files.exists(pluginZip1.unzippedPath()));
        assertTrue(Files.exists(pluginZip2.path()));
        assertTrue(Files.exists(pluginZip2.unzippedPath()));
        assertEquals(2, pluginManager.getPlugins().size());
        assertEquals(pluginZip1.pluginId(), pluginManager.idForPath(pluginZip1.unzippedPath()));
        assertEquals(pluginZip2.pluginId(), pluginManager.idForPath(pluginZip2.unzippedPath()));
    }

}

redpajama_set_name: RedPajamaGithub


text:
package com.ning.http.client.providers.netty;

import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.async.ProviderUtil;
import com.ning.http.client.async.ZeroCopyFileTest;

public class NettyZeroCopyFileTest extends ZeroCopyFileTest {
    @Override
    public AsyncHttpClient getAsyncHttpClient(AsyncHttpClientConfig config) {
        return ProviderUtil.nettyProvider(config);
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the MIT license.  See License.txt in the project root for license information.

using System;
using System.Collections.Immutable;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;

namespace Microsoft.NetCore.Analyzers.Runtime
{
    using static MicrosoftNetCoreAnalyzersResources;

    /// <summary>
    /// CA2015: <inheritdoc cref="DoNotDefineFinalizersForTypesDerivedFromMemoryManagerTitle"/>
    /// </summary>
    [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
    public sealed class DoNotDefineFinalizersForTypesDerivedFromMemoryManager : DiagnosticAnalyzer
    {
        internal const string RuleId = "CA2015";

        internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create(
            RuleId,
            CreateLocalizableResourceString(nameof(DoNotDefineFinalizersForTypesDerivedFromMemoryManagerTitle)),
            CreateLocalizableResourceString(nameof(DoNotDefineFinalizersForTypesDerivedFromMemoryManagerMessage)),
            DiagnosticCategory.Reliability,
            RuleLevel.BuildWarning,
            description: CreateLocalizableResourceString(nameof(DoNotDefineFinalizersForTypesDerivedFromMemoryManagerDescription)),
            isPortedFxCopRule: false,
            isDataflowRule: false);

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule);

        public override void Initialize(AnalysisContext context)
        {
            context.EnableConcurrentExecution();
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
            context.RegisterCompilationStartAction(context =>
            {
                var memoryManager1 = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemBuffersMemoryManager1);
                if (memoryManager1 == null)
                {
                    return;
                }

                context.RegisterSymbolAction(context =>
                {
                    AnalyzeSymbol((INamedTypeSymbol)context.Symbol, memoryManager1, context.ReportDiagnostic);
                }
                , SymbolKind.NamedType);
            });
        }

        private static void AnalyzeSymbol(INamedTypeSymbol namedTypeSymbol, INamedTypeSymbol memoryManager, Action<Diagnostic> addDiagnostic)
        {
            if (namedTypeSymbol.DerivesFromOrImplementsAnyConstructionOf(memoryManager))
            {
                foreach (ISymbol symbol in namedTypeSymbol.GetMembers())
                {
                    if (symbol is IMethodSymbol method && method.IsFinalizer())
                    {
                        addDiagnostic(method.CreateDiagnostic(Rule, method.Name));
                        break;
                    }
                }
            }
        }
    }
}


text: like search this will be a sample page containing the embedded version of the widget


text:
package ru.maximkulikov.goodgame.api.models;

import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;

/**
 * @author Maxim Kulikov
 * @since 04.01.2017
 */
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class GitHubSubscribers {

    private Boolean success;

    private List<GitHubSubscriber> response;

}


text:
import 'vs/css!./media/fileactions';
import * as nls from 'vs/nls';
import * as types from 'vs/base/common/types';
import { isWindows, isLinux } from 'vs/base/common/platform';
import { sequence, ITask, always } from 'vs/base/common/async';
import * as paths from 'vs/base/common/paths';
import * as resources from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import * as strings from 'vs/base/common/strings';
import { Action, IAction } from 'vs/base/common/actions';
import { MessageType, IInputValidator } from 'vs/base/browser/ui/inputbox/inputBox';
import { ITree, IHighlightEvent } from 'vs/base/parts/tree/browser/tree';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { VIEWLET_ID } from 'vs/workbench/parts/files/common/files';
import { ITextFileService, ITextFileOperationResult } from 'vs/workbench/services/textfile/common/textfiles';
import { IFileService, IFileStat, AutoSaveConfiguration } from 'vs/platform/files/common/files';
import { toResource, IUntitledResourceInput } from 'vs/workbench/common/editor';
import { ExplorerItem, Model, NewStatPlaceholder } from 'vs/workbench/parts/files/common/explorerModel';
import { ExplorerView } from 'vs/workbench/parts/files/electron-browser/views/explorerView';
import { ExplorerViewlet } from 'vs/workbench/parts/files/electron-browser/explorerViewlet';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { CollapseAction } from 'vs/workbench/browser/viewlet';
import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { IInstantiationService, ServicesAccessor, IConstructorSignature2 } from 'vs/platform/instantiation/common/instantiation';
import { ITextModel } from 'vs/editor/common/model';
import { IWindowService } from 'vs/platform/windows/common/windows';
import { REVEAL_IN_EXPLORER_COMMAND_ID, SAVE_ALL_COMMAND_ID, SAVE_ALL_LABEL, SAVE_ALL_IN_GROUP_COMMAND_ID } from 'vs/workbench/parts/files/electron-browser/fileCommands';
import { ITextModelService, ITextModelContentProvider } from 'vs/editor/common/services/resolverService';
import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { IModelService } from 'vs/editor/common/services/modelService';
import { ICommandService, CommandsRegistry } from 'vs/platform/commands/common/commands';
import { IListService, ListWidget } from 'vs/platform/list/browser/listService';
import { RawContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { Schemas } from 'vs/base/common/network';
import { IDialogService, IConfirmationResult, IConfirmation, getConfirmMessage } from 'vs/platform/dialogs/common/dialogs';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { Constants } from 'vs/editor/common/core/uint';
import { CLOSE_EDITORS_AND_GROUP_COMMAND_ID } from 'vs/workbench/browser/parts/editor/editorCommands';
import { IViewlet } from 'vs/workbench/common/viewlet';
import { coalesce } from 'vs/base/common/arrays';

export interface IEditableData {
	action: IAction;
	validator: IInputValidator;
}

export interface IFileViewletState {
	getEditableData(stat: ExplorerItem): IEditableData;
	setEditable(stat: ExplorerItem, editableData: IEditableData): void;
	clearEditable(stat: ExplorerItem): void;
}

export const NEW_FILE_COMMAND_ID = 'explorer.newFile';
export const NEW_FILE_LABEL = nls.localize('newFile', "New File");

export const NEW_FOLDER_COMMAND_ID = 'explorer.newFolder';
export const NEW_FOLDER_LABEL = nls.localize('newFolder', "New Folder");

export const TRIGGER_RENAME_LABEL = nls.localize('rename', "Rename");

export const MOVE_FILE_TO_TRASH_LABEL = nls.localize('delete', "Delete");

export const COPY_FILE_LABEL = nls.localize('copyFile', "Copy");

export const PASTE_FILE_LABEL = nls.localize('pasteFile', "Paste");

export const FileCopiedContext = new RawContextKey<boolean>('fileCopied', false);

export class BaseErrorReportingAction extends Action {

	constructor(
		id: string,
		label: string,
		private _notificationService: INotificationService
	) {
		super(id, label);
	}

	public get notificationService() {
		return this._notificationService;
	}

	protected onError(error: any): void {
		if (error.message === 'string') {
			error = error.message;
		}

		this._notificationService.error(toErrorMessage(error, false));
	}

	protected onErrorWithRetry(error: any, retry: () => Promise<any>): void {
		this._notificationService.prompt(Severity.Error, toErrorMessage(error, false),
			[{
				label: nls.localize('retry', "Retry"),
				run: () => retry()
			}]
		);
	}
}

export class BaseFileAction extends BaseErrorReportingAction {
	public element: ExplorerItem;

	constructor(
		id: string,
		label: string,
		@IFileService protected fileService: IFileService,
		@INotificationService notificationService: INotificationService,
		@ITextFileService protected textFileService: ITextFileService
	) {
		super(id, label, notificationService);

		this.enabled = false;
	}

	_isEnabled(): boolean {
		return true;
	}

	_updateEnablement(): void {
		this.enabled = !!(this.fileService && this._isEnabled());
	}
}

class TriggerRenameFileAction extends BaseFileAction {

	public static readonly ID = 'renameFile';

	private tree: ITree;
	private renameAction: BaseRenameAction;

	constructor(
		tree: ITree,
		element: ExplorerItem,
		@IFileService fileService: IFileService,
		@INotificationService notificationService: INotificationService,
		@ITextFileService textFileService: ITextFileService,
		@IInstantiationService instantiationService: IInstantiationService
	) {
		super(TriggerRenameFileAction.ID, TRIGGER_RENAME_LABEL, fileService, notificationService, textFileService);

		this.tree = tree;
		this.element = element;
		this.renameAction = instantiationService.createInstance(RenameFileAction, element);
		this._updateEnablement();
	}

	public validateFileName(name: string): string {
		const names: string[] = coalesce(name.split(/[\\/]/));
		if (names.length > 1) {	// error only occurs on multi-path
			const comparer = isLinux ? strings.compare : strings.compareIgnoreCase;
			if (comparer(names[0], this.element.name) === 0) {
				return nls.localize('renameWhenSourcePathIsParentOfTargetError', "Please use the 'New Folder' or 'New File' command to add children to an existing folder");
			}
		}

		return this.renameAction.validateFileName(this.element.parent, name);
	}

	public run(context?: any): Promise<any> {
		if (!context) {
			return Promise.reject(new Error('No context provided to BaseEnableFileRenameAction.'));
		}

		const viewletState = <IFileViewletState>context.viewletState;
		if (!viewletState) {
			return Promise.reject(new Error('Invalid viewlet state provided to BaseEnableFileRenameAction.'));
		}

		const stat = <ExplorerItem>context.stat;
		if (!stat) {
			return Promise.reject(new Error('Invalid stat provided to BaseEnableFileRenameAction.'));
		}

		viewletState.setEditable(stat, {
			action: this.renameAction,
			validator: (value) => {
				const message = this.validateFileName(value);

				if (!message) {
					return null;
				}

				return {
					content: message,
					formatContent: true,
					type: MessageType.ERROR
				};
			}
		});

		this.tree.refresh(stat, false).then(() => {
			this.tree.setHighlight(stat);

			const unbind = this.tree.onDidChangeHighlight((e: IHighlightEvent) => {
				if (!e.highlight) {
					viewletState.clearEditable(stat);
					this.tree.refresh(stat);
					unbind.dispose();
				}
			});
		});

		return void 0;
	}
}

export abstract class BaseRenameAction extends BaseFileAction {

	constructor(
		id: string,
		label: string,
		element: ExplorerItem,
		@IFileService fileService: IFileService,
		@INotificationService notificationService: INotificationService,
		@ITextFileService textFileService: ITextFileService
	) {
		super(id, label, fileService, notificationService, textFileService);

		this.element = element;
	}

	_isEnabled(): boolean {
		return super._isEnabled() && this.element && !this.element.isReadonly;
	}

	public run(context?: any): Promise<any> {
		if (!context) {
			return Promise.reject(new Error('No context provided to BaseRenameFileAction.'));
		}

		let name = <string>context.value;
		if (!name) {
			return Promise.reject(new Error('No new name provided to BaseRenameFileAction.'));
		}

		// Automatically trim whitespaces and trailing dots to produce nice file names
		name = getWellFormedFileName(name);
		const existingName = getWellFormedFileName(this.element.name);

		// Return early if name is invalid or didn't change
		if (name === existingName || this.validateFileName(this.element.parent, name)) {
			return Promise.resolve(null);
		}

		// Call function and Emit Event through viewer
		const promise = this.runAction(name).then(void 0, (error: any) => {
			this.onError(error);
		});

		return promise;
	}

	public validateFileName(parent: ExplorerItem, name: string): string {
		let source = this.element.name;
		let target = name;

		if (!isLinux) { // allow rename of same file also when case differs (e.g. Game.js => game.js)
			source = source.toLowerCase();
			target = target.toLowerCase();
		}

		if (getWellFormedFileName(source) === getWellFormedFileName(target)) {
			return null;
		}

		return validateFileName(parent, name);
	}

	public abstract runAction(newName: string): Promise<any>;
}

class RenameFileAction extends BaseRenameAction {

	public static readonly ID = 'workbench.files.action.renameFile';

	constructor(
		element: ExplorerItem,
		@IFileService fileService: IFileService,
		@INotificationService notificationService: INotificationService,
		@ITextFileService textFileService: ITextFileService
	) {
		super(RenameFileAction.ID, nls.localize('rename', "Rename"), element, fileService, notificationService, textFileService);

		this._updateEnablement();
	}

	public runAction(newName: string): Promise<any> {
		const parentResource = this.element.parent.resource;
		const targetResource = resources.joinPath(parentResource, newName);

		return this.textFileService.move(this.element.resource, targetResource);
	}
}

/* Base New File/Folder Action */
export class BaseNewAction extends BaseFileAction {
	private presetFolder: ExplorerItem;
	private tree: ITree;
	private isFile: boolean;
	private renameAction: BaseRenameAction;

	constructor(
		id: string,
		label: string,
		tree: ITree,
		isFile: boolean,
		editableAction: BaseRenameAction,
		element: ExplorerItem,
		@IFileService fileService: IFileService,
		@INotificationService notificationService: INotificationService,
		@ITextFileService textFileService: ITextFileService
	) {
		super(id, label, fileService, notificationService, textFileService);

		if (element) {
			this.presetFolder = element.isDirectory ? element : element.parent;
		}

		this.tree = tree;
		this.isFile = isFile;
		this.renameAction = editableAction;
	}

	public run(context?: any): Promise<any> {
		if (!context) {
			return Promise.reject(new Error('No context provided to BaseNewAction.'));
		}

		const viewletState = <IFileViewletState>context.viewletState;
		if (!viewletState) {
			return Promise.reject(new Error('Invalid viewlet state provided to BaseNewAction.'));
		}

		let folder = this.presetFolder;
		if (!folder) {
			const focus = <ExplorerItem>this.tree.getFocus();
			if (focus) {
				folder = focus.isDirectory ? focus : focus.parent;
			} else {
				const input: ExplorerItem | Model = this.tree.getInput();
				folder = input instanceof Model ? input.roots[0] : input;
			}
		}

		if (!folder) {
			return Promise.reject(new Error('Invalid parent folder to create.'));
		}
		if (folder.isReadonly) {
			return Promise.reject(new Error('Parent folder is readonly.'));
		}
		if (!!folder.getChild(NewStatPlaceholder.NAME)) {
			// Do not allow to creatae a new file/folder while in the process of creating a new file/folder #47606
			return Promise.resolve(new Error('Parent folder is already in the process of creating a file'));
		}

		return this.tree.reveal(folder, 0.5).then(() => {
			return this.tree.expand(folder).then(() => {
				const stat = NewStatPlaceholder.addNewStatPlaceholder(folder, !this.isFile);

				this.renameAction.element = stat;

				viewletState.setEditable(stat, {
					action: this.renameAction,
					validator: (value) => {
						const message = this.renameAction.validateFileName(folder, value);

						if (!message) {
							return null;
						}

						return {
							content: message,
							formatContent: true,
							type: MessageType.ERROR
						};
					}
				});

				return this.tree.refresh(folder).then(() => {
					return this.tree.expand(folder).then(() => {
						return this.tree.reveal(stat, 0.5).then(() => {
							this.tree.setHighlight(stat);

							const unbind = this.tree.onDidChangeHighlight((e: IHighlightEvent) => {
								if (!e.highlight) {
									stat.destroy();
									this.tree.refresh(folder);
									unbind.dispose();
								}
							});
						});
					});
				});
			});
		});
	}
}

/* New File */
export class NewFileAction extends BaseNewAction {

	constructor(
		tree: ITree,
		element: ExplorerItem,
		@IFileService fileService: IFileService,
		@INotificationService notificationService: INotificationService,
		@ITextFileService textFileService: ITextFileService,
		@IInstantiationService instantiationService: IInstantiationService
	) {
		super('explorer.newFile', NEW_FILE_LABEL, tree, true, instantiationService.createInstance(CreateFileAction, element), null, fileService, notificationService, textFileService);

		this.class = 'explorer-action new-file';
		this._updateEnablement();
	}
}

/* New Folder */
export class NewFolderAction extends BaseNewAction {

	constructor(
		tree: ITree,
		element: ExplorerItem,
		@IFileService fileService: IFileService,
		@INotificationService notificationService: INotificationService,
		@ITextFileService textFileService: ITextFileService,
		@IInstantiationService instantiationService: IInstantiationService
	) {
		super('explorer.newFolder', NEW_FOLDER_LABEL, tree, false, instantiationService.createInstance(CreateFolderAction, element), null, fileService, notificationService, textFileService);

		this.class = 'explorer-action new-folder';
		this._updateEnablement();
	}
}

/* Create new file from anywhere: Open untitled */
export class GlobalNewUntitledFileAction extends Action {
	public static readonly ID = 'workbench.action.files.newUntitledFile';
	public static readonly LABEL = nls.localize('newUntitledFile', "New Untitled File");

	constructor(
		id: string,
		label: string,
		@IEditorService private editorService: IEditorService
	) {
		super(id, label);
	}

	public run(): Promise<any> {
		return this.editorService.openEditor({ options: { pinned: true } } as IUntitledResourceInput); // untitled are always pinned
	}
}

/* Create New File/Folder (only used internally by explorerViewer) */
export abstract class BaseCreateAction extends BaseRenameAction {

	public validateFileName(parent: ExplorerItem, name: string): string {
		if (this.element instanceof NewStatPlaceholder) {
			return validateFileName(parent, name);
		}

		return super.validateFileName(parent, name);
	}
}

/* Create New File (only used internally by explorerViewer) */
class CreateFileAction extends BaseCreateAction {

	public static readonly ID = 'workbench.files.action.createFileFromExplorer';
	public static readonly LABEL = nls.localize('createNewFile', "New File");

	constructor(
		element: ExplorerItem,
		@IFileService fileService: IFileService,
		@IEditorService private editorService: IEditorService,
		@INotificationService notificationService: INotificationService,
		@ITextFileService textFileService: ITextFileService
	) {
		super(CreateFileAction.ID, CreateFileAction.LABEL, element, fileService, notificationService, textFileService);

		this._updateEnablement();
	}

	public runAction(fileName: string): Promise<any> {
		const resource = this.element.parent.resource;
		return this.fileService.createFile(resources.joinPath(resource, fileName)).then(stat => {
			return this.editorService.openEditor({ resource: stat.resource, options: { pinned: true } });
		}, (error) => {
			this.onErrorWithRetry(error, () => this.runAction(fileName));
		});
	}
}

/* Create New Folder (only used internally by explorerViewer) */
class CreateFolderAction extends BaseCreateAction {

	public static readonly ID = 'workbench.files.action.createFolderFromExplorer';
	public static readonly LABEL = nls.localize('createNewFolder', "New Folder");

	constructor(
		element: ExplorerItem,
		@IFileService fileService: IFileService,
		@INotificationService notificationService: INotificationService,
		@ITextFileService textFileService: ITextFileService
	) {
		super(CreateFolderAction.ID, CreateFolderAction.LABEL, null, fileService, notificationService, textFileService);

		this._updateEnablement();
	}

	public runAction(fileName: string): Promise<any> {
		const resource = this.element.parent.resource;
		return this.fileService.createFolder(resources.joinPath(resource, fileName)).then(void 0, (error) => {
			this.onErrorWithRetry(error, () => this.runAction(fileName));
		});
	}
}

class BaseDeleteFileAction extends BaseFileAction {

	private static readonly CONFIRM_DELETE_SETTING_KEY = 'explorer.confirmDelete';

	private skipConfirm: boolean;

	constructor(
		private tree: ITree,
		private elements: ExplorerItem[],
		private useTrash: boolean,
		@IFileService fileService: IFileService,
		@INotificationService notificationService: INotificationService,
		@IDialogService private dialogService: IDialogService,
		@ITextFileService textFileService: ITextFileService,
		@IConfigurationService private configurationService: IConfigurationService
	) {
		super('moveFileToTrash', MOVE_FILE_TO_TRASH_LABEL, fileService, notificationService, textFileService);

		this.tree = tree;
		this.useTrash = useTrash && elements.every(e => !paths.isUNC(e.resource.fsPath)); // on UNC shares there is no trash

		this._updateEnablement();
	}

	_isEnabled(): boolean {
		return super._isEnabled() && this.elements && this.elements.every(e => !e.isReadonly);
	}

	public run(): Promise<any> {

		// Remove highlight
		if (this.tree) {
			this.tree.clearHighlight();
		}

		let primaryButton: string;
		if (this.useTrash) {
			primaryButton = isWindows ? nls.localize('deleteButtonLabelRecycleBin', "&&Move to Recycle Bin") : nls.localize({ key: 'deleteButtonLabelTrash', comment: ['&& denotes a mnemonic'] }, "&&Move to Trash");
		} else {
			primaryButton = nls.localize({ key: 'deleteButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Delete");
		}

		const distinctElements = resources.distinctParents(this.elements, e => e.resource);

		// Handle dirty
		let confirmDirtyPromise: Promise<boolean> = Promise.resolve(true);
		const dirty = this.textFileService.getDirty().filter(d => distinctElements.some(e => resources.isEqualOrParent(d, e.resource, !isLinux /* ignorecase */)));
		if (dirty.length) {
			let message: string;
			if (distinctElements.length > 1) {
				message = nls.localize('dirtyMessageFilesDelete', "You are deleting files with unsaved changes. Do you want to continue?");
			} else if (distinctElements[0].isDirectory) {
				if (dirty.length === 1) {
					message = nls.localize('dirtyMessageFolderOneDelete', "You are deleting a folder with unsaved changes in 1 file. Do you want to continue?");
				} else {
					message = nls.localize('dirtyMessageFolderDelete', "You are deleting a folder with unsaved changes in {0} files. Do you want to continue?", dirty.length);
				}
			} else {
				message = nls.localize('dirtyMessageFileDelete', "You are deleting a file with unsaved changes. Do you want to continue?");
			}

			confirmDirtyPromise = this.dialogService.confirm({
				message,
				type: 'warning',
				detail: nls.localize('dirtyWarning', "Your changes will be lost if you don't save them."),
				primaryButton
			}).then(res => {
				if (!res.confirmed) {
					return false;
				}

				this.skipConfirm = true; // since we already asked for confirmation
				return this.textFileService.revertAll(dirty).then(() => true);
			});
		}

		// Check if file is dirty in editor and save it to avoid data loss
		return confirmDirtyPromise.then(confirmed => {
			if (!confirmed) {
				return null;
			}

			let confirmDeletePromise: Promise<IConfirmationResult>;

			// Check if we need to ask for confirmation at all
			if (this.skipConfirm || (this.useTrash && this.configurationService.getValue<boolean>(BaseDeleteFileAction.CONFIRM_DELETE_SETTING_KEY) === false)) {
				confirmDeletePromise = Promise.resolve({ confirmed: true } as IConfirmationResult);
			}

			// Confirm for moving to trash
			else if (this.useTrash) {
				const message = this.getMoveToTrashMessage(distinctElements);

				confirmDeletePromise = this.dialogService.confirm({
					message,
					detail: isWindows ? nls.localize('undoBin', "You can restore from the Recycle Bin.") : nls.localize('undoTrash', "You can restore from the Trash."),
					primaryButton,
					checkbox: {
						label: nls.localize('doNotAskAgain', "Do not ask me again")
					},
					type: 'question'
				});
			}

			// Confirm for deleting permanently
			else {
				const message = this.getDeleteMessage(distinctElements);
				confirmDeletePromise = this.dialogService.confirm({
					message,
					detail: nls.localize('irreversible', "This action is irreversible!"),
					primaryButton,
					type: 'warning'
				});
			}

			return confirmDeletePromise.then(confirmation => {

				// Check for confirmation checkbox
				let updateConfirmSettingsPromise: Promise<void> = Promise.resolve(void 0);
				if (confirmation.confirmed && confirmation.checkboxChecked === true) {
					updateConfirmSettingsPromise = this.configurationService.updateValue(BaseDeleteFileAction.CONFIRM_DELETE_SETTING_KEY, false, ConfigurationTarget.USER);
				}

				return updateConfirmSettingsPromise.then(() => {

					// Check for confirmation
					if (!confirmation.confirmed) {
						return Promise.resolve(null);
					}

					// Call function
					const servicePromise = Promise.all(distinctElements.map(e => this.fileService.del(e.resource, { useTrash: this.useTrash, recursive: true }))).then(() => {
						if (distinctElements[0].parent) {
							this.tree.setFocus(distinctElements[0].parent); // move focus to parent
						}
					}, (error: any) => {

						// Handle error to delete file(s) from a modal confirmation dialog
						let errorMessage: string;
						let detailMessage: string;
						let primaryButton: string;
						if (this.useTrash) {
							errorMessage = isWindows ? nls.localize('binFailed', "Failed to delete using the Recycle Bin. Do you want to permanently delete instead?") : nls.localize('trashFailed', "Failed to delete using the Trash. Do you want to permanently delete instead?");
							detailMessage = nls.localize('irreversible', "This action is irreversible!");
							primaryButton = nls.localize({ key: 'deletePermanentlyButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Delete Permanently");
						} else {
							errorMessage = toErrorMessage(error, false);
							primaryButton = nls.localize({ key: 'retryButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Retry");
						}

						return this.dialogService.confirm({
							message: errorMessage,
							detail: detailMessage,
							type: 'warning',
							primaryButton
						}).then(res => {

							// Focus back to tree
							this.tree.domFocus();

							if (res.confirmed) {
								if (this.useTrash) {
									this.useTrash = false; // Delete Permanently
								}

								this.skipConfirm = true;

								return this.run();
							}

							return Promise.resolve(void 0);
						});
					});

					return servicePromise;
				});
			});
		});
	}

	private getMoveToTrashMessage(distinctElements: ExplorerItem[]): string {
		if (this.containsBothDirectoryAndFile(distinctElements)) {
			return getConfirmMessage(nls.localize('confirmMoveTrashMessageFilesAndDirectories', "Are you sure you want to delete the following {0} files/directories and their contents?", distinctElements.length), distinctElements.map(e => e.resource));
		}

		if (distinctElements.length > 1) {
			if (distinctElements[0].isDirectory) {
				return getConfirmMessage(nls.localize('confirmMoveTrashMessageMultipleDirectories', "Are you sure you want to delete the following {0} directories and their contents?", distinctElements.length), distinctElements.map(e => e.resource));
			}

			return getConfirmMessage(nls.localize('confirmMoveTrashMessageMultiple', "Are you sure you want to delete the following {0} files?", distinctElements.length), distinctElements.map(e => e.resource));
		}

		if (distinctElements[0].isDirectory) {
			return nls.localize('confirmMoveTrashMessageFolder', "Are you sure you want to delete '{0}' and its contents?", distinctElements[0].name);
		}

		return nls.localize('confirmMoveTrashMessageFile', "Are you sure you want to delete '{0}'?", distinctElements[0].name);
	}

	private getDeleteMessage(distinctElements: ExplorerItem[]): string {
		if (this.containsBothDirectoryAndFile(distinctElements)) {
			return getConfirmMessage(nls.localize('confirmDeleteMessageFilesAndDirectories', "Are you sure you want to permanently delete the following {0} files/directories and their contents?", distinctElements.length), distinctElements.map(e => e.resource));
		}

		if (distinctElements.length > 1) {
			if (distinctElements[0].isDirectory) {
				return getConfirmMessage(nls.localize('confirmDeleteMessageMultipleDirectories', "Are you sure you want to permanently delete the following {0} directories and their contents?", distinctElements.length), distinctElements.map(e => e.resource));
			}

			return getConfirmMessage(nls.localize('confirmDeleteMessageMultiple', "Are you sure you want to permanently delete the following {0} files?", distinctElements.length), distinctElements.map(e => e.resource));
		}

		if (distinctElements[0].isDirectory) {
			return nls.localize('confirmDeleteMessageFolder', "Are you sure you want to permanently delete '{0}' and its contents?", distinctElements[0].name);
		}

		return nls.localize('confirmDeleteMessageFile', "Are you sure you want to permanently delete '{0}'?", distinctElements[0].name);
	}

	private containsBothDirectoryAndFile(distinctElements: ExplorerItem[]): boolean {
		const directories = distinctElements.filter(element => element.isDirectory);
		const files = distinctElements.filter(element => !element.isDirectory);

		return directories.length > 0 && files.length > 0;
	}
}

/* Add File */
export class AddFilesAction extends BaseFileAction {

	private tree: ITree;

	constructor(
		tree: ITree,
		element: ExplorerItem,
		clazz: string,
		@IFileService fileService: IFileService,
		@IEditorService private editorService: IEditorService,
		@IDialogService private dialogService: IDialogService,
		@INotificationService notificationService: INotificationService,
		@ITextFileService textFileService: ITextFileService
	) {
		super('workbench.files.action.addFile', nls.localize('addFiles', "Add Files"), fileService, notificationService, textFileService);

		this.tree = tree;
		this.element = element;

		if (clazz) {
			this.class = clazz;
		}

		this._updateEnablement();
	}

	public run(resourcesToAdd: URI[]): Promise<any> {
		const addPromise = Promise.resolve(null).then(() => {
			if (resourcesToAdd && resourcesToAdd.length > 0) {

				// Find parent to add to
				let targetElement: ExplorerItem;
				if (this.element) {
					targetElement = this.element;
				} else {
					const input: ExplorerItem | Model = this.tree.getInput();
					targetElement = this.tree.getFocus() || (input instanceof Model ? input.roots[0] : input);
				}

				if (!targetElement.isDirectory) {
					targetElement = targetElement.parent;
				}

				// Resolve target to check for name collisions and ask user
				return this.fileService.resolveFile(targetElement.resource).then((targetStat: IFileStat) => {

					// Check for name collisions
					const targetNames = new Set<string>();
					targetStat.children.forEach((child) => {
						targetNames.add(isLinux ? child.name : child.name.toLowerCase());
					});

					let overwritePromise: Promise<IConfirmationResult> = Promise.resolve({ confirmed: true });
					if (resourcesToAdd.some(resource => {
						return targetNames.has(!resources.hasToIgnoreCase(resource) ? resources.basename(resource) : resources.basename(resource).toLowerCase());
					})) {
						const confirm: IConfirmation = {
							message: nls.localize('confirmOverwrite', "A file or folder with the same name already exists in the destination folder. Do you want to replace it?"),
							detail: nls.localize('irreversible', "This action is irreversible!"),
							primaryButton: nls.localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace"),
							type: 'warning'
						};

						overwritePromise = this.dialogService.confirm(confirm);
					}

					return overwritePromise.then(res => {
						if (!res.confirmed) {
							return void 0;
						}

						// Run add in sequence
						const addPromisesFactory: ITask<Promise<void>>[] = [];
						resourcesToAdd.forEach(resource => {
							addPromisesFactory.push(() => {
								const sourceFile = resource;
								const targetFile = resources.joinPath(targetElement.resource, resources.basename(sourceFile));

								// if the target exists and is dirty, make sure to revert it. otherwise the dirty contents
								// of the target file would replace the contents of the added file. since we already
								// confirmed the overwrite before, this is OK.
								let revertPromise: Promise<ITextFileOperationResult> = Promise.resolve(null);
								if (this.textFileService.isDirty(targetFile)) {
									revertPromise = this.textFileService.revertAll([targetFile], { soft: true });
								}

								return revertPromise.then(() => {
									const target = resources.joinPath(targetElement.resource, resources.basename(sourceFile));
									return this.fileService.copyFile(sourceFile, target, true).then(stat => {

										// if we only add one file, just open it directly
										if (resourcesToAdd.length === 1) {
											this.editorService.openEditor({ resource: stat.resource, options: { pinned: true } });
										}
									}, error => this.onError(error));
								});
							});
						});

						return sequence(addPromisesFactory);
					});
				});
			}

			return void 0;
		});

		return addPromise.then(() => {
			this.tree.clearHighlight();
		}, (error: any) => {
			this.onError(error);
			this.tree.clearHighlight();
		});
	}
}

// Copy File/Folder
class CopyFileAction extends BaseFileAction {

	private tree: ITree;
	constructor(
		tree: ITree,
		private elements: ExplorerItem[],
		@IFileService fileService: IFileService,
		@INotificationService notificationService: INotificationService,
		@ITextFileService textFileService: ITextFileService,
		@IContextKeyService contextKeyService: IContextKeyService,
		@IClipboardService private clipboardService: IClipboardService
	) {
		super('filesExplorer.copy', COPY_FILE_LABEL, fileService, notificationService, textFileService);

		this.tree = tree;
		this._updateEnablement();
	}

	public run(): Promise<any> {

		// Write to clipboard as file/folder to copy
		this.clipboardService.writeResources(this.elements.map(e => e.resource));

		// Remove highlight
		if (this.tree) {
			this.tree.clearHighlight();
		}

		this.tree.domFocus();

		return Promise.resolve(null);
	}
}

// Paste File/Folder
class PasteFileAction extends BaseFileAction {

	public static readonly ID = 'filesExplorer.paste';

	private tree: ITree;

	constructor(
		tree: ITree,
		element: ExplorerItem,
		@IFileService fileService: IFileService,
		@INotificationService notificationService: INotificationService,
		@ITextFileService textFileService: ITextFileService,
		@IEditorService private editorService: IEditorService
	) {
		super(PasteFileAction.ID, PASTE_FILE_LABEL, fileService, notificationService, textFileService);

		this.tree = tree;
		this.element = element;
		if (!this.element) {
			const input: ExplorerItem | Model = this.tree.getInput();
			this.element = input instanceof Model ? input.roots[0] : input;
		}
		this._updateEnablement();
	}

	public run(fileToPaste: URI): Promise<any> {

		// Check if target is ancestor of pasted folder
		if (this.element.resource.toString() !== fileToPaste.toString() && resources.isEqualOrParent(this.element.resource, fileToPaste, !isLinux /* ignorecase */)) {
			throw new Error(nls.localize('fileIsAncestor', "File to paste is an ancestor of the destination folder"));
		}

		return this.fileService.resolveFile(fileToPaste).then(fileToPasteStat => {

			// Remove highlight
			if (this.tree) {
				this.tree.clearHighlight();
			}

			// Find target
			let target: ExplorerItem;
			if (this.element.resource.toString() === fileToPaste.toString()) {
				target = this.element.parent;
			} else {
				target = this.element.isDirectory ? this.element : this.element.parent;
			}

			const targetFile = findValidPasteFileTarget(target, { resource: fileToPaste, isDirectory: fileToPasteStat.isDirectory });

			// Copy File
			return this.fileService.copyFile(fileToPaste, targetFile).then(stat => {
				if (!stat.isDirectory) {
					return this.editorService.openEditor({ resource: stat.resource, options: { pinned: true } });
				}

				return void 0;
			}, error => this.onError(error)).then(() => {
				this.tree.domFocus();
			});
		}, error => {
			this.onError(new Error(nls.localize('fileDeleted', "File to paste was deleted or moved meanwhile")));
		});
	}
}

// Duplicate File/Folder
export class DuplicateFileAction extends BaseFileAction {
	private tree: ITree;
	private target: ExplorerItem;

	constructor(
		tree: ITree,
		fileToDuplicate: ExplorerItem,
		target: ExplorerItem,
		@IFileService fileService: IFileService,
		@IEditorService private editorService: IEditorService,
		@INotificationService notificationService: INotificationService,
		@ITextFileService textFileService: ITextFileService
	) {
		super('workbench.files.action.duplicateFile', nls.localize('duplicateFile', "Duplicate"), fileService, notificationService, textFileService);

		this.tree = tree;
		this.element = fileToDuplicate;
		this.target = (target && target.isDirectory) ? target : fileToDuplicate.parent;
		this._updateEnablement();
	}

	public run(): Promise<any> {

		// Remove highlight
		if (this.tree) {
			this.tree.clearHighlight();
		}

		// Copy File
		const result = this.fileService.copyFile(this.element.resource, findValidPasteFileTarget(this.target, { resource: this.element.resource, isDirectory: this.element.isDirectory })).then(stat => {
			if (!stat.isDirectory) {
				return this.editorService.openEditor({ resource: stat.resource, options: { pinned: true } });
			}

			return void 0;
		}, error => this.onError(error));

		return result;
	}
}

function findValidPasteFileTarget(targetFolder: ExplorerItem, fileToPaste: { resource: URI, isDirectory?: boolean }): URI {
	let name = resources.basenameOrAuthority(fileToPaste.resource);

	let candidate = resources.joinPath(targetFolder.resource, name);
	while (true) {
		if (!targetFolder.root.find(candidate)) {
			break;
		}

		name = incrementFileName(name, fileToPaste.isDirectory);
		candidate = resources.joinPath(targetFolder.resource, name);
	}

	return candidate;
}

export function incrementFileName(name: string, isFolder: boolean): string {
	const separators = '[\\.\\-_]';
	const maxNumber = Constants.MAX_SAFE_SMALL_INTEGER;

	// file.1.txt=>file.2.txt
	let suffixFileRegex = RegExp('(.*' + separators + ')(\\d+)(\\..*)$');
	if (!isFolder && name.match(suffixFileRegex)) {
		return name.replace(suffixFileRegex, (match, g1?, g2?, g3?) => {
			let number = parseInt(g2);
			return number < maxNumber
				? g1 + strings.pad(number + 1, g2.length) + g3
				: strings.format('{0}{1}.1{2}', g1, g2, g3);
		});
	}

	// 1.file.txt=>2.file.txt
	let prefixFileRegex = RegExp('(\\d+)(' + separators + '.*)(\\..*)$');
	if (!isFolder && name.match(prefixFileRegex)) {
		return name.replace(prefixFileRegex, (match, g1?, g2?, g3?) => {
			let number = parseInt(g1);
			return number < maxNumber
				? strings.pad(number + 1, g1.length) + g2 + g3
				: strings.format('{0}{1}.1{2}', g1, g2, g3);
		});
	}

	// 1.txt=>2.txt
	let prefixFileNoNameRegex = RegExp('(\\d+)(\\..*)$');
	if (!isFolder && name.match(prefixFileNoNameRegex)) {
		return name.replace(prefixFileNoNameRegex, (match, g1?, g2?) => {
			let number = parseInt(g1);
			return number < maxNumber
				? strings.pad(number + 1, g1.length) + g2
				: strings.format('{0}.1{1}', g1, g2);
		});
	}

	// file.txt=>file.1.txt
	const lastIndexOfDot = name.lastIndexOf('.');
	if (!isFolder && lastIndexOfDot >= 0) {
		return strings.format('{0}.1{1}', name.substr(0, lastIndexOfDot), name.substr(lastIndexOfDot));
	}

	// folder.1=>folder.2
	if (isFolder && name.match(/(\d+)$/)) {
		return name.replace(/(\d+)$/, (match: string, ...groups: any[]) => {
			let number = parseInt(groups[0]);
			return number < maxNumber
				? strings.pad(number + 1, groups[0].length)
				: strings.format('{0}.1', groups[0]);
		});
	}

	// 1.folder=>2.folder
	if (isFolder && name.match(/^(\d+)/)) {
		return name.replace(/^(\d+)(.*)$/, (match: string, ...groups: any[]) => {
			let number = parseInt(groups[0]);
			return number < maxNumber
				? strings.pad(number + 1, groups[0].length) + groups[1]
				: strings.format('{0}{1}.1', groups[0], groups[1]);
		});
	}

	// file/folder=>file.1/folder.1
	return strings.format('{0}.1', name);
}

// Global Compare with
export class GlobalCompareResourcesAction extends Action {

	public static readonly ID = 'workbench.files.action.compareFileWith';
	public static readonly LABEL = nls.localize('globalCompareFile', "Compare Active File With...");

	constructor(
		id: string,
		label: string,
		@IQuickOpenService private quickOpenService: IQuickOpenService,
		@IEditorService private editorService: IEditorService,
		@INotificationService private notificationService: INotificationService,
	) {
		super(id, label);
	}

	public run(): Promise<any> {
		const activeInput = this.editorService.activeEditor;
		const activeResource = activeInput ? activeInput.getResource() : void 0;
		if (activeResource) {

			// Compare with next editor that opens
			const toDispose = this.editorService.overrideOpenEditor(editor => {

				// Only once!
				toDispose.dispose();

				// Open editor as diff
				const resource = editor.getResource();
				if (resource) {
					return {
						override: this.editorService.openEditor({
							leftResource: activeResource,
							rightResource: resource
						}).then(() => void 0)
					};
				}

				return void 0;
			});

			// Bring up quick open
			this.quickOpenService.show('', { autoFocus: { autoFocusSecondEntry: true } }).then(() => {
				toDispose.dispose(); // make sure to unbind if quick open is closing
			});
		} else {
			this.notificationService.info(nls.localize('openFileToCompare', "Open a file first to compare it with another file."));
		}

		return Promise.resolve(true);
	}
}

// Refresh Explorer Viewer
export class RefreshViewExplorerAction extends Action {

	constructor(explorerView: ExplorerView, clazz: string) {
		super('workbench.files.action.refreshFilesExplorer', nls.localize('refresh', "Refresh"), clazz, true, (context: any) => explorerView.refresh());
	}
}

export class ToggleAutoSaveAction extends Action {
	public static readonly ID = 'workbench.action.toggleAutoSave';
	public static readonly LABEL = nls.localize('toggleAutoSave', "Toggle Auto Save");

	constructor(
		id: string,
		label: string,
		@IConfigurationService private configurationService: IConfigurationService
	) {
		super(id, label);
	}

	public run(): Promise<any> {
		const setting = this.configurationService.inspect('files.autoSave');
		let userAutoSaveConfig = setting.user;
		if (types.isUndefinedOrNull(userAutoSaveConfig)) {
			userAutoSaveConfig = setting.default; // use default if setting not defined
		}

		let newAutoSaveValue: string;
		if ([AutoSaveConfiguration.AFTER_DELAY, AutoSaveConfiguration.ON_FOCUS_CHANGE, AutoSaveConfiguration.ON_WINDOW_CHANGE].some(s => s === userAutoSaveConfig)) {
			newAutoSaveValue = AutoSaveConfiguration.OFF;
		} else {
			newAutoSaveValue = AutoSaveConfiguration.AFTER_DELAY;
		}

		return this.configurationService.updateValue('files.autoSave', newAutoSaveValue, ConfigurationTarget.USER);
	}
}

export abstract class BaseSaveAllAction extends BaseErrorReportingAction {
	private toDispose: IDisposable[];
	private lastIsDirty: boolean;

	constructor(
		id: string,
		label: string,
		@ITextFileService private textFileService: ITextFileService,
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
		@ICommandService protected commandService: ICommandService,
		@INotificationService notificationService: INotificationService,
	) {
		super(id, label, notificationService);

		this.toDispose = [];
		this.lastIsDirty = this.textFileService.isDirty();
		this.enabled = this.lastIsDirty;

		this.registerListeners();
	}

	protected abstract includeUntitled(): boolean;
	protected abstract doRun(context: any): Promise<any>;

	private registerListeners(): void {

		// listen to files being changed locally
		this.toDispose.push(this.textFileService.models.onModelsDirty(e => this.updateEnablement(true)));
		this.toDispose.push(this.textFileService.models.onModelsSaved(e => this.updateEnablement(false)));
		this.toDispose.push(this.textFileService.models.onModelsReverted(e => this.updateEnablement(false)));
		this.toDispose.push(this.textFileService.models.onModelsSaveError(e => this.updateEnablement(true)));

		if (this.includeUntitled()) {
			this.toDispose.push(this.untitledEditorService.onDidChangeDirty(resource => this.updateEnablement(this.untitledEditorService.isDirty(resource))));
		}
	}

	private updateEnablement(isDirty: boolean): void {
		if (this.lastIsDirty !== isDirty) {
			this.enabled = this.textFileService.isDirty();
			this.lastIsDirty = this.enabled;
		}
	}

	public run(context?: any): Promise<boolean> {
		return this.doRun(context).then(() => true, error => {
			this.onError(error);
			return null;
		});
	}

	public dispose(): void {
		this.toDispose = dispose(this.toDispose);

		super.dispose();
	}
}

export class SaveAllAction extends BaseSaveAllAction {

	public static readonly ID = 'workbench.action.files.saveAll';
	public static readonly LABEL = SAVE_ALL_LABEL;

	public get class(): string {
		return 'explorer-action save-all';
	}

	protected doRun(context: any): Promise<any> {
		return this.commandService.executeCommand(SAVE_ALL_COMMAND_ID);
	}

	protected includeUntitled(): boolean {
		return true;
	}
}

export class SaveAllInGroupAction extends BaseSaveAllAction {

	public static readonly ID = 'workbench.files.action.saveAllInGroup';
	public static readonly LABEL = nls.localize('saveAllInGroup', "Save All in Group");

	public get class(): string {
		return 'explorer-action save-all';
	}

	protected doRun(context: any): Promise<any> {
		return this.commandService.executeCommand(SAVE_ALL_IN_GROUP_COMMAND_ID, {}, context);
	}

	protected includeUntitled(): boolean {
		return true;
	}
}

export class CloseGroupAction extends Action {

	public static readonly ID = 'workbench.files.action.closeGroup';
	public static readonly LABEL = nls.localize('closeGroup', "Close Group");

	constructor(id: string, label: string, @ICommandService private commandService: ICommandService) {
		super(id, label, 'action-close-all-files');
	}

	public run(context?: any): Promise<any> {
		return this.commandService.executeCommand(CLOSE_EDITORS_AND_GROUP_COMMAND_ID, {}, context);
	}
}

export class FocusFilesExplorer extends Action {

	public static readonly ID = 'workbench.files.action.focusFilesExplorer';
	public static readonly LABEL = nls.localize('focusFilesExplorer', "Focus on Files Explorer");

	constructor(
		id: string,
		label: string,
		@IViewletService private viewletService: IViewletService
	) {
		super(id, label);
	}

	public run(): Promise<any> {
		return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
			const view = viewlet.getExplorerView();
			if (view) {
				view.setExpanded(true);
				view.getViewer().domFocus();
			}
		});
	}
}

export class ShowActiveFileInExplorer extends Action {

	public static readonly ID = 'workbench.files.action.showActiveFileInExplorer';
	public static readonly LABEL = nls.localize('showInExplorer', "Reveal Active File in Side Bar");

	constructor(
		id: string,
		label: string,
		@IEditorService private editorService: IEditorService,
		@INotificationService private notificationService: INotificationService,
		@ICommandService private commandService: ICommandService
	) {
		super(id, label);
	}

	public run(): Promise<any> {
		const resource = toResource(this.editorService.activeEditor, { supportSideBySide: true });
		if (resource) {
			this.commandService.executeCommand(REVEAL_IN_EXPLORER_COMMAND_ID, resource);
		} else {
			this.notificationService.info(nls.localize('openFileToShow', "Open a file first to show it in the explorer"));
		}

		return Promise.resolve(true);
	}
}

export class CollapseExplorerView extends Action {

	public static readonly ID = 'workbench.files.action.collapseExplorerFolders';
	public static readonly LABEL = nls.localize('collapseExplorerFolders', "Collapse Folders in Explorer");

	constructor(
		id: string,
		label: string,
		@IViewletService private viewletService: IViewletService
	) {
		super(id, label);
	}

	public run(): Promise<any> {
		return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
			const explorerView = viewlet.getExplorerView();
			if (explorerView) {
				const viewer = explorerView.getViewer();
				if (viewer) {
					const action = new CollapseAction(viewer, true, null);
					action.run();
					action.dispose();
				}
			}
		});
	}
}

export class RefreshExplorerView extends Action {

	public static readonly ID = 'workbench.files.action.refreshFilesExplorer';
	public static readonly LABEL = nls.localize('refreshExplorer', "Refresh Explorer");

	constructor(
		id: string,
		label: string,
		@IViewletService private viewletService: IViewletService
	) {
		super(id, label);
	}

	public run(): Promise<any> {
		return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
			const explorerView = viewlet.getExplorerView();
			if (explorerView) {
				explorerView.refresh();
			}
		});
	}
}

export class ShowOpenedFileInNewWindow extends Action {

	public static readonly ID = 'workbench.action.files.showOpenedFileInNewWindow';
	public static readonly LABEL = nls.localize('openFileInNewWindow', "Open Active File in New Window");

	constructor(
		id: string,
		label: string,
		@IEditorService private editorService: IEditorService,
		@IWindowService private windowService: IWindowService,
		@INotificationService private notificationService: INotificationService
	) {
		super(id, label);
	}

	public run(): Promise<any> {
		const fileResource = toResource(this.editorService.activeEditor, { supportSideBySide: true, filter: Schemas.file /* todo@remote */ });
		if (fileResource) {
			this.windowService.openWindow([fileResource], { forceNewWindow: true, forceOpenWorkspaceAsFile: true });
		} else {
			this.notificationService.info(nls.localize('openFileToShowInNewWindow', "Open a file first to open in new window"));
		}

		return Promise.resolve(true);
	}
}

export function validateFileName(parent: ExplorerItem, name: string): string {

	// Produce a well formed file name
	name = getWellFormedFileName(name);

	// Name not provided
	if (!name || name.length === 0 || /^\s+$/.test(name)) {
		return nls.localize('emptyFileNameError', "A file or folder name must be provided.");
	}

	// Relative paths only
	if (name[0] === '/' || name[0] === '\\') {
		return nls.localize('fileNameStartsWithSlashError', "A file or folder name cannot start with a slash.");
	}

	const names = coalesce(name.split(/[\\/]/));

	// Do not allow to overwrite existing file
	const childExists = !!parent.getChild(name);
	if (childExists) {
		return nls.localize('fileNameExistsError', "A file or folder **{0}** already exists at this location. Please choose a different name.", name);
	}

	// Invalid File name
	if (names.some((folderName) => !paths.isValidBasename(folderName))) {
		return nls.localize('invalidFileNameError', "The name **{0}** is not valid as a file or folder name. Please choose a different name.", trimLongName(name));
	}

	// Max length restriction (on Windows)
	if (isWindows) {
		const fullPathLength = name.length + parent.resource.fsPath.length + 1 /* path segment */;
		if (fullPathLength > 255) {
			return nls.localize('filePathTooLongError', "The name **{0}** results in a path that is too long. Please choose a shorter name.", trimLongName(name));
		}
	}

	return null;
}

function trimLongName(name: string): string {
	if (name && name.length > 255) {
		return `${name.substr(0, 255)}...`;
	}

	return name;
}

export function getWellFormedFileName(filename: string): string {
	if (!filename) {
		return filename;
	}

	// Trim tabs
	filename = strings.trim(filename, '\t');

	// Remove trailing dots, slashes, and spaces
	filename = strings.rtrim(filename, '.');
	filename = strings.rtrim(filename, '/');
	filename = strings.rtrim(filename, '\\');

	return filename;
}

export class CompareWithClipboardAction extends Action {

	public static readonly ID = 'workbench.files.action.compareWithClipboard';
	public static readonly LABEL = nls.localize('compareWithClipboard', "Compare Active File with Clipboard");

	private static readonly SCHEME = 'clipboardCompare';

	private registrationDisposal: IDisposable;

	constructor(
		id: string,
		label: string,
		@IEditorService private editorService: IEditorService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@ITextModelService private textModelService: ITextModelService,
		@IFileService private fileService: IFileService
	) {
		super(id, label);

		this.enabled = true;
	}

	public run(): Promise<any> {
		const resource: URI = toResource(this.editorService.activeEditor, { supportSideBySide: true });
		if (resource && (this.fileService.canHandleResource(resource) || resource.scheme === Schemas.untitled)) {
			if (!this.registrationDisposal) {
				const provider = this.instantiationService.createInstance(ClipboardContentProvider);
				this.registrationDisposal = this.textModelService.registerTextModelContentProvider(CompareWithClipboardAction.SCHEME, provider);
			}

			const name = resources.basename(resource);
			const editorLabel = nls.localize('clipboardComparisonLabel', "Clipboard ↔ {0}", name);

			const cleanUp = () => {
				this.registrationDisposal = dispose(this.registrationDisposal);
			};

			return always(this.editorService.openEditor({ leftResource: resource.with({ scheme: CompareWithClipboardAction.SCHEME }), rightResource: resource, label: editorLabel }), cleanUp);
		}

		return Promise.resolve(true);
	}

	public dispose(): void {
		super.dispose();

		this.registrationDisposal = dispose(this.registrationDisposal);
	}
}

class ClipboardContentProvider implements ITextModelContentProvider {
	constructor(
		@IClipboardService private clipboardService: IClipboardService,
		@IModeService private modeService: IModeService,
		@IModelService private modelService: IModelService
	) { }

	provideTextContent(resource: URI): Promise<ITextModel> {
		const model = this.modelService.createModel(this.clipboardService.readText(), this.modeService.create('text/plain'), resource);

		return Promise.resolve(model);
	}
}

interface IExplorerContext {
	viewletState: IFileViewletState;
	stat: ExplorerItem;
	selection: ExplorerItem[];
}

function getContext(listWidget: ListWidget, viewletService: IViewletService): IExplorerContext {
	// These commands can only be triggered when explorer viewlet is visible so get it using the active viewlet
	const tree = <ITree>listWidget;
	const stat = tree.getFocus();
	const selection = tree.getSelection();

	// Only respect the selection if user clicked inside it (focus belongs to it)
	return { stat, selection: selection && selection.indexOf(stat) >= 0 ? selection : [], viewletState: (<ExplorerViewlet>viewletService.getActiveViewlet()).getViewletState() };
}

// TODO@isidor these commands are calling into actions due to the complex inheritance action structure.
// It should be the other way around, that actions call into commands.
function openExplorerAndRunAction(accessor: ServicesAccessor, constructor: IConstructorSignature2<ITree, ExplorerItem, Action>): Promise<any> {
	const instantationService = accessor.get(IInstantiationService);
	const listService = accessor.get(IListService);
	const viewletService = accessor.get(IViewletService);
	const activeViewlet = viewletService.getActiveViewlet();
	let explorerPromise: Promise<IViewlet> = Promise.resolve(activeViewlet);
	if (!activeViewlet || activeViewlet.getId() !== VIEWLET_ID) {
		explorerPromise = viewletService.openViewlet(VIEWLET_ID, true);
	}

	return explorerPromise.then((explorer: ExplorerViewlet) => {
		const explorerView = explorer.getExplorerView();
		if (explorerView && explorerView.isVisible() && explorerView.isExpanded()) {
			explorerView.focus();
			const explorerContext = getContext(listService.lastFocusedList, viewletService);
			const action = instantationService.createInstance(constructor, listService.lastFocusedList, explorerContext.stat);

			return action.run(explorerContext);
		}

		return undefined;
	});
}

CommandsRegistry.registerCommand({
	id: NEW_FILE_COMMAND_ID,
	handler: (accessor) => {
		return openExplorerAndRunAction(accessor, NewFileAction);
	}
});

CommandsRegistry.registerCommand({
	id: NEW_FOLDER_COMMAND_ID,
	handler: (accessor) => {
		return openExplorerAndRunAction(accessor, NewFolderAction);
	}
});

export const renameHandler = (accessor: ServicesAccessor) => {
	const instantationService = accessor.get(IInstantiationService);
	const listService = accessor.get(IListService);
	const explorerContext = getContext(listService.lastFocusedList, accessor.get(IViewletService));

	const renameAction = instantationService.createInstance(TriggerRenameFileAction, listService.lastFocusedList, explorerContext.stat);
	return renameAction.run(explorerContext);
};

export const moveFileToTrashHandler = (accessor: ServicesAccessor) => {
	const instantationService = accessor.get(IInstantiationService);
	const listService = accessor.get(IListService);
	const explorerContext = getContext(listService.lastFocusedList, accessor.get(IViewletService));
	const stats = explorerContext.selection.length > 1 ? explorerContext.selection : [explorerContext.stat];

	const moveFileToTrashAction = instantationService.createInstance(BaseDeleteFileAction, listService.lastFocusedList, stats, true);
	return moveFileToTrashAction.run();
};

export const deleteFileHandler = (accessor: ServicesAccessor) => {
	const instantationService = accessor.get(IInstantiationService);
	const listService = accessor.get(IListService);
	const explorerContext = getContext(listService.lastFocusedList, accessor.get(IViewletService));
	const stats = explorerContext.selection.length > 1 ? explorerContext.selection : [explorerContext.stat];

	const deleteFileAction = instantationService.createInstance(BaseDeleteFileAction, listService.lastFocusedList, stats, false);
	return deleteFileAction.run();
};

export const copyFileHandler = (accessor: ServicesAccessor) => {
	const instantationService = accessor.get(IInstantiationService);
	const listService = accessor.get(IListService);
	const explorerContext = getContext(listService.lastFocusedList, accessor.get(IViewletService));
	const stats = explorerContext.selection.length > 1 ? explorerContext.selection : [explorerContext.stat];

	const copyFileAction = instantationService.createInstance(CopyFileAction, listService.lastFocusedList, stats);
	return copyFileAction.run();
};

export const pasteFileHandler = (accessor: ServicesAccessor) => {
	const instantationService = accessor.get(IInstantiationService);
	const listService = accessor.get(IListService);
	const clipboardService = accessor.get(IClipboardService);
	const explorerContext = getContext(listService.lastFocusedList, accessor.get(IViewletService));

	return Promise.all(resources.distinctParents(clipboardService.readResources(), r => r).map(toCopy => {
		const pasteFileAction = instantationService.createInstance(PasteFileAction, listService.lastFocusedList, explorerContext.stat);
		return pasteFileAction.run(toCopy);
	}));
};


text:
-- =============================================
-- Author:		Ken Taylor
-- Create date: August 6, 2013
-- Description:	Return a list of all Oracle Linked Database Servers
-- Usage
/*
USE [DBA]
GO

DECLARE	@return_value int

EXEC	@return_value = [dbo].[usp_GetOracleLinkedServerNames]

SELECT	'Return Value' = @return_value

GO
*/
-- Sample Results:
/*
SRV_NAME
FIS_DS
FIS_DS_PROD
ISODS_PROD
MOTHRA_PROD
MOTHRA_TEST
MOTHTEST
PAY_PERS_EXTR
SIS
SIS_DEV
*/
-- Modifications:
--	2013-10-30 by kjt:  Added filtering to remove SIS servers from list.
--  2014-04-01 by kjt: Added param @IncludeBannerItems to include Banner items if desired.
-- =============================================
CREATE PROCEDURE [dbo].[usp_GetOracleLinkedServerNames]
	-- Add the parameters for the stored procedure here
	@IncludeBannerItems bit = 0 --Set to 1 to include Banner info.
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    DECLARE @OracleLinkedServers TABLE (
		SRV_NAME varchar(100),
		SRV_PROVIDERNAME varchar(200),
		SRV_PRODUCT varchar(100),
		SRV_DATASOURCE varchar(500),
		SRV_PROVIDERSTRING varchar(500),
		SRV_LOCATION varchar(200),
		SRV_CAT varchar(100)
	)

	INSERT INTO @OracleLinkedServers
	EXEC sp_linkedservers

	IF @IncludeBannerItems = 0
		SELECT SRV_NAME Name FROM @OracleLinkedServers WHERE SRV_PROVIDERNAME = 'OraOLEDB.Oracle' AND SRV_NAME NOT LIKE 'SIS%'
	ELSE
		SELECT SRV_NAME Name FROM @OracleLinkedServers WHERE SRV_PROVIDERNAME = 'OraOLEDB.Oracle'

	/*
	FIS_DS
	FIS_DS_PROD
	ISODS_PROD
	MOTHRA_PROD
	MOTHRA_TEST
	MOTHTEST
	PAY_PERS_EXTR
	SIS
	SIS_DEV
	*/
END


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>BackgroundImagePanelExample</title>
<meta name="date" content="2013-04-14">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

test

Class BackgroundImagePanelExample

java.lang.Object

test.BackgroundImagePanelExample

public class BackgroundImagePanelExample
extends java.lang.Object

Constructor Summary

Constructors

Constructor and Description

BackgroundImagePanelExample()

Method Summary

Methods

Modifier and Type
Method and Description

static void
main(java.lang.String[] args)

static javax.swing.JPanel
wrapInBackgroundImage(javax.swing.JComponent component,
                     javax.swing.Icon backgroundIcon)

Wraps a Swing JComponent in a background image.

static javax.swing.JPanel
wrapInBackgroundImage(javax.swing.JComponent component,
                     javax.swing.Icon backgroundIcon,
                     int verticalAlignment,
                     int horizontalAlignment)

Wraps a Swing JComponent in a background image.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

BackgroundImagePanelExample

public BackgroundImagePanelExample()

Method Detail

wrapInBackgroundImage

public static javax.swing.JPanel wrapInBackgroundImage(javax.swing.JComponent component,
                                       javax.swing.Icon backgroundIcon)

Wraps a Swing JComponent in a background image. Simply invokes the overloded
 variant with Top/Leading alignment for background image.

Parameters:

component - - to wrap in the a background image

backgroundIcon - - the background image (Icon)

Returns:

the wrapping JPanel

wrapInBackgroundImage

public static javax.swing.JPanel wrapInBackgroundImage(javax.swing.JComponent component,
                                       javax.swing.Icon backgroundIcon,
                                       int verticalAlignment,
                                       int horizontalAlignment)

Wraps a Swing JComponent in a background image. The vertical and horizontal
 alignment of background image can be specified using the alignment
 contants from JLabel.

Parameters:

component - - to wrap in the a background image

backgroundIcon - - the background image (Icon)

verticalAlignment - - vertical alignment. See contants in JLabel.

horizontalAlignment - - horizontal alignment. See contants in JLabel.

Returns:

the wrapping JPanel

main

public static void main(java.lang.String[] args)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
include ../Makefile_cpp.in
PROG = dgate


text:
package terror

import (
	"fmt"
	"runtime"
	"strconv"

	"github.com/insionng/yougam/libraries/juju/errors"
	"github.com/insionng/yougam/libraries/ngaut/log"
	"github.com/insionng/yougam/libraries/pingcap/tidb/mysql"
)

// Common base error instances.
var (
	CommitNotInTransaction   = ClassExecutor.New(CodeCommitNotInTransaction, "commit not in transaction")
	RollbackNotInTransaction = ClassExecutor.New(CodeRollbackNotInTransaction, "rollback not in transaction")
	ExecResultIsEmpty        = ClassExecutor.New(CodeExecResultIsEmpty, "exec result is empty")

	MissConnectionID = ClassExpression.New(CodeMissConnectionID, "miss connection id information")
)

// ErrCode represents a specific error type in a error class.
// Same error code can be used in different error classes.
type ErrCode int

// Executor error codes.
const (
	CodeCommitNotInTransaction   ErrCode = 1
	CodeRollbackNotInTransaction         = 2
	CodeExecResultIsEmpty                = 3
)

// Expression error codes.
const (
	CodeMissConnectionID ErrCode = iota + 1
)

// ErrClass represents a class of errors.
type ErrClass int

// Error classes.
const (
	ClassAutoid ErrClass = iota + 1
	ClassDDL
	ClassDomain
	ClassEvaluator
	ClassExecutor
	ClassExpression
	ClassInspectkv
	ClassKV
	ClassMeta
	ClassOptimizer
	ClassOptimizerPlan
	ClassParser
	ClassPerfSchema
	ClassPrivilege
	ClassSchema
	ClassServer
	ClassStructure
	ClassVariable
	ClassXEval
	// Add more as needed.
)

// String implements fmt.Stringer interface.
func (ec ErrClass) String() string {
	switch ec {
	case ClassAutoid:
		return "autoid"
	case ClassDDL:
		return "ddl"
	case ClassDomain:
		return "domain"
	case ClassExecutor:
		return "executor"
	case ClassExpression:
		return "expression"
	case ClassInspectkv:
		return "inspectkv"
	case ClassMeta:
		return "meta"
	case ClassKV:
		return "kv"
	case ClassOptimizer:
		return "optimizer"
	case ClassParser:
		return "parser"
	case ClassPerfSchema:
		return "perfschema"
	case ClassPrivilege:
		return "privilege"
	case ClassSchema:
		return "schema"
	case ClassServer:
		return "server"
	case ClassStructure:
		return "structure"
	case ClassVariable:
		return "variable"
	}
	return strconv.Itoa(int(ec))
}

// EqualClass returns true if err is *Error with the same class.
func (ec ErrClass) EqualClass(err error) bool {
	e := errors.Cause(err)
	if e == nil {
		return false
	}
	if te, ok := e.(*Error); ok {
		return te.class == ec
	}
	return false
}

// NotEqualClass returns true if err is not *Error with the same class.
func (ec ErrClass) NotEqualClass(err error) bool {
	return !ec.EqualClass(err)
}

// New creates an *Error with an error code and an error message.
// Usually used to create base *Error.
func (ec ErrClass) New(code ErrCode, message string) *Error {
	return &Error{
		class:   ec,
		code:    code,
		message: message,
	}
}

// Error implements error interface and adds integer Class and Code, so
// errors with different message can be compared.
type Error struct {
	class   ErrClass
	code    ErrCode
	message string
	file    string
	line    int
}

// Class returns ErrClass
func (e *Error) Class() ErrClass {
	return e.class
}

// Code returns ErrCode
func (e *Error) Code() ErrCode {
	return e.code
}

// Location returns the location where the error is created,
// implements juju/errors locationer interface.
func (e *Error) Location() (file string, line int) {
	return e.file, e.line
}

// Error implements error interface.
func (e *Error) Error() string {
	return fmt.Sprintf("[%s:%d]%s", e.class, e.code, e.message)
}

// Gen generates a new *Error with the same class and code, and a new formatted message.
func (e *Error) Gen(format string, args ...interface{}) *Error {
	err := *e
	err.message = fmt.Sprintf(format, args...)
	_, err.file, err.line, _ = runtime.Caller(1)
	return &err
}

// Equal checks if err is equal to e.
func (e *Error) Equal(err error) bool {
	originErr := errors.Cause(err)
	if originErr == nil {
		return false
	}
	inErr, ok := originErr.(*Error)
	return ok && e.class == inErr.class && e.code == inErr.code
}

// NotEqual checks if err is not equal to e.
func (e *Error) NotEqual(err error) bool {
	return !e.Equal(err)
}

// ToSQLError convert Error to mysql.SQLError.
func (e *Error) ToSQLError() *mysql.SQLError {
	code := e.getMySQLErrorCode()
	return mysql.NewErrf(code, e.message)
}

var defaultMySQLErrorCode uint16

func (e *Error) getMySQLErrorCode() uint16 {
	codeMap, ok := ErrClassToMySQLCodes[e.class]
	if !ok {
		log.Warnf("Unknown error class: %v", e.class)
		return defaultMySQLErrorCode
	}
	code, ok := codeMap[e.code]
	if !ok {
		log.Warnf("Unknown error class: %v code: %v", e.class, e.code)
		return defaultMySQLErrorCode
	}
	return code
}

var (
	// ErrCode to mysql error code map.
	parserMySQLErrCodes     = map[ErrCode]uint16{}
	executorMySQLErrCodes   = map[ErrCode]uint16{}
	serverMySQLErrCodes     = map[ErrCode]uint16{}
	expressionMySQLErrCodes = map[ErrCode]uint16{}

	// ErrClassToMySQLCodes is the map of ErrClass to code-map.
	ErrClassToMySQLCodes map[ErrClass](map[ErrCode]uint16)
)

func init() {
	ErrClassToMySQLCodes = make(map[ErrClass](map[ErrCode]uint16))
	ErrClassToMySQLCodes[ClassExecutor] = executorMySQLErrCodes
	ErrClassToMySQLCodes[ClassExpression] = expressionMySQLErrCodes
	ErrClassToMySQLCodes[ClassParser] = parserMySQLErrCodes
	ErrClassToMySQLCodes[ClassServer] = serverMySQLErrCodes
	defaultMySQLErrorCode = mysql.ErrUnknown
}

// ErrorEqual returns a boolean indicating whether err1 is equal to err2.
func ErrorEqual(err1, err2 error) bool {
	e1 := errors.Cause(err1)
	e2 := errors.Cause(err2)

	if e1 == e2 {
		return true
	}

	if e1 == nil || e2 == nil {
		return e1 == e2
	}

	te1, ok1 := e1.(*Error)
	te2, ok2 := e2.(*Error)
	if ok1 && ok2 {
		return te1.class == te2.class && te1.code == te2.code
	}

	return e1.Error() == e2.Error()
}

// ErrorNotEqual returns a boolean indicating whether err1 isn't equal to err2.
func ErrorNotEqual(err1, err2 error) bool {
	return !ErrorEqual(err1, err2)
}


text:
package com.digi.entity.request;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;

/**
 * Created by tymoshenkol on 25-Aug-16.
 */
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(value="MessageToSend", description="SMS message")
public class MessageToSend implements Serializable {
	@ApiModelProperty(value = "Phone number", example = "14053264519", required = true)
	private String to;
	@ApiModelProperty(value = "SMS - body text", example = "TLV: test message =)", required = true)
	private String text;
}


text:
module QA
  module Service
    module DockerRun
      class Jenkins < Base
        def initialize
          @image = 'registry.gitlab.com/gitlab-org/gitlab-qa/jenkins-gitlab:version1'
          @name = 'jenkins-server'
          @port = '8080'
          super()
        end

        def host_address
          "http://#{host_name}:#{@port}"
        end

        def host_name
          if !QA::Runtime::Env.running_in_ci? && !runner_network.equal?('airgapped')
            'localhost'
          end

          super
        end

        def register!
          command = <<~CMD.tr("\n", ' ')
            docker run -d --rm
            --network #{network}
            --hostname #{host_name}
            --name #{@name}
            --env JENKINS_HOME=jenkins_home
            --publish #{@port}:8080
            --publish 50000:50000
            #{@image}
          CMD

          if !QA::Runtime::Env.running_in_ci? && !runner_network.equal?('airgapped')
            command.gsub!("--network #{network} ", '')
          end

          shell command
        end
      end
    end
  end
end


text:
/* SPDX-License-Identifier: MIT */

import { CssBaseline, PaletteMode, Toolbar } from "@mui/material";
import { StyledEngineProvider, ThemeProvider } from "@mui/material/styles";
import { Action, Update } from "history";
import * as React from "react";
import { Environment, RelayEnvironmentProvider } from "react-relay";
import type { Config } from "../config";
import { ConfigContext } from "../core";
import { History, HistoryContext, LocationContext } from "../core/history";
import type { RouteResponse } from "../core/router";
import { resolveRoute } from "../core/router";
import { LoginDialog } from "../dialogs";
import theme from "../theme";
import { AppToolbar } from "./AppToolbar";
import { ErrorPage } from "./ErrorPage";

type AppProps = {
  config: Config;
  history: History;
  relay: Environment;
};

export class App extends React.Component<AppProps> {
  state = {
    route: undefined as RouteResponse | undefined,
    location: this.props.history.location,
    error: undefined as Error | undefined,
    theme: (window?.localStorage?.getItem("theme") === "dark"
      ? "dark"
      : "light") as PaletteMode,
  };

  static getDerivedStateFromError(error: Error): { error: Error } {
    return { error };
  }

  dispose?: () => void;

  componentDidMount(): void {
    const { history } = this.props;
    this.dispose = history.listen(this.renderPath);
    this.renderPath({ location: history.location, action: Action.Pop });
  }

  componentDidUpdate(): void {
    if (this.state.route?.title) {
      self.document.title = this.state.route.title;
    }
  }

  componentWillUnmount(): void {
    if (this.dispose) this.dispose();
  }

  componentDidCatch(error: Error, errorInfo: unknown): void {
    // You can also log the error to an error reporting service
    console.error(error, errorInfo);
  }

  renderPath = async (ctx: Update): Promise<void> => {
    resolveRoute({
      path: ctx.location.pathname,
      query: new URLSearchParams(ctx.location.search),
      relay: this.props.relay,
    }).then((route) => {
      if (route.error) console.error(route.error);
      this.setState({ route, location: ctx.location, error: route.error });
    });
  };

  handleChangeTheme = (): void => {
    this.setState((x: { theme: PaletteMode }) => {
      const theme = x.theme === "light" ? "dark" : "light";
      window.localStorage?.setItem("theme", theme);
      return { ...x, theme };
    });
  };

  render(): JSX.Element {
    const { config, history } = this.props;
    const { route, location, error } = this.state;

    if (error) {
      return (
        <StyledEngineProvider injectFirst>
          <ThemeProvider theme={theme[this.state.theme]}>
            <ErrorPage error={error} history={history} />;
          </ThemeProvider>
        </StyledEngineProvider>
      );
    }

    return (
      <ConfigContext.Provider value={config}>
        <StyledEngineProvider injectFirst>
          <ThemeProvider theme={theme[this.state.theme]}>
            <RelayEnvironmentProvider environment={this.props.relay}>
              <HistoryContext.Provider value={history}>
                <LocationContext.Provider value={location}>
                  <CssBaseline />
                  <AppToolbar onChangeTheme={this.handleChangeTheme} />
                  <Toolbar />
                  {route?.component
                    ? React.createElement(route.component, route.props)
                    : null}
                  <LoginDialog />
                </LocationContext.Provider>
              </HistoryContext.Provider>
            </RelayEnvironmentProvider>
          </ThemeProvider>
        </StyledEngineProvider>
      </ConfigContext.Provider>
    );
  }
}


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Cake.CakeBoss")]
[assembly: AssemblyDescription("Cake-Build addin that extends allows you to control remote CakeBoss agents")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

 -->

<!--  These resources are around just to allow their values to be customized
     for different hardware and product builds.  -->

<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
  <string-array name="wfcOperatorErrorAlertMessages">
    <item msgid="6674750523418536585">"Për të bërë telefonata dhe për të dërguar mesazhe me Wi-Fi, në fillim kërkoji operatorit celular ta konfigurojë këtë shërbim. Më pas aktivizo përsëri telefonatat me Wi-Fi, nga Cilësimet."</item>
  </string-array>
  <string-array name="wfcOperatorErrorNotificationMessages">
    <item msgid="5880767641285399402">"Regjistrohu me operatorin tënd celular"</item>
  </string-array>
    <string name="wfcSpnFormat" msgid="5634367913183683816">"Telefonatat me Wi-Fi nga %s"</string>
</resources>


text:
<!DOCTYPE html>

	<title>Grid MultiChannel Test</title>
	<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no"/>
	<meta name="apple-mobile-web-app-capable" content="yes" />
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
	<link rel='stylesheet' href="support/common.css" />

	<div id='grid' data-dojo-id='grid' data-dojo-type='gridx.Grid' data-dojo-props='
		cacheClass: "gridx/core/model/cache/Async",
		store: store,
		structure: layout,
		pageSize: "auto",
		selectRowMultiple: true,
		selectRowTriggerOnCell: false,
		structureSwitchPortrait: portrait,
		modules: [
			"gridx/modules/AutoPagedBody",
			"gridx/modules/TouchVScroller",
			"gridx/modules/Sort",
			"gridx/modules/extendedSelect/Row",
			"gridx/modules/IndirectSelectColumn",
			"gridx/modules/HiddenColumns",
			"gridx/modules/StructureSwitch",
			"gridx/modules/ColumnResizer"
		]
	'>

			"gridx/modules/MultiChannelScroller",
			"gridx/modules/select/Cell",
			"gridx/modules/select/Column",


text:
namespace media {

// Theoretically, we can test on BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA),
// but since the only current user is V4L2 we are limiting the scope to OS_LINUX
// so the binary size does not inflate on non-using systems. Feel free to adapt
// this and BUILD.gn as our needs evolve.
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)

// Return a new vector containing duplicates of |fds|, or PCHECKs in case of an
// error.
MEDIA_EXPORT std::vector<base::ScopedFD> DuplicateFDs(
    const std::vector<base::ScopedFD>& fds);

#endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)

}  // namespace media

#endif  // MEDIA_BASE_SCOPEDFD_HELPER_H_


text:
[slider](http://dbkaplun.github.io/slider/)
========

Dead-simple Netflix-like scroller with drag support and autoscrolling on hover


text:
from polyphony import testbench
from polyphony import unroll

def unroll04():
    u = unroll([1, 2, 3], 4)

@testbench
def test():
    unroll04()

test()


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>CyclicBuffer Members</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Apache log4net™ SDK Documentation - Microsoft .NET Framework 4.0

CyclicBuffer Members

        CyclicBuffer overview

Public Instance Constructors

              CyclicBuffer Constructor

             Constructor

Public Instance Properties

Item	 Gets the ith oldest event currently in the buffer.

Length	 Gets the number of logging events in the buffer.

MaxSize	 Gets the maximum size of the buffer.

Public Instance Methods

Append	 Appends a loggingEvent to the buffer.

Clear	 Clear the buffer

Equals (inherited from Object)

GetHashCode (inherited from Object)

GetType (inherited from Object)

PopAll	 Pops all the logging events from the buffer into an array.

PopOldest	 Get and remove the oldest event in the buffer.

ToString (inherited from Object)

Protected Instance Methods

Finalize (inherited from Object)

MemberwiseClone (inherited from Object)

See Also

        CyclicBuffer Class | log4net.Util Namespace

      <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
        <param name="Keyword" value="CyclicBuffer class">
        </param>
        <param name="Keyword" value="log4net.Util.CyclicBuffer class">
        </param>
        <param name="Keyword" value="CyclicBuffer class, all members">
        </param>
      </object>

Copyright 2004-2013 The Apache Software Foundation.

Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Ann. Mag. nat. Hist. , Ser. 2 5: (1850)

#### Original name
Spiloma melanopum Ach. ex Turner

### Remarks
null


text:
#include "Zerocoin.h"
#include "ParallelTasks.h"

namespace libzerocoin {

SerialNumberSignatureOfKnowledge::SerialNumberSignatureOfKnowledge(const Params* p): params(p) { }

SerialNumberSignatureOfKnowledge::SerialNumberSignatureOfKnowledge(const Params* p, const PrivateCoin& coin, const Commitment& commitmentToCoin, uint256 msghash)
    :params(p), s_notprime(p->zkp_iterations), sprime(p->zkp_iterations) {

    ParallelTasks::DoNotDisturb dnd;

	// Sanity check: verify that the order of the "accumulatedValueCommitmentGroup" is
	// equal to the modulus of "coinCommitmentGroup". Otherwise we will produce invalid
	// proofs.
	if (params->coinCommitmentGroup.modulus != params->serialNumberSoKCommitmentGroup.groupOrder) {
		throw ZerocoinException("Groups are not structured correctly.");
	}

	Bignum a = params->coinCommitmentGroup.g;
	Bignum b = params->coinCommitmentGroup.h;
	Bignum g = params->serialNumberSoKCommitmentGroup.g;
	Bignum h = params->serialNumberSoKCommitmentGroup.h;

	CHashWriter hasher(0,0);
	hasher << *params << commitmentToCoin.getCommitmentValue() << coin.getSerialNumber();
    if (!msghash.IsNull())
        hasher << msghash;

	vector<Bignum> r(params->zkp_iterations);
	vector<Bignum> v(params->zkp_iterations);
	vector<Bignum> c(params->zkp_iterations);

	for(uint32_t i=0; i < params->zkp_iterations; i++) {
		//FIXME we really ought to use one BN_CTX for all of these
		// operations for performance reasons, not the one that
		// is created individually  by the wrapper
		r[i] = Bignum::randBignum(params->coinCommitmentGroup.groupOrder);
		v[i] = Bignum::randBignum(params->serialNumberSoKCommitmentGroup.groupOrder);
	}

	// Openssl's rng is not thread safe, so we don't call it in a parallel loop,
	// instead we generate the random values beforehand and run the calculations
	// based on those values in parallel.

    ParallelTasks challenges(params->zkp_iterations);

	for(uint32_t i=0; i < params->zkp_iterations; i++) {
		// compute g^{ {a^x b^r} h^v} mod p2
        challenges.Add([this, i, &coin, &c, &r, &v] {
            c[i] = challengeCalculation(coin.getSerialNumber(), r[i], v[i]);
        });
	}
    challenges.Wait();

	// We can't hash data in parallel either
	// because OPENMP cannot not guarantee loops
	// execute in order.
	for(uint32_t i=0; i < params->zkp_iterations; i++) {
		hasher << c[i];
	}
    this->hash = hasher.GetArith256Hash();
	unsigned char *hashbytes =  (unsigned char*) &hash;

    challenges.Reset();
	for(uint32_t i = 0; i < params->zkp_iterations; i++) {
		int bit = i % 8;
		int byte = i / 8;

		bool challenge_bit = ((hashbytes[byte] >> bit) & 0x01);
		if (challenge_bit) {
			s_notprime[i]       = r[i];
			sprime[i]           = v[i];
		} else {
            challenges.Add([this, i, &r, &v, &b, &commitmentToCoin, &coin] {
                s_notprime[i]   = r[i] - coin.getRandomness();
                sprime[i]       = v[i] - (commitmentToCoin.getRandomness() *
			                              b.pow_mod(r[i] - coin.getRandomness(), params->serialNumberSoKCommitmentGroup.groupOrder));
            });
		}
    }
    challenges.Wait();
}

inline Bignum SerialNumberSignatureOfKnowledge::challengeCalculation(const Bignum& a_exp,const Bignum& b_exp,
        const Bignum& h_exp) const {

	Bignum a = params->coinCommitmentGroup.g;
	Bignum b = params->coinCommitmentGroup.h;
	Bignum g = params->serialNumberSoKCommitmentGroup.g;
	Bignum h = params->serialNumberSoKCommitmentGroup.h;

	Bignum exponent = (a.pow_mod(a_exp, params->serialNumberSoKCommitmentGroup.groupOrder)
	                   * b.pow_mod(b_exp, params->serialNumberSoKCommitmentGroup.groupOrder)) % params->serialNumberSoKCommitmentGroup.groupOrder;

	return (g.pow_mod(exponent, params->serialNumberSoKCommitmentGroup.modulus) * h.pow_mod(h_exp, params->serialNumberSoKCommitmentGroup.modulus)) % params->serialNumberSoKCommitmentGroup.modulus;
}

bool SerialNumberSignatureOfKnowledge::Verify(const Bignum& coinSerialNumber, const Bignum& valueOfCommitmentToCoin,
        const uint256 msghash) const {

    ParallelTasks::DoNotDisturb dnd;

	Bignum a = params->coinCommitmentGroup.g;
	Bignum b = params->coinCommitmentGroup.h;
	Bignum g = params->serialNumberSoKCommitmentGroup.g;
	Bignum h = params->serialNumberSoKCommitmentGroup.h;

	// Make sure that the serial number has a unique representation
	if (coinSerialNumber < 0 || coinSerialNumber >= params->coinCommitmentGroup.groupOrder){
		return false;
	}

	CHashWriter hasher(0,0);
	hasher << *params << valueOfCommitmentToCoin <<coinSerialNumber;
    if (!msghash.IsNull())
        hasher << msghash;

	vector<CBigNum> tprime(params->zkp_iterations);
	unsigned char *hashbytes = (unsigned char*) &this->hash;

    ParallelTasks challenges(params->zkp_iterations);

	for(uint32_t i = 0; i < params->zkp_iterations; i++) {
        challenges.Add([this, i, hashbytes, &b, &h, &tprime, &coinSerialNumber, &valueOfCommitmentToCoin] {
            int bit = i % 8;
            int byte = i / 8;
            bool challenge_bit = ((hashbytes[byte] >> bit) & 0x01);
            if(challenge_bit) {
                tprime[i] = challengeCalculation(coinSerialNumber, s_notprime[i], sprime[i]);
            } else {
                Bignum exp = b.pow_mod(s_notprime[i], params->serialNumberSoKCommitmentGroup.groupOrder);
                tprime[i] = ((valueOfCommitmentToCoin.pow_mod(exp, params->serialNumberSoKCommitmentGroup.modulus) % params->serialNumberSoKCommitmentGroup.modulus) *
                             (h.pow_mod(sprime[i], params->serialNumberSoKCommitmentGroup.modulus) % params->serialNumberSoKCommitmentGroup.modulus)) %
                            params->serialNumberSoKCommitmentGroup.modulus;
            }
        });
	}
    challenges.Wait();

	for(uint32_t i = 0; i < params->zkp_iterations; i++) {
		hasher << tprime[i];
	}
    return hasher.GetArith256Hash() == hash;
}

} /* namespace libzerocoin */


text:
<?php

/**
 * Get the number of rows in the result set
 *
 * @phpstub
 *
 * @param resource $result
 *
 * @return int Number of rows, when process is successful.
 */
function cubrid_num_rows($result)
{
}


text:
[![npm](https://img.shields.io/npm/v/markus-cinema-client.svg)](https://www.npmjs.com/package/markus-cinema-client)
[![GitHub release](https://img.shields.io/github/release/oliverviljamaa/markus-cinema-client.svg)](https://github.com/oliverviljamaa/markus-cinema-client/releases)

[![CircleCI](https://img.shields.io/circleci/project/github/oliverviljamaa/markus-cinema-client/master.svg)](https://circleci.com/gh/oliverviljamaa/markus-cinema-client)
[![Code Climate](https://img.shields.io/codeclimate/coverage/github/oliverviljamaa/markus-cinema-client.svg)](https://codeclimate.com/github/oliverviljamaa/markus-cinema-client/coverage)
[![npm](https://img.shields.io/npm/l/markus-cinema-client.svg)](https://github.com/oliverviljamaa/markus-cinema-client/blob/master/LICENSE)

JavaScript client for fetching data from cinemas that use MARKUS Cinema System.

## Background

Multiple cinemas in Finland, Estonia, Latvia and Lithuania use MARKUS Cinema System that exposes XML with upcoming shows and more.

For example:
* https://www.forumcinemas.ee/XML
* https://www.apollokino.ee/XML
* https://cinamon.ee/xml
* http://www.finnkino.fi/xml
* https://cinamonkino.lv/xml

This is a promise-based JavaScript client that takes care of fetching the XML, parsing it and extracting the relevant data.

## Usage

### Install

`yarn add markus-cinema-client`
or
`npm install --save markus-cinema-client`

### Use

```javascript
import { getShows } from 'markus-cinema-client';

const options = { area: 1008, dt: '14.02.2017' };

getShows('http://www.forumcinemas.ee/xml', options).then((shows) => {
  ...
});
```

## Features

Currently, only `getShows` for `Schedule` is implemented. However, most of the API-s also expose `Areas`, `ScheduleDates`, `Events`, `News`, etc.

For features and bugs, feel free to [add issues](https://github.com/oliverviljamaa/markus-cinema-client/issues) or contribute.

## Contributing

1. Run tests in watch mode with `yarn test:watch` or `npm run test:watch` and ensure every line is tested. For a run-once check with ESLint, run `yarn test` or `npm test`.
1. Bump version number according to [semver](http://semver.org/) and add an item that a release will be based on to `CHANGELOG.md`.
1. Submit your pull request from a feature branch and get code reviewed.
1. If the pull request is approved, coverage stays high and CircleCI build passes, you will be able to merge.
1. Code will automatically be released to GitHub and published to npm.