text:
#import "SoomlaProfile.h"
#import "Reward.h"
#import "AuthController.h"
#import "SocialController.h"
#import "UserProfileUtils.h"
#import "ProfileEventHandling.h"
#import "UserProfileNotFoundException.h"
#import "UserProfileStorage.h"

#import <UIKit/UIKit.h>

#define SOOMLA_PROFILE_VERSION @"1.1.5"

// if using Unity social provider this is YES
BOOL UsingExternalProvider;

@implementation SoomlaProfile

+ (void)usingExternalProvider:(BOOL)isExternal {

    UsingExternalProvider = isExternal;
}

+ (BOOL)isUsingExternalProvider {
    return UsingExternalProvider;
}

+ (NSString*)getVersion {
    return SOOMLA_PROFILE_VERSION;
}

- (void)initialize {
    [self initialize:nil];
}

- (void)initialize:(NSDictionary *)customParams {
    if (UsingExternalProvider) {
        authController = [[AuthController alloc] initWithoutLoadingProviders];
        socialController = [[SocialController alloc] initWithoutLoadingProviders];
    }
    else {
        authController = [[AuthController alloc] initWithParameters:customParams];
        socialController = [[SocialController alloc] initWithParameters:customParams];
    }

    [ProfileEventHandling postProfileInitialized];

    [authController settleAutoLogin];
    [socialController settleAutoLogin];
}

- (void)loginWithProvider:(Provider)provider {
    [self loginWithProvider:provider andPayload:@"" andReward:nil];
}

- (void)loginWithProvider:(Provider)provider andReward:(Reward *)reward {
    [self loginWithProvider:provider andPayload:@"" andReward:reward];
}

- (void)loginWithProvider:(Provider)provider andPayload:(NSString *)payload andReward:(Reward *)reward {
    @try {
        [authController loginWithProvider:provider andAutoLogin:NO andPayload:payload andReward:reward];
    }
    @catch (NSException *exception) {

        // TODO: implement logic like in java that will raise the exception. Currently not raised
        [socialController loginWithProvider:provider andAutoLogin:NO andPayload:payload andReward:reward];
    }
}

- (void)logoutWithProvider:(Provider)provider {
    @try {
        [authController logoutWithProvider:provider];
    }
    @catch (NSException *exception) {

        // TODO: implement logic like in java that will raise the exception. Currently not raised
        [socialController logoutWithProvider:provider];
    }
}

- (BOOL)isLoggedInWithProvider:(Provider)provider {
    @try {
        return [authController isLoggedInWithProvider:provider];
    }
    @catch (NSException *exception) {

        // TODO: implement logic like in java that will raise the exception. Currently not raised
        return [socialController isLoggedInWithProvider:provider];
    }

}

- (UserProfile *)getStoredUserProfileWithProvider:(Provider)provider {
    @try {
        return [authController getStoredUserProfileWithProvider:provider];
    }
    @catch (NSException *exception) {

        // TODO: implement logic like in java that will raise the exception. Currently not raised
        return [socialController getStoredUserProfileWithProvider:provider];
    }
}

- (NSArray *)getStoredUserProfiles {
    NSArray* providers = [UserProfileUtils availableProviders];
    NSMutableArray* userProfiles = [NSMutableArray array];
    for(NSNumber* providerNum in providers) {
        @try {
            UserProfile* userProfile = [UserProfileStorage getUserProfile:(Provider)[providerNum intValue]];
            if (userProfile) {
                [userProfiles addObject:userProfile];
            }
        }@catch (NSException *exception) {
            // Skip
        }
    }
    return userProfiles;
}

- (void)updateStatusWithProvider:(Provider)provider andStatus:(NSString *)status andPayload:(NSString *)payload andReward:(Reward *)reward andConfirmation:(bool)showConfirmation andCustomMessage:(NSString *)customMessage {
    [socialController updateStatusWithProvider:provider andStatus:status andPayload:payload andReward:reward andConfirmation:showConfirmation andCustomMessage:customMessage];
}

- (void)updateStatusWithProvider:(Provider)provider andStatus:(NSString *)status andPayload:(NSString *)payload andReward:(Reward *)reward {
    [self updateStatusWithProvider:provider andStatus:status andPayload:payload andReward:reward andConfirmation:false andCustomMessage:nil];
}

- (void)updateStatusWithProvider:(Provider)provider andStatus:(NSString *)status andReward:(Reward *)reward {
    [self updateStatusWithProvider:provider andStatus:status andPayload:@"" andReward:reward andConfirmation:false andCustomMessage:nil];
}

- (void)updateStatusWithProviderDialog:(Provider)provider andLink:(NSString *)link andPayload:(NSString *)payload andReward:(Reward *)reward {
    [socialController updateStatusWithProviderDialog:provider andLink:link andPayload:payload andReward:reward];
}

- (void)updateStatusWithProviderDialog:(Provider)provider andLink:(NSString *)link andReward:(Reward *)reward {
    [self updateStatusWithProviderDialog:provider andLink:link andPayload:@"" andReward:reward];
}

- (void)updateStoryWithProvider:(Provider)provider
                     andMessage:(NSString *)message
                        andName:(NSString *)name
                     andCaption:(NSString *)caption
                 andDescription:(NSString *)description
                        andLink:(NSString *)link
                     andPicture:(NSString *)picture
                     andPayload:(NSString *)payload
                      andReward:(Reward *)reward {

    [self updateStoryWithProvider:provider andMessage:message andName:name andCaption:caption andDescription:description andLink:link andPicture:picture andPayload:payload andReward:reward andShowConfirmation:false andCustomMessage:NULL];
}

- (void)updateStoryWithProvider:(Provider)provider andMessage:(NSString *)message andName:(NSString *)name andCaption:(NSString *)caption andDescription:(NSString *)description andLink:(NSString *)link andPicture:(NSString *)picture andPayload:(NSString *)payload andReward:(Reward *)reward andShowConfirmation:(bool)showConfirmation andCustomMessage:(NSString *)customMessage {

    [socialController updateStoryWithProvider:provider
                                   andMessage:message
                                      andName:name
                                   andCaption:caption
                               andDescription:description
                                      andLink:link
                                   andPicture:picture
                                   andPayload:payload
                                    andReward:reward
                          andShowConfirmation:showConfirmation
                             andCustomMessage: customMessage];
}

- (void)updateStoryWithProvider:(Provider)provider
                     andMessage:(NSString *)message
                        andName:(NSString *)name
                     andCaption:(NSString *)caption
                 andDescription:(NSString *)description
                        andLink:(NSString *)link
                     andPicture:(NSString *)picture
                      andReward:(Reward *)reward {
    [self updateStoryWithProvider:provider andMessage:message andName:name andCaption:caption
                   andDescription:description andLink:link andPicture:picture andPayload:@"" andReward:reward];
}

- (void)updateStoryWithProviderDialog:(Provider)provider
                                  andName:(NSString *)name
                               andCaption:(NSString *)caption
                           andDescription:(NSString *)description
                                  andLink:(NSString *)link
                               andPicture:(NSString *)picture
                           andPayload:(NSString *)payload
                                andReward:(Reward *)reward {
    [socialController updateStoryWithProviderDialog:provider andName:name andCaption:caption
                               andDescription:description andLink:link andPicture:picture andPayload:payload andReward:reward];
}

- (void)updateStoryWithProviderDialog:(Provider)provider
                              andName:(NSString *)name
                           andCaption:(NSString *)caption
                       andDescription:(NSString *)description
                              andLink:(NSString *)link
                           andPicture:(NSString *)picture
                            andReward:(Reward *)reward {
    [self updateStoryWithProviderDialog:provider andName:name andCaption:caption
                   andDescription:description andLink:link andPicture:picture andPayload:@"" andReward:reward];
}

- (void)uploadImageWithProvider:(Provider)provider
                     andMessage:(NSString *)message
                    andFilePath:(NSString *)filePath
                     andPayload:(NSString *)payload
                      andReward:(Reward *)reward {

    [self uploadImageWithProvider:provider andMessage:message andFilePath:filePath andPayload:payload andReward:reward andConfirmation:false andCustomMessage:nil];
}

- (void)uploadImageWithProvider:(Provider)provider
                     andMessage:(NSString *)message
               andImageFileName:(NSString *)imageFileName
                   andImageData:(NSData *)imageData
                     andPayload:(NSString *)payload
                      andReward:(Reward *)reward
                andConfirmation:(BOOL)confirmation
               andCustomMessage:(NSString *)customMessage {

    [socialController uploadImageWithProvider:provider
                                   andMessage:message
                             andImageFileName:imageFileName
                                 andImageData:imageData
                                   andPayload:payload
                                    andReward:reward
                          andShowConfirmation:confirmation
                             andCustomMessage:customMessage
    ];
}
- (void)uploadImageWithProvider:(Provider)provider
                     andMessage:(NSString *)message
                    andFilePath:(NSString *)filePath
                     andPayload:(NSString *)payload
                      andReward:(Reward *)reward
                andConfirmation:(BOOL)showConfirmation
               andCustomMessage:(NSString *)customMessage {

    [socialController uploadImageWithProvider:provider
                                   andMessage:message
                                  andFilePath:filePath
                                   andPayload:payload
                                    andReward:reward
                          andShowConfirmation:showConfirmation
                             andCustomMessage:customMessage];
}

- (void)uploadImageWithProvider:(Provider)provider
                     andMessage:(NSString *)message
                    andFilePath:(NSString *)filePath
                      andReward:(Reward *)reward {
    [self uploadImageWithProvider:provider andMessage:message andFilePath:filePath andPayload:@"" andReward:reward];
}

- (void)getContactsWithProvider:(Provider)provider andPayload:(NSString *)payload andReward:(Reward *)reward {
    [socialController getContactsWith:provider andFromStart:false andPayload:payload andReward:reward];
}

- (void)getContactsWithProvider:(Provider)provider andFromStart: (bool)fromStart andPayload:(NSString *)payload andReward:(Reward *)reward {
    [socialController getContactsWith:provider andFromStart:fromStart andPayload:payload andReward:reward];
}

- (void)getContactsWithProvider:(Provider)provider andReward:(Reward *)reward {
    [self getContactsWithProvider:provider andPayload:@"" andReward:reward];
}

- (void)getFeedWithProvider:(Provider)provider andFromStart:(bool)fromStart andPayload:(NSString *)payload andReward:(Reward *)reward {
    [socialController getFeedProvider:provider andFromStart:false andPayload:payload andReward:reward];
}

- (void)getFeedWithProvider:(Provider)provider andReward:(Reward *)reward {
    [self getFeedWithProvider:provider andFromStart:NO andPayload:@"" andReward:reward];
}

- (void)like:(Provider)provider andPageId:(NSString *)pageId andReward:(Reward *)reward {
    [socialController like:provider andPageId:pageId andReward:reward];
}

- (void)openAppRatingPage {

    NSString* appID = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    float iOSVersion = [[UIDevice currentDevice].systemVersion floatValue];
    NSString *reviewURL;

    if (iOSVersion<7) { //IOS < 7.0
        NSString *templateReviewURLiOS6 = @"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APP_ID";
        reviewURL = [templateReviewURLiOS6 stringByReplacingOccurrencesOfString:@"APP_ID" withString:appID];

    } else { //IOS >= 7.0
        NSString *templateReviewURLiOS7 = @"itms-apps://itunes.apple.com/app/idAPP_ID";
        reviewURL = [templateReviewURLiOS7 stringByReplacingOccurrencesOfString:@"APP_ID" withString:[NSString stringWithFormat:@"%@", appID]];
    }

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:reviewURL]];
    [ProfileEventHandling postUserRating];

}

- (void)multiShareWithText:(NSString *)text andImageFilePath:(NSString *)imageFilePath {
    NSArray *postItems;
    if (imageFilePath && imageFilePath.length > 0) {
        UIImage *image = [UIImage imageWithContentsOfFile:imageFilePath];
        postItems = @[text, image];
    } else {
        postItems = @[text];
    }

    UIActivityViewController *activityVC = [[UIActivityViewController alloc]
            initWithActivityItems:postItems
            applicationActivities:nil];

    UIViewController *rootViewController = [[UIApplication sharedApplication] keyWindow].rootViewController;
    if ( [rootViewController respondsToSelector:@selector(popoverPresentationController)] ) {
        activityVC.popoverPresentationController.sourceView = rootViewController.view;
    }
    [rootViewController presentViewController:activityVC animated:YES completion:nil];
}

- (BOOL)tryHandleOpenURL:(Provider)provider openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [socialController tryHandleOpenURL:provider openURL:url sourceApplication:sourceApplication annotation:annotation];
}

- (BOOL)tryHandleOpenURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [socialController tryHandleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
}

// private

+ (SoomlaProfile*)getInstance {
    static SoomlaProfile* _instance = nil;

    @synchronized( self ) {
        if( _instance == nil ) {
            _instance = [[SoomlaProfile alloc ] init];
        }
    }

    return _instance;
}

@end


text:
1. Git clone
```
git clone https://github.com/tahmid-tanzim/filtering-matches-web-client.git
```

2. Run `npm install` from the root directory

3. Run `npm run dev` for development purpose. Browser URL `http://localhost:3000`

4. Run `npm run build` for production version. Then copy files from the `/build` directory to Nginx server root.

5. Unit tests are run with `npm run unit`.

6. E2E tests are run with `npm run test`.

> Node version - 8.2.0
> npm  version - 5.2.0

redpajama_set_name: RedPajamaGithub


text:
  {{ label }}

        <button class="btn btn-default" type="button" ng-click="decrease()"></button>

      <input type="text" class="form-control" id="{{id}}" ng-model="item" />

        <button class="btn btn-default" type="button" ng-click="increase()"></button>


text:
var partialURL = 'http://localhost:8000';
var i;
var errors = [];

casper.test.begin(
    'Visit hoyodesmog pages and check for errors',
    1,
    function suite(test) {
        casper.start(partialURL, function() {
            this.wait(30000, function() {
                test.assertTitle('Real-Time Mexico City Air Quality Index',
                                 'homepage title is the one expected');
                test.assertExists('svg g path', 'station square exists');
                test.assertExists('canvas', 'canvas exists');
                test.assertExists('img.leaflet-tile-loaded', 'map tiles exist');
            });
        });

        casper.thenOpen(partialURL + '/es/index.html', function() {
            this.wait(30000, function() {
                test.assertExists('svg g path', 'station square exists');
                test.assertExists('canvas', 'canvas exists');
                test.assertExists('img.leaflet-tile-loaded', 'map tiles exist');
            });
        });

        casper.thenOpen(partialURL + '/es/temperature.html', function() {
            this.wait(30000, function() {
                test.assertExists('svg g path', 'station square exists');
                test.assertExists('canvas', 'canvas exists');
                test.assertExists('img.leaflet-tile-loaded', 'map tiles exist');
            });
        });

        casper.thenOpen(partialURL + '/temperature.html', function() {
            this.wait(30000, function() {
                test.assertExists('svg g path', 'station square exists');
                test.assertExists('canvas', 'canvas exists');
                test.assertExists('img.leaflet-tile-loaded', 'map tiles exist');
            });
        });

        casper.thenOpen(partialURL + '/wind.html', function() {
            this.wait(30000, function() {
                test.assertExists('svg g path', 'station square exists');
                test.assertExists('canvas', 'canvas exists');
                test.assertExists('img.leaflet-tile',
                                  'en wind map tiles exist');
            });
        });

        casper.thenOpen(partialURL + '/es/wind.html', function() {
            this.wait(30000, function() {
                test.assertExists('svg g path', 'station square exists');
                test.assertExists('canvas', 'canvas exists');
                test.assertExists('img.leaflet-tile-loaded',
                                  'es wind map tiles exist');
            });
        });

        casper.thenOpen(partialURL + '/es/ozone.html', function() {
            this.wait(30000, function() {
                test.assertExists('div.line-chart svg path',
                                  'small multiple line chart exists');
                test.assertEval(function() {
                    return __utils__
                        .findAll('div.line-chart svg path').length >= 10;
                }, 'should have lots of charts');
            });
        });
        casper.thenOpen(partialURL + '/ozone.html', function() {
            this.wait(30000, function() {
                test.assertExists('div.line-chart svg path',
                                  'small multiple line chart exists');
                test.assertEval(function() {
                    return __utils__
                        .findAll('div.line-chart svg path').length >= 10;
                }, 'should have lots of charts');
            });
        });

        casper.thenOpen(partialURL + '/es/pm10.html', function() {
            this.wait(30000, function() {
                test.assertExists('div.line-chart svg path',
                                  'small multiple line chart exists');
            });
        });
        casper.thenOpen(partialURL + '/pm10.html', function() {
            this.wait(30000, function() {
                test.assertExists('div.line-chart svg path',
                                  'small multiple line chart exists');
            });
        });

        casper.thenOpen(partialURL + '/es/so2.html', function() {
            this.wait(30000, function() {
                test.assertExists('div.line-chart svg path',
                                  'small multiple line chart exists');
            });
        });
        casper.thenOpen(partialURL + '/so2.html', function() {
            this.wait(30000, function() {
                test.assertExists('div.line-chart svg path',
                                  'small multiple line chart exists');
            });
        });

        casper.thenOpen(partialURL + '/es/no2.html', function() {
            this.wait(30000, function() {
                test.assertExists('div.line-chart svg path',
                                  'small multiple line chart exists');
            });
        });
        casper.thenOpen(partialURL + '/no2.html', function() {
            this.wait(30000, function() {
                test.assertExists('div.line-chart svg path',
                                  'small multiple line chart exists');
            });
        });

        casper.thenOpen(partialURL + '/es/co.html', function() {
            this.wait(30000, function() {
                test.assertExists('div.line-chart svg path',
                                  'small multiple line chart exists');
            });
        });
        casper.thenOpen(partialURL + '/co.html', function() {
            this.wait(30000, function() {
                test.assertExists('div.line-chart svg path',
                                  'small multiple line chart exists');
            });
        });

        casper.thenOpen(partialURL + '/es/nox.html', function() {
            this.wait(30000, function() {
                test.assertExists('div.line-chart svg path',
                                  'small multiple line chart exists');
            });
        });
        casper.thenOpen(partialURL + '/nox.html', function() {
            this.wait(30000, function() {
                test.assertExists('div.line-chart svg path',
                                  'small multiple line chart exists');
            });
        });

        casper.thenOpen(partialURL + '/es/pm25.html', function() {
            this.wait(30000, function() {
                test.assertExists('div.line-chart svg path',
                                  'small multiple line chart exists');
            });
        });
        casper.thenOpen(partialURL + '/pm25.html', function() {
            this.wait(30000, function() {
                test.assertExists('div.line-chart svg path',
                                  'small multiple line chart exists');
            });
        });

        casper.thenOpen(partialURL + '/es/about.html');
        casper.thenOpen(partialURL + '/about.html');

        casper.on('page.error', function(msg, trace) {
            this.echo('Error:    ' + msg, 'ERROR');
            this.echo('file:     ' + trace[0].file, 'WARNING');
            this.echo('line:     ' + trace[0].line, 'WARNING');
            this.echo('function: ' + trace[0]['function'], 'WARNING');
            errors.push(msg);
            test.fail('console error');
        });

        casper.on('resource.received', function(resource) {
            var status = resource.status;
            if (status >= 400) {
                test.fail('resource failed to load');
                casper.log('Resource ' + resource.url +
                           ' failed to load (' + status + ')', 'error');

                errors.push({
                    url: resource.url,
                    status: resource.status
                });
            }
        });

        casper.run(function() {
            if (errors.length > 0) {
                this.echo(errors.length +
                          'errors found', 'WARNING');
            } else {
                this.echo(errors.length + ' Javascript errors found', 'INFO');
            }
            casper.exit();
        });
    });


text:
import { TextEditor, Uri, window } from 'vscode';
import { Commands } from '../constants';
import type { Container } from '../container';
import { GitUri } from '../git/gitUri';
import { GitCommit, GitLog, GitStashCommit } from '../git/models';
import { Logger } from '../logger';
import { Messages } from '../messages';
import { command } from '../system/command';
import { ActiveEditorCachedCommand, CommandContext, getCommandUri, isCommandContextViewNodeHasCommit } from './base';
import { executeGitCommand } from './gitCommands.actions';

export interface ShowQuickCommitFileCommandArgs {
	sha?: string;
	commit?: GitCommit | GitStashCommit;
	fileLog?: GitLog;
	revisionUri?: string;
}

@command()
export class ShowQuickCommitFileCommand extends ActiveEditorCachedCommand {
	static getMarkdownCommandArgs(args: ShowQuickCommitFileCommandArgs): string {
		return super.getMarkdownCommandArgsCore<ShowQuickCommitFileCommandArgs>(Commands.ShowQuickCommitFile, args);
	}

	constructor(private readonly container: Container) {
		super([
			Commands.ShowQuickCommitFile,
			Commands.ShowQuickCommitRevision,
			Commands.ShowQuickCommitRevisionInDiffLeft,
			Commands.ShowQuickCommitRevisionInDiffRight,
		]);
	}

	protected override async preExecute(context: CommandContext, args?: ShowQuickCommitFileCommandArgs) {
		if (context.editor != null && context.command.startsWith(Commands.ShowQuickCommitRevision)) {
			args = { ...args };

			const gitUri = await GitUri.fromUri(context.editor.document.uri);
			args.sha = gitUri.sha;
		}

		if (context.type === 'viewItem') {
			args = { ...args };
			args.sha = context.node.uri.sha;

			if (isCommandContextViewNodeHasCommit(context)) {
				args.commit = context.node.commit as any;
			}
		}

		return this.execute(context.editor, context.uri, args);
	}

	async execute(editor?: TextEditor, uri?: Uri, args?: ShowQuickCommitFileCommandArgs) {
		uri = getCommandUri(uri, editor);
		if (uri == null) return;

		args = { ...args };

		let gitUri;
		if (args.revisionUri !== undefined) {
			gitUri = GitUri.fromRevisionUri(Uri.parse(args.revisionUri, true));
			args.sha = gitUri.sha;
		} else {
			gitUri = await GitUri.fromUri(uri);
		}

		if (args.sha === undefined) {
			if (editor == null) return;

			const blameline = editor.selection.active.line;
			if (blameline < 0) return;

			try {
				const blame = await this.container.git.getBlameForLine(gitUri, blameline);
				if (blame == null) {
					void Messages.showFileNotUnderSourceControlWarningMessage('Unable to show commit file details');

					return;
				}

				// Because the previous sha of an uncommitted file isn't trust worthy we just have to kick out
				if (blame.commit.isUncommitted) {
					void Messages.showLineUncommittedWarningMessage('Unable to show commit file details');

					return;
				}

				args.sha = blame.commit.sha;

				args.commit = blame.commit;
			} catch (ex) {
				Logger.error(ex, 'ShowQuickCommitFileDetailsCommand', `getBlameForLine(${blameline})`);
				void window.showErrorMessage('Unable to show commit file details. See output channel for more details');

				return;
			}
		}

		try {
			if (args.commit == null /*|| args.commit.file != null*/) {
				if (args.fileLog != null) {
					args.commit = args.fileLog.commits.get(args.sha);
					// If we can't find the commit, kill the fileLog
					if (args.commit == null) {
						args.fileLog = undefined;
					}
				}

				if (args.fileLog == null) {
					const repoPath = args.commit?.repoPath ?? gitUri.repoPath;
					args.commit = await this.container.git.getCommitForFile(repoPath, gitUri, {
						ref: args.sha,
					});
					if (args.commit == null) {
						void Messages.showCommitNotFoundWarningMessage('Unable to show commit file details');

						return;
					}
				}
			}

			if (args.commit == null) {
				void Messages.showCommitNotFoundWarningMessage('Unable to show commit file details');

				return;
			}

			const path = args.commit?.file?.path ?? gitUri.fsPath;
			if (GitCommit.is(args.commit)) {
				if (args.commit.files == null) {
					await args.commit.ensureFullDetails();
				}
			}

			// const shortSha = GitRevision.shorten(args.sha);

			// if (args.commit instanceof GitBlameCommit) {
			// 	args.commit = (await this.container.git.getCommit(args.commit.repoPath, args.commit.ref))!;
			// }

			void (await executeGitCommand({
				command: 'show',
				state: {
					repo: args.commit.repoPath,
					reference: args.commit,
					fileName: path,
				},
			}));

			// if (args.goBackCommand === undefined) {
			// 	const commandArgs: ShowQuickCommitCommandArgs = {
			// 		commit: args.commit,
			// 		sha: args.sha,
			// 	};

			// 	// Create a command to get back to the commit details
			// 	args.goBackCommand = new CommandQuickPickItem(
			// 		{
			// 			label: `go back ${GlyphChars.ArrowBack}`,
			// 			description: `to details of ${GlyphChars.Space}$(git-commit) ${shortSha}`,
			// 		},
			// 		Commands.ShowQuickCommit,
			// 		[args.commit.toGitUri(), commandArgs],
			// 	);
			// }

			// // Create a command to get back to where we are right now
			// const currentCommand = new CommandQuickPickItem(
			// 	{
			// 		label: `go back ${GlyphChars.ArrowBack}`,
			// 		description: `to details of ${args.commit.getFormattedPath()} from ${
			// 			GlyphChars.Space
			// 		}$(git-commit) ${shortSha}`,
			// 	},
			// 	Commands.ShowQuickCommitFile,
			// 	[args.commit.toGitUri(), args],
			// );

			// const pick = await CommitFileQuickPick.show(args.commit as GitCommit, uri, {
			// 	goBackCommand: args.goBackCommand,
			// 	currentCommand: currentCommand,
			// 	fileLog: args.fileLog,
			// });
			// if (pick === undefined) return undefined;

			// if (pick instanceof CommandQuickPickItem) return pick.execute();

			// return undefined;
		} catch (ex) {
			Logger.error(ex, 'ShowQuickCommitFileDetailsCommand');
			void Messages.showGenericErrorMessage('Unable to show commit file details');
		}
	}
}


text:
<?php

namespace YCMS\Modules\Contracts;

interface RunableInterface
{
    /**
     * Run the specified command.
     *
     * @param string $command
     *
     * @return mixed
     */
    public function run($command);
}


text:
class CommentWithoutTranslation < ActiveRecord::Base
  self.table_name = "comments_without_translations"
  belongs_to :article
end


text:
require 'optparse'
require 'fileutils'

def populate_possible_matches(directories, pattern)
  #Find all the matching filename from each directory

  matches = []
  pattern = pattern.chomp(".ump") + "\\.ump"
  pattern = pattern.gsub("*", ".*")
  directories.each do |directory|
    possibles = Dir.entries(directory)

    possibles.each do |filename|
      if filename =~ /#{pattern}/
        matches << directory + "/" + filename
      end
    end
  end

  return matches
end

def check_for_flags(filenames, language)
  #read each file and check the target languages

  matches = []

  #For langauge choice, we are looking for @@@testlanguage=lang,lang,....
  #If this tag is missing, it will always add it to the directory
  filenames.each do |filename|
    should_add = true
    open(filename, 'r').each do |line|
      tag = line[/@@@testlanguage=.*/]
      next if tag.nil?
      if tag =~ /.*#{language}.*/
        break
      else
        should_add = false
        break
      end
    end
    matches << filename if should_add
  end

  return matches
end

def copy_to_output(filenames, output_dir)

  filenames.each do |filename|
    new_filename = "#{output_dir}/#{filename.split("/")[-1]}"
    FileUtils.cp(filename, new_filename)
  end
end

# command line input arguments
search_dir = []
language = ""
output_dir = ""
search_pattern = ""

OptionParser.new do |option|
  option.on('-i DIRNAME') { |dirname| search_dir << dirname }
  option.on('-l LANGNAME') { |langname| language = langname }
  option.on('-o DIRNAME') { |dirname| output_dir = dirname }
  option.on('-s PATTERN') { |pattern| search_pattern = pattern }
  option.on('-h') { puts option; exit }
  option.parse!
end

matches = populate_possible_matches(search_dir, search_pattern)
matches = check_for_flags(matches, language)
copy_to_output(matches, output_dir)


text:
package openperipheral.addons.glasses.drawable;

import openmods.structured.StructureField;
import openperipheral.addons.glasses.utils.IPointListBuilder;
import openperipheral.addons.glasses.utils.IPolygonBuilder;
import openperipheral.addons.glasses.utils.Point2d;
import openperipheral.addons.glasses.utils.PointListBuilder;
import openperipheral.addons.glasses.utils.RenderState;
import openperipheral.addons.glasses.utils.SolidPolygonBuilder;
import openperipheral.api.adapter.AdapterSourceName;
import openperipheral.api.adapter.Property;
import openperipheral.api.adapter.method.ScriptObject;

@ScriptObject
@AdapterSourceName("glasses_polygon")
public class SolidPolygon extends Polygon<Point2d> {

	@Property
	@StructureField
	public int color = 0xFFFFFF;

	@Property
	@StructureField
	public float opacity = 1.0f;

	public SolidPolygon() {}

	public SolidPolygon(int color, float opacity, Point2d... points) {
		super(points);

		this.color = color;
		this.opacity = opacity;
	}

	@Override
	protected IPointListBuilder<Point2d> createBuilder() {
		return new PointListBuilder();
	}

	@Override
	protected IPolygonBuilder<Point2d> createPolygonBuilder() {
		return new SolidPolygonBuilder();
	}

	@Override
	protected DrawableType getTypeEnum() {
		return DrawableType.POLYGON;
	}

	@Override
	protected void drawContents(RenderState renderState, float partialTicks) {
		if (canRender()) {
			super.drawContents(renderState, partialTicks);
			renderState.setColor(color, opacity);
			renderPolygon(renderState);
		}
	}

}


text:
// Generated by http://code.google.com/p/protostuff/ ... DO NOT EDIT!
// Generated from protobuf

package org.apache.drill.exec.proto.beans;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import com.dyuproject.protostuff.GraphIOUtil;
import com.dyuproject.protostuff.Input;
import com.dyuproject.protostuff.Message;
import com.dyuproject.protostuff.Output;
import com.dyuproject.protostuff.Schema;

public final class Roles implements Externalizable, Message<Roles>, Schema<Roles>
{

    public static Schema<Roles> getSchema()
    {
        return DEFAULT_INSTANCE;
    }

    public static Roles getDefaultInstance()
    {
        return DEFAULT_INSTANCE;
    }

    static final Roles DEFAULT_INSTANCE = new Roles();

    static final Boolean DEFAULT_SQL_QUERY = new Boolean(true);
    static final Boolean DEFAULT_LOGICAL_PLAN = new Boolean(true);
    static final Boolean DEFAULT_PHYSICAL_PLAN = new Boolean(true);
    static final Boolean DEFAULT_JAVA_EXECUTOR = new Boolean(true);
    static final Boolean DEFAULT_DISTRIBUTED_CACHE = new Boolean(true);

    private Boolean sqlQuery = DEFAULT_SQL_QUERY;
    private Boolean logicalPlan = DEFAULT_LOGICAL_PLAN;
    private Boolean physicalPlan = DEFAULT_PHYSICAL_PLAN;
    private Boolean javaExecutor = DEFAULT_JAVA_EXECUTOR;
    private Boolean distributedCache = DEFAULT_DISTRIBUTED_CACHE;

    public Roles()
    {

    }

    // getters and setters

    // sqlQuery

    public Boolean getSqlQuery()
    {
        return sqlQuery;
    }

    public Roles setSqlQuery(Boolean sqlQuery)
    {
        this.sqlQuery = sqlQuery;
        return this;
    }

    // logicalPlan

    public Boolean getLogicalPlan()
    {
        return logicalPlan;
    }

    public Roles setLogicalPlan(Boolean logicalPlan)
    {
        this.logicalPlan = logicalPlan;
        return this;
    }

    // physicalPlan

    public Boolean getPhysicalPlan()
    {
        return physicalPlan;
    }

    public Roles setPhysicalPlan(Boolean physicalPlan)
    {
        this.physicalPlan = physicalPlan;
        return this;
    }

    // javaExecutor

    public Boolean getJavaExecutor()
    {
        return javaExecutor;
    }

    public Roles setJavaExecutor(Boolean javaExecutor)
    {
        this.javaExecutor = javaExecutor;
        return this;
    }

    // distributedCache

    public Boolean getDistributedCache()
    {
        return distributedCache;
    }

    public Roles setDistributedCache(Boolean distributedCache)
    {
        this.distributedCache = distributedCache;
        return this;
    }

    // java serialization

    public void readExternal(ObjectInput in) throws IOException
    {
        GraphIOUtil.mergeDelimitedFrom(in, this, this);
    }

    public void writeExternal(ObjectOutput out) throws IOException
    {
        GraphIOUtil.writeDelimitedTo(out, this, this);
    }

    // message method

    public Schema<Roles> cachedSchema()
    {
        return DEFAULT_INSTANCE;
    }

    // schema methods

    public Roles newMessage()
    {
        return new Roles();
    }

    public Class<Roles> typeClass()
    {
        return Roles.class;
    }

    public String messageName()
    {
        return Roles.class.getSimpleName();
    }

    public String messageFullName()
    {
        return Roles.class.getName();
    }

    public boolean isInitialized(Roles message)
    {
        return true;
    }

    public void mergeFrom(Input input, Roles message) throws IOException
    {
        for(int number = input.readFieldNumber(this);; number = input.readFieldNumber(this))
        {
            switch(number)
            {
                case 0:
                    return;
                case 1:
                    message.sqlQuery = input.readBool();
                    break;
                case 2:
                    message.logicalPlan = input.readBool();
                    break;
                case 3:
                    message.physicalPlan = input.readBool();
                    break;
                case 4:
                    message.javaExecutor = input.readBool();
                    break;
                case 5:
                    message.distributedCache = input.readBool();
                    break;
                default:
                    input.handleUnknownField(number, this);
            }
        }
    }

    public void writeTo(Output output, Roles message) throws IOException
    {
        if(message.sqlQuery != null && message.sqlQuery != DEFAULT_SQL_QUERY)
            output.writeBool(1, message.sqlQuery, false);

        if(message.logicalPlan != null && message.logicalPlan != DEFAULT_LOGICAL_PLAN)
            output.writeBool(2, message.logicalPlan, false);

        if(message.physicalPlan != null && message.physicalPlan != DEFAULT_PHYSICAL_PLAN)
            output.writeBool(3, message.physicalPlan, false);

        if(message.javaExecutor != null && message.javaExecutor != DEFAULT_JAVA_EXECUTOR)
            output.writeBool(4, message.javaExecutor, false);

        if(message.distributedCache != null && message.distributedCache != DEFAULT_DISTRIBUTED_CACHE)
            output.writeBool(5, message.distributedCache, false);
    }

    public String getFieldName(int number)
    {
        switch(number)
        {
            case 1: return "sqlQuery";
            case 2: return "logicalPlan";
            case 3: return "physicalPlan";
            case 4: return "javaExecutor";
            case 5: return "distributedCache";
            default: return null;
        }
    }

    public int getFieldNumber(String name)
    {
        final Integer number = __fieldMap.get(name);
        return number == null ? 0 : number.intValue();
    }

    private static final java.util.HashMap<String,Integer> __fieldMap = new java.util.HashMap<String,Integer>();
    static
    {
        __fieldMap.put("sqlQuery", 1);
        __fieldMap.put("logicalPlan", 2);
        __fieldMap.put("physicalPlan", 3);
        __fieldMap.put("javaExecutor", 4);
        __fieldMap.put("distributedCache", 5);
    }

}


text:
#ifndef __GameScene_h__
#define __GameScene_h__

#include "PhysicalWorld.h"

class GameScene	: public Scene
{
	public :

		// create GameScene depend on stage
		static GameScene*		create ( KDint nStage = 1 );

	public :

		virtual KDbool			init ( KDint nStage );

		KDvoid					menuPopSceneCallback ( Object* pSender );
};

class StageBasic : public Layer
{
	public :

		virtual KDbool		init ( KDvoid );

		virtual KDvoid			update ( KDfloat fDelta );

		virtual KDbool			initWorld ( KDvoid );

		KDvoid					overStage ( KDbool bPlayerDied );

		virtual KDvoid			changeToNextStage ( KDvoid ) = 0;
		KDvoid					changeToOverScene ( KDvoid );

		KDvoid					menuTestCallback ( Object* pSender );

	protected :

		Layer*					m_pStageLayer;
		Player*					m_pPlayer;
		EnemyListBuilder*		m_pEnemyBuilder;

		PhysicalWorld*			m_pPhysicalWorld;
};

class StageOne : public StageBasic
{
	public :

		static StageOne*		create ( KDvoid );

		virtual KDbool			init ( KDvoid );

		virtual KDvoid			changeToNextStage ( KDvoid );

		KDvoid					menuNextStageCallback ( Object* pSender );
};

class StageTwo : public StageBasic
{
	public :

		static StageTwo*		create ( KDvoid );

		virtual KDbool			init ( KDvoid );

		virtual KDvoid			changeToNextStage ( KDvoid );
};

class GameOverScene : public Scene
{
	public :

		static GameOverScene*	create ( KDvoid );

		virtual KDbool			init ( KDvoid );

		KDvoid					menuPopSceneCallback ( Object* pSender );

		KDvoid					menuCloseCallback ( Object* pSender );
};

class VictoryScene : public Scene
{
	public :

		// create a victory scene,define pItem depend on stage
		static VictoryScene*	create ( KDvoid );

		virtual KDbool			init ( KDvoid );

		KDvoid					menuPopSceneCallback ( Object* pSender );

		KDvoid					menuCloseCallback ( Object* pSender );
};

#endif	// __GameScene_h__


text:
<?php
/**
 * Created by PhpStorm.
 * User: zoowii
 * Date: 14-2-19
 * Time: 下午11:19
 */

namespace RP\util;

use RP\models\AccountBinding;
use RP\models\User;

class OAuthUtil
{
    public static function getRelatedUser($type, $openid)
    {
        $accountBinding = AccountBinding::findOneByAttributes(array(
            'source' => $type,
            'binding_id' => $openid
        ));
        if (is_null($accountBinding)) {
            return null;
        }
        $user = $accountBinding->getRelatedUser();
        return $user;
    }

    public static function getDisplayName($type, $userinfo)
    {
        switch ($type) {
            case 'qq':
            {
                return $userinfo['nickname'];
            }
                break;
            default:
                {
                // TODO:
                throw new \Exception("Unsupported oauth2 type");
                }
                break;
        }
    }

}


text:
<?php
namespace Workflow\Controller\Admin;

use Workflow\Controller\AppController;

/**
 * TransitionActions Controller
 *
 * @property \Workflow\Model\Table\TransitionActionsTable $TransitionActions
 */
class TransitionActionsController extends AppController
{

    /**
     * Index method
     *
     * @return void
     */
    public function index()
    {
        $this->set('transitionActions', $this->paginate($this->TransitionActions));
        $this->set('_serialize', ['transitionActions']);
    }

    /**
     * View method
     *
     * @param string|null $id Transition Action id.
     * @return void
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function view($id = null)
    {
        $transitionAction = $this->TransitionActions->get($id, [
            'contain' => []
        ]);
        $this->set('transitionAction', $transitionAction);
        $this->set('_serialize', ['transitionAction']);
    }

    /**
     * Add method
     *
     * @return void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $transitionAction = $this->TransitionActions->newEntity();
        if ($this->request->is('post')) {
            $transitionAction = $this->TransitionActions->patchEntity($transitionAction, $this->request->data);
            if ($this->TransitionActions->save($transitionAction)) {
                $this->Flash->success(__('The transition action has been saved.'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The transition action could not be saved. Please, try again.'));
            }
        }
        $this->set(compact('transitionAction'));
        $this->set('_serialize', ['transitionAction']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Transition Action id.
     * @return void Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $transitionAction = $this->TransitionActions->get($id, [
            'contain' => []
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $transitionAction = $this->TransitionActions->patchEntity($transitionAction, $this->request->data);
            if ($this->TransitionActions->save($transitionAction)) {
                $this->Flash->success(__('The transition action has been saved.'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The transition action could not be saved. Please, try again.'));
            }
        }
        $this->set(compact('transitionAction'));
        $this->set('_serialize', ['transitionAction']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Transition Action id.
     * @return void Redirects to index.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $transitionAction = $this->TransitionActions->get($id);
        if ($this->TransitionActions->delete($transitionAction)) {
            $this->Flash->success(__('The transition action has been deleted.'));
        } else {
            $this->Flash->error(__('The transition action could not be deleted. Please, try again.'));
        }
        return $this->redirect(['action' => 'index']);
    }
}


text:
package net.dirtyfilthy.bouncycastle.x509;

public class NoSuchParserException
    extends Exception
{
    public NoSuchParserException(String message)
    {
        super(message);
    }
}


text:
<?php

namespace Duck;

use IronMQ;

/**
 * IronMQ queue
 */
class Queue
{

    /**
     * @var IronMQ
     */
    private $queue;

    /**
     * @var string
     */
    private $queueName;

    /**
     * @var int
     */
    private $timeout;

    public function __construct($token, $projectId, $queueName)
    {
        $this->queue = new IronMQ(
            array(
                'token' => $token,
                'project_id' => $projectId
            )
        );
        $this->queueName = $queueName;
        $this->queue->updateQueue($this->queueName, array());
    }

    /**
     * @param int $timeout
     */
    public function setTimeout($timeout)
    {
        $this->timeout = $timeout;
    }

    /**
     * @return int
     */
    public function getTimeout()
    {
        return $this->timeout;
    }

    /**
     * Enqueues Duck
     *
     */
    public function enqueue(Duck $duck)
    {
        $msg = serialize($duck);
        $this->queue->postMessage($this->queueName, $msg, array('timeout' => $this->timeout));
    }

    /**
     * Dequeues message
     *
     * @return Message
     */
    public function dequeue()
    {
        $msg = $this->queue->getMessage($this->queueName, $this->timeout);

        if (!$msg) {
            return false;
        }

        $duck = unserialize($msg->body);
        return array(
            $duck,
            $msg->id
        );
    }

    /**
     * Purges the queue
     */
    public function purge()
    {
        $this->queue->clearQueue($this->queueName);
    }

    /**
     * Acknowledges message
     *
     * @param Message $message
     */
    public function ack($id)
    {
        $this->queue->deleteMessage($this->queueName, $id);
    }
}


text:
/**
 * Route Mappings
 * (sails.config.routes)
 *
 * Your routes map URLs to views and controllers.
 *
 * If Sails receives a URL that doesn't match any of the routes below,
 * it will check for matching files (images, scripts, stylesheets, etc.)
 * in your assets directory.  e.g. `http://localhost:1337/images/foo.jpg`
 * might match an image file: `/assets/images/foo.jpg`
 *
 * Finally, if those don't match either, the default 404 handler is triggered.
 * See `api/responses/notFound.js` to adjust your app's 404 logic.
 *
 * Note: Sails doesn't ACTUALLY serve stuff from `assets`-- the default Gruntfile in Sails copies
 * flat files from `assets` to `.tmp/public`.  This allows you to do things like compile LESS or
 * CoffeeScript for the front-end.
 *
 * For more information on configuring custom routes, check out:
 * http://sailsjs.org/#!/documentation/concepts/Routes/RouteTargetSyntax.html
 */

module.exports.routes = {

  /***************************************************************************
  *                                                                          *
  * Make the view located at `views/homepage.ejs` (or `views/homepage.jade`, *
  * etc. depending on your default view engine) your home page.              *
  *                                                                          *
  * (Alternatively, remove this and add an `index.html` file in your         *
  * `assets` directory)                                                      *
  *                                                                          *
  ***************************************************************************/

  '/': {
    view: 'homepage'
  },

  /***************************************************************************
  *                                                                          *
  * Custom routes here...                                                    *
  *                                                                          *
  * If a request to a URL doesn't match any of the custom routes above, it   *
  * is matched against Sails route blueprints. See `config/blueprints.js`    *
  * for configuration options and examples.                                  *
  *                                                                          *
  ***************************************************************************/

  /* Login */
  'POST /login': 'Contact.login',

  /* Contact */
  'GET /contact': 'Contact.getContacts',
  'GET /contact/:nickname': 'Contact.getContactByNickname',
  'GET /contact/:nickname/sms': 'Contact.getSMSByNickname',

  'PUT /contact': 'Contact.updateContact',

  'POST /contact': 'Contact.createContact',

  'DELETE /contact': 'Contact.deleteContact',

  /* Phone */
  'PUT /phone': 'Phone.updatePhone',
  'POST /phone': 'Phone.addPhone',

  /* SMS */
  'POST /sms': 'Sms.send',

  /* Groupe */
  'GET /group': 'Group.getGroups',
  'GET /group/:name': 'Group.getGroupByName',

  'PUT /group': 'Group.updateGroup',
  'PUT /group/contact': 'Group.assignContact',

  'POST /group': 'Group.createGroup',

  'DELETE /group': 'Group.deleteGroup',

  /* Campagne */
  'GET /campaign': 'Campaign.getCampaigns',
  'GET /campaign/:name': 'Campaign.getCampaignByName',

  'PUT /campaign': 'Campaign.updateCampaign',
  'PUT /campaign/group': 'Campaign.assignGroup',

  'POST /campaign': 'Campaign.createCampaign',

  'DELETE /campaign': 'Campaign.deleteCampaign'

};


text:
<?php

defined('_JEXEC') or die;

$app   = JFactory::getApplication();
$doc   = JFactory::getDocument();
$lang  = JFactory::getLanguage();
$input = $app->input;
$user  = JFactory::getUser();

// Load optional RTL Bootstrap CSS
JHtml::_('bootstrap.loadCss', false, $this->direction);

// Load system style CSS
$doc->addStyleSheet('templates/system/css/system.css');

// Loadtemplate CSS
$doc->addStyleSheet('templates/' . $this->template . '/css/template.css');

// Load additional CSS styles for colors
if (!$this->params->get('colourChoice'))
{
	$colour = 'standard';
}
else
{
	$colour = htmlspecialchars($this->params->get('colourChoice'));
}

$doc->addStyleSheet('templates/' . $this->template . '/css/colour_' . $colour . '.css');

// Load specific language related CSS
$file = 'language/' . $lang->getTag() . '/' . $lang->getTag() . '.css';

if (is_file($file))
{
	$doc->addStyleSheet($file);
}

// Load additional CSS styles for rtl sites
if ($this->direction == 'rtl')
{
	$doc->addStyleSheet('templates/' . $this->template . '/css/template_rtl.css');
	$doc->addStyleSheet('templates/' . $this->template . '/css/colour_' . $colour . '_rtl.css');
}

// Load specific language related CSS
$file = 'language/' . $lang->getTag() . '/' . $lang->getTag() . '.css';

if (JFile::exists($file))
{
	$doc->addStyleSheet($file);
}

// Load additional CSS styles for bold Text
if ($this->params->get('boldText'))
{
	$doc->addStyleSheet('templates/' . $this->template . '/css/boldtext.css');
}

// Load template javascript
$doc->addScript('templates/' . $this->template . '/js/template.js', 'text/javascript');

// Logo file
if ($this->params->get('logoFile'))
{
	$logo = JUri::root() . $this->params->get('logoFile');
}
else
{
	$logo = $this->baseurl . '/templates/' . $this->template . '/images/logo.png';
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language; ?>" dir="<?php echo  $this->direction; ?>">

<jdoc:include type="head" />

<?php echo $this->params->get('showSiteName') ? $app->get('sitename') . " " . JText::_('JADMINISTRATION') : JText::_('JADMINISTRATION'); ?>

<?php echo JText::_('TPL_HATHOR_SKIP_TO_MAIN_CONTENT'); ?>

<?php echo JText::_('TPL_HATHOR_MAIN_MENU'); ?>

			<jdoc:include type="modules" name="menu" />

		<jdoc:include type="modules" name="status"/>

		<jdoc:include type="modules" name="title" />

		<jdoc:include type="message" />

						<jdoc:include type="modules" name="icon" />

						<jdoc:include type="component" />

			<?php echo JText::_('JGLOBAL_WARNJAVASCRIPT'); ?>

		<jdoc:include type="modules" name="footer" style="none"  />

			<?php $joomla = 'Joomla!®';
			echo JText::sprintf('JGLOBAL_ISFREESOFTWARE', $joomla); ?>


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports Microsoft.CodeAnalysis.Editor.FindUsages
Imports Microsoft.CodeAnalysis.Editor.GoToBase

Namespace Microsoft.CodeAnalysis.Editor.UnitTests.GoToBase
    <[UseExportProvider]>
    Public Class GoToBaseTests
        Private Async Function TestAsync(workspaceDefinition As XElement, Optional shouldSucceed As Boolean = True) As Task
            Await GoToHelpers.TestAsync(
                workspaceDefinition,
                Async Function(document As Document, position As Integer, context As SimpleFindUsagesContext)
                    Dim gotoBaseService = document.GetLanguageService(Of IGoToBaseService)
                    Await gotoBaseService.FindBasesAsync(document, position, context)
                End Function,
                shouldSucceed)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestEmptyFile() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
$$
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace, shouldSucceed:=False)
        End Function

#Region "Classes And Interfaces"

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithSingleClass() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class $$C { }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithAbstractClass() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
abstract class [|C|]
{
}

class $$D : C
{
}
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithAbstractClassFromInterface() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
interface [|I|] { }
abstract class [|C|] : I { }
class $$D : C { }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithSealedClass() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class [|D|] { }
sealed class $$C : D
{
}
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithEnum() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
enum $$C
{
}
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithNonAbstractClass() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class [|C|]
{
}

class $$D : C
{
}
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithSingleClassImplementation() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class $$C : I { }
interface [|I|] { }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithTwoClassImplementations() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class $$C : I { }
class D : I { }
interface [|I|] { }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestClassHierarchyWithParentSiblings() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class E : D { }
class $$D : B { }
class [|B|] : A { }
class C : A { }
class [|A|] : I2 { }
interface [|I2|] : I { }
interface I1 : I { }
interface [|I|] : J1, J2 { }
interface [|J1|] { }
interface [|J2|] { }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

#End Region

#Region "Structs"

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithStruct() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
struct $$C
{
}
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithSingleStructImplementation() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
struct $$C : I { }
interface [|I|] { }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestStructWithInterfaceHierarchy() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
struct $$S : I2 { }
interface [|I2|] : I { }
interface I1 : I { }
interface [|I|] : J1, J2 { }
interface [|J1|] { }
interface [|J2|] { }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

#End Region

#Region "Methods"

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithOneMethodImplementation_01() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C : I { public void $$M() { } }
interface I { void [|M|](); }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithOneMethodImplementation_02() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C : I { public void $$M() { } }
interface I { void [|M|]() {} }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithOneMethodImplementation_03() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C : I { void I.$$M() { } }
interface I { void [|M|]() {} }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithOneMethodImplementation_04() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
interface C : I
{
    void I.$$M() { }
    void M();
}
interface I { void [|M|](); }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithOneMethodImplementation_05() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
interface C : I
{
    void I.$$M() { }
    void M();
}
interface I { void [|M|]() {} }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithOneMethodImplementation_06() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
interface C : I
{
    void I.M() { }
    void $$M();
}
interface I { void M(); }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithOneMethodImplementation_07() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
interface C : I
{
    void I.M() { }
    void $$M();
}
interface I { void M() {} }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithOneMethodImplementationInStruct() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
struct S : I { public void $$M() { } }
interface I { void [|M|](); }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithTwoMethodImplementations() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C : I { public void $$M() { } }
class D : I { public void M() { } }
interface I { void [|M|](); }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestOverrideWithOverloads_01() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C : D { public override void $$M() { } }
class D
{
    public virtual void [|M|]() { }
    public virtual void M(int a) { }
}
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestOverrideWithOverloads_02() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C : D { public override void $$M(int a) { } }
class D
{
    public virtual void M() { }
    public virtual void [|M|](int a) { }
}
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestImplementWithOverloads_01() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C : I
{
    public void $$M() { }
    public void M(int a) { }
}
interface I
{
    void [|M|]();
    void M(int a);
}
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestImplementWithOverloads_02() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C : I
{
    public void M() { }
    public void $$M(int a) { }
}
interface I
{
    void M();
    void [|M|](int a);
}
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithNonInheritedImplementation() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C { public void $$M() { } }
class D : C, I { }
interface I { void M(); }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithVirtualMethodImplementationWithInterfaceOnBaseClass() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C : I { public virtual void [|M|]() { } }
class D : C { public override void $$M() { } }
interface I { void [|M|](); }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithVirtualMethodHiddenWithInterfaceOnBaseClass() As Task
            ' We should not find a hidden method.
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C : I { public virtual void M() { } }
class D : C { public new void $$M() { } }
interface I { void [|M|](); }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithVirtualMethodImplementationWithInterfaceOnDerivedClass() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C { public virtual void [|M|]() { } }
class D : C, I { public override void $$M() { } }
interface I { void [|M|](); }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithVirtualMethodHiddenWithInterfaceOnDerivedClass() As Task
            ' We should not find a hidden method.
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C { public virtual void M() { } }
class D : C, I { public new void $$M() { } }
interface I { void [|M|](); }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithVirtualMethodImplementationAndInterfaceImplementedOnDerivedType() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C : I { public virtual void [|M|]() { } }
class D : C, I { public override void $$M() { } }
interface I { void [|M|](); }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithVirtualMethodHiddenAndInterfaceImplementedOnDerivedType() As Task
            ' We should not find a hidden method.
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C : I { public virtual void M() { } }
class D : C, I { public new void $$M() { } }
interface I { void [|M|](); }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithAbstractMethodImplementation() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C : I { public abstract void [|M|]() { } }
class D : C { public override void $$M() { } }}
interface I { void [|M|](); }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithSimpleMethod() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C
{
    public void $$M() { }
}
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithOverridableMethodOnBase() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C
{
    public virtual void [|M|]() { }
}

class D : C
{
    public override void $$M() { }
}
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithOverridableMethodOnImplementation() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C
{
    public virtual void $$M() { }
}

class D : C
{
    public override void M() { }
}
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithIntermediateAbstractOverrides() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
    abstract class A {
        public virtual void [|M|]() { }
    }
    abstract class B : A {
        public abstract override void M();
    }
    sealed class C1 : B {
        public override void M() { }
    }
    sealed class C2 : A {
        public override void $$M() => base.M();
    }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

#End Region

#Region "Properties and Events"
        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithOneEventImplementation() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
using System;

class C : I { public event EventHandler $$E; }
interface I { event EventHandler [|E|]; }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithOneEventImplementationInStruct() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
using System;

struct S : I { public event EventHandler $$E; }
interface I { event EventHandler [|E|]; }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithOneEventExplicitImplementation() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
using System;

class C : I { event EventHandler I.$$E; }
interface I { event EventHandler [|E|]; }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithOneEventExplicitImplementationInStruct() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
using System;

struct S : I { event EventHandler I.$$E; }
interface I { event EventHandler [|E|]; }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithOnePropertyImplementation() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
using System;

class C : I { public int $$P { get; set; } }
interface I { int [|P|] { get; set; } }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithOnePropertyExplicitImplementation() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
using System;

class C : I { int I.$$P { get; set; } }
interface I { int [|P|] { get; set; } }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithOnePropertyImplementationInStruct() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
using System;

struct S : I { public int $$P { get; set; } }
interface I { int [|P|] { get; set; } }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.GoToBase)>
        Public Async Function TestWithOnePropertyExplicitImplementationInStruct() As Task
            Dim workspace =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
using System;

struct S : I { int I.$$P { get; set; } }
interface I { int [|P|] { get; set; } }
        </Document>
    </Project>
</Workspace>

            Await TestAsync(workspace)
        End Function

#End Region

    End Class
End Namespace


text:
package websocket.drawboard;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.locks.ReentrantLock;

import javax.imageio.ImageIO;

import websocket.drawboard.wsmessages.BinaryWebsocketMessage;
import websocket.drawboard.wsmessages.StringWebsocketMessage;

/**
 * A Room represents a drawboard where a number of
 * users participate.

 *
 * Note: Instance methods should only be invoked by calling
 * {@link #invokeAndWait(Runnable)} to ensure access is correctly synchronized.
 */
public final class Room {

    /**
     * Specifies the type of a room message that is sent to a client.

     * Note: Currently we are sending simple string messages - for production
     * apps, a JSON lib should be used for object-level messages.

     *
     * The number (single char) will be prefixed to the string when sending
     * the message.
     */
    public static enum MessageType {
        /**
         * '0': Error: contains error message.
         */
        ERROR('0'),
        /**
         * '1': DrawMesssage: contains serialized DrawMessage(s) prefixed
         *      with the current Player's {@link Player#lastReceivedMessageId}
         *      and ",".

         *      Multiple draw messages are concatenated with "|" as separator.
         */
        DRAW_MESSAGE('1'),
        /**
         * '2': ImageMessage: Contains number of current players in this room.
         *      After this message a Binary Websocket message will follow,
         *      containing the current Room image as PNG.

         *      This is the first message that a Room sends to a new Player.
         */
        IMAGE_MESSAGE('2'),
        /**
         * '3': PlayerChanged: contains "+" or "-" which indicate a player
         *      was added or removed to this Room.
         */
        PLAYER_CHANGED('3');

        private final char flag;

        private MessageType(char flag) {
            this.flag = flag;
        }

    }

    /**
     * The lock used to synchronize access to this Room.
     */
    private final ReentrantLock roomLock = new ReentrantLock();

    /**
     * Indicates if this room has already been shutdown.
     */
    private volatile boolean closed = false;

    /**
     * If true, outgoing DrawMessages will be buffered until the
     * drawmessageBroadcastTimer ticks. Otherwise they will be sent
     * immediately.
     */
    private static final boolean BUFFER_DRAW_MESSAGES = true;

    /**
     * A timer which sends buffered drawmessages to the client at once
     * at a regular interval, to avoid sending a lot of very small
     * messages which would cause TCP overhead and high CPU usage.
     */
    private final Timer drawmessageBroadcastTimer = new Timer();

    private static final int TIMER_DELAY = 30;

    /**
     * The current active broadcast timer task. If null, then no Broadcast task is scheduled.
     * The Task will be scheduled if the first player enters the Room, and
     * cancelled if the last player exits the Room, to avoid unnecessary timer executions.
     */
    private TimerTask activeBroadcastTimerTask;

    /**
     * The current image of the room drawboard. DrawMessages that are
     * received from Players will be drawn onto this image.
     */
    private final BufferedImage roomImage =
            new BufferedImage(900, 600, BufferedImage.TYPE_INT_RGB);
    private final Graphics2D roomGraphics = roomImage.createGraphics();

    /**
     * The maximum number of players that can join this room.
     */
    private static final int MAX_PLAYER_COUNT = 100;

    /**
     * List of all currently joined players.
     */
    private final List<Player> players = new ArrayList<>();

    public Room() {
        roomGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        // Clear the image with white background.
        roomGraphics.setBackground(Color.WHITE);
        roomGraphics.clearRect(0, 0, roomImage.getWidth(),
                roomImage.getHeight());
    }

    private TimerTask createBroadcastTimerTask() {
        return new TimerTask() {
            @Override
            public void run() {
                invokeAndWait(new Runnable() {
                    @Override
                    public void run() {
                        broadcastTimerTick();
                    }
                });
            }
        };
    }

    /**
     * Creates a Player from the given Client and adds it to this room.
     *
     * @param client the client
     *
     * @return The newly created player
     */
    public Player createAndAddPlayer(Client client) {
        if (players.size() >= MAX_PLAYER_COUNT) {
            throw new IllegalStateException("Maximum player count ("
                    + MAX_PLAYER_COUNT + ") has been reached.");
        }

        Player p = new Player(this, client);

        // Broadcast to the other players that one player joined.
        broadcastRoomMessage(MessageType.PLAYER_CHANGED, "+");

        // Add the new player to the list.
        players.add(p);

        // If currently no Broacast Timer Task is scheduled, then we need to create one.
        if (activeBroadcastTimerTask == null) {
            activeBroadcastTimerTask = createBroadcastTimerTask();
            drawmessageBroadcastTimer.schedule(activeBroadcastTimerTask,
                    TIMER_DELAY, TIMER_DELAY);
        }

        // Send him the current number of players and the current room image.
        String content = String.valueOf(players.size());
        p.sendRoomMessage(MessageType.IMAGE_MESSAGE, content);

        // Store image as PNG
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        try {
            ImageIO.write(roomImage, "PNG", bout);
        } catch (IOException e) { /* Should never happen */ }

        // Send the image as binary message.
        BinaryWebsocketMessage msg = new BinaryWebsocketMessage(
                ByteBuffer.wrap(bout.toByteArray()));
        p.getClient().sendMessage(msg);

        return p;

    }

    /**
     * @see Player#removeFromRoom()
     * @param p
     */
    private void internalRemovePlayer(Player p) {
        boolean removed = players.remove(p);
        assert removed;

        // If the last player left the Room, we need to cancel the Broadcast Timer Task.
        if (players.size() == 0) {
            // Cancel the task.
            // Note that it can happen that the TimerTask is just about to execute (from
            // the Timer thread) but waits until all players are gone (or even until a new
            // player is added to the list), and then executes. This is OK. To prevent it,
            // a TimerTask subclass would need to have some boolan "cancel" instance variable and
            // query it in the invocation of Room#invokeAndWait.
            activeBroadcastTimerTask.cancel();
            activeBroadcastTimerTask = null;
        }

        // Broadcast that one player is removed.
        broadcastRoomMessage(MessageType.PLAYER_CHANGED, "-");
    }

    /**
     * @see Player#handleDrawMessage(DrawMessage, long)
     * @param p
     * @param msg
     * @param msgId
     */
    private void internalHandleDrawMessage(Player p, DrawMessage msg,
            long msgId) {
        p.setLastReceivedMessageId(msgId);

        // Draw the RoomMessage onto our Room Image.
        msg.draw(roomGraphics);

        // Broadcast the Draw Message.
        broadcastDrawMessage(msg);
    }

    /**
     * Broadcasts the given drawboard message to all connected players.

     * Note: For DrawMessages, please use
     * {@link #broadcastDrawMessage(DrawMessage)}
     * as this method will buffer them and prefix them with the correct
     * last received Message ID.
     * @param type
     * @param content
     */
    private void broadcastRoomMessage(MessageType type, String content) {
        for (Player p : players) {
            p.sendRoomMessage(type, content);
        }
    }

    /**
     * Broadcast the given DrawMessage. This will buffer the message
     * and the {@link #drawmessageBroadcastTimer} will broadcast them
     * at a regular interval, prefixing them with the player's current
     * {@link Player#lastReceivedMessageId}.
     * @param msg
     */
    private void broadcastDrawMessage(DrawMessage msg) {
        if (!BUFFER_DRAW_MESSAGES) {
            String msgStr = msg.toString();

            for (Player p : players) {
                String s = String.valueOf(p.getLastReceivedMessageId())
                        + "," + msgStr;
                p.sendRoomMessage(MessageType.DRAW_MESSAGE, s);
            }
        } else {
            for (Player p : players) {
                p.getBufferedDrawMessages().add(msg);
            }
        }
    }

    /**
     * Tick handler for the broadcastTimer.
     */
    private void broadcastTimerTick() {
        // For each Player, send all per Player buffered
        // DrawMessages, prefixing each DrawMessage with the player's
        // lastReceivedMessageId.
        // Multiple messages are concatenated with "|".

        for (Player p : players) {

            StringBuilder sb = new StringBuilder();
            List<DrawMessage> drawMessages = p.getBufferedDrawMessages();

            if (drawMessages.size() > 0) {
                for (int i = 0; i < drawMessages.size(); i++) {
                    DrawMessage msg = drawMessages.get(i);

                    String s = String.valueOf(p.getLastReceivedMessageId())
                            + "," + msg.toString();
                    if (i > 0)
                        sb.append("|");

                    sb.append(s);
                }
                drawMessages.clear();

                p.sendRoomMessage(MessageType.DRAW_MESSAGE, sb.toString());
            }
        }
    }

    /**
     * A list of cached {@link Runnable}s to prevent recursive invocation of Runnables
     * by one thread. This variable is only used by one thread at a time and then
     * set to null.
     */
    private List<Runnable> cachedRunnables = null;

    /**
     * Submits the given Runnable to the Room Executor and waits until it
     * has been executed. Currently, this simply means that the Runnable
     * will be run directly inside of a synchronized() block.

     * Note that if a runnable recursively calls invokeAndWait() with another
     * runnable on this Room, it will not be executed recursively, but instead
     * cached until the original runnable is finished, to keep the behavior of
     * using a Executor.
     *
     * @param task The task to be executed
     */
    public void invokeAndWait(Runnable task)  {

        // Check if the current thread already holds a lock on this room.
        // If yes, then we must not directly execute the Runnable but instead
        // cache it until the original invokeAndWait() has finished.
        if (roomLock.isHeldByCurrentThread()) {

            if (cachedRunnables == null) {
                cachedRunnables = new ArrayList<>();
            }
            cachedRunnables.add(task);

        } else {

            roomLock.lock();
            try {
                // Explicitely overwrite value to ensure data consistency in
                // current thread
                cachedRunnables = null;

                if (!closed) {
                    task.run();
                }

                // Run the cached runnables.
                if (cachedRunnables != null) {
                    for (int i = 0; i < cachedRunnables.size(); i++) {
                        if (!closed) {
                            cachedRunnables.get(i).run();
                        }
                    }
                    cachedRunnables = null;
                }

            } finally {
                roomLock.unlock();
            }

        }

    }

    /**
     * Shuts down the roomExecutor and the drawmessageBroadcastTimer.
     */
    public void shutdown() {
        invokeAndWait(new Runnable() {
            @Override
            public void run() {
                closed = true;
                drawmessageBroadcastTimer.cancel();
                roomGraphics.dispose();
            }
        });
    }

    /**
     * A Player participates in a Room. It is the interface between the
     * {@link Room} and the {@link Client}.

     *
     * Note: This means a player object is actually a join between Room and
     * Client.
     */
    public final class Player {

        /**
         * The room to which this player belongs.
         */
        private Room room;

        /**
         * The room buffers the last draw message ID that was received from
         * this player.
         */
        private long lastReceivedMessageId = 0;

        private final Client client;

        /**
         * Buffered DrawMessages that will be sent by a Timer.
         */
        private final List<DrawMessage> bufferedDrawMessages =
                new ArrayList<>();

        private List<DrawMessage> getBufferedDrawMessages() {
            return bufferedDrawMessages;
        }

        private Player(Room room, Client client) {
            this.room = room;
            this.client = client;
        }

        public Room getRoom() {
            return room;
        }

        public Client getClient() {
            return client;
        }

        /**
         * Removes this player from its room, e.g. when
         * the client disconnects.
         */
        public void removeFromRoom() {
            if (room != null) {
                room.internalRemovePlayer(this);
                room = null;
            }
        }

        private long getLastReceivedMessageId() {
            return lastReceivedMessageId;
        }
        private void setLastReceivedMessageId(long value) {
            lastReceivedMessageId = value;
        }

        /**
         * Handles the given DrawMessage by drawing it onto this Room's
         * image and by broadcasting it to the connected players.
         *
         * @param msg   The draw message received
         * @param msgId The ID for the draw message recieved
         */
        public void handleDrawMessage(DrawMessage msg, long msgId) {
            room.internalHandleDrawMessage(this, msg, msgId);
        }

        /**
         * Sends the given room message.
         * @param type
         * @param content
         */
        private void sendRoomMessage(MessageType type, String content) {
            if (content == null || type == null)
                throw new NullPointerException();

            String completeMsg = String.valueOf(type.flag) + content;

            client.sendMessage(new StringWebsocketMessage(completeMsg));
        }
    }
}