text:
define(['underscore', 'backbone'], function(_, Backbone){

    var ProjectModel = Backbone.Model.extend({});

    return ProjectModel;
});

redpajama_set_name: RedPajamaGithub


text:
@implementation FileUploadCompletedDetails
@end

@implementation FileUploadFailedDetails
@end

@interface TestFixtureBase ()

- (void)loadIds;
- (void)createUsers;
- (void)createUser:(NSString *)prefix suffix:(int)suffix;
- (NSString *)authenticateUser:(NSString *)userId password:(NSString *)password;

@end

NSMutableDictionary *m_users;

@implementation TestFixtureBase

- (id)initWithInvocation:(NSInvocation *)invocation
{
    self = [super initWithInvocation:invocation];

    _fileUploadCompletedReceived = [[NSMutableArray alloc] init];
    _fileUploadFailedReceived = [[NSMutableArray alloc] init];

    if (self)
    {
        __weak TestFixtureBase *weakSelf = self;
        successBlock = ^(NSString *serviceName, NSString *serviceOperation, NSString *jsonData,
                         BCCallbackObject cbObject)
        {
            if(_expectFail >= 1)
            {
                _XCTPrimitiveFail(weakSelf, @"%@", jsonData);
            }

            _apiCountExpected -= 1;
            if (_apiCountExpected <= 0)
            {
               _result = true;
            }
            _jsonResponse = jsonData;
        };

        failureBlock = ^(NSString *serviceName, NSString *serviceOperation, NSInteger statusCode,
                         NSInteger returnCode, NSString *statusMessage, BCCallbackObject cbObject)
        {
            if(_expectFail == 0)
            {
                _XCTPrimitiveFail(weakSelf, @"%@", statusMessage);
            }

            _apiCountExpected -= 1;
            if (_apiCountExpected <= 0)
            {
                _result = true;
            }
            _statusCode = statusCode;
            _reasonCode = returnCode;
            _statusMessage = statusMessage;
        };

        globalErrorBlock = ^(NSString *serviceName, NSString *serviceOperation, NSInteger statusCode,
                              NSInteger returnCode, NSString *statusMessage, BCCallbackObject cbObject)
        {
            if(_expectFail == 0)
            {
                _XCTPrimitiveFail(weakSelf, @"%@", statusMessage);
            }

            _apiCountExpected -= 1;
            if (_apiCountExpected <= 0)
            {
                _result = true;
            }
            _statusCode = statusCode;
            _reasonCode = returnCode;
            _statusMessage = statusMessage;
            _globalErrorCount += 1;
        };

        networkErrorBlock = ^()
        {
            if(_expectFail == 0)
            {
                _XCTPrimitiveFail(weakSelf, @"Network error block unexpected");
            }

            _apiCountExpected -= 1;
            if (_apiCountExpected <= 0)
            {
                _result = true;
            }
           // _statusCode = statusCode;
           // _reasonCode = returnCode;
           // _statusMessage = statusMessage;
            _networkErrorCount += 1;
        };

        eventBlock = ^(NSString *eventsJson) {
            _eventCallbackReceived = true;
            _eventCallbackJson = eventsJson;
        };

        fileUploadCompletedBlock = ^(NSString *fileUploadId, NSString *jsonResponse) {
            FileUploadCompletedDetails * details = [[FileUploadCompletedDetails alloc] init];
            [details setFileUploadId:fileUploadId];
            [details setJsonResponse:jsonResponse];
            [_fileUploadCompletedReceived addObject:details];
        };
        fileUploadFailedBlock = ^(NSString *fileUploadId, NSInteger status, NSInteger reasonCode, NSString *jsonResponse) {
            FileUploadFailedDetails * details = [[FileUploadFailedDetails alloc] init];
            [details setFileUploadId:fileUploadId];
            [details setStatus:status];
            [details setReasonCode:reasonCode];
            [details setJsonResponse:jsonResponse];
            [_fileUploadFailedReceived addObject:details];
        };

        rewardBlock = ^(NSString *eventsJson) {

            NSData *data = [eventsJson dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *jsonObj = [NSJSONSerialization JSONObjectWithData:data
                                                                    options:NSJSONReadingMutableContainers
                                                                      error:nil];
            int apiRewardsSize = 0;
            apiRewardsSize = (int) [(NSArray *)[jsonObj objectForKey:@"apiRewards"] count];
            _rewardCallbacksReceived += 1;
            _apiRewardsReceived += apiRewardsSize;
            _rewardCallbackJson = eventsJson;
        };

        rttConnectSuccessBlock = ^(BCCallbackObject cbObject)
        {
            if(_expectFail >= 1)
            {
                _XCTPrimitiveFail(weakSelf, @"");
            }

            _apiCountExpected -= 1;
            if (_apiCountExpected <= 0)
            {
               _result = true;
            }
        };

        rttConnectFailureBlock = ^(NSString *errorMessage, BCCallbackObject cbObject)
        {
            if(_expectFail == 0)
            {
                _XCTPrimitiveFail(weakSelf, @"%@", errorMessage);
            }

            _apiCountExpected -= 1;
            if (_apiCountExpected <= 0)
            {
                _result = true;
            }
            _statusMessage = errorMessage;
        };

        rttEventBlock = ^(NSString *jsonData, BCCallbackObject cbObject)
        {
            if(_expectFail >= 1)
            {
                _XCTPrimitiveFail(weakSelf, @"");
            }

            _apiCountExpected -= 1;
            if (_apiCountExpected <= 0)
            {
               _result = true;
            }
            _jsonResponse = jsonData;
        };
    }
    return self;
}

- (void)setUp
{
    m_bcWrapper = [[BrainCloudWrapper alloc] init];

    [super setUp];
    [self loadIds];
    m_client = [m_bcWrapper getBCClient];
    NSDictionary* secretMap = @{
        m_appId      : m_secret,
        m_childAppId : m_childSecret,
    };
    [m_client initializeWithApps:m_serverUrl
                    defaultAppId:m_appId
                       secretMap:secretMap
                      appVersion:m_version];
    [m_client enableLogging:TRUE];
    [self createUsers];

    if ([self authenticateOnSetup])
    {
        [[m_client authenticationService]
            authenticateUniversal:[TestFixtureBase getUser:@"UserA"].m_id
                         password:[TestFixtureBase getUser:@"UserA"].m_password
                      forceCreate:true
                  completionBlock:successBlock
             errorCompletionBlock:failureBlock
                         cbObject:nil];
        [self waitForResult];
    }
}

- (void)tearDown
{
    [m_client resetCommunication];
    [[m_client authenticationService] clearSavedProfile];
    [super tearDown];
}

- (void)loadIds
{
    // syntax if loading file from bundle of a running app
    // NSString *filePath = [[NSBundle mainBundle] pathForResource:@"ids" ofType:@"txt"];

    // syntax if loading file from XTC
    NSString *filePath =
        [[NSBundle bundleForClass:[self class]] pathForResource:@"ids" ofType:@"txt"];

    NSString *fileContents =
        [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];

    for (NSString *line in
         [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]])
    {
        if ([line hasPrefix:@"appId"])
        {
            NSRange range = [line rangeOfString:@"="];
            m_appId = [line substringFromIndex:range.location + 1];
        }
        else if ([line hasPrefix:@"serverUrl"])
        {
            NSRange range = [line rangeOfString:@"="];
            m_serverUrl = [line substringFromIndex:range.location + 1];
        }
        else if ([line hasPrefix:@"secret"])
        {
            NSRange range = [line rangeOfString:@"="];
            m_secret = [line substringFromIndex:range.location + 1];
        }
        else if ([line hasPrefix:@"version"])
        {
            NSRange range = [line rangeOfString:@"="];
            m_version = [line substringFromIndex:range.location + 1];
        }
        else if ([line hasPrefix:@"childAppId"])
        {
            NSRange range = [line rangeOfString:@"="];
            m_childAppId = [line substringFromIndex:range.location + 1];
        }
        else if ([line hasPrefix:@"childSecret"])
        {
            NSRange range = [line rangeOfString:@"="];
            m_childSecret = [line substringFromIndex:range.location + 1];
        }
        else if ([line hasPrefix:@"parentLevelName"])
        {
            NSRange range = [line rangeOfString:@"="];
            m_parentLevel = [line substringFromIndex:range.location + 1];
        }
        else if ([line hasPrefix:@"peerName"])
        {
            NSRange range = [line rangeOfString:@"="];
            m_peerName = [line substringFromIndex:range.location + 1];
        }
    }
}

- (void)waitForResult
{
    [self waitForResultExpectedCount:1 expectFail:false];
}

- (void)waitForFailedResult
{
    [self waitForResultExpectedCount:1 expectFail:true];
}

- (void)waitForResultExpectedCount:(int)numApiCalls
{
    [self waitForResultExpectedCount:numApiCalls expectFail:false];
}

- (void)waitForResultExpectedCount:(int)numApiCalls
                        expectFail:(bool)expectFail
{
    [self reset];
    _apiCountExpected = numApiCalls;
    _expectFail = expectFail ? 1 : 0;

    long maxWait = MAX_WAIT_SECS * 1000;

    while (!_result && maxWait > 0)
    {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];
        maxWait -= 10;
        [m_client runCallBacks];
    }

    if (!_result)
    {
        _XCTPrimitiveFail(self, @"Timed out");
    }
}

- (void)reset
{
    _result = false;
    _apiCountExpected = 0;
    _jsonResponse = @"";
    _statusCode = 0;
    _reasonCode = 0;
    _statusMessage = @"";
    _eventCallbackReceived = false;
    _eventCallbackJson = @"";
    _rewardCallbacksReceived = 0;
    _rewardCallbackJson = @"";
    _apiRewardsReceived = 0;
    _expectFail = 0;

    // [m_client resetCommunication];
    // [[m_client authenticationService] clearSavedProfile]; // [dsl] Ok this causes issues. Why is this even there. We dont reset briancluod here, but only the test results
}

- (void)createUsers
{
    if (m_users != nil) return;
    m_users = [[NSMutableDictionary alloc] init];
    [self createUser:@"UserA" suffix:arc4random()];
    [self createUser:@"UserB" suffix:arc4random()];
    [self createUser:@"UserC" suffix:arc4random()];

    [[m_client playerStateService] logout:successBlock
                     errorCompletionBlock:failureBlock
                                 cbObject:nil];
    [self waitForResult];
}

- (void)createUser:(NSString *)prefix suffix:(int)suffix
{
    TestUser *user = [[TestUser alloc] initWithIds:prefix suffix:suffix];
    user.m_profileId = [self authenticateUser:user.m_id password:user.m_password];

    [[m_client playerStateService] updateContactEmail:@"braincloudunittest@gmail.com"
                                          completionBlock:successBlock
                                     errorCompletionBlock:failureBlock
                                                 cbObject:nil];
    [self waitForResult];

    [m_users setObject:user forKey:prefix];
}

- (NSString *)authenticateUser:(NSString *)userId password:(NSString *)password
{
    [[m_client authenticationService] authenticateUniversal:userId
                                                   password:password
                                                forceCreate:true
                                            completionBlock:successBlock
                                       errorCompletionBlock:failureBlock
                                                   cbObject:nil];
    [self waitForResult];
    NSString *playerId = [m_client authenticationService].profileID;
    [[m_client authenticationService] clearSavedProfile];
    return playerId;
}

+ (NSDictionary *)getDataFromResponse:(NSString *)jsonResponse
{
    NSData *data = [jsonResponse dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *jsonObj = [NSJSONSerialization JSONObjectWithData:data
                                                            options:NSJSONReadingMutableContainers
                                                              error:nil];
    return (NSDictionary *)[jsonObj objectForKey:@"data"];
}

+ (TestUser *)getUser:(NSString *)userId
{
    return [m_users objectForKey:userId];
}

- (bool)authenticateOnSetup { return true; }

- (bool)goToChildProfile
{
    [[m_client identityService] switchToSingletonChildProfile:m_childAppId
                                         forceCreate:true
                                     completionBlock:successBlock
                                errorCompletionBlock:failureBlock
                                            cbObject:nil];
    [self waitForResult];
    return self.result;
}

- (bool)goToParentProfile
{
    [[m_client identityService] switchToParentProfile:m_parentLevel
                                              completionBlock:successBlock
                                         errorCompletionBlock:failureBlock
                                                     cbObject:nil];
    [self waitForResult];
    return self.result;
}

- (bool)attachPeer:(NSString*)user
{
    TestUser* tUser = [TestFixtureBase getUser:user];
    [[m_client identityService] attachPeerProfile:m_peerName
                                       externalId:tUser.m_id
                              authenticationToken:tUser.m_password
                               authenticationType:[AuthenticationTypeObjc Universal]
                                 externalAuthName:nil
                                      forceCreate:true
                                      completionBlock:successBlock
                                 errorCompletionBlock:failureBlock
                                             cbObject:nil];
    [self waitForResult];
    return self.result;
}

- (bool)detachPeer
{
    [[m_client identityService] detachPeer:m_peerName
                                      completionBlock:successBlock
                                 errorCompletionBlock:failureBlock
                                             cbObject:nil];
    [self waitForResult];
    return self.result;
}

+ (NSString *)getJsonString:(id)object
{
    NSError *writeError = nil;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:0 error:&writeError];

    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    return jsonString;
}

@end


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

import * as _ from 'lodash';
import {
  Component,
  ComponentFactoryResolver,
  ComponentRef,
  ElementRef,
  Injector,
  OnDestroy,
  OnInit,
  ViewChild,
  ViewContainerRef
} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {StringUtil} from '@common/util/string.util';
import {CommonUtil} from '@common/util/common.util';
import {Alert} from '@common/util/alert.util';
import {Metadata, SourceType} from '@domain/meta-data-management/metadata';
import {AbstractComponent} from '@common/component/abstract.component';
import {ConfirmRefModalComponent} from '@common/component/modal/confirm/confirm-ref.component';
import {Modal} from '@common/domain/modal';
import {CookieConstant} from '@common/constant/cookie.constant';
import {CreateWorkbenchContainerComponent} from '../../workbench/component/create-workbench/refactoring/create-workbench-container.component';
import {CreateWorkbookComponent} from '../../workbook/component/create-workbook/refactoring/create-workbook.component';
import {MetadataService} from '../../meta-data-management/metadata/service/metadata.service';
import {ExploreDataConstant} from '../constant/explore-data-constant';
import {SortOption} from '../explore-data/service/explore-data-util.service';
import {MetadataContainerComponent} from '../explore-data/popup/metadata-container.component';

@Component({
  selector: 'app-exploredata-favorite-data',
  templateUrl: './favorite-data.component.html',
  entryComponents: [CreateWorkbenchContainerComponent, CreateWorkbookComponent, ConfirmRefModalComponent, MetadataContainerComponent]
})
export class FavoriteDataComponent extends AbstractComponent implements OnInit, OnDestroy {

  @ViewChild('component_create_workbench', {read: ViewContainerRef}) readonly createWorkbenchEntry: ViewContainerRef;
  createWorkbenchEntryRef: ComponentRef<CreateWorkbenchContainerComponent>;

  @ViewChild('component_create_workbook', {read: ViewContainerRef}) readonly createWorkbookEntry: ViewContainerRef;
  createWorkbookEntryRef: ComponentRef<CreateWorkbookComponent>;

  @ViewChild('component_confirm', {read: ViewContainerRef}) readonly confirmModalEntry: ViewContainerRef;
  confirmModalEntryRef: ComponentRef<ConfirmRefModalComponent>;

  @ViewChild('component_metadata_detail', {read: ViewContainerRef}) readonly metadataContainerEntry: ViewContainerRef;
  metadataContainerEntryRef: ComponentRef<MetadataContainerComponent>;

  /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  | Private Variables
  |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

  /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  | Protected Variables
  |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

  /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  | Public Variables
  |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

  // metadata list
  metadataList: Metadata[] = [];

  // search
  searchRange = {name: 'NAME_CONTAINS', value: ExploreDataConstant.SearchRange.DATA_NAME};
  searchedKeyword: string = '';

  // sort
  selectedSort = 'createdTime, desc';

  public sortOptions = {
    // TODO: popularity is not implemented yet
    // popularity: new SortOption('popularity'),
    modifiedTime: new SortOption('modifiedTime'),
    name: new SortOption('name', 'asc'),
  };

  // filter
  selectedSourceTypeFilter = 'ALL';
  sourceTypeList = [
    {label: 'All', value: ''},
    {label: this.translateService.instant('msg.comm.th.ds'), value: SourceType.ENGINE},
    {label: this.translateService.instant('msg.storage.li.db'), value: SourceType.JDBC},
    {label: this.translateService.instant('msg.storage.li.hive'), value: SourceType.STAGING},
  ];

  // more button
  showMoreFlag = false;

  /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  | Constructor
  |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

  // 생성자
  constructor(
    protected element: ElementRef,
    private activatedRoute: ActivatedRoute,
    private resolver: ComponentFactoryResolver,
    private metadataService: MetadataService,
    protected injector: Injector) {
    super(element, injector);
  }

  /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  | Override Method
  |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

  // Init
  public ngOnInit() {
    super.ngOnInit();

    this.subscriptions.push(this.activatedRoute.queryParams.subscribe(params => {
      const paramKeys = Object.keys(params);
      const isExistSearchParams = paramKeys.length > 0;
      const searchParams = {};
      // if exist search param in URL
      if (isExistSearchParams) {
        paramKeys.forEach((key) => {
          if (key === 'size') {
            this.page.size = params['size'];
          } else if (key === 'page') {
            this.page.page = params['page'];
          } else if (key === 'sort') {
            this.selectedSort = params['sort'];
          } else if (key === 'containsText') {
            this.searchedKeyword = params['containsText'];
          } else {
            searchParams[key] = params[key].split(',');
          }
        });
        // TODO 추후 criterion component로 이동
        delete searchParams['pseudoParam'];
        // init criterion search param
      }

      this.getMetadataList(this.getMetadataListParams()).then();

      // set datasource list
    }));
  }

  // Destroy
  public ngOnDestroy() {
    super.ngOnDestroy();
  }

  /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  | Public Method
  |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

  /**
   * Reload page for new query params.
   * @param {boolean} isFirstPage
   */
  public reloadPage(isFirstPage: boolean = true) {
    (isFirstPage) && (this.page.page = 0);
    this.router.navigate(
      [this.router.url.replace(/\?.*/gi, '')],
      {queryParams: this.getMetadataListParams(), replaceUrl: true}
    ).then();
  } // function - reloadPage

  getMetadataListParams() {
    let params;
    params = {
      page: this.page.page,
      size: this.page.size,
      sort: this.selectedSort,
    };

    // if not empty search keyword
    if (StringUtil.isNotEmpty(this.searchedKeyword)) {
      params[this.searchRange.value] = this.searchedKeyword.trim();
    }

    // source type
    if (this.selectedSourceTypeFilter !== undefined) {
      params['sourceType'] = this.selectedSourceTypeFilter;
    }

    if (this.selectedSourceTypeFilter === 'ALL') {
      delete params['sourceType'];
    }
    return params;
  }

  async getMetadataList(params) {
    this.loadingShow();
    const result = await this.metadataService.getMetadataListByMyFavorite(params).catch((e) => this.commonExceptionHandler(e));

    if (!_.isNil(result)) {
      // add ddp-scroll class to layout
      this.pageResult = result.page;
      // set metadata list
      if (result._embedded) {
        this.metadataList = result._embedded.metadatas;
      } else {
        this.metadataList = [];
      }

      this.loadingHide();
    }
  }

  /**
   * Search connection keypress event
   * @param {string} keyword
   */
  public onChangedSearchKeyword(keyword: string): void {
    // set search keyword
    this.searchedKeyword = keyword;
    // reload page
    this.reloadPage(true);
  }

  /**
   * More connection click event
   */
  changePage(data: { page: number, size: number }): void {
    // if more metadata list
    if (data) {
      this.page.page = data.page;
      this.page.size = data.size;

      this.reloadPage(false);
    }
  }

  /**
   * Sort column clicked
   * @param type
   */
  public toggleSortOption(type: string) {
    // Initialize every column's option except selected column
    Object.keys(this.sortOptions).forEach(key => {
      if (key !== type) {
        this.sortOptions[key].option = 'default';
      }
    });
    if (this.sortOptions[type].option === 'none') {
      this.sortOptions[type].option = 'desc';
    } else if (this.sortOptions[type].option === 'asc') {
      this.sortOptions[type].option = 'desc';
    } else {
      this.sortOptions[type].option = 'asc';
    }

    this.selectedSort = type + ',' + this.sortOptions[type].option;
    this.reloadPage();
  }

  public toggleMoreButton() {
    this.showMoreFlag = !this.showMoreFlag;
  }

  public onSelectSourceType(event) {
    this.selectedSourceTypeFilter = event.value;
    this.reloadPage();
  }

  public onClickEditData(metadataId: string) {
    event.stopImmediatePropagation();
    event.stopPropagation();
    this.router.navigate(['management/metadata/metadata', metadataId]).then();
  }

  async onClickCreateWorkbench(metadata: Metadata) {
    event.stopImmediatePropagation();
    event.stopPropagation();
    if (Metadata.isSourceTypeIsJdbc(metadata.sourceType)) {
      const metadataDetail = await this.metadataService.getDetailMetaData(metadata.id).catch(e => this.commonExceptionHandler(e));
      this._showConfirmComponent().then(() => this._showCreateWorkbenchComponent(metadataDetail));
    }
  }

  async onClickCreateWorkbook(metadata: Metadata) {
    event.stopImmediatePropagation();
    event.stopPropagation();
    if (Metadata.isSourceTypeIsEngine(metadata.sourceType)) {
      const metadataDetail = await this.metadataService.getDetailMetaData(metadata.id).catch(e => this.commonExceptionHandler(e));
      this._showConfirmComponent().then(() => this._showCreateWorkbookComponent(metadataDetail));
    }
  }

  onClickFavoriteIconInList(selectedMetadata: Metadata) {
    event.stopImmediatePropagation();
    event.stopPropagation();

    this.metadataService.toggleMetadataFavorite(selectedMetadata.id, selectedMetadata.favorite).catch((e) => this.commonExceptionHandler(e));

    const index = this.metadataList.findIndex((metadata) => {
      return metadata.id === selectedMetadata.id;
    });

    this.metadataList.splice(index, 1);
    this.pageResult.totalElements -= 1;
  }

  // Show Metadata detail modal
  onClickMetadata(metadata: Metadata) {
    event.stopPropagation();
    event.stopImmediatePropagation();
    // declare variables needed for metadata-container(modal) component
    let metadataDetail;
    let recentlyQueriesForDatabase;
    let topUserList;
    let recentlyUpdatedList;
    let recentlyUsedList;

    // get datas...
    const getRecentlyQueriesForDatabase = async (sourcetype: SourceType) => {
      if (sourcetype === SourceType.STAGEDB) {
        recentlyQueriesForDatabase = await this.metadataService.getRecentlyQueriesInMetadataDetailForDatabase(metadataDetail.source.id, this.page.page, this.page.size, this.page.sort)
          .catch(error => this.commonExceptionHandler(error));
      } else {
        if (metadataDetail.source.source !== undefined) {
          recentlyQueriesForDatabase = await this.metadataService.getRecentlyQueriesInMetadataDetailForDatabase(metadataDetail.source.source.id, this.page.page, this.page.size, this.page.sort)
            .catch(error => this.commonExceptionHandler(error));
        } else {
          recentlyQueriesForDatabase = await this.metadataService.getRecentlyQueriesInMetadataDetailForDatabase(metadataDetail.source.id, this.page.page, this.page.size, this.page.sort)
            .catch(error => this.commonExceptionHandler(error));
        }
      }
    };

    const getTopUser = async () => {
      topUserList = await this.metadataService.getTopUserInMetadataDetail(metadata.id).catch(error => this.commonExceptionHandler(error));
      topUserList = topUserList === undefined ? [] : topUserList;
    };

    const getRecentlyUpdatedList = async () => {
      recentlyUpdatedList = await this.metadataService.getRecentlyUpdatedInMetadataDetail(metadata.id).catch(error => this.commonExceptionHandler(error));
    };

    const getRecentlyUsedList = async () => {
      recentlyUsedList = await this.metadataService.getRecentlyUsedInMetadataDetail(metadata.id, {
        sort: 'modifiedTime',
        size: 5,
        page: 0
      }).catch(error => this.commonExceptionHandler(error));
    };

    this.metadataService.getDetailMetaData(metadata.id).then(async (result) => {
      this.loadingShow();
      metadataDetail = result;

      await getTopUser();
      await getRecentlyUpdatedList();

      if (metadata.sourceType === SourceType.ENGINE) {
        await getRecentlyUsedList();

        this.metadataContainerEntryRef = this.metadataContainerEntry.createComponent(this.resolver.resolveComponentFactory(MetadataContainerComponent));
        this.metadataContainerEntryRef.instance.metadataDetailData = metadataDetail;
        this.metadataContainerEntryRef.instance.topUserList = topUserList;
        this.metadataContainerEntryRef.instance.recentlyUpdatedList = recentlyUpdatedList;
        if (recentlyUsedList !== undefined && recentlyUsedList['_embedded'] !== undefined) {
          this.metadataContainerEntryRef.instance.recentlyUsedDashboardList = recentlyUsedList['_embedded']['dashboards'];
        }

        this.metadataContainerEntryRef.instance.metadataId = metadata.id;
      } else if (metadata.sourceType === SourceType.JDBC || metadata.sourceType === SourceType.STAGEDB) {
        await getRecentlyQueriesForDatabase(metadata.sourceType);
        this.metadataContainerEntryRef = this.metadataContainerEntry.createComponent(this.resolver.resolveComponentFactory(MetadataContainerComponent));
        this.metadataContainerEntryRef.instance.metadataDetailData = metadataDetail;
        this.metadataContainerEntryRef.instance.topUserList = topUserList;
        this.metadataContainerEntryRef.instance.recentlyUpdatedList = recentlyUpdatedList;
        if (recentlyQueriesForDatabase['_embedded']) {
          this.metadataContainerEntryRef.instance.recentlyQueriesForDataBase = recentlyQueriesForDatabase['_embedded']['queryhistories'];
        }
        this.metadataContainerEntryRef.instance.metadataId = metadata.id;
      }
      this.loadingHide();
      // close modal event listener
      this.metadataContainerEntryRef.instance.closedPopup.subscribe(() => {
        this.metadataContainerEntryRef.destroy();
      });
      // toggle favorite in modal listener
      this.metadataContainerEntryRef.instance.onToggleFavorite.subscribe(() => {
        // modal is shown in list screen
        this.getMetadataList(this.getMetadataListParams()).catch(e => this.commonExceptionHandler(e));
        // modal is shown in main screen
      });

    }).catch(error => {
      console.log(error);
      this.commonExceptionHandler(error)
    });
  }

  isNotEmptySearchKeyword(): boolean {
    return StringUtil.isNotEmpty(this.searchedKeyword);
  }

  isEmptyMetadataList(): boolean {
    return _.isNil(this.metadataList) || this.metadataList.length === 0;
  }

  isEnableTag(metadata: Metadata): boolean {
    return !Metadata.isEmptyTags(metadata);
  }

  isExistMoreTags(metadata: Metadata): boolean {
    return metadata.tags.length > 1;
  }

  isEnableDescription(metadata: Metadata): boolean {
    return StringUtil.isNotEmpty(metadata.description);
  }

  /**
   * Returns True is current user is manager
   */
  public isShowEditData(metadata: Metadata): boolean {
    return Metadata.isSourceTypeIsStaging(metadata.sourceType);
  }

  isShowCreateWorkbench(metadata: Metadata): boolean {
    return Metadata.isSourceTypeIsJdbc(metadata.sourceType);
  }

  isShowCreateWorkbook(metadata: Metadata): boolean {
    return Metadata.isSourceTypeIsEngine(metadata.sourceType);
  }

  getTotalElementsGuide() {
    if (this.isNotEmptySearchKeyword()) {
      return this.translateService.instant('msg.explore.ui.list.content.total.searched', {
        totalElements: this.getTotalElements(),
        searchedKeyword: this.searchedKeyword.trim()
      });
    } else {
      return this.translateService.instant('msg.explore.ui.list.content.total', {totalElements: this.getTotalElements()});
    }
  }

  getTotalElements(): string {
    return CommonUtil.numberWithCommas(this.pageResult.totalElements);
  }

  getMetadataName(name: string) {
    if (this.isNotEmptySearchKeyword() && (this.searchRange.value === ExploreDataConstant.SearchRange.ALL || this.searchRange.value === ExploreDataConstant.SearchRange.DATA_NAME)) {
      return name.replace(this.searchedKeyword, `<span class="ddp-txt-search type-search">${this.searchedKeyword}</span>`);
    } else {
      return name;
    }
  }

  getMetadataDescription(description: string) {
    if (this.isNotEmptySearchKeyword() && (this.searchRange.value === ExploreDataConstant.SearchRange.ALL || this.searchRange.value === ExploreDataConstant.SearchRange.DESCRIPTION)) {
      return '-' + description.replace(this.searchedKeyword, `<span class="ddp-txt-search type-search">${this.searchedKeyword}</span>`);
    } else {
      return '-' + description;
    }
  }

  getMetadataCreator(creator: string) {
    if (this.isNotEmptySearchKeyword() && (this.searchRange.value === ExploreDataConstant.SearchRange.ALL || this.searchRange.value === ExploreDataConstant.SearchRange.CREATOR)) {
      return creator.replace(this.searchedKeyword, `<span class="ddp-txt-search type-search">${this.searchedKeyword}</span>`);
    } else {
      return creator;
    }
  }

  getTooltipValue(metadata): string {
    let result = metadata.name;
    if (metadata.description) {
      result += ` - ${metadata.description}`;
    }
    return result;
  }

  private _showConfirmComponent() {
    return new Promise((resolve, _reject) => {
      // show confirm modal
      this.confirmModalEntryRef = this.confirmModalEntry.createComponent(this.resolver.resolveComponentFactory(ConfirmRefModalComponent));
      const modal: Modal = new Modal();

      modal.name = this.translateService.instant('msg.storage.alert.metadata.column.code.table.detail.modal.name');
      modal.description = this.translateService.instant('msg.storage.alert.metadata.column.code.table.detail.modal.description');
      modal.btnName = this.translateService.instant('msg.storage.alert.metadata.column.code.table.detail.modal.btn');
      this.confirmModalEntryRef.instance.init(modal);
      this.confirmModalEntryRef.instance.cancelEvent.subscribe(() => {
        // destroy confirm component
        this.confirmModalEntryRef.destroy();
      });
      this.confirmModalEntryRef.instance.confirmEvent.subscribe((result) => {
        // destroy confirm component
        this.confirmModalEntryRef.destroy();
        resolve(result);
      });
    });
  }

  private async _showCreateWorkbookComponent(metadata: Metadata) {

    this.createWorkbookEntryRef = this.createWorkbookEntry.createComponent(this.resolver.resolveComponentFactory(CreateWorkbookComponent));

    const metadataDetail = await this.metadataService.getDetailMetaData(metadata.id).catch(e => this.commonExceptionHandler(e));
    console.log(metadataDetail);

    const workspace = JSON.parse(this.cookieService.get(CookieConstant.KEY.MY_WORKSPACE));
    // set data in component
    this.createWorkbookEntryRef.instance.setWorkspaceId(workspace.id);
    this.createWorkbookEntryRef.instance.setSourceId(metadataDetail.source.source.id);
    this.createWorkbookEntryRef.instance.accessFromExplore();
    this.createWorkbookEntryRef.instance.closedPopup.subscribe(() => {
      this.createWorkbookEntryRef.destroy();
    });
    this.createWorkbookEntryRef.instance.completedPopup.subscribe((workbookId: string) => {
      if (_.isNil(workbookId)) {
        // link to workspace
        this.router.navigateByUrl('/workspace').then();
      } else {
        // link to workspace
        this.router.navigateByUrl('/workbook/' + workbookId).then();
      }
    });
  }

  private async _showCreateWorkbenchComponent(metadataDetail: Metadata) {
    if (metadataDetail.source.source !== undefined) {
      this.createWorkbenchEntryRef = this.createWorkbenchEntry.createComponent(this.resolver.resolveComponentFactory(CreateWorkbenchContainerComponent));

      // const metadataDetail = await this.metadataService.getDetailMetaData(metadata.id).catch(e => this.commonExceptionHandler(e));

      const workspace = JSON.parse(this.cookieService.get(CookieConstant.KEY.MY_WORKSPACE));

      // set data in component
      this.createWorkbenchEntryRef.instance.setWorkspaceId(workspace.id);
      this.createWorkbenchEntryRef.instance.setConnectionInModel(metadataDetail.source.source);
      this.createWorkbenchEntryRef.instance.setSchemaName(metadataDetail.source.schema);
      this.createWorkbenchEntryRef.instance.setTableName(metadataDetail.source.table);
      this.createWorkbenchEntryRef.instance.accessFromExplore();
      this.createWorkbenchEntryRef.instance.closedPopup.subscribe(() => {
        this.createWorkbenchEntryRef.destroy();
      });
      this.createWorkbenchEntryRef.instance.completedPopup.subscribe((workbenchId: string) => {
        if (_.isNil(workbenchId)) {
          // link to workspace
          this.router.navigateByUrl('/workspace').then();
        } else {
          // link to workspace
          this.router.navigateByUrl('/workbench/' + workbenchId).then();
        }
      });
    } else {
      Alert.error(this.translateService.instant('msg.explore.alert.error.cannot.make.workbench'))
    }

  }

  /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  | Protected Method
  |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

  /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  | Private Method
  |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

}


text:
<?php
/**
 * @author @jenschude <jens.schulze@commercetools.de>
 */

namespace Commercetools\Core\Request\TaxCategories;

use Commercetools\Core\Model\Common\Context;
use Commercetools\Core\Model\TaxCategory\TaxCategoryDraft;
use Commercetools\Core\Request\AbstractCreateRequest;
use Commercetools\Core\Model\TaxCategory\TaxCategory;
use Commercetools\Core\Response\ApiResponseInterface;
use Commercetools\Core\Model\MapperInterface;

/**
 * @package Commercetools\Core\Request\TaxCategories
 * @link https://docs.commercetools.com/http-api-projects-taxCategories.html#create-taxcategory
 * @method TaxCategory mapResponse(ApiResponseInterface $response)
 * @method TaxCategory mapFromResponse(ApiResponseInterface $response, MapperInterface $mapper = null)
 */
class TaxCategoryCreateRequest extends AbstractCreateRequest
{
    protected $resultClass = TaxCategory::class;

    /**
     * @param TaxCategoryDraft $taxCategory
     * @param Context $context
     */
    public function __construct(TaxCategoryDraft $taxCategory, Context $context = null)
    {
        parent::__construct(TaxCategoriesEndpoint::endpoint(), $taxCategory, $context);
    }

    /**
     * @param TaxCategoryDraft $taxCategory
     * @param Context $context
     * @return static
     */
    public static function ofDraft(TaxCategoryDraft $taxCategory, Context $context = null)
    {
        return new static($taxCategory, $context);
    }
}


text:
<?php
/**
 * This file is part of the @package@.
 *
 * @author: Nikolay Ermin <keltanas@gmail.com>
 * @version: @version@
 */

namespace Keltanas\PageBundle\EventListener;

use Doctrine\ORM\EntityManager;
use Keltanas\PageBundle\Entity\Post;
use Keltanas\PageBundle\Entity\Tag;
use Keltanas\PageBundle\Event\PostEvent;
use Keltanas\PageBundle\Repository\TagRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class TagsHandlerSubscriber implements EventSubscriberInterface
{
    /** @var EntityManager */
    private $em;

    /**
     *
     * For instance:
     *
     * array('eventName' => 'methodName')
     * array('eventName' => array('methodName', $priority))
     * array('eventName' => array(array('methodName1', $priority), array('methodName2'))
     *
     * @return array
     */
    public static function getSubscribedEvents()
    {
        return [
            PostEvent::POST_CREATE => 'onPostCreate',
            PostEvent::POST_UPDATE => 'onPostUpdate',
            PostEvent::POST_REMOVE => 'onPostRemove',
        ];
    }

    public function onPostRemove(PostEvent $event)
    {
        $this->em = $event->getEntityManager();
        $this->removeTags($event->getEntity()->getTagsArray($event->getEntity()->getTags()));
    }

    public function onPostCreate(PostEvent $event)
    {
        $this->em = $event->getEntityManager();

        if (Post::STATUS_PUBLIC == $event->getEntity()->getStatus()) {
            $this->addTags($event->getEntity()->getTagsArray($event->getEntity()->getTags()));
        }
    }

    public function onPostUpdate(PostEvent $event)
    {
        $this->em = $event->getEntityManager();

        /** @var Post $entity */
        $entity = $event->getEntity();

        $uow = $this->em->getUnitOfWork();
        $uow->computeChangeSet($this->em->getClassMetadata(get_class($entity)), $entity);

        $changeSet = $uow->getEntityChangeSet($entity);
        if (!isset($changeSet['tags'])) {
            return;
        }
        if (isset($changeSet['status'])) {
            $oldStatus = $changeSet['status'][0];
            $newStatus = $changeSet['status'][1];
        } else {
            $oldStatus = $newStatus = $entity->getStatus();
        }

        $oldTags = $changeSet['tags'][0];
        $oldTagsArray = $entity->getTagsArray($oldTags);

        $newTags = $changeSet['tags'][1];
        $newTagsArray = $entity->getTagsArray($newTags);

        if ($newStatus && $oldStatus) {
            $this->addTags(array_values(array_diff($newTagsArray, $oldTagsArray)));
            $this->removeTags(array_values(array_diff($oldTagsArray, $newTagsArray)));
        } elseif ($newStatus && !$oldStatus) {
            $this->addTags(array_values($newTagsArray));
        } elseif (!$newStatus && $oldStatus) {
            $this->removeTags(array_values($oldTagsArray));
        }
    }

    /**
     * @param array $tags
     */
    private function addTags(array $tags)
    {
        if (!$tags) {
            return;
        }
        /** @var TagRepository $tagRepository */
        $tagRepository = $this->em->getRepository(Tag::class);
        foreach ($tags as $tagName) {
            $tag = $tagRepository->findOneBy(['name'=>$tagName]);
            if (!$tag) {
                $tag = new Tag();
                $tag->setName($tagName);
                $tag->setFreq(0);
            }
            $tag->setFreq($tag->getFreq() + 1);
            $this->em->persist($tag);
            $this->em->getUnitOfWork()->computeChangeSet($this->em->getClassMetadata(get_class($tag)), $tag);
        }
    }

    /**
     * @param array $tags
     */
    private function removeTags(array $tags)
    {
        if (!$tags) {
            return;
        }
        /** @var TagRepository $tagRepository */
        $tagRepository = $this->em->getRepository(Tag::class);
        $tagsList = $tagRepository->findBy(['name'=>$tags]);
        /** @var Tag $tag */
        foreach ($tagsList as $tag) {
            $tag->setFreq($tag->getFreq() - 1);
            $this->em->persist($tag);
            $this->em->getUnitOfWork()->computeChangeSet($this->em->getClassMetadata(get_class($tag)), $tag);
        }
    }
}


text:
<!--
  ~ Copyright (c) 2007 Mockito contributors
  ~ This program is made available under the terms of the MIT License.
  -->

<body>
Invocation and related classes.
</body>


text:
/*
Theme Name:         Pringle.com
Theme URI:          http://pringle.com
Description:        Pringle.com WordPress Theme
Version:            1.0.0
Author:             Cristian Ionel
Author URI:         https://webcodesigner.com/
Text Domain:        sage

License:            MIT License
License URI:        http://opensource.org/licenses/MIT
*/


text:
//Original Scripts by IIColour (IIColour_Spectrum)

using UnityEngine;
using System.Collections;

public class CustomEvent : MonoBehaviour
{
    public CustomEventTree[] interactEventTrees;
    public CustomEventTree[] bumpEventTrees;

    private DialogBoxHandler Dialog;

    private NPCHandler thisNPCHandler;
    private bool deactivateOnFinish = false;

    private int eventTreeIndex = 0;
    private int currentEventIndex = 0;

    void Awake()
    {
        if (transform.GetComponent<NPCHandler>() != null)
        {
            thisNPCHandler = transform.GetComponent<NPCHandler>();
        }
        Dialog = GameObject.Find("GUI").GetComponent<DialogBoxHandler>();
    }

    public void setThisNPCHandlerBusy(bool boolValue)
    {
        if (thisNPCHandler != null)
        {
            thisNPCHandler.busy = boolValue;
        }
    }

    private IEnumerator interact()
    {
        yield return StartCoroutine(runEventTrees(interactEventTrees));
    }

    private IEnumerator bump()
    {
        yield return StartCoroutine(runEventTrees(bumpEventTrees));
    }

    private IEnumerator runEventTrees(CustomEventTree[] treesArray)
    {
        if (treesArray.Length > 0)
        {
            eventTreeIndex = 0;
            if (PlayerMovement.player.setCheckBusyWith(this.gameObject))
            {
                setThisNPCHandlerBusy(true);

                for (currentEventIndex = 0;
                    currentEventIndex < treesArray[eventTreeIndex].events.Length;
                    currentEventIndex++)
                {
                    if (!treesArray[eventTreeIndex].events[currentEventIndex].runSimultaneously)
                    {
                        yield return StartCoroutine(runEvent(treesArray, currentEventIndex));
                    }
                    else
                    {
                        StartCoroutine(runEvent(treesArray, currentEventIndex));
                    }
                }

                setThisNPCHandlerBusy(false);
                PlayerMovement.player.unsetCheckBusyWith(this.gameObject);
            }
            if (deactivateOnFinish)
            {
                this.gameObject.SetActive(false);
            }
        }
    }

    private IEnumerator runEvent(CustomEventTree[] treesArray, int index)
    {
        CustomEventDetails currentEvent = treesArray[eventTreeIndex].events[index];
        CustomEventDetails nextEvent = null;
        if (index + 1 < treesArray[eventTreeIndex].events.Length)
        {
            //if not the last event
            nextEvent = treesArray[eventTreeIndex].events[index + 1];
        }

        NPCHandler targetNPC = null;

        CustomEventDetails.CustomEventType ty = currentEvent.eventType;

        Debug.Log("Run event. Type: " + ty.ToString());

        switch (ty)
        {
            case (CustomEventDetails.CustomEventType.Wait):
                yield return new WaitForSeconds(currentEvent.float0);
                break;

            case (CustomEventDetails.CustomEventType.Walk):
                if (currentEvent.object0.GetComponent<NPCHandler>() != null)
                {
                    targetNPC = currentEvent.object0.GetComponent<NPCHandler>();

                    int initialDirection = targetNPC.direction;
                    targetNPC.direction = (int) currentEvent.dir;
                    for (int i = 0; i < currentEvent.int0; i++)
                    {
                        targetNPC.direction = (int) currentEvent.dir;
                        Vector3 forwardsVector = targetNPC.getForwardsVector(true);
                        if (currentEvent.bool0)
                        {
                            //if direction locked in
                            targetNPC.direction = initialDirection;
                        }
                        while (forwardsVector == new Vector3(0, 0, 0))
                        {
                            targetNPC.direction = (int) currentEvent.dir;
                            forwardsVector = targetNPC.getForwardsVector(true);
                            if (currentEvent.bool0)
                            {
                                //if direction locked in
                                targetNPC.direction = initialDirection;
                            }
                            yield return new WaitForSeconds(0.1f);
                        }

                        targetNPC.setOverrideBusy(true);
                        yield return StartCoroutine(targetNPC.move(forwardsVector, currentEvent.float0));
                        targetNPC.setOverrideBusy(false);
                    }
                    targetNPC.setFrameStill();
                } //Move the player if set to player
                if (currentEvent.object0 == PlayerMovement.player.gameObject)
                {
                    int initialDirection = PlayerMovement.player.direction;

                    PlayerMovement.player.speed = (currentEvent.float0 > 0)
                        ? PlayerMovement.player.walkSpeed / currentEvent.float0
                        : PlayerMovement.player.walkSpeed;
                    for (int i = 0; i < currentEvent.int0; i++)
                    {
                        PlayerMovement.player.updateDirection((int) currentEvent.dir);
                        Vector3 forwardsVector = PlayerMovement.player.getForwardVector();
                        if (currentEvent.bool0)
                        {
                            //if direction locked in
                            PlayerMovement.player.updateDirection(initialDirection);
                        }

                        PlayerMovement.player.setOverrideAnimPause(true);
                        yield return
                            StartCoroutine(PlayerMovement.player.move(forwardsVector, false, currentEvent.bool0));
                        PlayerMovement.player.setOverrideAnimPause(false);
                    }
                    PlayerMovement.player.speed = PlayerMovement.player.walkSpeed;
                }
                break;

            case (CustomEventDetails.CustomEventType.TurnTo):
                int direction;
                float xDistance;
                float zDistance;
                if (currentEvent.object0.GetComponent<NPCHandler>() != null)
                {
                    targetNPC = currentEvent.object0.GetComponent<NPCHandler>();
                }
                if (targetNPC != null)
                {
                    if (currentEvent.object1 != null)
                    {
                        //calculate target objects's position relative to this objects's and set direction accordingly.
                        xDistance = targetNPC.hitBox.position.x - currentEvent.object1.transform.position.x;
                        zDistance = targetNPC.hitBox.position.z - currentEvent.object1.transform.position.z;
                        if (xDistance >= Mathf.Abs(zDistance))
                        {
                            //Mathf.Abs() converts zDistance to a positive always.
                            direction = 3;
                        } //this allows for better accuracy when checking orientation.
                        else if (xDistance <= Mathf.Abs(zDistance) * -1)
                        {
                            direction = 1;
                        }
                        else if (zDistance >= Mathf.Abs(xDistance))
                        {
                            direction = 2;
                        }
                        else
                        {
                            direction = 0;
                        }
                        targetNPC.setDirection(direction);
                    }
                    if (currentEvent.int0 != 0)
                    {
                        direction = targetNPC.direction + currentEvent.int0;
                        while (direction > 3)
                        {
                            direction -= 4;
                        }
                        while (direction < 0)
                        {
                            direction += 4;
                        }
                        targetNPC.setDirection(direction);
                    }
                }
                break;

            case (CustomEventDetails.CustomEventType.Dialog):
                for (int i = 0; i < currentEvent.strings.Length; i++)
                {
                    Dialog.drawDialogBox();
                    yield return StartCoroutine(Dialog.drawText(currentEvent.strings[i]));

                    if (i < currentEvent.strings.Length - 1)
                    {
                        while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back"))
                        {
                            yield return null;
                        }
                    }
                }
                if (nextEvent != null)
                {
                    if (nextEvent.eventType != CustomEventDetails.CustomEventType.Choice)
                    {
                        while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back"))
                        {
                            yield return null;
                        }
                        if (!EventRequiresDialogBox(nextEvent.eventType))
                        {
                            Dialog.undrawDialogBox();
                        } // do not undraw the box if the next event needs it
                    }
                }
                else
                {
                    while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back"))
                    {
                        yield return null;
                    }
                    Dialog.undrawDialogBox();
                }
                break;

            case (CustomEventDetails.CustomEventType.Choice):
                if (currentEvent.strings.Length > 1)
                {
                    Dialog.drawChoiceBox(currentEvent.strings);
                    yield return StartCoroutine(Dialog.choiceNavigate(currentEvent.strings));
                }
                else
                {
                    Dialog.drawChoiceBox();
                    yield return StartCoroutine(Dialog.choiceNavigate());
                }
                int chosenIndex = Dialog.chosenIndex;
                chosenIndex = currentEvent.ints.Length - 1 - chosenIndex; //flip it to reflect the original input
                Dialog.undrawChoiceBox();
                Dialog.undrawDialogBox();
                if (chosenIndex < currentEvent.ints.Length)
                {
                    //only change tree if index is valid
                    if (currentEvent.ints[chosenIndex] != eventTreeIndex &&
                        currentEvent.ints[chosenIndex] < treesArray.Length)
                    {
                        JumpToTree(currentEvent.ints[chosenIndex]);
                    }
                }
                break;

            case CustomEventDetails.CustomEventType.Sound:
                SfxHandler.Play(currentEvent.sound);
                break;

            case CustomEventDetails.CustomEventType.ReceiveItem:
                //Play Good for TM, Average for Item
                AudioClip itemGetMFX = (currentEvent.bool0)
                    ? Resources.Load<AudioClip>("Audio/mfx/GetGood")
                    : Resources.Load<AudioClip>("Audio/mfx/GetDecent");
                BgmHandler.main.PlayMFX(itemGetMFX);

                string firstLetter = currentEvent.string0.Substring(0, 1).ToLowerInvariant();
                Dialog.drawDialogBox();
                if (currentEvent.bool0)
                {
                    Dialog.StartCoroutine(Dialog.drawText(
                        SaveData.currentSave.playerName + " received TM" +
                        ItemDatabase.getItem(currentEvent.string0).getTMNo() + ": " + currentEvent.string0 + "!"));
                }
                else
                {
                    if (currentEvent.int0 > 1)
                    {
                        Dialog.StartCoroutine(Dialog.drawText(
                            SaveData.currentSave.playerName + " received " + currentEvent.string0 + "s!"));
                    }
                    else if (firstLetter == "a" || firstLetter == "e" || firstLetter == "i" || firstLetter == "o" ||
                             firstLetter == "u")
                    {
                        Dialog.StartCoroutine(Dialog.drawText(
                            SaveData.currentSave.playerName + " received an " + currentEvent.string0 + "!"));
                    }
                    else
                    {
                        Dialog.StartCoroutine(Dialog.drawText(
                            SaveData.currentSave.playerName + " received a " + currentEvent.string0 + "!"));
                    }
                }
                yield return new WaitForSeconds(itemGetMFX.length);

                bool itemAdd = SaveData.currentSave.Bag.addItem(currentEvent.string0, currentEvent.int0);

                Dialog.drawDialogBox();
                if (itemAdd)
                {
                    if (currentEvent.bool0)
                    {
                        yield return
                            Dialog.StartCoroutine(Dialog.drawTextSilent(
                                SaveData.currentSave.playerName + " put the TM" +
                                ItemDatabase.getItem(currentEvent.string0).getTMNo() + " \\away into the bag."));
                    }
                    else
                    {
                        if (currentEvent.int0 > 1)
                        {
                            yield return
                                Dialog.StartCoroutine(Dialog.drawTextSilent(
                                    SaveData.currentSave.playerName + " put the " + currentEvent.string0 +
                                    "s \\away into the bag."));
                        }
                        else
                        {
                            yield return
                                Dialog.StartCoroutine(Dialog.drawTextSilent(
                                    SaveData.currentSave.playerName + " put the " + currentEvent.string0 +
                                    " \\away into the bag."));
                        }
                    }
                    while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back"))
                    {
                        yield return null;
                    }
                }
                else
                {
                    yield return Dialog.StartCoroutine(Dialog.drawTextSilent( "But there was no room..."));
                    while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back"))
                    {
                        yield return null;
                    }
                }
                Dialog.undrawDialogBox();
                break;

            case CustomEventDetails.CustomEventType.ReceivePokemon:
                if (SaveData.currentSave.PC.hasSpace(0))
                {
                    //Play Great for Pokemon
                    AudioClip pokeGetMFX = Resources.Load<AudioClip>("Audio/mfx/GetGreat");

                    PokemonData pkd = PokemonDatabase.getPokemon(currentEvent.ints[0]);

                    string pkName = pkd.getName();
                    Pokemon.Gender pkGender = Pokemon.Gender.CALCULATE;

                    if (pkd.getMaleRatio() == -1)
                    {
                        pkGender = Pokemon.Gender.NONE;
                    }
                    else if (pkd.getMaleRatio() == 0)
                    {
                        pkGender = Pokemon.Gender.FEMALE;
                    }
                    else if (pkd.getMaleRatio() == 100)
                    {
                        pkGender = Pokemon.Gender.MALE;
                    }
                    else
                    {
//if not a set gender
                        if (currentEvent.ints[2] == 0)
                        {
                            pkGender = Pokemon.Gender.MALE;
                        }
                        else if (currentEvent.ints[2] == 1)
                        {
                            pkGender = Pokemon.Gender.FEMALE;
                        }
                    }

                    Dialog.drawDialogBox();
                    yield return
                        Dialog.StartCoroutine(Dialog.drawText(
                            SaveData.currentSave.playerName + " received the " + pkName + "!"));
                    BgmHandler.main.PlayMFX(pokeGetMFX);
                    yield return new WaitForSeconds(pokeGetMFX.length);

                    string nickname = currentEvent.strings[0];
                    if (currentEvent.strings[1].Length == 0)
                    {
                        //If no OT set, allow nicknaming of Pokemon

                        Dialog.drawDialogBox();
                        yield return
                            StartCoroutine(
                                Dialog.drawTextSilent("Would you like to give a nickname to \nthe " + pkName +
                                                      " you received?"));
                        Dialog.drawChoiceBox();
                        yield return StartCoroutine(Dialog.choiceNavigate());
                        int nicknameCI = Dialog.chosenIndex;
                        Dialog.undrawDialogBox();
                        Dialog.undrawChoiceBox();

                        if (nicknameCI == 1)
                        {
                            //give nickname
                            //SfxHandler.Play(selectClip);
                            yield return StartCoroutine(ScreenFade.main.Fade(false, 0.4f));

                            Scene.main.Typing.gameObject.SetActive(true);
                            StartCoroutine(Scene.main.Typing.control(10, "", pkGender,
                                Pokemon.GetIconsFromID_(currentEvent.ints[0], currentEvent.bool0)));
                            while (Scene.main.Typing.gameObject.activeSelf)
                            {
                                yield return null;
                            }
                            if (Scene.main.Typing.typedString.Length > 0)
                            {
                                nickname = Scene.main.Typing.typedString;
                            }

                            yield return StartCoroutine(ScreenFade.main.Fade(true, 0.4f));
                        }
                    }
                    if (!EventRequiresDialogBox(nextEvent.eventType))
                    {
                        Dialog.undrawDialogBox();
                    }

                    int[] IVs = new int[]
                    {
                        Random.Range(0, 32), Random.Range(0, 32), Random.Range(0, 32),
                        Random.Range(0, 32), Random.Range(0, 32), Random.Range(0, 32)
                    };
                    if (currentEvent.bool1)
                    {
                        //if using Custom IVs
                        IVs[0] = currentEvent.ints[5];
                        IVs[1] = currentEvent.ints[6];
                        IVs[2] = currentEvent.ints[7];
                        IVs[3] = currentEvent.ints[8];
                        IVs[4] = currentEvent.ints[9];
                        IVs[5] = currentEvent.ints[10];
                    }

                    string pkNature = (currentEvent.ints[3] == 0)
                        ? NatureDatabase.getRandomNature().getName()
                        : NatureDatabase.getNature(currentEvent.ints[3] - 1).getName();

                    string[] pkMoveset = pkd.GenerateMoveset(currentEvent.ints[1]);
                    for (int i = 0; i < 4; i++)
                    {
                        if (currentEvent.strings[4 + i].Length > 0)
                        {
                            pkMoveset[i] = currentEvent.strings[4 + i];
                        }
                    }

                    Debug.Log(pkMoveset[0] + ", " + pkMoveset[1] + ", " + pkMoveset[2] + ", " + pkMoveset[3]);

                    Pokemon pk = new Pokemon(currentEvent.ints[0], nickname, pkGender, currentEvent.ints[1],
                        currentEvent.bool0, currentEvent.strings[2], currentEvent.strings[3],
                        currentEvent.strings[1], IVs[0], IVs[1], IVs[2], IVs[3], IVs[4], IVs[5], 0, 0, 0, 0, 0, 0,
                        pkNature, currentEvent.ints[4],
                        pkMoveset, new int[4]);

                    SaveData.currentSave.PC.addPokemon(pk);
                }
                else
                {
                    //jump to new tree
                    JumpToTree(currentEvent.int0);
                }
                break;

            case (CustomEventDetails.CustomEventType.SetActive):
                if (currentEvent.bool0)
                {
                    currentEvent.object0.SetActive(true);
                }
                else
                {
                    if (currentEvent.object0 == this.gameObject)
                    {
                        deactivateOnFinish = true;
                    }
                    else if (currentEvent.object0 != PlayerMovement.player.gameObject)
                    {
                        //important to never deactivate the player
                        currentEvent.object0.SetActive(false);
                    }
                }
                break;

            case CustomEventDetails.CustomEventType.SetCVariable:
                SaveData.currentSave.setCVariable(currentEvent.string0, currentEvent.float0);
                break;

            case (CustomEventDetails.CustomEventType.LogicCheck):
                bool passedCheck = false;

                CustomEventDetails.Logic lo = currentEvent.logic;

                switch (lo)
                {
                    case CustomEventDetails.Logic.CVariableEquals:
                        if (currentEvent.float0 == SaveData.currentSave.getCVariable(currentEvent.string0))
                        {
                            passedCheck = true;
                        }
                        break;
                    case CustomEventDetails.Logic.CVariableGreaterThan:
                        if (SaveData.currentSave.getCVariable(currentEvent.string0) > currentEvent.float0)
                        {
                            passedCheck = true;
                        }
                        break;
                    case CustomEventDetails.Logic.CVariableLessThan:
                        if (SaveData.currentSave.getCVariable(currentEvent.string0) < currentEvent.float0)
                        {
                            passedCheck = true;
                        }
                        break;
                    case CustomEventDetails.Logic.GymBadgeNoOwned:
                        if (Mathf.FloorToInt(currentEvent.float0) < SaveData.currentSave.gymsBeaten.Length &&
                            Mathf.FloorToInt(currentEvent.float0) >= 0)
                        {
                            //ensure input number is valid
                            if (SaveData.currentSave.gymsBeaten[Mathf.FloorToInt(currentEvent.float0)])
                            {
                                passedCheck = true;
                            }
                        }
                        break;
                    case CustomEventDetails.Logic.GymBadgesEarned:
                        int badgeCount = 0;
                        for (int bi = 0; bi < SaveData.currentSave.gymsBeaten.Length; bi++)
                        {
                            if (SaveData.currentSave.gymsBeaten[bi])
                            {
                                badgeCount += 1;
                            }
                        }
                        if (badgeCount >= currentEvent.float0)
                        {
                            passedCheck = true;
                        }
                        break;
                    case CustomEventDetails.Logic.PokemonIDIsInParty:
                        for (int pi = 0; pi < 6; pi++)
                        {
                            if (SaveData.currentSave.PC.boxes[0][pi] != null)
                            {
                                if (SaveData.currentSave.PC.boxes[0][pi].getID() ==
                                    Mathf.FloorToInt(currentEvent.float0))
                                {
                                    passedCheck = true;
                                    pi = 6;
                                }
                            }
                        }
                        break;
                    case CustomEventDetails.Logic.SpaceInParty:
                        if (currentEvent.bool0)
                        {
                            if (!SaveData.currentSave.PC.hasSpace(0))
                            {
                                passedCheck = true;
                            }
                        }
                        else
                        {
                            if (SaveData.currentSave.PC.hasSpace(0))
                            {
                                passedCheck = true;
                            }
                        }
                        break;
                }

                if (passedCheck)
                {
                    int newTreeIndex = currentEvent.int0;
                    if (newTreeIndex != eventTreeIndex && //only change tree if index is valid
                        newTreeIndex < treesArray.Length)
                    {
                        JumpToTree(newTreeIndex);
                    }
                }
                break;

            case CustomEventDetails.CustomEventType.TrainerBattle:

                //custom cutouts not yet implemented
                StartCoroutine(ScreenFade.main.FadeCutout(false, ScreenFade.slowedSpeed, null));

                //Automatic LoopStart usage not yet implemented
                Scene.main.Battle.gameObject.SetActive(true);

                Trainer trainer = currentEvent.object0.GetComponent<Trainer>();

                if (trainer.battleBGM != null)
                {
                    Debug.Log(trainer.battleBGM.name);
                    BgmHandler.main.PlayOverlay(trainer.battleBGM, trainer.samplesLoopStart);
                }
                else
                {
                    BgmHandler.main.PlayOverlay(Scene.main.Battle.defaultTrainerBGM,
                        Scene.main.Battle.defaultTrainerBGMLoopStart);
                }
                Scene.main.Battle.gameObject.SetActive(false);
                yield return new WaitForSeconds(1.6f);

                Scene.main.Battle.gameObject.SetActive(true);
                StartCoroutine(Scene.main.Battle.control(true, trainer, currentEvent.bool0));

                while (Scene.main.Battle.gameObject.activeSelf)
                {
                    yield return null;
                }

                //yield return new WaitForSeconds(sceneTransition.FadeIn(0.4f));
                yield return StartCoroutine(ScreenFade.main.Fade(true, 0.4f));

                if (currentEvent.bool0)
                {
                    if (Scene.main.Battle.victor == 1)
                    {
                        int newTreeIndex = currentEvent.int0;
                        if (newTreeIndex != eventTreeIndex && //only change tree if index is valid
                            newTreeIndex < treesArray.Length)
                        {
                            JumpToTree(newTreeIndex);
                        }
                    }
                }

                break;
        }
    }

    private bool EventRequiresDialogBox(CustomEventDetails.CustomEventType eventType)
    {
        //Events that require immediate use of the DialogBox
        if (eventType == CustomEventDetails.CustomEventType.Dialog ||
            eventType == CustomEventDetails.CustomEventType.Choice ||
            eventType == CustomEventDetails.CustomEventType.ReceiveItem ||
            eventType == CustomEventDetails.CustomEventType.ReceivePokemon)
        {
            return true;
        }
        return false;
    }

    private void JumpToTree(int index)
    {
        eventTreeIndex = index;
        currentEventIndex = -1;
    }
}

[System.Serializable]
public class CustomEventTree
{
    public string treeName;
    public CustomEventDetails[] events;
}

[System.Serializable]
public class CustomEventDetails
{
    public enum CustomEventType
    {
        Wait, //float0: wait time
        Walk, //direction | int0: walk spaces | object0: Character to move | bool0: lock direction
        TurnTo, //int0: direction modifier | object0: NPC to turn | object1: Object to turn to
        Dialog, //strings: lines of dialog
        Choice, //strings: choices (none for Yes/No) | ints: eventTrees to jump to (same for continue)
        Sound, //sound: sound to play
        ReceiveItem,
        ReceivePokemon, //ints[0]: Pokemon ID | ints[1]: Level | ints[2]: Gender | ints[3]: Nature | ints[4]: Ability
        //strings[0]: Nickname | strings[1]: OT | strings[2]: Poké Ball | strings[3]: Held Item
        //ints[5-10]: Custom IVs | strings[4-7]: Custom Moves | bool0: Is Shiny | bool1: Use Custom IVs
        SetActive, //object0: game object to activate
        SetCVariable, //string0: CVariable name | float0: new value
        LogicCheck, //logic | float0: check value | string0: CVariable name
        TrainerBattle //object0: trainer script | bool0: allowed to lose | int0: tree to jump to on loss
    }

    public enum Direction
    {
        Up,
        Right,
        Down,
        Left
    }

    public enum Logic
    {
        CVariableEquals,
        CVariableGreaterThan,
        CVariableLessThan,
        GymBadgeNoOwned,
        GymBadgesEarned,
        PokemonIDIsInParty,
        SpaceInParty
    }

    public CustomEventType eventType;

    public Direction dir;

    public Logic logic;

    public int int0;
    public float float0;
    public string string0;

    public bool bool0;
    public bool bool1;

    public int[] ints;
    public string[] strings;

    public GameObject object0;
    public GameObject object1;

    public AudioClip sound;

    public bool runSimultaneously;
}

[System.Serializable]
public class CVariable
{
    public string name;
    public float value;

    public CVariable(string name, float value)
    {
        this.name = name;
        this.value = value;
    }
}


text:
declare module UUID {

    interface UUIDStatic {

        /**
         * Generates a version 4 {@link UUID}.
         * @returns {string} A version 4 UUID string.
         */
        v4(): string;

    }
}

declare var uuid:  UUID.UUIDStatic;

declare module "uuid" {
    export = uuid;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
-->

<gml:ParameterValueGroup xsi:schemaLocation = "http://www.opengis.net/gml/3.2 http://schemas.opengis.net/gml/3.2.1/coordinateOperations.xsd"
                         xmlns:gml          = "http://www.opengis.net/gml/3.2"
                         xmlns:xlink        = "http://www.w3.org/1999/xlink"
                         xmlns:xsi          = "http://www.w3.org/2001/XMLSchema-instance">

  <gml:parameterValue>
    <gml:ParameterValue>
      <gml:value uom="urn:ogc:def:uom:EPSG::9102">40.0</gml:value>
      <gml:operationParameter>
        <gml:OperationParameter gml:id="epsg-parameter-8801">
          <gml:identifier codeSpace="IOGP">urn:ogc:def:parameter:EPSG::8801</gml:identifier>
          <gml:name codeSpace="EPSG">Latitude of natural origin</gml:name>
          <gml:name codeSpace="OGC">latitude_of_origin</gml:name>
          <gml:remarks>This parameter is shown for completeness, but should never have a value different than 0 for this projection.</gml:remarks>
        </gml:OperationParameter>
      </gml:operationParameter>
    </gml:ParameterValue>
  </gml:parameterValue>
  <gml:parameterValue>
    <gml:ParameterValue>
      <gml:value uom="urn:ogc:def:uom:EPSG::9102">-60.0</gml:value>
      <gml:operationParameter>
        <gml:OperationParameter gml:id="epsg-parameter-8802">
          <gml:identifier codeSpace="IOGP">urn:ogc:def:parameter:EPSG::8802</gml:identifier>
          <gml:name codeSpace="EPSG">Longitude of natural origin</gml:name>
          <gml:name codeSpace="OGC">central_meridian</gml:name>
        </gml:OperationParameter>
      </gml:operationParameter>
    </gml:ParameterValue>
  </gml:parameterValue>
  <gml:parameterValue>
    <gml:ParameterValue>
      <gml:value uom="urn:ogc:def:uom:EPSG::9201">1.0</gml:value>
      <gml:operationParameter>
        <gml:OperationParameter gml:id="epsg-parameter-8805">
          <gml:identifier codeSpace="IOGP">urn:ogc:def:parameter:EPSG::8805</gml:identifier>
          <gml:name codeSpace="EPSG">Scale factor at natural origin</gml:name>
          <gml:name codeSpace="OGC">scale_factor</gml:name>
        </gml:OperationParameter>
      </gml:operationParameter>
    </gml:ParameterValue>
  </gml:parameterValue>
  <gml:group>
    <gml:OperationParameterGroup gml:id="epsg-9804">
      <gml:identifier codeSpace="EPSG">9804</gml:identifier>
      <gml:name codeSpace="EPSG">Mercator (variant A)</gml:name>
      <gml:name codeSpace="OGC">Mercator_1SP</gml:name>
      <gml:minimumOccurs>0</gml:minimumOccurs>
      <!--
        The first three parameters below this point are the same than the parameters defined above.
        The xlink:href attribute allows to reference existing instances instead than repeating them.
        Repetition will be tested with another file: DuplicatedParameters.xml
      -->
      <gml:parameter xlink:href="#epsg-parameter-8801"/>
      <gml:parameter xlink:href="#epsg-parameter-8802"/>
      <gml:parameter xlink:href="#epsg-parameter-8805"/>
      <gml:parameter>
        <gml:OperationParameter gml:id="epsg-parameter-8806">
          <gml:identifier codeSpace="IOGP">urn:ogc:def:parameter:EPSG::8806</gml:identifier>
          <gml:name codeSpace="EPSG">False easting</gml:name>
          <gml:name codeSpace="OGC">false_easting</gml:name>
          <gml:minimumOccurs>0</gml:minimumOccurs>
        </gml:OperationParameter>
      </gml:parameter>
      <gml:parameter>
        <gml:OperationParameter gml:id="epsg-parameter-8807">
          <gml:identifier codeSpace="IOGP">urn:ogc:def:parameter:EPSG::8807</gml:identifier>
          <gml:name codeSpace="EPSG">False northing</gml:name>
          <gml:name codeSpace="OGC">false_northing</gml:name>
          <gml:minimumOccurs>0</gml:minimumOccurs>
        </gml:OperationParameter>
      </gml:parameter>
    </gml:OperationParameterGroup>
  </gml:group>
</gml:ParameterValueGroup>


text:
//
// partial2js
// Copyright (c) 2014 Dennis Sänger
// Licensed under the MIT
// http://opensource.org/licenses/MIT
//
"use strict";

var glob    = require('glob-all');
var fs      = require('fs');
var path    = require('path');
var stream  = require('stream');
var htmlmin = require('html-minifier').minify;
var escape  = require('js-string-escape');

var eol     = require('os').EOL;

function Partial2Js( opts ) {

  opts = opts || {};

  var self = this;
  this.debug = !!opts.debug;

  this.patterns = [];
  this.files = [];
  this.contents = {};
  this.uniqueFn = function( file ) {
    return file;
  };

  var log = (function log() {
    if ( this.debug ) {
      console.log.apply( console, arguments );
    }
  }).bind( this );

  var find = (function() {
    this.files = glob.sync( this.patterns.slice( 0 )) || [];
  }).bind( this );

  function cleanPatterns( patterns ) {
    return patterns.map(function( entry ) {
      return entry.replace(/\/\*+/g, '');
    });
  }

  function compare( patterns, a, b ) {
    return matchInPattern( patterns, a ) - matchInPattern( patterns, b );
  }

  var sort = (function() {
    var clean = cleanPatterns( this.patterns );
    this.files.sort(function( a, b ) {
      return compare( clean, a, b );
    });
  }).bind( this );

  //
  // this function is not every functional ;)
  // Should use findIndex() [ES6] as soon as possible
  //
  function matchInPattern( patterns, entry ) {
    var res = patterns.length + 100;
    patterns.every(function( pattern, index ) {
      if ( entry.indexOf( pattern ) > -1 ) {
        res = index;
        return false;
      }
      return true;
    });
    return res;
  }

  var unique = (function() {

    if ( typeof this.uniqueFn === 'function' && this.files && this.files.length ) {
      var obj = {};
      this.files.forEach(function( file ) {
        var key = self.uniqueFn( file );
        if ( !obj[key] ) {
          obj[key] = file;
        }
      });
      this.files = obj;
    }

  }).bind( this );

  var asString = (function( moduleName ) {
    var buffer = '';

    buffer += '(function(window,document){' + eol;
    buffer += '"use strict";' + eol;
    buffer += 'angular.module("'+moduleName+'",[]).run(["$templateCache",function($templateCache){' + eol;

    for ( var k in this.contents ) {
      buffer += '  $templateCache.put("'+k+'","'+this.contents[k]+'");' + eol;
    }

    buffer += '}]);' + eol;
    buffer += '})(window,document);';

    return buffer;

  }).bind( this );

  var read = (function() {
    var id, path, stat;
    this.contents = {};

    for( var k in this.files ) {
      id = k;
      path = this.files[k];

      stat = fs.statSync( path );
      if ( stat.isFile()) {
        log('read file:', path, '=>', id );
        this.contents[id] = fs.readFileSync( path );
      }
    }

    return this.contents;

  }).bind( this );

  var asStream = function( string ) {
    var s = new stream.Readable();
    s._read = function noop() {};
    s.push( string );
    s.push(null);
    return s;
  };

  var minify = (function() {
    var opts = {
      collapseWhitespace: true,
      preserveLineBreaks: false,
      removeComments: true,
      removeRedundantAttributes: true,
      removeEmptyAttributes: false,
      keepClosingSlash: true,
      maxLineLength: 0,
      customAttrCollapse: /.+/,
      html5: true
    };

    for ( var k in this.contents ) {
      this.contents[k] = escape(htmlmin( String(this.contents[k]), opts ));
    }
  }).bind( this );

  this.add = function( pattern ) {
    this.patterns.push( pattern );
    return this;
  };

  this.not = function( pattern ) {
    this.patterns.push( '!'+pattern );
    return this;
  };

  this.folder = function( folder ) {
    if ( folder && String( folder ) === folder ) {
      folder = path.resolve( folder ) + '/**/*';
      this.patterns.push( folder );
    }
    return this;
  };

  this.unique = function( fn ) {
    this.uniqueFn = fn;
    return this;
  };

  this.stringify = function( moduleName ) {
    find();
    sort();
    unique();
    read();
    minify();
    return asString( moduleName );
  };

  this.stream = function( moduleName ) {
    return asStream( this.stringify( moduleName ) );
  };

}

module.exports = function( opts ) {
  return new Partial2Js( opts );
};


text:
package org.kavaproject.kavatouch.foundation.staging;

import org.kavaproject.kavatouch.internal.OccClass;

@OccClass("NSURLBookmarkFileCreationOptions")
public interface URLBookmarkFileCreationOptions {
}


text:
module Core.Utils where

import Numeric (showHex)
import Data.Maybe (fromJust)
import Data.List (group, groupBy, sortBy)

-- | Removes duplicate items from the given sorted list.
nubSorted :: Eq a => [a] -> [a]
nubSorted = map head . group

-- | Sorts list and removes duplicates. Function @f@ is applied to items
--   before comparsion.
--
-- @
-- 'sortAndNubWith' f == 'Data.List.nubBy'  (\\a b -> fa == fb) .
--                     'Data.List.sortBy' (\\a b -> compare (f a) (f b)
-- @
sortAndNubWith :: Ord b => (a -> b) -> [a] -> [a]
sortAndNubWith f = mergeSort . map (:[])
  where
    mergeSort []  = []
    mergeSort [a] = a
    mergeSort xs  = mergeSort $ mergePairs xs

    mergePairs []       = []
    mergePairs [a]      = [a]
    mergePairs (a:b:xs) = merge a b:mergePairs xs

    merge ass@(a:as) bss@(b:bs)
      = case compare (f a) (f b) of
          LT -> a:merge as  bss
          GT -> b:merge ass bs
          EQ -> a:merge as  bs  -- Duplicate is removed here.
    merge as@(_:_) [] = as
    merge []       bs = bs

-- | Sorts the list of pairs by the second value. Then groups values
--   in the list by the second value.
sortAndGroupBySnd :: Ord b => [(a, b)] -> [[(a, b)]]
sortAndGroupBySnd = groupBy (co2 (==) snd) . sortBy (co2 compare snd)
  where
    co2 f t a b = f (t a) (t b)

-- | List of white characters.
whiteChars :: String
whiteChars = " \t\n\r\f\v"

-- | List of the characters which have single-character escape code.
escapeChars :: String
escapeChars = "\0\a\b\f\n\r\t\v\ESC"

-- | List of escape codes. The escape codes correspond to the characters
--   in 'escapeChars'.
escapeCodes :: String
escapeCodes = "0abfnrtve"

-- | Escapes special character. Special character is a backslash and
--   every character with code lower than 32.
escapeSpecial :: Char -> String
escapeSpecial c
  | c == '\\'            = "\\\\"
  | c `elem` escapeChars = '\\':lookup' (zip escapeChars escapeCodes) c:""
  | code < 32            = "\\x" ++ replicate (2 - length hex) '0' ++ hex
  | otherwise            = [c]
  where
    code = fromEnum c
    hex  = showHex code ""

-- | Like 'lookup' but unsafe with flipped arguments.
lookup' :: (Eq a) => [(a, b)] -> a -> b
lookup' alist = fromJust . flip lookup alist

-- | @'safeFoldl1' e f xs@ returns @'foldl1' f xs@ when @xs@ is nonempty
--   otherwise returns @e@.
safeFoldl1 :: a -> (a -> a -> a) -> [a] -> a
safeFoldl1 e _ [] = e
safeFoldl1 _ f xs = foldl1 f xs


text:
(function () {
'use strict';

function addMonths(startdate, count) {
  var date = startdate && startdate.setUTCDate && new Date(+startdate);
  if (!(date instanceof Date)) {
    return startdate
  }
  count |= 0;
  if (!count || isNaN(date)) {
    return date
  }
  var offset = +date - date.setUTCHours(12, 0, 0, 0);
  var day = date.getUTCDate();
  date.setUTCMonth(date.getUTCMonth() + count, 2);
  var month = date.getUTCMonth();
  date.setUTCDate(day);
  if (date.getUTCMonth() !== month) {
    date.setUTCDate(0);
  }
  date.setMilliseconds(offset);
  return date
}

Object.defineProperty(Date.prototype, 'addMonths', {
  value: function (count) {
    return addMonths(this, count)
  },
  configurable: true,
  writable: true
});

}());


text:
mydir = File.expand_path(File.dirname(__FILE__))

begin
  require 'psych'
rescue LoadError
end

require 'i18n'
require 'set' # Fixes a bug in i18n 0.6.11

if I18n.respond_to?(:enforce_available_locales=)
  I18n.enforce_available_locales = true
end

I18n.load_path += Dir[File.join(mydir, 'locales', '**/*.yml')]
I18n.reload! if I18n.backend.initialized?

module Faker
  class Config
    @locale = nil
    @random = nil
    @site = nil

    class << self
      attr_writer :locale
      attr_writer :random
      attr_writer :site

      def locale
        @locale || I18n.locale
      end

      def own_locale
        @locale
      end

      def site
        @site
      end

      def random
        @random || Random::DEFAULT
      end
    end
  end

  class Base
    Numbers = Array(0..9)
    ULetters = Array('A'..'Z')
    Letters = ULetters + Array('a'..'z')

    class << self
      ## make sure numerify results doesn't start with a zero
      def numerify(number_string)
        number_string.sub(/#/) { (rand(9)+1).to_s }.gsub(/#/) { rand(10).to_s }
      end

      def letterify(letter_string)
        letter_string.gsub(/\?/) { sample(ULetters) }
      end

      def bothify(string)
        letterify(numerify(string))
      end

      # Given a regular expression, attempt to generate a string
      # that would match it.  This is a rather simple implementation,
      # so don't be shocked if it blows up on you in a spectacular fashion.
      #
      # It does not handle ., *, unbounded ranges such as {1,},
      # extensions such as (?=), character classes, some abbreviations
      # for character classes, and nested parentheses.
      #
      # I told you it was simple. :) It's also probably dog-slow,
      # so you shouldn't use it.
      #
      # It will take a regex like this:
      #
      # /^[A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}$/
      #
      # and generate a string like this:
      #
      # "U3V  3TP"
      #
      def regexify(re)
        re = re.source if re.respond_to?(:source) # Handle either a Regexp or a String that looks like a Regexp
        re.
          gsub(/^\/?\^?/, '').gsub(/\$?\/?$/, '').                                                                      # Ditch the anchors
          gsub(/\{(\d+)\}/, '{\1,\1}').gsub(/\?/, '{0,1}').                                                             # All {2} become {2,2} and ? become {0,1}
          gsub(/(\[[^\]]+\])\{(\d+),(\d+)\}/) {|match| $1 * sample(Array(Range.new($2.to_i, $3.to_i))) }.                # [12]{1,2} becomes [12] or [12][12]
          gsub(/(\([^\)]+\))\{(\d+),(\d+)\}/) {|match| $1 * sample(Array(Range.new($2.to_i, $3.to_i))) }.                # (12|34){1,2} becomes (12|34) or (12|34)(12|34)
          gsub(/(\\?.)\{(\d+),(\d+)\}/) {|match| $1 * sample(Array(Range.new($2.to_i, $3.to_i))) }.                      # A{1,2} becomes A or AA or \d{3} becomes \d\d\d
          gsub(/\((.*?)\)/) {|match| sample(match.gsub(/[\(\)]/, '').split('|')) }.                                      # (this|that) becomes 'this' or 'that'
          gsub(/\[([^\]]+)\]/) {|match| match.gsub(/(\w\-\w)/) {|range| sample(Array(Range.new(*range.split('-')))) } }. # All A-Z inside of [] become C (or X, or whatever)
          gsub(/\[([^\]]+)\]/) {|match| sample($1.split('')) }.                                                          # All [ABC] become B (or A or C)
          gsub('\d') {|match| sample(Numbers) }.
          gsub('\w') {|match| sample(Letters) }
      end

      # Helper for the common approach of grabbing a translation
      # with an array of values and selecting one of them.
      def fetch(key)
        fetched = sample(translate("faker.#{key}"))
        if fetched && fetched.match(/^\//) and fetched.match(/\/$/) # A regex
          regexify(fetched)
        else
          fetched
        end
      end

      # Helper for the common approach of grabbing a translation
      # with an array of values and returning all of them.
      def fetch_all(key)
        fetched = translate("faker.#{key}")
        fetched = fetched.last if fetched.size <= 1
        if !fetched.respond_to?(:sample) && fetched.match(/^\//) and fetched.match(/\/$/) # A regex
          regexify(fetched)
        else
          fetched
        end
      end

      # Load formatted strings from the locale, "parsing" them
      # into method calls that can be used to generate a
      # formatted translation: e.g., "#{first_name} #{last_name}".
      def parse(key)
        fetched = fetch(key)
        parts = fetched.scan(/(\(?)#\{([A-Za-z]+\.)?([^\}]+)\}([^#]+)?/).map {|prefix, kls, meth, etc|
          # If the token had a class Prefix (e.g., Name.first_name)
          # grab the constant, otherwise use self
          cls = kls ? Faker.const_get(kls.chop) : self

          # If an optional leading parentheses is not present, prefix.should == "", otherwise prefix.should == "("
          # In either case the information will be retained for reconstruction of the string.
          text = prefix

          # If the class has the method, call it, otherwise
          # fetch the transation (i.e., faker.name.first_name)
          text += cls.respond_to?(meth) ? cls.send(meth) : fetch("#{(kls || self).to_s.split('::').last.downcase}.#{meth.downcase}")

          # And tack on spaces, commas, etc. left over in the string
          text += etc.to_s
        }
        # If the fetched key couldn't be parsed, then fallback to numerify
        parts.any? ? parts.join : numerify(fetched)
      end

      # Call I18n.translate with our configured locale if no
      # locale is specified
      def translate(*args)

        opts = args.last.is_a?(Hash) ? args.pop : {}
        opts[:locale] ||= Faker::Config.locale
        opts[:raise] = true

        I18n.locale = Faker::Config.locale
        I18n.translate(*(args.push(opts)))

      rescue I18n::MissingTranslationData
        opts = args.last.is_a?(Hash) ? args.pop : {}
        opts[:locale] = :en

        # Super-simple fallback -- fallback to en if the
        # translation was missing.  If the translation isn't
        # in en either, then it will raise again.
        I18n.translate(*(args.push(opts)))
      end

      # Executes block with given locale set.
      def with_locale(tmp_locale = nil)
        current_locale = Faker::Config.own_locale
        Faker::Config.locale = tmp_locale
        I18n.with_locale(tmp_locale) { yield }
      ensure
        Faker::Config.locale = current_locale
      end

      def flexible(key)
        @flexible_key = key
      end

      # You can add whatever you want to the locale file, and it will get caught here.
      # E.g., in your locale file, create a
      #   name:
      #     girls_name: ["Alice", "Cheryl", "Tatiana"]
      # Then you can call Faker::Name.girls_name and it will act like #first_name
      def method_missing(m, *args, &block)
        super unless @flexible_key

        # Use the alternate form of translate to get a nil rather than a "missing translation" string
        if translation = translate(:faker)[@flexible_key][m]
          sample(translation)
        else
          super
        end
      end

      # Generates a random value between the interval
      def rand_in_range(from, to)
        from, to = to, from if to < from
        rand(from..to)
      end

      def unique(max_retries = 10_000)
        @unique_generator ||= UniqueGenerator.new(self, max_retries)
      end

      def sample(list)
        list.respond_to?(:sample) ? list.sample(random: Faker::Config.random) : list
      end

      def shuffle(list)
        list.shuffle(random: Faker::Config.random)
      end

      def rand(max = nil)
        if max.nil?
          Faker::Config.random.rand
        elsif max.is_a?(Range) || max.to_i > 0
          Faker::Config.random.rand(max)
        else
          0
        end
      end
    end
  end
end

Dir.glob(File.join(File.dirname(__FILE__), 'faker','*.rb')).sort.each {|f| require f }

require 'extensions/array'
require 'extensions/symbol'

require 'helpers/char'
require 'helpers/unique_generator'