text:
import { EventEmitter, ElementRef, Renderer2, ChangeDetectorRef, NgZone, Input, Output, ContentChildren, Component, ChangeDetectionStrategy, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DomHandler } from 'primeng/dom';
import { PrimeTemplate } from 'primeng/api';
import { trigger, state, style, transition, animate } from '@angular/animations';

var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
let OverlayPanel = class OverlayPanel {
    constructor(el, renderer, cd, zone) {
        this.el = el;
        this.renderer = renderer;
        this.cd = cd;
        this.zone = zone;
        this.dismissable = true;
        this.autoZIndex = true;
        this.baseZIndex = 0;
        this.showTransitionOptions = '225ms ease-out';
        this.hideTransitionOptions = '195ms ease-in';
        this.onShow = new EventEmitter();
        this.onHide = new EventEmitter();
        this.overlayVisible = false;
        this.render = false;
        this.isContainerClicked = true;
    }
    ngAfterContentInit() {
        this.templates.forEach((item) => {
            switch (item.getType()) {
                case 'content':
                    this.contentTemplate = item.template;
                    break;
                default:
                    this.contentTemplate = item.template;
                    break;
            }
        });
    }
    onContainerClick() {
        this.isContainerClicked = true;
    }
    bindDocumentClickListener() {
        if (!this.documentClickListener && this.dismissable) {
            this.zone.runOutsideAngular(() => {
                let documentEvent = DomHandler.isIOS() ? 'touchstart' : 'click';
                this.documentClickListener = this.renderer.listen('document', documentEvent, (event) => {
                    if (!this.container.contains(event.target) && this.target !== event.target && !this.target.contains(event.target) && !this.isContainerClicked) {
                        this.zone.run(() => {
                            this.hide();
                        });
                    }
                    this.isContainerClicked = false;
                    this.cd.markForCheck();
                });
            });
        }
    }
    unbindDocumentClickListener() {
        if (this.documentClickListener) {
            this.documentClickListener();
            this.documentClickListener = null;
        }
    }
    toggle(event, target) {
        if (this.overlayVisible) {
            if (this.hasTargetChanged(event, target)) {
                this.destroyCallback = () => {
                    this.show(null, (target || event.currentTarget || event.target));
                };
            }
            this.overlayVisible = false;
        }
        else {
            this.show(event, target);
        }
    }
    show(event, target) {
        this.target = target || event.currentTarget || event.target;
        this.overlayVisible = true;
        this.render = true;
    }
    hasTargetChanged(event, target) {
        return this.target != null && this.target !== (target || event.currentTarget || event.target);
    }
    appendContainer() {
        if (this.appendTo) {
            if (this.appendTo === 'body')
                document.body.appendChild(this.container);
            else
                DomHandler.appendChild(this.container, this.appendTo);
        }
    }
    restoreAppend() {
        if (this.container && this.appendTo) {
            this.el.nativeElement.appendChild(this.container);
        }
    }
    align() {
        if (this.autoZIndex) {
            this.container.style.zIndex = String(this.baseZIndex + (++DomHandler.zindex));
        }
        DomHandler.absolutePosition(this.container, this.target);
        if (DomHandler.getOffset(this.container).top < DomHandler.getOffset(this.target).top) {
            DomHandler.addClass(this.container, 'ui-overlaypanel-flipped');
        }
        if (Math.floor(DomHandler.getOffset(this.container).left) < Math.floor(DomHandler.getOffset(this.target).left) &&
            DomHandler.getOffset(this.container).left > 0) {
            DomHandler.addClass(this.container, 'ui-overlaypanel-shifted');
        }
    }
    onAnimationStart(event) {
        if (event.toState === 'open') {
            this.container = event.element;
            this.onShow.emit(null);
            this.appendContainer();
            this.align();
            this.bindDocumentClickListener();
            this.bindDocumentResizeListener();
        }
    }
    onAnimationEnd(event) {
        switch (event.toState) {
            case 'void':
                if (this.destroyCallback) {
                    this.destroyCallback();
                    this.destroyCallback = null;
                }
                break;
            case 'close':
                this.onContainerDestroy();
                this.onHide.emit({});
                this.render = false;
                break;
        }
    }
    hide() {
        this.overlayVisible = false;
    }
    onCloseClick(event) {
        this.hide();
        event.preventDefault();
    }
    onWindowResize(event) {
        this.hide();
    }
    bindDocumentResizeListener() {
        this.documentResizeListener = this.onWindowResize.bind(this);
        window.addEventListener('resize', this.documentResizeListener);
    }
    unbindDocumentResizeListener() {
        if (this.documentResizeListener) {
            window.removeEventListener('resize', this.documentResizeListener);
            this.documentResizeListener = null;
        }
    }
    onContainerDestroy() {
        this.target = null;
        this.unbindDocumentClickListener();
        this.unbindDocumentResizeListener();
    }
    ngOnDestroy() {
        this.target = null;
        this.destroyCallback = null;
        if (this.container) {
            this.restoreAppend();
            this.onContainerDestroy();
        }
    }
};
OverlayPanel.ctorParameters = () => [
    { type: ElementRef },
    { type: Renderer2 },
    { type: ChangeDetectorRef },
    { type: NgZone }
];
__decorate([
    Input()
], OverlayPanel.prototype, "dismissable", void 0);
__decorate([
    Input()
], OverlayPanel.prototype, "showCloseIcon", void 0);
__decorate([
    Input()
], OverlayPanel.prototype, "style", void 0);
__decorate([
    Input()
], OverlayPanel.prototype, "styleClass", void 0);
__decorate([
    Input()
], OverlayPanel.prototype, "appendTo", void 0);
__decorate([
    Input()
], OverlayPanel.prototype, "autoZIndex", void 0);
__decorate([
    Input()
], OverlayPanel.prototype, "ariaCloseLabel", void 0);
__decorate([
    Input()
], OverlayPanel.prototype, "baseZIndex", void 0);
__decorate([
    Input()
], OverlayPanel.prototype, "showTransitionOptions", void 0);
__decorate([
    Input()
], OverlayPanel.prototype, "hideTransitionOptions", void 0);
__decorate([
    Output()
], OverlayPanel.prototype, "onShow", void 0);
__decorate([
    Output()
], OverlayPanel.prototype, "onHide", void 0);
__decorate([
    ContentChildren(PrimeTemplate)
], OverlayPanel.prototype, "templates", void 0);
OverlayPanel = __decorate([
    Component({
        selector: 'p-overlayPanel',
        template: `

                <ng-content></ng-content>
                <ng-container *ngTemplateOutlet="contentTemplate"></ng-container>

    `,
        animations: [
            trigger('animation', [
                state('void', style({
                    transform: 'translateY(5%)',
                    opacity: 0
                })),
                state('close', style({
                    transform: 'translateY(5%)',
                    opacity: 0
                })),
                state('open', style({
                    transform: 'translateY(0)',
                    opacity: 1
                })),
                transition('void => open', animate('{{showTransitionParams}}')),
                transition('open => close', animate('{{hideTransitionParams}}'))
            ])
        ],
        changeDetection: ChangeDetectionStrategy.Default
    })
], OverlayPanel);
let OverlayPanelModule = class OverlayPanelModule {
};
OverlayPanelModule = __decorate([
    NgModule({
        imports: [CommonModule],
        exports: [OverlayPanel],
        declarations: [OverlayPanel]
    })
], OverlayPanelModule);

/**
 * Generated bundle index. Do not edit.
 */

export { OverlayPanel, OverlayPanelModule };
//# sourceMappingURL=primeng-overlaypanel.js.map

redpajama_set_name: RedPajamaGithub


text:
package org.drooms.impl.logic;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.drooms.api.Edge;
import org.drooms.api.Node;
import org.drooms.api.Player;
import org.drooms.api.Playground;
import org.drooms.impl.util.shortestpath.astar.UnweightedAStarShortestPath;
import org.drooms.impl.util.shortestpath.astar.UnweightedAStarShortestPath.VertexDistanceHeuristics;

import edu.uci.ics.jung.algorithms.shortestpath.ShortestPath;
import edu.uci.ics.jung.algorithms.shortestpath.ShortestPathUtils;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.UndirectedGraph;
import edu.uci.ics.jung.graph.UndirectedSparseGraph;
import edu.uci.ics.jung.graph.util.Graphs;

/**
 * A helper class for the strategies to be able to quickly and easily find paths
 * from one {@link Node} to another.
 */
public class PathTracker {

    private static UndirectedGraph<Node, Edge> cloneGraph(final Graph<Node, Edge> src,
            final Collection<Node> removeNodes) {
        final UndirectedGraph<Node, Edge> clone = new UndirectedSparseGraph<>();
        for (final Edge e : src.getEdges()) {
            final boolean isEdgeAdded = clone.addEdge(e, src.getIncidentVertices(e));
            if (!isEdgeAdded) {
                throw new IllegalStateException("Failed cloning graph. This surely is a bug in Drooms.");
            }
        }
        for (final Node node : removeNodes) {
            clone.removeVertex(node);
        }
        return Graphs.unmodifiableUndirectedGraph(clone);
    }

    private UndirectedGraph<Node, Edge> currentGraph;
    private ShortestPath<Node, Edge> currentPath;
    private Node currentPosition;

    private final Player player;
    private final Playground playground;

    /**
     * Initialize the class.
     *
     * @param playground
     *            The playground to base the path-finding algos on.
     * @param p
     *            The player that will be using this particular instance.
     */
    public PathTracker(final Playground playground, final Player p) {
        this.playground = playground;
        this.player = p;
    }

    /**
     * Retrieve the current position of the player's worm's head, that is the
     * one found during the last {@link #movePlayers(Map)} call.
     *
     * @return The position, or null if {@link #movePlayers(Map)} had never been
     *         called before.
     */
    public Node getCurrentPosition() {
        return this.currentPosition;
    }

    /**
     * Find the shortest path between two nodes.
     *
     * @param start
     *            Beginning of the path.
     * @param end
     *            End of the path.
     * @return Unmodifiable list of nodes on the path, ordered from start to
     *         end. Empty if path cannot be found.
     */
    public List<Edge> getPath(final Node start, final Node end) {
        return Collections.unmodifiableList(ShortestPathUtils.getPath(this.currentGraph, this.currentPath, start, end));
    }

    /**
     * Find the shortest path from the start node that leads through the other
     * two nodes in any order.
     *
     * @param start
     *            Beginning of the path.
     * @param node2
     *            Any of the other two nodes.
     * @param node3
     *            Any of the other two nodes.
     * @return Unmodifiable list of nodes on the path, ordered from start to
     *         end. Empty if path cannot be found.
     */
    public List<Edge> getPath(final Node start, final Node node2, final Node node3) {
        final List<Edge> path2 = this.getPath(start, node2);
        final List<Edge> path3 = this.getPath(start, node3);
        final List<Edge> path23 = new ArrayList<Edge>(this.getPath(node2, node3));
        final List<Edge> result = new ArrayList<Edge>();
        if (path2.size() > path3.size()) {
            result.addAll(path3);
            Collections.reverse(path23);
        } else {
            result.addAll(path2);
        }
        result.addAll(path23);
        return Collections.unmodifiableList(result);
    }

    public Player getPlayer() {
        return this.player;
    }

    public Playground getPlayground() {
        return this.playground;
    }

    /**
     * Update the internal state of this class so that future paths can avoid
     * places where the worms currently reside.
     *
     * @param newPositions
     *            New current positions of all the worms.
     */
    protected void movePlayers(final Map<Player, Deque<Node>> newPositions) {
        final Set<Node> unavailable = new HashSet<>();
        for (final Map.Entry<Player, Deque<Node>> entry : newPositions.entrySet()) {
            final Deque<Node> playerNodes = entry.getValue();
            unavailable.addAll(playerNodes);
            if (entry.getKey() == this.player) {
                /*
                 * the head node needs to remain, since otherwise there would be
                 * no path between the current position and any other position.
                 */
                unavailable.remove(playerNodes.getFirst());
            }
        }
        final Graph<Node, Edge> graphWithoutPlayers = this.playground.getGraph();
        this.currentGraph = PathTracker.cloneGraph(graphWithoutPlayers, unavailable);
        this.currentPath = new UnweightedAStarShortestPath<>(this.currentGraph, VertexDistanceHeuristics.EUCLIDEAN);
        this.currentPosition = newPositions.get(this.player).getFirst();
    }

}


text:
package org.apache.kylin.common.util;

import org.apache.commons.io.Charsets;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class TempMetadataBuilder {

    /**
     * Provided metadata for Parquet Storage
     */
    public static final String N_SPARK_PROJECT_KYLIN_META_TEST_DATA = "../../examples/test_case_data/parquet_test";
    public static final String N_SPARK_PROJECT_KYLIN_META_TEST_DATA_2 = "../examples/test_case_data/parquet_test";

    /**
     * Temporary metadata dir
     */
    public static final String TEMP_TEST_METADATA = "../examples/test_metadata";

    private static final Logger logger = LoggerFactory.getLogger(TempMetadataBuilder.class);

    /**
     * @see TempMetadataBuilder#TEMP_TEST_METADATA
     */
    public static String prepareNLocalTempMetadata() {
        return prepareNLocalTempMetadata(false);
    }

    public static String prepareNLocalTempMetadata(boolean debug) {
        if (new File(N_SPARK_PROJECT_KYLIN_META_TEST_DATA).exists()) {
            return new TempMetadataBuilder(debug, "../" + TEMP_TEST_METADATA, N_SPARK_PROJECT_KYLIN_META_TEST_DATA).build();
        }
        return new TempMetadataBuilder(debug, TEMP_TEST_METADATA, N_SPARK_PROJECT_KYLIN_META_TEST_DATA_2).build();
    }

    public static String prepareNLocalTempMetadata(boolean debug, String overlay) {
        if (new File(overlay).exists()) {
            return new TempMetadataBuilder(debug, "../" + TEMP_TEST_METADATA, overlay).build();
        }
        return new TempMetadataBuilder(debug, TEMP_TEST_METADATA, overlay).build();
    }

    // ============================================================================

    private String[] metaSrcs = null;
    private boolean debug = false;
    private String dst;

    private TempMetadataBuilder(boolean debug, String dst, String... metaSrcs) {
        this.metaSrcs = metaSrcs;
        this.debug = debug;
        this.dst = dst;
    }

    private String build() {
        logger.debug("Prepare temp metadata for ut/it .");
        if ("true".equals(System.getProperty("skipMetaPrep"))) {
            return dst;
        }

        try {
            if (debug) {
                logger.info("Preparing local temp metadata");
                for (String metaSrc : metaSrcs) {
                    logger.info("Found one META_TEST_SRC: {}", new File(metaSrc).getCanonicalPath());
                }
                logger.info("TEMP_TEST_METADATA={}", new File(TEMP_TEST_METADATA).getCanonicalPath());
            }

            FileUtils.deleteQuietly(new File(dst));

            for (String metaSrc : metaSrcs) {
                FileUtils.copyDirectory(new File(metaSrc), new File(dst));
            }

            appendKylinProperties(dst);
            //overrideEngineTypeAndStorageType(TEMP_TEST_METADATA, grabDefaultEngineTypes(TEMP_TEST_METADATA), null);

            if (debug) {
                File copy = new File(dst + ".debug");
                FileUtils.deleteDirectory(copy);
                FileUtils.copyDirectory(new File(dst), copy);
                logger.info("Make copy for debug: {}", copy.getCanonicalPath());
            }

            return dst;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void appendKylinProperties(String tempMetadataDir) throws IOException {
        File propsFile = new File(tempMetadataDir, "kylin.properties");

        // append kylin.properties
        File appendFile = new File(tempMetadataDir, "kylin.properties.append");
        if (appendFile.exists()) {
            if (debug) {
                logger.info("Appending kylin.properties from {}", appendFile.getCanonicalPath());
            }

            String appendStr = FileUtils.readFileToString(appendFile, Charsets.UTF_8);
            FileUtils.writeStringToFile(propsFile, appendStr, Charsets.UTF_8, true);
            FileUtils.deleteQuietly(appendFile);
        }
    }

    private void overrideEngineTypeAndStorageType(String tempMetadataDir, Pair<Integer, Integer> typePair,
            List<String> includeFiles) throws IOException {
        int engineType = typePair.getFirst();
        int storageType = typePair.getSecond();

        if (debug) {
            logger.info("Override engine type to be {}", engineType);
            logger.info("Override storage type to be {}", storageType);
        }

        // re-write cube_desc/*.json
        File cubeDescDir = new File(tempMetadataDir, "cube_desc");
        File[] cubeDescFiles = cubeDescDir.listFiles();
        if (cubeDescFiles == null)
            return;

        for (File f : cubeDescFiles) {
            if (includeFiles != null && !includeFiles.contains(f.getName())) {
                continue;
            }
            if (debug) {
                logger.info("Process override {}", f.getCanonicalPath());
            }
            List<String> lines = FileUtils.readLines(f, Charsets.UTF_8);
            for (int i = 0, n = lines.size(); i < n; i++) {
                String l = lines.get(i);
                if (l.contains("\"engine_type\"")) {
                    lines.set(i, "  \"engine_type\" : " + engineType + ",");
                }
                if (l.contains("\"storage_type\"")) {
                    lines.set(i, "  \"storage_type\" : " + storageType + ",");
                }
            }
            FileUtils.writeLines(f, "UTF-8", lines);
        }
    }

    private Pair<Integer, Integer> grabDefaultEngineTypes(String tempMetadataDir) throws IOException {
        int engineType = -1;
        int storageType = -1;

        List<String> lines = FileUtils.readLines(new File(tempMetadataDir, "kylin.properties"), Charsets.UTF_8);
        for (String l : lines) {
            if (l.startsWith("kylin.engine.default")) {
                engineType = Integer.parseInt(l.substring(l.lastIndexOf('=') + 1).trim());
            }
            if (l.startsWith("kylin.storage.default")) {
                storageType = Integer.parseInt(l.substring(l.lastIndexOf('=') + 1).trim());
            }
        }

        if (debug) {
            logger.info("Grap from kylin.properties, engine type is {}", engineType);
            logger.info("Grap from kylin.properties, storage type is {}", storageType);
        }

        String tmp = System.getProperty("kylin.engine");
        if (!StringUtils.isBlank(tmp)) {
            engineType = Integer.parseInt(tmp.trim());
            if (debug) {
                logger.info("By system property, engine type is {}", engineType);
            }
        }
        tmp = System.getProperty("kylin.storage");
        if (!StringUtils.isBlank(tmp)) {
            storageType = Integer.parseInt(tmp.trim());
            if (debug) {
                logger.info("By system property, storage type is {}", storageType);
            }
        }

        if (engineType < 0 || storageType < 0)
            throw new IllegalStateException();

        return Pair.newPair(engineType, storageType);
    }

}


text:
using System.Collections.Generic;
using System.Linq;

namespace Octogami.Yahtzee.Application.Framework.DiceCombinationValidators
{
	public class DiceOfAKindValidator : IDiceOfAKindValidator
	{
		public bool IsValid(int numberOfDiceToMatch, IEnumerable<IDie> dice)
		{
			var values = dice.ToList();
			foreach (var uniqueValue in values.Select(x => x.Value).Distinct())
			{
				if (values.Count(x => x.Value == uniqueValue) >= numberOfDiceToMatch)
				{
					return true;
				}
			}

			return false;
		}
	}
}


text:
#ifdef WIN32
    #ifdef RHEXPORTLIB_EXPORTS
    #define RHEXPORTLIB_API __declspec(dllexport)
    #else
    #define RHEXPORTLIB_API __declspec(dllimport)
    #endif
#else
    #define RHEXPORTLIB_API
#endif

// This class is exported from the RHExportLib.dll
class RHEXPORTLIB_API CRHExportLib {
public:
	CRHExportLib(void);
	// TODO: add your methods here.
};

extern RHEXPORTLIB_API int nRHExportLib;

RHEXPORTLIB_API int fnRHExportLib(void);

#endif


text:
* qc.TimerEvent add(number delay=, function cb, object context, ...*)

## Parameters
| Parameter | Type | Description |
| ------------- | ------------- | -------------|
| delay | number | The number of milliseconds that should elapse before the callback is invoked. |
| cb | function | The callback that will be called when the Timer event occurs. |
| context | undefined、object | The context in which the callback will be called. |
| ...* | ...* | Additional arguments that will be supplied to the callback. |

## Description
Create a new timer event.

## Example
````
	var t = game.timer.add(1000, function() {
		console.log('Timer trigger.');
	})
````


text:
//Problem 5. Print Your Name
//Modify the previous application to print your name.

using System;
class PrintName
{
    static void Main()
    {
        Console.WriteLine("Dimitar");

    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * Team: jungle
 * User: Roma Baranenko
 * Contacts: <jungle.romabb8@gmail.com>
 * Date: 05.12.17
 * Time: 15:06
 */

namespace TelegramBotAPI\Traits;

/**
 * Trait ThumbHeightTrait
 * @package TelegramBotAPI\Traits
 * @author Roma Baranenko <jungle.romabb8@gmail.com>
 */
trait ThumbHeightTrait {

    /**
     * @var null|int $thumbHeight
     */
    protected $thumbHeight;

    /**
     * @return int|null
     */
    public function getThumbHeight() {
        return $this->thumbHeight;
    }

    /**
     * @param int|null $thumbHeight
     */
    public function setThumbHeight($thumbHeight) {
        $this->thumbHeight = $thumbHeight;
    }
}


text:
module.exports = {
	spread: true,
	destructuring: true
};


text:
import { Component, ViewChild } from "@angular/core";
import { Nav, Platform } from "ionic-angular";
import { StatusBar } from "@ionic-native/status-bar";
import { SplashScreen } from "@ionic-native/splash-screen";

import { HomeComponent } from "../components/home/home";
import { ListTaskComponent } from "../components/listTask/listTask";
import { LoginComponent } from "../components/login/login";
import { CreateTaskComponent } from "../components/createTask/createTask";
import { MyListTaskComponent } from "../components/myListTask/myListTask";

// import { SearchComponent } from '../components/search/search';
// import { SettingsComponent } from '../components/settings/settings';
// import { HelpComponent } from '../components/help/help';

@Component({
  templateUrl: "app.html"
})
export class KNGKEngineer {
  @ViewChild(Nav) public nav: Nav;

  public rootPage: any = LoginComponent; // HomeComponent;
  public lastPage: any = HomeComponent;

  public pages: Array<{ title: string; component: any }>;

  constructor(
    public platform: Platform,
    public statusBar: StatusBar,
    public splashScreen: SplashScreen
  ) {
    this.initializeApp();

    // used for an example of ngFor and navigation
    this.pages = [
      { title: "Домашняя страница", component: HomeComponent },
      { title: "Все заявки", component: ListTaskComponent },
      { title: "Заявки выполняемые мною", component: MyListTaskComponent },
      // { title: 'Поиск заявки', component: SearchComponent },
      { title: "Создать заявку", component: CreateTaskComponent },
      // { title: 'Настройки', component: SettingsComponent },
      // { title: 'Справка', component: HelpComponent },

      { title: "Выход", component: LoginComponent }
    ];
  }

  public initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });
  }

  public openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
  }
}


text:
#region license

#endregion

using System;
using System.Runtime.InteropServices;

namespace DirectShowLib.MultimediaStreaming
{
    #region Interfaces

#if ALLOW_UNTESTED_INTERFACES

    [ComImport, System.Security.SuppressUnmanagedCodeSecurity,
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
    Guid("327FC560-AF60-11D0-8212-00C04FC32C45")]
    public interface IMemoryData
    {
        [PreserveSig]
        int SetBuffer(
            [In] int cbSize,
            [In] IntPtr pbData,
            [In] int dwFlags
            );

        [PreserveSig]
        int GetInfo(
            out int pdwLength,
            [Out] IntPtr ppbData,
            out int pcbActualData
            );

        [PreserveSig]
        int SetActual(
            [In] int cbDataValid
            );
    }

    [ComImport, System.Security.SuppressUnmanagedCodeSecurity,
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
    Guid("54C719C0-AF60-11D0-8212-00C04FC32C45")]
    public interface IAudioData : IMemoryData
    {
        #region IMemoryData Methods

        [PreserveSig]
        new int SetBuffer(
            [In] int cbSize,
            [In] IntPtr pbData,
            [In] int dwFlags
            );

        [PreserveSig]
        new int GetInfo(
            out int pdwLength,
            [Out] IntPtr ppbData,
            out int pcbActualData
            );

        [PreserveSig]
        new int SetActual(
            [In] int cbDataValid
            );

        #endregion

        [PreserveSig]
        int GetFormat(
            [Out] WaveFormatEx pWaveFormatCurrent
            );

        [PreserveSig]
        int SetFormat(
            [In, MarshalAs(UnmanagedType.LPStruct)] WaveFormatEx lpWaveFormat
            );
    }

    [ComImport, System.Security.SuppressUnmanagedCodeSecurity,
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
    Guid("345FEE00-ABA5-11D0-8212-00C04FC32C45")]
    public interface IAudioStreamSample : IStreamSample
    {
        #region IStreamSample Methods

        [PreserveSig]
        new int GetMediaStream(
            [MarshalAs(UnmanagedType.Interface)] out IMediaStream ppMediaStream
            );

        [PreserveSig]
        new int GetSampleTimes(
            out long pStartTime,
            out long pEndTime,
            out long pCurrentTime
            );

        [PreserveSig]
        new int SetSampleTimes(
            [In] DsLong pStartTime,
            [In] DsLong pEndTime
            );

        [PreserveSig]
        new int Update(
            [In] SSUpdate dwFlags,
            [In] IntPtr hEvent,
            [In] IntPtr pfnAPC,
            [In] IntPtr dwAPCData
            );

        [PreserveSig]
        new int CompletionStatus(
            [In] CompletionStatusFlags dwFlags,
            [In] int dwMilliseconds
            );

        #endregion

        [PreserveSig]
        int GetAudioData(
            [MarshalAs(UnmanagedType.Interface)] out IAudioData ppAudio
            );
    }

#endif

    [ComImport, System.Security.SuppressUnmanagedCodeSecurity,
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
    Guid("F7537560-A3BE-11D0-8212-00C04FC32C45")]
    public interface IAudioMediaStream : IMediaStream
    {
        #region IMediaStream Methods

        [PreserveSig]
        new int GetMultiMediaStream(
            [MarshalAs(UnmanagedType.Interface)] out IMultiMediaStream ppMultiMediaStream
            );

        [PreserveSig]
        new int GetInformation(
            out Guid pPurposeId,
            out StreamType pType);

        [PreserveSig]
        new int SetSameFormat(
            [In, MarshalAs(UnmanagedType.Interface)] IMediaStream pStreamThatHasDesiredFormat,
            [In] int dwFlags);

        [PreserveSig]
        new int AllocateSample(
            [In] int dwFlags,
            [MarshalAs(UnmanagedType.Interface)] out IStreamSample ppSample
            );

        [PreserveSig]
        new int CreateSharedSample(
            [In, MarshalAs(UnmanagedType.Interface)] IStreamSample pExistingSample,
            [In] int dwFlags,
            [MarshalAs(UnmanagedType.Interface)] out IStreamSample ppNewSample
            );

        [PreserveSig]
        new int SendEndOfStream(
            int dwFlags
            );

        #endregion

        [PreserveSig]
        int GetFormat(
            [Out, MarshalAs(UnmanagedType.LPStruct)] WaveFormatEx pWaveFormatCurrent
            );

        [PreserveSig]
        int SetFormat(
            [In] WaveFormatEx lpWaveFormat
            );

        [PreserveSig]
        int CreateSample(
#if ALLOW_UNTESTED_INTERFACES
            [In, MarshalAs(UnmanagedType.Interface)] IAudioData pAudioData,
            [In] int dwFlags,
            [MarshalAs(UnmanagedType.Interface)] out IAudioStreamSample ppSample
#else
            [In, MarshalAs(UnmanagedType.Interface)] object pAudioData,
            [In] int dwFlags,
            [MarshalAs(UnmanagedType.Interface)] out object ppSample
#endif
            );
    }

    #endregion
}


text:
#	include "oolua_tests_pch.h"
#	include "oolua.h"
#	include "common_cppunit_headers.h"
#	include <sstream>
#	include "expose_stub_classes.h"

namespace
{
	template<typename T>
	std::string stringify(T const& t)
	{
		std::stringstream ss;
		ss <<t;
		return ss.str();
	}
	template<typename T>
	void table_containing_key_value_pair(OOLUA::Script * lvm, OOLUA::Table* t, std::string const& key, T& value)
	{
		lvm->run_chunk(
			std::string("func = function() ")
				+std::string("t = {} ")
				+std::string("t[\"") + key + std::string("\"]=") + stringify(value)
				+std::string(" return t ")
			+std::string("end") );

		lvm->call("func");
		OOLUA::pull(*lvm, *t);
	}
	void assign_valid_table(OOLUA::Script* s, OOLUA::Table& t)
	{
		s->register_class<Stub1>();
		lua_getfield(*s, LUA_REGISTRYINDEX, OOLUA::Proxy_class<Stub1>::class_name);
		OOLUA::pull(*s, t);
	}

	int stackNotEmptyCalled = 0;
	void callBackFunc_stackNotEmpty(lua_State* /*DontCare*/) //NOLINT(readability/casting)
	{
		stackNotEmptyCalled = 1;
	}

	struct MemberCallBack
	{
		int called;
		MemberCallBack()
			: called(0)
		{}
		void call_back(lua_State* vm)
		{
			called += 1;
			lua_pop(vm, 1);
		}
	};
} // namespace

class Table : public CPPUNIT_NS::TestFixture
{
	CPPUNIT_TEST_SUITE(Table);
		CPPUNIT_TEST(at_checkForKeyWhichIsValid_valueComparesEqualToInput);
		CPPUNIT_TEST(safeAt_checkForKeyWhichIsInvalid_returnsFalse);
		CPPUNIT_TEST(safeAt_checkForKeyWhichIsValid_valueComparesEqual);
		CPPUNIT_TEST(safeAt_checkForKeyWhichIsValid_returnsTrue);

		CPPUNIT_TEST(safeAt_checkForInvalidKeyWhichIsATableFromADifferentLuaState_returnsFalse);

		CPPUNIT_TEST(remove_valueWhichIsValid_safeAtReturnsFalse);
		CPPUNIT_TEST(pull_pullValidTableOffStack_stackIsEmptyAfterCall);
		CPPUNIT_TEST(getTable_pullValidTableOffStackAndCallFunc_stackSizeIsOne);
		CPPUNIT_TEST(valid_pullValidTableOffStackAndCallFunc_resultIsTrue);
		CPPUNIT_TEST(valid_pullValidTableOffStackAndCallFunc_stackIsEmptyAfterCall);
		CPPUNIT_TEST(valid_assignedNullLuaPointer_resultIsFalse);
		CPPUNIT_TEST(valid_defaultConstructed_resultIsFalse);
		CPPUNIT_TEST(valid_constructedWithValidLuaPointAndValidGlobalName_resultIsTrue);
		CPPUNIT_TEST(valid_assignedNullLuaPointer_resultIsFalse);
		CPPUNIT_TEST(valid_assignedValidLuaPointer_resultIsFalse);
		CPPUNIT_TEST(valid_assignedValidLuaPointerAndValidGlobalName_resultIsTrue);
		CPPUNIT_TEST(valid_assignedValidLuaPointerAndValidGlobalName_stackIsEmptyAfterCall);

		CPPUNIT_TEST(newTable_callValidOnTable_returnsTrue);
		CPPUNIT_TEST(newTable_checkStack_stackIsEmpty);
		CPPUNIT_TEST(newTable_constructAndCheckStack_afterCallStackIsEmpty);
		CPPUNIT_TEST(newTable_fromCplusplus_validReturnsTrue);

		CPPUNIT_TEST(copyConstruct_usingNewTable_copyIsValid);
		CPPUNIT_TEST(copyConstruct_usingNewTable_orginalIsValid);
		CPPUNIT_TEST(copyConstruct_usingInvalidTable_copyIsNotValid);

		CPPUNIT_TEST(tableSetValue_tableIsOnTop_storedValueIsCorrect);
		CPPUNIT_TEST(tableSetValue_tableIsOnTop_afterCallStackHasOneEntry);

		CPPUNIT_TEST(setValue_valueSetInLua_cppSideRepresentationHasChange);

		CPPUNIT_TEST(table_reference_is_unquie_for_the_instance);

		CPPUNIT_TEST(construct_LuaTableFromLuaTableRef_compiles);

		CPPUNIT_TEST(valid_assignedValidLuaPointerAndInvalidName_resultIsFalse);

		CPPUNIT_TEST(valid_assignedValidLuaPointerAndEmptyStringName_resultIsFalse);

		CPPUNIT_TEST(bindScript_tableReferenceIsAlreadyValid_validReturnsFalse);

		CPPUNIT_TEST(bindScript_tableReferenceIsAlreadyBoundWithThisState_validReturnsTrue);

		CPPUNIT_TEST(traverse_stackIsNotEmpty_callBackIsCalled);
		CPPUNIT_TEST(forEachKeyValue_stackIsNotEmpty_callBackIsCalled);

		CPPUNIT_TEST(ipairs_stackIsNotEmptyTableHasOneEntry_IterationCountIsOne);
		CPPUNIT_TEST(ipairs_stackIsNotEmptyTableHasFiveEntry_IterationCountIsFive);
		CPPUNIT_TEST(ipairs_stackHasOneEntryTableHasFiveEntry_afterIterationsStackCountIsOne);

		CPPUNIT_TEST(assignment_selfAssignmentOnValidTable_refIsRegistryCopyOfOriginalValue);
		CPPUNIT_TEST(newTable_callingTheModuleFunctionNewTable_returnTypeIsATable);
	CPPUNIT_TEST_SUITE_END();

	OOLUA::Script * m_lua;
	OOLUA::Table* table;
public:
	Table()
		: m_lua(0)
		, table(0)
	{}
	Table(Table const&);
	Table& operator =(Table const&);
	void setUp()
	{
		m_lua = new OOLUA::Script;
		table = new OOLUA::Table;
	}
	void tearDown()
	{
		delete table;
		delete m_lua;
	}

	void at_checkForKeyWhichIsValid_valueComparesEqualToInput()
	{
		int input(1);
		int value(0);
		table_containing_key_value_pair(m_lua, table, "key", input);
		table->at("key", value);
		CPPUNIT_ASSERT_EQUAL(input, value);
	}

	void safeAt_checkForKeyWhichIsInvalid_returnsFalse()
	{
		m_lua->run_chunk(
			"func = function()"
				"t = {} "
				"return t "
			"end");
		m_lua->call("func");
		OOLUA::pull(*m_lua, *table);
		int value(0);
		CPPUNIT_ASSERT_EQUAL(false, table->safe_at("key", value));
	}

	void safeAt_checkForInvalidKeyWhichIsATableFromADifferentLuaState_returnsFalse()
	{
		OOLUA::new_table(*m_lua, *table);
		OOLUA::Script s;
		OOLUA::Table t;
		OOLUA::new_table(s, t);
		int value(0);
		CPPUNIT_ASSERT_EQUAL(false, table->safe_at(t, value));
	}

	void safeAt_checkForKeyWhichIsValid_returnsTrue()
	{
		int input(1);
		int value(0);
		table_containing_key_value_pair(m_lua, table, "key", input);
		CPPUNIT_ASSERT_EQUAL(true, table->safe_at("key", value));
	}

	void safeAt_checkForKeyWhichIsValid_valueComparesEqual()
	{
		int input(1);
		int value(0);
		table_containing_key_value_pair(m_lua, table, "key", input);
		table->safe_at("key", value);
		CPPUNIT_ASSERT_EQUAL(input, value);
	}

	void remove_valueWhichIsValid_safeAtReturnsFalse()
	{
		int input(1);
		int value(0);
		table_containing_key_value_pair(m_lua, table, "key", input);
		table->remove("key");
		CPPUNIT_ASSERT_EQUAL(false, table->safe_at("key", value) );
	}

	void pull_pullValidTableOffStack_stackIsEmptyAfterCall()
	{
		assign_valid_table(m_lua, *table);
		CPPUNIT_ASSERT_EQUAL(int(0), lua_gettop(*m_lua)); //NOLINT(readability/casting)
	}

	void getTable_pullValidTableOffStackAndCallFunc_stackSizeIsOne()
	{
		assign_valid_table(m_lua, *table);
		table->push_on_stack(*m_lua);
		CPPUNIT_ASSERT_EQUAL(int(1), lua_gettop(*m_lua)); //NOLINT(readability/casting)
	}

	void valid_pullValidTableOffStackAndCallFunc_resultIsTrue()
	{
		assign_valid_table(m_lua, *table);
		CPPUNIT_ASSERT_EQUAL(true, table->valid());
	}

	void valid_pullValidTableOffStackAndCallFunc_stackIsEmptyAfterCall()
	{
		assign_valid_table(m_lua, *table);
		table->valid();
		CPPUNIT_ASSERT_EQUAL(int(0), lua_gettop(*m_lua)); //NOLINT(readability/casting)
	}

	void valid_defaultConstructed_resultIsFalse()
	{
		CPPUNIT_ASSERT_EQUAL(false, table->valid());
	}

	void valid_constructedWithValidLuaPointAndValidGlobalName_resultIsTrue()
	{
		m_lua->register_class<Stub1>();
		OOLUA::Table t(*m_lua, OOLUA::Proxy_class<Stub1>::class_name);
		CPPUNIT_ASSERT_EQUAL(true, t.valid());
	}

	void valid_assignedNullLuaPointer_resultIsFalse()
	{
		table->bind_script(0);
		CPPUNIT_ASSERT_EQUAL(false, table->valid());
	}

	void valid_assignedValidLuaPointer_resultIsFalse()
	{
		table->bind_script(*m_lua);
		CPPUNIT_ASSERT_EQUAL(false, table->valid());
	}

	void valid_assignedValidLuaPointerAndValidGlobalName_resultIsTrue()
	{
		m_lua->register_class<Stub1>();
		table->bind_script(*m_lua);
		table->set_table(OOLUA::Proxy_class<Stub1>::class_name);
		CPPUNIT_ASSERT_EQUAL(true, table->valid());
	}

	void valid_assignedValidLuaPointerAndValidGlobalName_stackIsEmptyAfterCall()
	{
		m_lua->register_class<Stub1>();
		table->bind_script(*m_lua);
		table->set_table(OOLUA::Proxy_class<Stub1>::class_name);
		table->valid();
		CPPUNIT_ASSERT_EQUAL(0, lua_gettop(*m_lua));
	}

	void valid_assignedValidLuaPointerAndInvalidName_resultIsFalse()
	{
		table->bind_script(*m_lua);
		table->set_table("Does not exist");
		CPPUNIT_ASSERT_EQUAL(false, table->valid() );
	}

	void valid_assignedValidLuaPointerAndEmptyStringName_resultIsFalse()
	{
		table->bind_script(*m_lua);
		table->set_table("");
		CPPUNIT_ASSERT_EQUAL(false, table->valid());
	}

	void newTable_callValidOnTable_returnsTrue()
	{
		CPPUNIT_ASSERT_EQUAL(true, OOLUA::new_table(*m_lua).valid());
	}

	void newTable_checkStack_stackIsEmpty()
	{
		OOLUA::new_table(*m_lua);
		int stackSize = lua_gettop(*m_lua);
		CPPUNIT_ASSERT_EQUAL(0, stackSize);
	}

	void newTable_fromCplusplus_validReturnsTrue()
	{
		OOLUA::Table t;
		OOLUA::new_table(*m_lua, t);
		CPPUNIT_ASSERT_EQUAL(true, t.valid());
	}

	void newTable_constructAndCheckStack_afterCallStackIsEmpty()
	{
		OOLUA::Table t;
		OOLUA::new_table(*m_lua, t);
		int stackSize = lua_gettop(*m_lua);
		CPPUNIT_ASSERT_EQUAL(0, stackSize);
	}

	void copyConstruct_usingNewTable_orginalIsValid()
	{
		OOLUA::Table orignal;
		OOLUA::new_table(*m_lua, orignal);
		OOLUA::Table copy(orignal);

		CPPUNIT_ASSERT_EQUAL(true, orignal.valid());
	}

	void copyConstruct_usingNewTable_copyIsValid()
	{
		OOLUA::Table copy(OOLUA::new_table(*m_lua));
		CPPUNIT_ASSERT_EQUAL(true, copy.valid());
	}

	void copyConstruct_usingInvalidTable_copyIsNotValid()
	{
		OOLUA::Table invalid;
		OOLUA::Table copy(invalid);
		CPPUNIT_ASSERT_EQUAL(false, copy.valid());
	}

	void tableSetValue_tableIsOnTop_storedValueIsCorrect()
	{
		OOLUA::Table t;
		OOLUA::new_table(*m_lua, t);
		t.push_on_stack(*m_lua);
		OOLUA::table_set_value(*m_lua, -1, "a", 0);
		int storedValue(1);
		t.at("a", storedValue);
		lua_pop(*m_lua, 1);
		CPPUNIT_ASSERT_EQUAL(0, storedValue);
	}

	void tableSetValue_tableIsOnTop_afterCallStackHasOneEntry()
	{
		OOLUA::Table t;
		OOLUA::new_table(*m_lua, t);
		t.push_on_stack(*m_lua);
		OOLUA::table_set_value(*m_lua, -1, "a", 1);
		int stackSize = lua_gettop(*m_lua);
		CPPUNIT_ASSERT_EQUAL(1, stackSize);
	}

	/**[OOLuaTableAtExample]*/
	void setValue_valueSetInLua_cppSideRepresentationHasChange()
	{
		OOLUA::Table t;
		OOLUA::new_table(*m_lua, t);

		m_lua->run_chunk("func = function(t) t['a'] = 1; end");
		m_lua->call("func", t);

		int storedValue(0);
		t.at("a", storedValue);
		CPPUNIT_ASSERT_EQUAL(1, storedValue);
	}
	/**[OOLuaTableAtExample]*/

	void table_reference_is_unquie_for_the_instance()
	{
		lua_newtable(*m_lua);
		int tableRef = luaL_ref(*m_lua, LUA_REGISTRYINDEX);
		lua_rawgeti(*m_lua, LUA_REGISTRYINDEX, tableRef);
		int tableRef2 = luaL_ref(*m_lua, LUA_REGISTRYINDEX);

		CPPUNIT_ASSERT_EQUAL(true, tableRef != tableRef2);
	}

	void construct_LuaTableFromLuaTableRef_compiles()
	{
		m_lua->run_chunk("func = function() local t={} return t end");
		m_lua->call("func");
		OOLUA::Lua_table_ref ref;
		OOLUA::pull(*m_lua, ref);
		OOLUA::Table t(ref);
	}

	/*
	 table references are only valid for there own vm
	 */
	void bindScript_tableReferenceIsAlreadyValid_validReturnsFalse()
	{
		OOLUA::Table table_;
		OOLUA::new_table(*m_lua, table_);
		OOLUA::Script another_lua_instance;
		table_.bind_script(another_lua_instance);
		CPPUNIT_ASSERT_EQUAL(false, table_.valid());
	}

	void bindScript_tableReferenceIsAlreadyBoundWithThisState_validReturnsTrue()
	{
		OOLUA::Table table_;
		OOLUA::new_table(*m_lua, table_);
		table_.bind_script(*m_lua);
		CPPUNIT_ASSERT_EQUAL(true, table_.valid());
	}

	void traverse_stackIsNotEmpty_callBackIsCalled()
	{
		OOLUA::push(*m_lua, 1);

		OOLUA::Table table_;
		OOLUA::new_table(*m_lua, table_);
		table_.set(1, 1);
		stackNotEmptyCalled = 0;
		table_.traverse(callBackFunc_stackNotEmpty);
		CPPUNIT_ASSERT_EQUAL(int(1), stackNotEmptyCalled); //NOLINT(readability/casting)
	}

	void forEachKeyValue_stackIsNotEmpty_callBackIsCalled()
	{
		OOLUA::push(*m_lua, 1);
		OOLUA::Table table_;
		OOLUA::new_table(*m_lua, table_);
		table_.set(1, 1);

		MemberCallBack l;
		OOLUA::for_each_key_value(table_, &l, &MemberCallBack::call_back);
		CPPUNIT_ASSERT_EQUAL(int(1), l.called); //NOLINT(readability/casting)
	}

	void ipairs_stackIsNotEmptyTableHasOneEntry_IterationCountIsOne()
	{
		OOLUA::push(*m_lua, 1);
		OOLUA::Table table_;
		OOLUA::new_table(*m_lua, table_);
		table_.set(1, 1);

		int count = 0;
		oolua_ipairs(table_)
		{
			count += 1;
		}
		oolua_ipairs_end()
		CPPUNIT_ASSERT_EQUAL(int(1), count); //NOLINT(readability/casting)
	}

	void ipairs_stackIsNotEmptyTableHasFiveEntry_IterationCountIsFive()
	{
		OOLUA::push(*m_lua, 1);
		OOLUA::Table table_;
		OOLUA::new_table(*m_lua, table_);

		for(int i = 1; i < 6; ++i) table_.set(i, i);

		int count = 0;
		oolua_ipairs(table_)
		{
			count += 1;
		}
		oolua_ipairs_end()
		CPPUNIT_ASSERT_EQUAL(int(5), count); //NOLINT(readability/casting)
	}

	void ipairs_stackHasOneEntryTableHasFiveEntry_afterIterationsStackCountIsOne()
	{
		OOLUA::push(*m_lua, 1);
		OOLUA::Table table_;
		OOLUA::new_table(*m_lua, table_);

		for(int i = 1; i < 6; ++i) table_.set(i, i);

		oolua_ipairs(table_)
		{
			//nop
		}
		oolua_ipairs_end()
		CPPUNIT_ASSERT_EQUAL(int(1), lua_gettop(*m_lua)); //NOLINT(readability/casting)
	}

	void assignment_selfAssignmentOnValidTable_refIsRegistryCopyOfOriginalValue()
	{
		OOLUA::Table t;
		OOLUA::new_table(*m_lua, t);

		//put the instance on the stack to compare after the assignment
		m_lua->push(t);

		t = t;
		m_lua->push(t);
		CPPUNIT_ASSERT_EQUAL(1, lua_rawequal(*m_lua, -1, -2));
	}
	void newTable_callingTheModuleFunctionNewTable_returnTypeIsATable()
	{
		m_lua->run_chunk("local OOLua = require('OOLua') "
						"return OOLua.new_table()");
		CPPUNIT_ASSERT_EQUAL(LUA_TTABLE, lua_type(*m_lua, -1));
	}
};

CPPUNIT_TEST_SUITE_REGISTRATION(Table);


text:
/**
 * @requires SuperMap/Handler.js
 */

/**
 * Class: SuperMap.Handler.Drag
 * 拖拽事件的事件处理器,用来处理与拖拽有关的一系列浏览器事件。控件使用该处理器获知拖拽事件的开始,发生和结束。
 *
 * 使用拖拽事件处理器的控件通常要构建针对 down 、move和done事件的回调。这些对应key值的回调函数会在拖拽开始,
 * 每一次拖拽过程,拖拽结束时被分别调用。此外,如果用户区分符合拖拽序列结束的事件类型,
 * 控件也可以对key值为"up"和"out"的事件进行
 * 回调。如果拖拽没有发生(鼠标没有移动),那么"down"和"up"回调将被调用,但是拖拽"done"回调函数不会被调用。
 *
 * Inherits from:
 *  - <SuperMap.Handler>
 */
SuperMap.Handler.Drag = SuperMap.Class(SuperMap.Handler, {

    /**
     * Property: started
     * {Boolean} When a mousedown or touchstart event is received, we want to
     * record it, but not set 'dragging' until the mouse moves after starting.
     */
    started: false,

    /**
     * Property: stopDown
     * {Boolean} Stop propagation of mousedown events from getting to listeners
     *     on the same element.  Default is true.
     */
    stopDown: true,

    /**
     * Property: dragging
     * {Boolean}
     */
    dragging: false,

    /**
     * Property: touch
     * {Boolean} When a touchstart event is fired, touch will be true and all
     *     mouse related listeners will do nothing.
     */
    touch: false,

    /**
     * Property: last
     * {<SuperMap.Pixel>} The last pixel location of the drag.
     */
    last: null,

    /**
     * Property: start
     * {<SuperMap.Pixel>} The first pixel location of the drag.
     */
    start: null,

    /**
     * Property: lastMoveEvt
     * {Object} The last mousemove event that occurred. Used to
     *     position the map correctly when our "delay drag"
     *     timeout expired.
     */
    lastMoveEvt: null,

    /**
     * Property: oldOnselectstart
     * {Function}
     */
    oldOnselectstart: null,

    /**
     * Property: interval
     * {Integer} In order to increase performance, an interval (in
     *     milliseconds) can be set to reduce the number of drag events
     *     called. If set, a new drag event will not be set until the
     *     interval has passed.
     *     Defaults to 0, meaning no interval.
     */
    interval: 0,

    /**
     * Property: timeoutId
     * {String} The id of the timeout used for the mousedown interval.
     *     This is "private", and should be left alone.
     */
    timeoutId: null,

    /**
     * APIProperty: documentDrag
     * {Boolean} 如果设置为true,则当鼠标移出当前map的viewport范围后当前事件处理器对象仍然会处理鼠标move事件。默认值为 false。
     *
     */
    documentDrag: false,

    /**
     * Property: documentEvents
     * {Boolean} Are we currently observing document events?
     */
    documentEvents: null,

    /**
     * Constructor: SuperMap.Handler.Drag
     * 构造函数,创建一个拖拽事件对象。
     *
     * Parameters:
     * control - {<SuperMap.Control>} 构建事件的控件,如果该事件没有被控件使用,
     * 那么必须明确调用setMap方法给当前事件赋予一个有效值。
     * callbacks - {Object} 回调函数对象,包含一个供拖拽事件完成时调用的回调函数。
     * 回调函数接受当前鼠标事件event对象作为唯一参数。
     * 也可以添加对"move"和"done"的回调。也可以明确添加对"down"、"up"、"out"的回调来响应处理这些事件。
     * options - {Object} 一个可选对象,其属性将会赋值到事件处理器对象上。
     */
    initialize: function (control, callbacks, options) {
        SuperMap.Handler.prototype.initialize.apply(this, arguments);

        if (this.documentDrag === true) {
            var me = this;
            this._docMove = function (evt) {
                me.mousemove({
                    xy: {x: evt.clientX, y: evt.clientY},
                    element: document
                });
            };
            this._docUp = function (evt) {
                me.mouseup({xy: {x: evt.clientX, y: evt.clientY}});
            };
        }
    },

    /**
     * Method: dragstart
     * This private method is factorized from mousedown and touchstart methods
     *
     * Parameters:
     * evt - {Event} The event
     *
     * Returns:
     * {Boolean} Let the event propagate.
     */
    dragstart: function (evt) {
        var propagate = true;
        this.dragging = false;
        if (this.checkModifiers(evt) &&
            (SuperMap.Event.isLeftClick(evt) ||
            SuperMap.Event.isSingleTouch(evt)) && !SuperMap.isApp) {
            this.started = true;
            this.start = evt.xy;
            this.last = evt.xy;
            //设置拖动时的鼠标样式
            SuperMap.Element.addClass(
                this.map.viewPortDiv, "smDragDown");
            var imagesLocation = SuperMap.Util.getImagesLocation();
            this.map.viewPortDiv.style.cursor = "url('" + imagesLocation + "cursors/PanDown.cur'),move";
            this.down(evt);
            this.callback("down", [evt.xy]);

            SuperMap.Event.stop(evt);

            if (!this.oldOnselectstart) {
                this.oldOnselectstart = document.onselectstart ?
                    document.onselectstart : SuperMap.Function.True;
            }
            document.onselectstart = SuperMap.Function.False;

            propagate = !this.stopDown;
        } else {
            if (this.started && SuperMap.Event.isRightClick(evt)) {
                document.oncontextmenu = function () {
                    return false;
                };
                this.out(evt);
                this.callback("out", []);
                propagate = false;
            } else {
                document.oncontextmenu = function () {
                    return true;
                };
            }
            this.started = false;
            this.start = null;
            this.last = null;

        }
        return propagate;
    },

    /**
     * Method: dragmove
     * This private method is factorized from mousemove and touchmove methods
     *
     * Parameters:
     * evt - {Event} The event
     *
     * Returns:
     * {Boolean} Let the event propagate.
     */
    dragmove: function (evt) {
        this.lastMoveEvt = evt;
        if (this.started && !this.timeoutId && (evt.xy.x !== this.last.x ||
            evt.xy.y !== this.last.y)) {
            if (this.documentDrag === true && this.documentEvents) {
                if (evt.element === document) {
                    this.adjustXY(evt);
                    // do setEvent manually because the documentEvents are not
                    // registered with the map
                    this.setEvent(evt);
                } else {
                    this.removeDocumentEvents();
                }
            }
            if (this.interval > 0) {
                this.timeoutId = setTimeout(
                    SuperMap.Function.bind(this.removeTimeout, this),
                    this.interval);
            }
            this.dragging = true;

            this.move(evt);
            this.callback("move", [evt.xy]);
            if (!this.oldOnselectstart) {
                this.oldOnselectstart = document.onselectstart;
                document.onselectstart = SuperMap.Function.False;
            }
            this.last = evt.xy;
        }
        return true;
    },

    /**
     * Method: dragend
     * This private method is factorized from mouseup and touchend methods
     *
     * Parameters:
     * evt - {Event} The event
     *
     * Returns:
     * {Boolean} Let the event propagate.
     */
    dragend: function (evt) {
        if (this.started) {
            if (this.documentDrag === true && this.documentEvents) {
                this.adjustXY(evt);
                this.removeDocumentEvents();
            }
            var dragged = (this.start !== this.last);
            this.started = false;
            this.dragging = false;
            //设置拖动完成后的鼠标样式
            SuperMap.Element.removeClass(
                this.map.viewPortDiv, "smDragDown");
            this.map.viewPortDiv.style.cursor = "";

            this.up(evt);
            this.callback("up", [evt.xy]);
            if (dragged) {
                this.callback("done", [evt.xy]);
            }
            document.onselectstart = this.oldOnselectstart;
        }
        return true;
    },

    /**
     * The four methods below (down, move, up, and out) are used by subclasses
     *     to do their own processing related to these mouse events.
     */

    /**
     * Method: down
     * This method is called during the handling of the mouse down event.
     *     Subclasses can do their own processing here.
     *
     * Parameters:
     * evt - {Event} The mouse down event
     */
    down: function (evt) {
    },

    /**
     * Method: move
     * This method is called during the handling of the mouse move event.
     *     Subclasses can do their own processing here.
     *
     * Parameters:
     * evt - {Event} The mouse move event
     *
     */
    move: function (evt) {
    },

    /**
     * Method: up
     * This method is called during the handling of the mouse up event.
     *     Subclasses can do their own processing here.
     *
     * Parameters:
     * evt - {Event} The mouse up event
     */
    up: function (evt) {
    },

    /**
     * Method: out
     * This method is called during the handling of the mouse out event.
     *     Subclasses can do their own processing here.
     *
     * Parameters:
     * evt - {Event} The mouse out event
     */
    out: function (evt) {
    },

    /**
     * The methods below are part of the magic of event handling.  Because
     *     they are named like browser events, they are registered as listeners
     *     for the events they represent.
     */

    /**
     * Method: mousedown
     * Handle mousedown events
     *
     * Parameters:
     * evt - {Event}
     *
     * Returns:
     * {Boolean} Let the event propagate.
     */
    mousedown: function (evt) {
        return this.dragstart(evt);
    },

    /**
     * Method: touchstart
     * Handle touchstart events
     *
     * Parameters:
     * evt - {Event}
     *
     * Returns:
     * {Boolean} Let the event propagate.
     */
    touchstart: function (evt) {
        if (!this.touch) {
            this.touch = true;
            // unregister mouse listeners
            this.map.events.un({
                mousedown: this.mousedown,
                mouseup: this.mouseup,
                mousemove: this.mousemove,
                click: this.click,
                scope: this
            });
        }
        return this.dragstart(evt);
    },

    /**
     * Method: mousemove
     * Handle mousemove events
     *
     * Parameters:
     * evt - {Event}
     *
     * Returns:
     * {Boolean} Let the event propagate.
     */
    mousemove: function (evt) {
        return this.dragmove(evt);
    },

    /**
     * Method: touchmove
     * Handle touchmove events
     *
     * Parameters:
     * evt - {Event}
     *
     * Returns:
     * {Boolean} Let the event propagate.
     */
    touchmove: function (evt) {
        return this.dragmove(evt);
    },

    /**
     * Method: removeTimeout
     * Private. Called by mousemove() to remove the drag timeout.
     */
    removeTimeout: function () {
        this.timeoutId = null;
        // if timeout expires while we're still dragging (mouseup
        // hasn't occurred) then call mousemove to move to the
        // correct position
        if (this.dragging) {
            this.mousemove(this.lastMoveEvt);
        }
    },

    /**
     * Method: mouseup
     * Handle mouseup events
     *
     * Parameters:
     * evt - {Event}
     *
     * Returns:
     * {Boolean} Let the event propagate.
     */
    mouseup: function (evt) {
        return this.dragend(evt);
    },

    /**
     * Method: touchend
     * Handle touchend events
     *
     * Parameters:
     * evt - {Event}
     *
     * Returns:
     * {Boolean} Let the event propagate.
     */
    touchend: function (evt) {
        // override evt.xy with last position since touchend does not have
        // any touch position
        evt.xy = this.last;
        return this.dragend(evt);
    },

    /**
     * Method: mouseout
     * Handle mouseout events
     *
     * Parameters:
     * evt - {Event}
     *
     * Returns:
     * {Boolean} Let the event propagate.
     */
    mouseout: function (evt) {
        if (this.started && SuperMap.Util.mouseLeft(evt, this.map.eventsDiv)) {
            if (this.documentDrag === true) {
                this.addDocumentEvents();
            } else {
                var dragged = (this.start !== this.last);
                this.started = false;
                this.dragging = false;
                //设置拖动鼠标出地图后的鼠标样式
                SuperMap.Element.removeClass(
                    this.map.viewPortDiv, "smDragDown");
                var imagesLocation = SuperMap.Util.getImagesLocation();
                this.map.viewPortDiv.style.cursor = "url('" + imagesLocation + "cursors/Pan.cur'),default";

                this.out(evt);
                this.callback("out", [evt]);
                if (dragged) {
                    this.callback("done", [evt.xy]);
                }
                if (document.onselectstart) {
                    document.onselectstart = this.oldOnselectstart;
                }
            }
        }
        return true;
    },

    /**
     * Method: click
     * The drag handler captures the click event.  If something else registers
     *     for clicks on the same element, its listener will not be called
     *     after a drag.
     *
     * Parameters:
     * evt - {Event}
     *
     * Returns:
     * {Boolean} Let the event propagate.
     */
    click: function (evt) {
        // let the click event propagate only if the mouse moved
        return (this.start === this.last);
    },

    /**
     * Method: activate
     * Activate the handler.
     *
     * Returns:
     * {Boolean} The handler was successfully activated.
     */
    activate: function () {
        var activated = false;
        if (SuperMap.Handler.prototype.activate.apply(this, arguments)) {
            this.dragging = false;
            activated = true;
        }
        return activated;
    },

    /**
     * Method: deactivate
     * Deactivate the handler.
     *
     * Returns:
     * {Boolean} The handler was successfully deactivated.
     */
    deactivate: function () {
        var deactivated = false;
        if (SuperMap.Handler.prototype.deactivate.apply(this, arguments)) {
            this.touch = false;
            this.started = false;
            this.dragging = false;
            this.start = null;
            this.last = null;
            deactivated = true;
        }
        return deactivated;
    },

    /**
     * Method: adjustXY
     * Converts event coordinates that are relative to the document body to
     * ones that are relative to the map viewport. The latter is the default in
     * SuperMap.
     *
     * Parameters:
     * evt - {Object}
     */
    adjustXY: function (evt) {
        var pos = SuperMap.Util.pagePosition(this.map.viewPortDiv);
        evt.xy.x -= pos[0];
        evt.xy.y -= pos[1];
    },

    /**
     * Method: addDocumentEvents
     * Start observing document events when documentDrag is true and the mouse
     * cursor leaves the map viewport while dragging.
     */
    addDocumentEvents: function () {
        this.documentEvents = true;
        SuperMap.Event.observe(document, "mousemove", this._docMove);
        SuperMap.Event.observe(document, "mouseup", this._docUp);
    },

    /**
     * Method: removeDocumentEvents
     * Stops observing document events when documentDrag is true and the mouse
     * cursor re-enters the map viewport while dragging.
     */
    removeDocumentEvents: function () {
        this.documentEvents = false;
        SuperMap.Event.stopObserving(document, "mousemove", this._docMove);
        SuperMap.Event.stopObserving(document, "mouseup", this._docUp);
    },

    CLASS_NAME: "SuperMap.Handler.Drag"
});


text:
const path = require('path')

const shell = require('shelljs')

const execTypes = require('../execTypes')
const { errorExit } = require('../utils')

shell.config.verbose = true
shell.config.fatal = true

const typesDir = '@interactjs/types'

;(async () => {
  const modulesDir = path.resolve('packages')

  execTypes.modular(modulesDir)
  await execTypes.combined(path.join(modulesDir, typesDir))
})().catch(errorExit)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Monilia castellanii Re

### Remarks
null


text:
package org.apache.hadoop.metrics2.impl;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.hadoop.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.hadoop.metrics2.MetricsCollector;
import org.apache.hadoop.metrics2.MetricsRecordBuilder;
import org.apache.hadoop.metrics2.MetricsSource;
import org.apache.hadoop.metrics2.MetricsTag;
import org.apache.hadoop.metrics2.annotation.Metric;
import org.apache.hadoop.metrics2.annotation.Metrics;
import org.apache.hadoop.metrics2.lib.MetricsAnnotations;
import org.apache.hadoop.metrics2.lib.MetricsRegistry;
import org.apache.hadoop.metrics2.lib.MetricsSourceBuilder;
import org.apache.hadoop.metrics2.lib.MutableCounterLong;
import static org.apache.hadoop.metrics2.lib.Interns.info;
import static org.junit.Assert.assertEquals;

import org.apache.log4j.Logger;
import org.junit.Test;

import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;

public class TestMetricsSourceAdapter {
  private static final int RACE_TEST_RUNTIME = 10000; // 10 seconds

  @Test
  public void testPurgeOldMetrics() throws Exception {
    // create test source with a single metric counter of value 1
    PurgableSource source = new PurgableSource();
    MetricsSourceBuilder sb = MetricsAnnotations.newSourceBuilder(source);
    final MetricsSource s = sb.build();

    List<MetricsTag> injectedTags = new ArrayList<MetricsTag>();
    MetricsSourceAdapter sa = new MetricsSourceAdapter(
        "tst", "tst", "testdesc", s, injectedTags, null, null, 1, false);

    MBeanInfo info = sa.getMBeanInfo();
    boolean sawIt = false;
    for (MBeanAttributeInfo mBeanAttributeInfo : info.getAttributes()) {
      sawIt |= mBeanAttributeInfo.getName().equals(source.lastKeyName);
    };
    assertTrue("The last generated metric is not exported to jmx", sawIt);

    Thread.sleep(1000); // skip JMX cache TTL

    info = sa.getMBeanInfo();
    sawIt = false;
    for (MBeanAttributeInfo mBeanAttributeInfo : info.getAttributes()) {
      sawIt |= mBeanAttributeInfo.getName().equals(source.lastKeyName);
    };
    assertTrue("The last generated metric is not exported to jmx", sawIt);
  }

  //generate a new key per each call
  private static class PurgableSource implements MetricsSource {
    int nextKey = 0;
    String lastKeyName = null;
    @Override
    public void getMetrics(MetricsCollector collector, boolean all) {
      MetricsRecordBuilder rb =
          collector.addRecord("purgablesource")
              .setContext("test");
      lastKeyName = "key" + nextKey++;
      rb.addGauge(info(lastKeyName, "desc"), 1);
    }
  }

  @Test
  public void testGetMetricsAndJmx() throws Exception {
    // create test source with a single metric counter of value 0
    TestSource source = new TestSource("test");
    MetricsSourceBuilder sb = MetricsAnnotations.newSourceBuilder(source);
    final MetricsSource s = sb.build();

    List<MetricsTag> injectedTags = new ArrayList<MetricsTag>();
    MetricsSourceAdapter sa = new MetricsSourceAdapter(
        "test", "test", "test desc", s, injectedTags, null, null, 1, false);

    // all metrics are initially assumed to have changed
    MetricsCollectorImpl builder = new MetricsCollectorImpl();
    Iterable<MetricsRecordImpl> metricsRecords = sa.getMetrics(builder, true);

    // Validate getMetrics and JMX initial values
    MetricsRecordImpl metricsRecord = metricsRecords.iterator().next();
    assertEquals(0L,
        metricsRecord.metrics().iterator().next().value().longValue());

    Thread.sleep(100); // skip JMX cache TTL
    assertEquals(0L, (Number)sa.getAttribute("C1"));

    // change metric value
    source.incrementCnt();

    // validate getMetrics and JMX
    builder = new MetricsCollectorImpl();
    metricsRecords = sa.getMetrics(builder, true);
    metricsRecord = metricsRecords.iterator().next();
    assertTrue(metricsRecord.metrics().iterator().hasNext());
    Thread.sleep(100); // skip JMX cache TTL
    assertEquals(1L, (Number)sa.getAttribute("C1"));
  }

  @SuppressWarnings("unused")
  @Metrics(context="test")
  private static class TestSource {
    @Metric("C1 desc") MutableCounterLong c1;
    final MetricsRegistry registry;

    TestSource(String recName) {
      registry = new MetricsRegistry(recName);
    }

    public void incrementCnt() {
      c1.incr();
    }
  }

  /**
   * Test a race condition when updating the JMX cache (HADOOP-12482):
   * 1. Thread A reads the JMX metric every 2 JMX cache TTL. It marks the JMX
   *    cache to be updated by marking lastRecs to null. After this it adds a
   *    new key to the metrics. The next call to read should pick up this new
   *    key.
   * 2. Thread B triggers JMX metric update every 1 JMX cache TTL. It assigns
   *    lastRecs to a new object (not null any more).
   * 3. Thread A tries to read JMX metric again, sees lastRecs is not null and
   *    does not update JMX cache. As a result the read does not pickup the new
   *    metric.
   * @throws Exception
   */
  @Test
  public void testMetricCacheUpdateRace() throws Exception {
    // Create test source with a single metric counter of value 1.
    TestMetricsSource source = new TestMetricsSource();
    MetricsSourceBuilder sourceBuilder =
        MetricsAnnotations.newSourceBuilder(source);

    final long JMX_CACHE_TTL = 250; // ms
    List<MetricsTag> injectedTags = new ArrayList<>();
    MetricsSourceAdapter sourceAdapter =
        new MetricsSourceAdapter("test", "test",
            "test JMX cache update race condition", sourceBuilder.build(),
            injectedTags, null, null, JMX_CACHE_TTL, false);

    ScheduledExecutorService updaterExecutor =
        Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().build());
    ScheduledExecutorService readerExecutor =
        Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().build());

    final AtomicBoolean hasError = new AtomicBoolean(false);

    // Wake up every 1 JMX cache TTL to set lastRecs before updateJmxCache() is
    // called.
    SourceUpdater srcUpdater = new SourceUpdater(sourceAdapter, hasError);
    ScheduledFuture<?> updaterFuture =
        updaterExecutor.scheduleAtFixedRate(srcUpdater,
            sourceAdapter.getJmxCacheTTL(), sourceAdapter.getJmxCacheTTL(),
            TimeUnit.MILLISECONDS);
    srcUpdater.setFuture(updaterFuture);

    // Wake up every 2 JMX cache TTL so updateJmxCache() will try to update
    // JMX cache.
    SourceReader srcReader = new SourceReader(source, sourceAdapter, hasError);
    ScheduledFuture<?> readerFuture =
        readerExecutor.scheduleAtFixedRate(srcReader,
            0, // set JMX info cache at the beginning
            2 * sourceAdapter.getJmxCacheTTL(), TimeUnit.MILLISECONDS);
    srcReader.setFuture(readerFuture);

    // Let the threads do their work.
    Thread.sleep(RACE_TEST_RUNTIME);

    assertFalse("Hit error", hasError.get());

    // cleanup
    updaterExecutor.shutdownNow();
    readerExecutor.shutdownNow();
    updaterExecutor.awaitTermination(1000, TimeUnit.MILLISECONDS);
    readerExecutor.awaitTermination(1000, TimeUnit.MILLISECONDS);
  }

  /**
   * Thread safe source: stores a key value pair. Allows thread safe key-value
   * pair reads/writes.
   */
  private static class TestMetricsSource implements MetricsSource {
    private String key = "key0";
    private int val = 0;

    synchronized String getKey() {
      return key;
    }

    synchronized void setKV(final String newKey, final int newVal) {
      key = newKey;
      val = newVal;
    }

    @Override
    public void getMetrics(MetricsCollector collector, boolean all) {
      MetricsRecordBuilder rb =
          collector.addRecord("TestMetricsSource").setContext("test");
      synchronized(this) {
        rb.addGauge(info(key, "TestMetricsSource key"), val);
      }
    }
  }

  /**
   * An thread that updates the metrics source every 1 JMX cache TTL
   */
  private static class SourceUpdater implements Runnable {
    private MetricsSourceAdapter sa = null;
    private ScheduledFuture<?> future = null;
    private AtomicBoolean hasError = null;
    private static final Logger LOG = Logger.getLogger(SourceUpdater.class);

    public SourceUpdater(MetricsSourceAdapter sourceAdapter,
        AtomicBoolean err) {
      sa = sourceAdapter;
      hasError = err;
    }

    public void setFuture(ScheduledFuture<?> f) {
      future = f;
    }

    @Override
    public void run() {
      MetricsCollectorImpl builder = new MetricsCollectorImpl();
      try {
        // This resets lastRecs.
        sa.getMetrics(builder, true);
        LOG.info("reset lastRecs");
      } catch (Exception e) {
        // catch all errors
        hasError.set(true);
        LOG.error(e.getStackTrace());
      } finally {
        if (hasError.get()) {
          LOG.error("Hit error, stopping now");
          future.cancel(false);
        }
      }
    }
  }

  /**
   * An thread that reads the metrics source every JMX cache TTL. After each
   * read it updates the metric source to report a new key. The next read must
   * be able to pick up this new key.
   */
  private static class SourceReader implements Runnable {
    private MetricsSourceAdapter sa = null;
    private TestMetricsSource src = null;
    private int cnt = 0;
    private ScheduledFuture<?> future = null;
    private AtomicBoolean hasError = null;
    private static final Logger LOG = Logger.getLogger(SourceReader.class);

    public SourceReader(
        TestMetricsSource source, MetricsSourceAdapter sourceAdapter,
        AtomicBoolean err) {
      src = source;
      sa = sourceAdapter;
      hasError = err;
    }

    public void setFuture(ScheduledFuture<?> f) {
      future = f;
    }

    @Override
    public void run() {
      try {
        // This will trigger updateJmxCache().
        MBeanInfo info = sa.getMBeanInfo();
        final String key = src.getKey();
        for (MBeanAttributeInfo mBeanAttributeInfo : info.getAttributes()) {
          // Found the new key, update the metric source and move on.
          if (mBeanAttributeInfo.getName().equals(key)) {
            LOG.info("found key/val=" + cnt + "/" + cnt);
            cnt++;
            src.setKV("key" + cnt, cnt);
            return;
          }
        }
        LOG.error("key=" + key + " not found. Stopping now.");
        hasError.set(true);
      } catch (Exception e) {
        // catch other errors
        hasError.set(true);
        LOG.error(e.getStackTrace());
      } finally {
        if (hasError.get()) {
          future.cancel(false);
        }
      }
    }
  }
}


text:
Input::
//// [/a/lib/lib.d.ts]
/// <reference no-default-lib="true"/>
interface Boolean {}
interface Function {}
interface CallableFunction {}
interface NewableFunction {}
interface IArguments {}
interface Number { toExponential: any; }
interface Object {}
interface RegExp {}
interface String { charAt: any; }
interface Array<T> { length: number; [n: number]: T; }

//// [/users/username/projects/project/file1.ts]
export const x = 10;

//// [/users/username/projects/project/file2.ts]
export const y = 20;

//// [/users/username/projects/project/tsconfig.json]
{"compilerOptions":{"incremental":true,"module":"amd","outFile":"out.js"}}

/a/lib/tsc.js -i
Output::

Program root files: ["/users/username/projects/project/file1.ts","/users/username/projects/project/file2.ts"]
Program options: {"incremental":true,"module":2,"outFile":"/users/username/projects/project/out.js","configFilePath":"/users/username/projects/project/tsconfig.json"}
Program structureReused: Not
Program files::
/a/lib/lib.d.ts
/users/username/projects/project/file1.ts
/users/username/projects/project/file2.ts

No cached semantic diagnostics in the builder::

WatchedFiles::

FsWatches::

FsWatchesRecursive::

exitCode:: ExitStatus.Success

//// [/users/username/projects/project/out.js]
define("file1", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    exports.x = void 0;
    exports.x = 10;
});
define("file2", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    exports.y = void 0;
    exports.y = 20;
});

//// [/users/username/projects/project/out.tsbuildinfo]
{"bundle":{"commonSourceDirectory":"./","sourceFiles":["./file1.ts","./file2.ts"],"js":{"sections":[{"pos":0,"end":334,"kind":"text"}]}},"version":"FakeTSVersion"}

//// [/users/username/projects/project/out.tsbuildinfo.readable.baseline.txt]
{
  "bundle": {
    "commonSourceDirectory": "./",
    "sourceFiles": [
      "./file1.ts",
      "./file2.ts"
    ],
    "js": {
      "sections": [
        {
          "pos": 0,
          "end": 334,
          "kind": "text"
        }
      ]
    }
  },
  "version": "FakeTSVersion",
  "size": 163
}

//// [/users/username/projects/project/out.tsbuildinfo.baseline.txt]
======================================================================
File:: /users/username/projects/project/out.js
----------------------------------------------------------------------
text: (0-334)
define("file1", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    exports.x = void 0;
    exports.x = 10;
});
define("file2", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    exports.y = void 0;
    exports.y = 20;
});

======================================================================


text:
@implementation T8ATBCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self.contentView addSubview:self.funcBtn];

        [self.funcBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self).offset(-10);
            make.centerY.equalTo(self);
            make.width.equalTo(@52);
            make.height.equalTo(@30);
        }];
    }
    return self;
}

- (void)funcBtnPressed
{

}

#pragma mark - getter
- (UIButton *)funcBtn
{
    if (!_funcBtn) {
        _funcBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        _funcBtn.backgroundColor = UIColorRGB(0xa0a9ae);
        _funcBtn.layer.cornerRadius = 3;
        _funcBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_funcBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_funcBtn addTarget:self action:@selector(funcBtnPressed) forControlEvents:UIControlEventTouchUpInside];
    }
    return _funcBtn;
}

@end


text:
package com.google.sps.servlets;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;

import org.junit.Before;
import org.junit.Test;
import org.junit.After;

import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.appengine.tools.development.testing.LocalUserServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Entity;

import com.google.gson.Gson;
import com.google.sps.data.Card;

@RunWith(JUnit4.class)
public final class EditCardServletTest {

  private final LocalServiceTestHelper helper =
      new LocalServiceTestHelper(
              new LocalDatastoreServiceTestConfig()
                  .setDefaultHighRepJobPolicyUnappliedJobPercentage(0),
              new LocalUserServiceTestConfig())
          .setEnvIsAdmin(true)
          .setEnvIsLoggedIn(true)
          .setEnvEmail("test@gmail.com")
          .setEnvAuthDomain("gmail.com");

  private HttpServletRequest mockRequest;
  private HttpServletResponse mockResponse;
  private StringWriter responseWriter;
  private EditCardServlet servlet;
  private DatastoreService datastore;

  @Before
  public void setUp() throws Exception {
    helper.setUp();
    servlet = new EditCardServlet();
    mockRequest = mock(HttpServletRequest.class);
    mockResponse = mock(HttpServletResponse.class);

    // Set up a fake HTTP response
    responseWriter = new StringWriter();
    when(mockResponse.getWriter()).thenReturn(new PrintWriter(responseWriter));

    datastore = DatastoreServiceFactory.getDatastoreService();
  }

  @After
  public void tearDown() throws Exception {
    helper.tearDown();
  }

  @Test
  public void editCard() throws Exception {
    Card currentCard =
        new Card.Builder()
            .setImageBlobKey("null")
            .setRawText("hello")
            .setTextTranslated("hola")
            .build();

    // Generate a folder entity to obtain a folder key
    // which would be used to set as the parent of the card entities
    Entity folder = new Entity("Folder", "testID");
    String folderKey = KeyFactory.keyToString(folder.getKey());

    Card cardInDatastore = Card.storeCardInDatastore(currentCard, datastore, folderKey);
    String cardKey = cardInDatastore.getCardKey();

    when(mockRequest.getParameter("cardKey")).thenReturn(cardKey);
    when(mockRequest.getParameter("rawText")).thenReturn("hello");
    when(mockRequest.getParameter("testStatus")).thenReturn("True");
    when(mockRequest.getParameter("textTranslated")).thenReturn("xin chào");

    servlet.doPut(mockRequest, mockResponse);

    Entity editedCard = datastore.get(KeyFactory.stringToKey(cardKey));

    String response = new Gson().toJson(new Card(editedCard));
    String expectedResponse =
        "{\"imageBlobKey\":\"null\",\"rawText\":\"hello\",\"textTranslated\":\"xin chào\",\"key\":\"agR0ZXN0chwLEgZGb2xkZXIiBnRlc3RJRAwLEgRDYXJkGAEM\"}";
    assertEquals(response, expectedResponse);
  }
}


text:
package io.advantageous.qbit.todo;

import io.advantageous.qbit.reactive.Callback;

import java.util.List;

/**
 * created by rhightower on 2/24/15.
 */
public interface TodoServiceClient {

    void add(TodoItem todoItem);

    void list(Callback<List<TodoItem>> callback);

}


text:
package strlit

import (
	"testing"
)

func TestInternalSyntaxErrorAsError(t *testing.T) {

	var err error = internalSyntaxError{} // THIS IS WHAT ACTUALLY MATTERS!

	if nil == err {
		t.Error("This should never happen.")
	}
}
func TestInternalSyntaxErrorAsSyntaxError(t *testing.T) {

	var complainer SyntaxError = internalSyntaxError{} // THIS IS WHAT ACTUALLY MATTERS!

	if nil == complainer {
		t.Error("This should never happen.")
	}
}


text:
package org.apache.camel.component.aws2.iam.integration;

import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.aws2.iam.IAM2Constants;
import org.apache.camel.component.aws2.iam.IAM2Operations;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.iam.model.CreateUserResponse;

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

public class IAMCreateUserIT extends Aws2IAMBase {

    @EndpointInject("mock:result")
    private MockEndpoint mock;

    @Test
    public void iamCreateUserTest() throws Exception {

        mock.expectedMessageCount(1);
        Exchange exchange = template.request("direct:createUser", new Processor() {
            @Override
            public void process(Exchange exchange) {
                exchange.getIn().setHeader(IAM2Constants.OPERATION, IAM2Operations.createUser);
                exchange.getIn().setHeader(IAM2Constants.USERNAME, "test");
            }
        });

        assertMockEndpointsSatisfied();

        CreateUserResponse resultGet = (CreateUserResponse) exchange.getIn().getBody();
        assertEquals("test", resultGet.user().userName());
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            @Override
            public void configure() {
                from("direct:createUser").to("aws2-iam://test?operation=createUser")
                        .to("mock:result");

            }
        };
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace DocumentFormat.OpenXml.Packaging
{
    internal static class ImagePartTypeInfo
    {
        internal static string GetContentType(ImagePartType imageType)
            => imageType switch
            {
                ImagePartType.Bmp => "image/bmp",
                ImagePartType.Gif => "image/gif",
                ImagePartType.Png => "image/png",
                ImagePartType.Tiff => "image/tiff",

                // ImagePartType.Xbm => "image/xbm",
                ImagePartType.Icon => "image/x-icon",
                ImagePartType.Pcx => "image/x-pcx",

                // ImagePartType.Pcz => "image/x-pcz",
                // ImagePartType.Pict => "image/pict",
                ImagePartType.Jpeg => "image/jpeg",
                ImagePartType.Emf => "image/x-emf",
                ImagePartType.Wmf => "image/x-wmf",
                ImagePartType.Svg => "image/svg+xml",
                _ => throw new ArgumentOutOfRangeException(nameof(imageType)),
            };

        internal static string GetTargetExtension(ImagePartType imageType)
            => imageType switch
            {
                ImagePartType.Bmp => ".bmp",
                ImagePartType.Gif => ".gif",
                ImagePartType.Png => ".png",
                ImagePartType.Tiff => ".tiff",

                // ImagePartType.Xbm => ".xbm",
                ImagePartType.Icon => ".ico",
                ImagePartType.Pcx => ".pcx",

                // ImagePartType.Pcz => ".pcz",
                // ImagePartType.Pict => ".pict",
                ImagePartType.Jpeg => ".jpg",
                ImagePartType.Emf => ".emf",
                ImagePartType.Wmf => ".wmf",
                ImagePartType.Svg => ".svg",
                _ => ".image",
            };

        internal static ImagePartType GetImagePartType(string extension)
            => extension.ToLower() switch
            {
                ".bmp" => ImagePartType.Bmp,
                ".emf" => ImagePartType.Emf,
                ".ico" => ImagePartType.Icon,
                ".jpg" => ImagePartType.Jpeg,
                ".jpeg" => ImagePartType.Jpeg,
                ".pcx" => ImagePartType.Pcx,
                ".png" => ImagePartType.Png,
                ".svg" => ImagePartType.Svg,
                ".tiff" => ImagePartType.Tiff,
                ".wmf" => ImagePartType.Wmf,
                _ => throw new NotSupportedException($"{extension} is not supported"),
            };
    }
}


text:
#include "fRabbifierMuzzleModel.h"
#include <QBrush>
#include <QIcon>
#include <QDebug>
#include <QPainter>
#include <QAbstractTextDocumentLayout>
#include <QApplication>
#include <QMainWindow>
#include <QTimer>
#include <QDebug>
#include <QImage>
#include <QPixmap>
#include <QLabel>
#include <QPixmap>
#include <QFileDialog>
#include "f.h"
#include "str.h"

/*!
 * Creates a model object with the given \a ds and \a parent.
 */
fRabbifierMuzzleModel::fRabbifierMuzzleModel(QObject *parent)
    :QAbstractTableModel(parent),
      m_pLog(nullptr)
{

}

void fRabbifierMuzzleModel::sort(int column, Qt::SortOrder order/* = Qt::AscendingOrder*/)
{
    emit layoutChanged();
}

/*!
 * Destroys the model.
 */
fRabbifierMuzzleModel::~fRabbifierMuzzleModel()
{

}

int fRabbifierMuzzleModel::rowCount(const QModelIndex &/*parent*/) const
{
    QString sMuzzlesDir = str::makeAbsFN(qApp->applicationDirPath(), "/res");
    QString sPattern = "muzzle?.png";

    QDirIterator it(sMuzzlesDir, QStringList() << sPattern, QDir::Files);
    int i=0;
    while (it.hasNext())
    {
        it.next();
        i++;
    }

    return i;
}

int fRabbifierMuzzleModel::columnCount(const QModelIndex &/*parent*/) const
{
    return 1;
}

Qt::ItemFlags fRabbifierMuzzleModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return Qt::NoItemFlags;
    return Qt::ItemIsSelectable | Qt::ItemIsEnabled;// | Qt::ItemIsEditable;
}

QVariant fRabbifierMuzzleModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    int row2BeReturned = index.row();
    int col2BeReturned = index.column();

    if((role == Qt::DisplayRole) || (role == Qt::DecorationRole) || (role == Qt::SizeHintRole))
    {
        if(role == Qt::DisplayRole)
        {
            return QString::number(row2BeReturned);
        }

        QString sAbsFN = str::makeAbsFN(qApp->applicationDirPath(), "/res/muzzle"+QString::number(row2BeReturned)+".png");
        if(!QFile::exists(sAbsFN))
        {
            qDebug() << "fnf " << sAbsFN;
        }
        QImage qimg(sAbsFN);
        qimg = qimg.scaled(55, 55, Qt::KeepAspectRatio);
        QPixmap pixmap = QPixmap::fromImage(qimg);

        if(role == Qt::SizeHintRole)
        {
            return pixmap.size();
        }
        if(role == Qt::DecorationRole)
        {
            return pixmap;
        }

        return QString::number(row2BeReturned);
    }
    if((role == Qt::ToolTipRole) || (role == Qt::StatusTipRole))
    {
        return QString::number(row2BeReturned);
    }
    else if (role == Qt::EditRole)
    {
        return QVariant();	//should not happen
    }
    else if (role == Qt::TextAlignmentRole)
    {
        Qt::Alignment align;
        align |= Qt::AlignJustify;
        return QVariant(align);
    }
    else if (role == Qt::FontRole)
    {
		return QVariant();
    }
    else if (role == Qt::TextColorRole)
    {

    }
    else if (role == Qt::ForegroundRole)
    {

    }
    else if (role == Qt::BackgroundRole)
    {
       return QVariant::fromValue(QColor(Qt::white));
    }

    return QVariant();
}

QVariant fRabbifierMuzzleModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role == Qt::DecorationRole)
    {
        if (orientation == Qt::Vertical)
        {

        }
    }
    else if(role == Qt::SizeHintRole)
    {
        //if (orientation == Qt::Horizontal)
        if(section == 2)
        {
            //return QVariant(QSize(55, 55));
        }
    }
    else if (role == Qt::DisplayRole)
    {
        if (orientation == Qt::Horizontal)
        {
			//column headers
            return "muzzle";
        }
        else
        {
			//row 'header'
            //return QString::number(section + 1);
        }
    }
    return QVariant();
}

bool fRabbifierMuzzleModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    Q_UNUSED(value)

    if (!index.isValid())
        return false;

    if (role == Qt::EditRole)
    {	//should not happen
		return false;
    }

    return false;
}
void fRabbifierMuzzleModel::setEnv(logger* pLog)
{
    this->m_pLog = pLog;
}
QModelIndex fRabbifierMuzzleModel::buddy(const QModelIndex &index) const
{
    return index;
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

namespace Azure.Analytics.Synapse.Spark.Models
{
    /// <summary>
    /// Describes the different ways of Spark batch job operation could complete.
    /// If <see cref="JobSubmission"/> is used, the operation will be considered as complete when Livy state is starting/running/error/dead/success/killed.
    /// If <see cref="JobExecution"/> is used, the operation will be considered as complete when Livy state is error/dead/success/killed.
    /// </summary>
    public enum SparkBatchOperationCompletionType
    {
        JobSubmission,
        JobExecution
    }
}