text:
import * as tl from 'azure-pipelines-task-lib';
import * as path from 'path';
import * as assert from 'assert';
import * as ttm from 'azure-pipelines-task-lib/mock-test';
var ltx = require('ltx');
import fs = require('fs');

describe('IISWebsiteDeploymentOnMachineGroup test suite', function() {
     var taskSrcPath = path.join(__dirname, '..','deployiiswebapp.js');
     this.timeout(60000);
     before((done) => {
        tl.cp(path.join(__dirname, "..", "node_modules", "azure-pipelines-tasks-webdeployment-common-v4", "Tests", 'L1XmlVarSub', 'Web.config'), path.join(__dirname, "..", "node_modules", "azure-pipelines-tasks-webdeployment-common-v4", "Tests", 'L1XmlVarSub', 'Web_test.config'), null, false);
        tl.cp(path.join(__dirname, "..", "node_modules", "azure-pipelines-tasks-webdeployment-common-v4", "Tests", 'L1XmlVarSub', 'Web.Debug.config'), path.join(__dirname, "..", "node_modules", "azure-pipelines-tasks-webdeployment-common-v4", "Tests", 'L1XmlVarSub', 'Web_test.Debug.config'), null, false);
        tl.cp(path.join(__dirname, "..", "node_modules","azure-pipelines-tasks-webdeployment-common-v4","Tests", 'L1XdtTransform', 'Web.config'), path.join(__dirname, "..", "node_modules","azure-pipelines-tasks-webdeployment-common-v4","Tests", 'L1XdtTransform', 'Web_test.config'), null, false);
        tl.cp(path.join(__dirname, "..", "node_modules", "azure-pipelines-tasks-webdeployment-common-v4", "Tests", 'L1XmlVarSub', 'parameters.xml'), path.join(__dirname, "..", "node_modules", "azure-pipelines-tasks-webdeployment-common-v4", "Tests", 'L1XmlVarSub', 'parameters_test.xml'), null, false);
        done();
    });
    after(function() {
        tl.rmRF(path.join(__dirname, "..", "node_modules","azure-pipelines-tasks-webdeployment-common-v4","Tests", 'L1XdtTransform', 'Web_test.config'));
        tl.rmRF(path.join(__dirname, "..", "node_modules", "azure-pipelines-tasks-webdeployment-common-v4", "Tests", 'L1XmlVarSub', 'Web_test.config'));
        tl.rmRF(path.join(__dirname, "..", "node_modules", "azure-pipelines-tasks-webdeployment-common-v4", "Tests", 'L1XmlVarSub', 'Web_Test.Debug.config'));
        tl.rmRF(path.join(__dirname, "..", "node_modules", "azure-pipelines-tasks-webdeployment-common-v4", "Tests", 'L1XmlVarSub', 'parameters_test.xml'));
    });

    if(!tl.osType().match(/^Win/)) {
        return;
    }
    it('Runs successfully with default inputs', (done:MochaDone) => {
        let tp = path.join(__dirname, 'L0WindowsDefault.js');
        let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp);

        tr.run();

		assert(tr.invokedToolCount == 1, 'should have invoked tool once');
        assert(tr.stderr.length == 0 || tr.errorIssues.length, 'should not have written to stderr');
        assert(tr.succeeded, 'task should have succeeded');
        done();
    });

	it('Runs successfully with all other inputs', (done) => {
        let tp = path.join(__dirname, 'L0WindowsAllInput.js');
        let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp);

        tr.run();

		assert(tr.invokedToolCount == 1, 'should have invoked tool once');
        assert(tr.stderr.length == 0 && tr.errorIssues.length == 0, 'should not have written to stderr');
        assert(tr.succeeded, 'task should have succeeded');
        done();
    });

	it('Fails if msdeploy fails to execute', (done) => {
        let tp = path.join(__dirname, 'L0WindowsFailDefault.js');
        let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp);

        tr.run();

        var expectedErr = 'Error: msdeploy failed with return code: 1';
		assert(tr.invokedToolCount == 3, 'should have invoked tool thrice despite failure');
        assert(tr.errorIssues.length > 0 || tr.stderr.length > 0, 'should have written to stderr');
        assert(tr.stdErrContained(expectedErr) || tr.createdErrorIssue(expectedErr), 'E should have said: ' + expectedErr);
        assert(tr.failed, 'task should have failed');
        done();
    });

    it('Runs successfully with parameter file present in package', (done) => {
        let tp = path.join(__dirname, 'L0WindowsParamFileinPkg.js');
        let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp);

		tr.run();

		assert(tr.invokedToolCount == 1, 'should have invoked tool once');
        assert(tr.stderr.length == 0 && tr.errorIssues.length == 0, 'should not have written to stderr');
        assert(tr.succeeded, 'task should have succeeded');
        done();
    });

    it('Fails if parameters file provided by user is not present', (done) => {
        this.timeout(parseInt(process.env.TASK_TEST_TIMEOUT) || 20000);

        let tp = path.join(__dirname, 'L0WindowsFailSetParamFile.js');
        let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp);

		tr.run();

		assert(tr.invokedToolCount == 0, 'should not have invoked any tool');
        assert(tr.stderr.length > 0 || tr.errorIssues.length > 0, 'should have written to stderr');
        var expectedErr = 'Error: loc_mock_SetParamFilenotfound0 invalidparameterFile.xml';
        assert(tr.stdErrContained(expectedErr) || tr.createdErrorIssue(expectedErr), 'should have said: ' + expectedErr);
        assert(tr.failed, 'task should have succeeded');
        done();
});

    it('Fails if more than one package matched with specified pattern', (done) => {
        let tp = path.join(__dirname, 'L0WindowsManyPackage.js');
        let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp);

        tr.run();
	assert(tr.invokedToolCount == 0, 'should not have invoked any tool');
        assert(tr.stderr.length > 0 || tr.errorIssues.length > 0, 'should have written to stderr');
        var expectedErr = 'Error: loc_mock_MorethanonepackagematchedwithspecifiedpatternPleaserestrainthesearchpattern';
        assert(tr.stdErrContained(expectedErr) || tr.createdErrorIssue(expectedErr), 'should have said: ' + expectedErr);
        assert(tr.failed, 'task should have failed');
        done();
    });

    it('Fails if package or folder name is invalid', (done) => {
        let tp = path.join(__dirname, 'L0WindowsNoPackage.js');
        let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp);

		tr.run();

        assert(tr.invokedToolCount == 0, 'should not have invoked any tool');
        assert(tr.stderr.length > 0 || tr.errorIssues.length > 0, 'should have written to stderr');
        var expectedErr = 'Error: loc_mock_Nopackagefoundwithspecifiedpattern';
        assert(tr.stdErrContained(expectedErr) || tr.createdErrorIssue(expectedErr), 'should have said: ' + expectedErr);
        assert(tr.failed, 'task should have failed');
        done();
    });

    it('Runs Successfully with XDT Transformation (Mock)', (done) => {
        this.timeout(1000);
        let tp = path.join(__dirname, 'L0WindowsXdtTransformation.js');
        let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp);
        tr.run();

        assert(tr.invokedToolCount == 2, 'should have invoked tool twice');
        let expectedErr = "loc_mock_XDTTransformationsappliedsuccessfully";
        assert(tr.stdout.search(expectedErr) >= 0);
        assert(tr.stderr.length == 0  && tr.errorIssues.length == 0, 'should not have written to stderr');
        assert(tr.succeeded, 'task should have succeeded');
        done();
    });

    it('Fails if XDT Transformation throws error (Mock)', (done) => {
        let tp = path.join(__dirname, 'L0WindowsXdtTransformationFail.js');
        let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp);
        tr.run();

        var expectedErr = 'Error: loc_mock_XdtTransformationErrorWhileTransforming C:\\tempFolder\\web.config C:\\tempFolder\\web.Release.config';
        assert(tr.invokedToolCount == 1, 'should have invoked tool only once');
        assert(tr.stderr.length > 0 || tr.errorIssues.length > 0, 'should have written to stderr');
        assert(tr.stdErrContained(expectedErr) || tr.createdErrorIssue(expectedErr), 'E should have said: ' + expectedErr);
        assert(tr.failed, 'task should have failed');
        done();
        });

    it('Runs successfully with XDT Transformation (L1)', (done:MochaDone) => {
        this.timeout(parseInt(process.env.TASK_TEST_TIMEOUT) || 20000);

        let tp = path.join(__dirname, "..", "node_modules","azure-pipelines-tasks-webdeployment-common-v4","Tests","L1XdtTransform.js");
        let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp);
        tr.run();

        if(tl.osType().match(/^Win/)) {
            var resultFile = ltx.parse(fs.readFileSync(path.join(__dirname, "..", "node_modules","azure-pipelines-tasks-webdeployment-common-v4","Tests", 'L1XdtTransform', 'Web_test.config')));
            var expectFile = ltx.parse(fs.readFileSync(path.join(__dirname, "..", "node_modules","azure-pipelines-tasks-webdeployment-common-v4","Tests", 'L1XdtTransform','Web_Expected.config')));
            assert(ltx.equal(resultFile, expectFile) , 'Should Transform attributes on Web.config');
        }
        else {
            tl.warning('Cannot test XDT Transformation in Non Windows Agent');
        }
        done();
    });

    it('Runs successfully with XML variable substitution', (done:MochaDone) => {
        let tp = path.join(__dirname, "..", "node_modules", "azure-pipelines-tasks-webdeployment-common-v4", "Tests", 'L1XmlVarSub.js');
        let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp);
        tr.run();

        var resultFile = ltx.parse(fs.readFileSync(path.join(__dirname,  "..", "node_modules","azure-pipelines-tasks-webdeployment-common-v4","Tests", 'L1XmlVarSub', 'Web_test.config')));
        var expectFile = ltx.parse(fs.readFileSync(path.join(__dirname, "..", "node_modules","azure-pipelines-tasks-webdeployment-common-v4","Tests", 'L1XmlVarSub', 'Web_Expected.config')));
        assert(ltx.equal(resultFile, expectFile) , 'Should have substituted variables in Web.config file');
        var resultFile = ltx.parse(fs.readFileSync(path.join(__dirname, "..", "node_modules", "azure-pipelines-tasks-webdeployment-common-v4", "Tests", 'L1XmlVarSub', 'Web_test.Debug.config')));
        var expectFile = ltx.parse(fs.readFileSync(path.join(__dirname, "..", "node_modules", "azure-pipelines-tasks-webdeployment-common-v4", "Tests", 'L1XmlVarSub', 'Web_Expected.Debug.config')));
        assert(ltx.equal(resultFile, expectFile) , 'Should have substituted variables in Web.Debug.config file');
        done();
    });

    it('Runs successfully with JSON variable substitution', (done:MochaDone) => {
        let tp = path.join(__dirname, "..", "node_modules", "azure-pipelines-tasks-webdeployment-common-v4", "Tests", 'L1JsonVarSub.js');
        let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp);
        tr.run();

        assert(tr.stdout.search('JSON - eliminating object variables validated') > 0, 'JSON - eliminating object variables validation error');
        assert(tr.stdout.search('JSON - simple string change validated') > 0,'JSON -simple string change validation error' );
        assert(tr.stdout.search('JSON - system variable elimination validated') > 0, 'JSON -system variable elimination validation error');
        assert(tr.stdout.search('JSON - special variables validated') > 0, 'JSON - special variables validation error');
        assert(tr.stdout.search('JSON - variables with dot character validated') > 0, 'JSON varaibles with dot character validated');
        assert(tr.stdout.search('JSON - substitute inbuilt JSON attributes validated') > 0, 'JSON inbuilt variable substitution validation error');
        assert(tr.stdout.search('VALID JSON COMMENTS TESTS PASSED') > 0, 'VALID JSON COMMENTS TESTS PASSED');
        assert(tr.stdout.search('INVALID JSON COMMENTS TESTS PASSED') > 0, 'INVALID JSON COMMENTS TESTS PASSED');
        assert(tr.succeeded, 'task should have succeeded');
        done();
    });

    it('Validate File Encoding', (done:MochaDone) => {
        let tp = path.join(__dirname, "..", "node_modules", "azure-pipelines-tasks-webdeployment-common-v4", "Tests", 'L1ValidateFileEncoding.js');
        let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp);
        tr.run();

        assert(tr.stdout.search('UTF-8 with BOM validated') >= 0, 'Should have validated UTF-8 with BOM');
        assert(tr.stdout.search('UTF-16LE with BOM validated') >= 0, 'Should have validated UTF-16LE with BOM');
        assert(tr.stdout.search('UTF-16BE with BOM validated') >= 0, 'Should have validated UTF-16BE with BOM');
        assert(tr.stdout.search('UTF-32LE with BOM validated') >= 0, 'Should have validated UTF-32LE with BOM');
        assert(tr.stdout.search('UTF-32BE with BOM validated') >= 0, 'Should have validated UTF-32BE with BOM');

        assert(tr.stdout.search('UTF-8 without BOM validated') >= 0, 'Should have validated UTF-8 without BOM');
        assert(tr.stdout.search('UTF-16LE without BOM validated') >= 0, 'Should have validated UTF-16LE without BOM');
        assert(tr.stdout.search('UTF-16BE without BOM validated') >= 0, 'Should have validated UTF-16BE without BOM');
        assert(tr.stdout.search('UTF-32LE without BOM validated') >= 0, 'Should have validated UTF-32LE without BOM');
        assert(tr.stdout.search('UTF-32BE without BOM validated') >= 0, 'Should have validated UTF-32BE without BOM');

        assert(tr.stdout.search('Short File Buffer Error') >= 0, 'Should have validated short Buffer');
        assert(tr.stdout.search('Unknown encoding type') >= 0, 'Should throw for Unknown File Buffer');
        done();
    });

     it('Validate azure-pipelines-tasks-webdeployment-common-v4.utility.copyDirectory()', (done:MochaDone) => {
        let tp = path.join(__dirname, "..", "node_modules", "azure-pipelines-tasks-webdeployment-common-v4", "Tests", 'L0CopyDirectory.js');
        let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp);
        tr.run();

        assert(tr.stdout.search('## Copy Files Successful ##') >=0, 'should have copied the files');
        assert(tr.stdout.search('## mkdir Successful ##') >= 0, 'should have created dir including dest folder');
        done();
    });

    it('Validate MSDeploy parameters', (done:MochaDone) => {
        let tp = path.join(__dirname, "..", "node_modules","azure-pipelines-tasks-webdeployment-common-v4","Tests","L0MSDeployUtility.js");
        let tr : ttm.MockTestRunner = new ttm.MockTestRunner(tp);
        tr.run();

        assert(tr.stdout.search('MSBUILD DEFAULT PARAMS PASSED') > 0, 'should have printed MSBUILD DEFAULT PARAMS PASSED');
        assert(tr.stdout.search('ARGUMENTS WITH SET PARAMS PASSED') > 0, 'should have printed ARGUMENTS WITH SET PARAMS PASSED');
        assert(tr.stdout.search('ARGUMENT WITH FOLDER PACKAGE PASSED') > 0, 'should have printed ARGUMENT WITH FOLDER PACKAGE PASSED');
        assert(tr.stdout.search('ARGUMENT WITH EXCLUDE APP DATA PASSED') > 0, 'should have printed ARGUMENT WITH EXCLUDE APP DATA PASSED');
        assert(tr.stdout.search('ARGUMENT WITH WAR PACKAGE PASSED') > 0, 'should have printed ARGUMENT WITH WAR PACKAGE PASSED');
        assert(tr.stdout.search('ARGUMENT WITH OVERRIDE RETRY FLAG PASSED') > 0, 'should have printed ARGUMENT WITH OVERRIDE RETRY FLAG PASSED');
        done();
    });
});


text:
package org.elasticsearch.cluster;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.FailedNodeException;
import org.elasticsearch.action.admin.cluster.node.stats.NodeStats;
import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsRequest;
import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsRequest;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.admin.indices.stats.ShardStats;
import org.elasticsearch.action.support.DefaultShardOperationFailedException;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.allocation.DiskThresholdSettings;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.CountDown;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.store.StoreStats;
import org.elasticsearch.monitor.fs.FsInfo;
import org.elasticsearch.threadpool.ThreadPool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;

/**
 * InternalClusterInfoService provides the ClusterInfoService interface,
 * routinely updated on a timer. The timer can be dynamically changed by
 * setting the cluster.info.update.interval setting (defaulting
 * to 30 seconds). The InternalClusterInfoService only runs on the master node.
 * Listens for changes in the number of data nodes and immediately submits a
 * ClusterInfoUpdateJob if a node has been added.
 *
 * Every time the timer runs, gathers information about the disk usage and
 * shard sizes across the cluster.
 */
public class InternalClusterInfoService implements ClusterInfoService, ClusterStateListener {

    private static final Logger logger = LogManager.getLogger(InternalClusterInfoService.class);

    public static final Setting<TimeValue> INTERNAL_CLUSTER_INFO_UPDATE_INTERVAL_SETTING = Setting.timeSetting(
        "cluster.info.update.interval",
        TimeValue.timeValueSeconds(30),
        TimeValue.timeValueSeconds(10),
        Property.Dynamic,
        Property.NodeScope
    );
    public static final Setting<TimeValue> INTERNAL_CLUSTER_INFO_TIMEOUT_SETTING = Setting.positiveTimeSetting(
        "cluster.info.update.timeout",
        TimeValue.timeValueSeconds(15),
        Property.Dynamic,
        Property.NodeScope
    );

    private volatile boolean enabled;
    private volatile TimeValue updateFrequency;
    private volatile TimeValue fetchTimeout;

    private volatile ImmutableOpenMap<String, DiskUsage> leastAvailableSpaceUsages;
    private volatile ImmutableOpenMap<String, DiskUsage> mostAvailableSpaceUsages;
    private volatile IndicesStatsSummary indicesStatsSummary;

    private final ThreadPool threadPool;
    private final Client client;
    private final List<Consumer<ClusterInfo>> listeners = new CopyOnWriteArrayList<>();

    private final Object mutex = new Object();
    private final List<ActionListener<ClusterInfo>> nextRefreshListeners = new ArrayList<>();
    private AsyncRefresh currentRefresh;
    private RefreshScheduler refreshScheduler;

    public InternalClusterInfoService(Settings settings, ClusterService clusterService, ThreadPool threadPool, Client client) {
        this.leastAvailableSpaceUsages = ImmutableOpenMap.of();
        this.mostAvailableSpaceUsages = ImmutableOpenMap.of();
        this.indicesStatsSummary = IndicesStatsSummary.EMPTY;
        this.threadPool = threadPool;
        this.client = client;
        this.updateFrequency = INTERNAL_CLUSTER_INFO_UPDATE_INTERVAL_SETTING.get(settings);
        this.fetchTimeout = INTERNAL_CLUSTER_INFO_TIMEOUT_SETTING.get(settings);
        this.enabled = DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED_SETTING.get(settings);
        ClusterSettings clusterSettings = clusterService.getClusterSettings();
        clusterSettings.addSettingsUpdateConsumer(INTERNAL_CLUSTER_INFO_TIMEOUT_SETTING, this::setFetchTimeout);
        clusterSettings.addSettingsUpdateConsumer(INTERNAL_CLUSTER_INFO_UPDATE_INTERVAL_SETTING, this::setUpdateFrequency);
        clusterSettings.addSettingsUpdateConsumer(
            DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED_SETTING,
            this::setEnabled
        );
    }

    private void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    private void setFetchTimeout(TimeValue fetchTimeout) {
        this.fetchTimeout = fetchTimeout;
    }

    void setUpdateFrequency(TimeValue updateFrequency) {
        this.updateFrequency = updateFrequency;
    }

    @Override
    public void clusterChanged(ClusterChangedEvent event) {
        final Runnable newRefresh;
        synchronized (mutex) {
            if (event.localNodeMaster() == false) {
                refreshScheduler = null;
                return;
            }

            if (refreshScheduler == null) {
                logger.trace("elected as master, scheduling cluster info update tasks");
                refreshScheduler = new RefreshScheduler();
                nextRefreshListeners.add(refreshScheduler.getListener());
            }
            newRefresh = getNewRefresh();
            assert assertRefreshInvariant();
        }
        newRefresh.run();

        // Refresh if a data node was added
        for (DiscoveryNode addedNode : event.nodesDelta().addedNodes()) {
            if (addedNode.canContainData()) {
                refreshAsync(new PlainActionFuture<>());
                break;
            }
        }
    }

    private class AsyncRefresh {

        private final List<ActionListener<ClusterInfo>> thisRefreshListeners;
        private final CountDown countDown = new CountDown(2);

        AsyncRefresh(List<ActionListener<ClusterInfo>> thisRefreshListeners) {
            this.thisRefreshListeners = thisRefreshListeners;
        }

        void execute() {
            assert countDown.isCountedDown() == false;

            logger.trace("starting async refresh");

            final NodesStatsRequest nodesStatsRequest = new NodesStatsRequest("data:true");
            nodesStatsRequest.clear();
            nodesStatsRequest.addMetric(NodesStatsRequest.Metric.FS.metricName());
            nodesStatsRequest.timeout(fetchTimeout);
            client.admin().cluster().nodesStats(nodesStatsRequest, ActionListener.runAfter(new ActionListener<>() {
                @Override
                public void onResponse(NodesStatsResponse nodesStatsResponse) {
                    logger.trace("received node stats response");

                    for (final FailedNodeException failure : nodesStatsResponse.failures()) {
                        final Throwable cause = failure.getCause();
                        if (logger.isDebugEnabled()) {
                            logger.warn(new ParameterizedMessage("failed to retrieve stats for node [{}]", failure.nodeId()), cause);
                        } else {
                            logger.warn("failed to retrieve stats for node [{}]: {}", failure.nodeId(), cause.getMessage());
                        }
                    }

                    ImmutableOpenMap.Builder<String, DiskUsage> leastAvailableUsagesBuilder = ImmutableOpenMap.builder();
                    ImmutableOpenMap.Builder<String, DiskUsage> mostAvailableUsagesBuilder = ImmutableOpenMap.builder();
                    fillDiskUsagePerNode(
                        adjustNodesStats(nodesStatsResponse.getNodes()),
                        leastAvailableUsagesBuilder,
                        mostAvailableUsagesBuilder
                    );
                    leastAvailableSpaceUsages = leastAvailableUsagesBuilder.build();
                    mostAvailableSpaceUsages = mostAvailableUsagesBuilder.build();
                }

                @Override
                public void onFailure(Exception e) {
                    if (e instanceof ClusterBlockException) {
                        logger.trace("failed to retrieve node stats", e);
                    } else {
                        logger.warn("failed to retrieve node stats", e);
                    }
                    leastAvailableSpaceUsages = ImmutableOpenMap.of();
                    mostAvailableSpaceUsages = ImmutableOpenMap.of();
                }
            }, this::onStatsProcessed));

            final IndicesStatsRequest indicesStatsRequest = new IndicesStatsRequest();
            indicesStatsRequest.clear();
            indicesStatsRequest.store(true);
            indicesStatsRequest.indicesOptions(IndicesOptions.STRICT_EXPAND_OPEN_CLOSED_HIDDEN);
            indicesStatsRequest.timeout(fetchTimeout);
            client.admin().indices().stats(indicesStatsRequest, ActionListener.runAfter(new ActionListener<>() {
                @Override
                public void onResponse(IndicesStatsResponse indicesStatsResponse) {
                    logger.trace("received indices stats response");

                    if (indicesStatsResponse.getShardFailures().length > 0) {
                        final Set<String> failedNodeIds = new HashSet<>();
                        for (final DefaultShardOperationFailedException shardFailure : indicesStatsResponse.getShardFailures()) {
                            if (shardFailure.getCause() instanceof FailedNodeException) {
                                final FailedNodeException failedNodeException = (FailedNodeException) shardFailure.getCause();
                                if (failedNodeIds.add(failedNodeException.nodeId())) {
                                    if (logger.isDebugEnabled()) {
                                        logger.warn(
                                            new ParameterizedMessage(
                                                "failed to retrieve shard stats from node [{}]",
                                                failedNodeException.nodeId()
                                            ),
                                            failedNodeException
                                        );
                                    } else {
                                        logger.warn(
                                            "failed to retrieve shard stats from node [{}]: {}",
                                            failedNodeException.nodeId(),
                                            failedNodeException.getCause().getMessage()
                                        );
                                    }
                                }
                                logger.trace(
                                    new ParameterizedMessage(
                                        "failed to retrieve stats for shard [{}][{}]",
                                        shardFailure.index(),
                                        shardFailure.shardId()
                                    ),
                                    shardFailure.getCause()
                                );
                            } else {
                                logger.warn(
                                    new ParameterizedMessage(
                                        "failed to retrieve stats for shard [{}][{}]",
                                        shardFailure.index(),
                                        shardFailure.shardId()
                                    ),
                                    shardFailure.getCause()
                                );
                            }
                        }
                    }

                    final ShardStats[] stats = indicesStatsResponse.getShards();
                    final ImmutableOpenMap.Builder<String, Long> shardSizeByIdentifierBuilder = ImmutableOpenMap.builder();
                    final ImmutableOpenMap.Builder<ShardId, Long> shardDataSetSizeBuilder = ImmutableOpenMap.builder();
                    final ImmutableOpenMap.Builder<ShardRouting, String> dataPathByShardRoutingBuilder = ImmutableOpenMap.builder();
                    final Map<ClusterInfo.NodeAndPath, ClusterInfo.ReservedSpace.Builder> reservedSpaceBuilders = new HashMap<>();
                    buildShardLevelInfo(
                        stats,
                        shardSizeByIdentifierBuilder,
                        shardDataSetSizeBuilder,
                        dataPathByShardRoutingBuilder,
                        reservedSpaceBuilders
                    );

                    final ImmutableOpenMap.Builder<ClusterInfo.NodeAndPath, ClusterInfo.ReservedSpace> rsrvdSpace = ImmutableOpenMap
                        .builder();
                    reservedSpaceBuilders.forEach((nodeAndPath, builder) -> rsrvdSpace.put(nodeAndPath, builder.build()));

                    indicesStatsSummary = new IndicesStatsSummary(
                        shardSizeByIdentifierBuilder.build(),
                        shardDataSetSizeBuilder.build(),
                        dataPathByShardRoutingBuilder.build(),
                        rsrvdSpace.build()
                    );
                }

                @Override
                public void onFailure(Exception e) {
                    if (e instanceof ClusterBlockException) {
                        logger.trace("failed to retrieve indices stats", e);
                    } else {
                        logger.warn("failed to retrieve indices stats", e);
                    }
                    indicesStatsSummary = IndicesStatsSummary.EMPTY;
                }
            }, this::onStatsProcessed));
        }

        private void onStatsProcessed() {
            if (countDown.countDown()) {
                logger.trace("stats all received, computing cluster info and notifying listeners");
                try {
                    final ClusterInfo clusterInfo = getClusterInfo();
                    boolean anyListeners = false;
                    for (final Consumer<ClusterInfo> listener : listeners) {
                        anyListeners = true;
                        try {
                            logger.trace("notifying [{}] of new cluster info", listener);
                            listener.accept(clusterInfo);
                        } catch (Exception e) {
                            logger.info(new ParameterizedMessage("failed to notify [{}] of new cluster info", listener), e);
                        }
                    }
                    assert anyListeners : "expected to notify at least one listener";

                    for (final ActionListener<ClusterInfo> listener : thisRefreshListeners) {
                        listener.onResponse(clusterInfo);
                    }
                } finally {
                    onRefreshComplete(this);
                }
            }
        }
    }

    private void onRefreshComplete(AsyncRefresh completedRefresh) {
        final Runnable newRefresh;
        synchronized (mutex) {
            assert currentRefresh == completedRefresh;
            currentRefresh = null;

            // We only ever run one refresh at once; if another refresh was requested while this one was running then we must start another
            // to ensure that the stats it sees are up-to-date.
            newRefresh = getNewRefresh();
            assert assertRefreshInvariant();
        }
        newRefresh.run();
    }

    private Runnable getNewRefresh() {
        assert Thread.holdsLock(mutex) : "mutex not held";

        if (currentRefresh != null) {
            return () -> {};
        }

        if (nextRefreshListeners.isEmpty()) {
            return () -> {};
        }

        final ArrayList<ActionListener<ClusterInfo>> thisRefreshListeners = new ArrayList<>(nextRefreshListeners);
        nextRefreshListeners.clear();

        if (enabled) {
            currentRefresh = new AsyncRefresh(thisRefreshListeners);
            return currentRefresh::execute;
        } else {
            return () -> {
                leastAvailableSpaceUsages = ImmutableOpenMap.of();
                mostAvailableSpaceUsages = ImmutableOpenMap.of();
                indicesStatsSummary = IndicesStatsSummary.EMPTY;
                thisRefreshListeners.forEach(l -> l.onResponse(ClusterInfo.EMPTY));
            };
        }
    }

    private boolean assertRefreshInvariant() {
        assert Thread.holdsLock(mutex) : "mutex not held";
        // We never leave a refresh listener waiting unless we're already refreshing (which will pick up the waiting listener on completion)
        assert nextRefreshListeners.isEmpty() || currentRefresh != null;
        return true;
    }

    private class RefreshScheduler {

        ActionListener<ClusterInfo> getListener() {
            return ActionListener.wrap(() -> {
                if (shouldRefresh()) {
                    threadPool.scheduleUnlessShuttingDown(updateFrequency, ThreadPool.Names.SAME, () -> {
                        if (shouldRefresh()) {
                            refreshAsync(getListener());
                        }
                    });
                }
            });
        }

        private boolean shouldRefresh() {
            synchronized (mutex) {
                return refreshScheduler == this;
            }
        }
    }

    @Override
    public ClusterInfo getClusterInfo() {
        final IndicesStatsSummary indicesStatsSummary = this.indicesStatsSummary; // single volatile read
        return new ClusterInfo(
            leastAvailableSpaceUsages,
            mostAvailableSpaceUsages,
            indicesStatsSummary.shardSizes,
            indicesStatsSummary.shardDataSetSizes,
            indicesStatsSummary.shardRoutingToDataPath,
            indicesStatsSummary.reservedSpace
        );
    }

    // allow tests to adjust the node stats on receipt
    List<NodeStats> adjustNodesStats(List<NodeStats> nodeStats) {
        return nodeStats;
    }

    void refreshAsync(ActionListener<ClusterInfo> future) {
        final Runnable newRefresh;
        synchronized (mutex) {
            nextRefreshListeners.add(future);
            newRefresh = getNewRefresh();
            assert assertRefreshInvariant();
        }
        newRefresh.run();
    }

    @Override
    public void addListener(Consumer<ClusterInfo> clusterInfoConsumer) {
        listeners.add(clusterInfoConsumer);
    }

    static void buildShardLevelInfo(
        ShardStats[] stats,
        ImmutableOpenMap.Builder<String, Long> shardSizes,
        ImmutableOpenMap.Builder<ShardId, Long> shardDataSetSizeBuilder,
        ImmutableOpenMap.Builder<ShardRouting, String> newShardRoutingToDataPath,
        Map<ClusterInfo.NodeAndPath, ClusterInfo.ReservedSpace.Builder> reservedSpaceByShard
    ) {
        for (ShardStats s : stats) {
            final ShardRouting shardRouting = s.getShardRouting();
            newShardRoutingToDataPath.put(shardRouting, s.getDataPath());

            final StoreStats storeStats = s.getStats().getStore();
            if (storeStats == null) {
                continue;
            }
            final long size = storeStats.sizeInBytes();
            final long dataSetSize = storeStats.totalDataSetSizeInBytes();
            final long reserved = storeStats.getReservedSize().getBytes();

            final String shardIdentifier = ClusterInfo.shardIdentifierFromRouting(shardRouting);
            logger.trace("shard: {} size: {} reserved: {}", shardIdentifier, size, reserved);
            shardSizes.put(shardIdentifier, size);
            if (dataSetSize > shardDataSetSizeBuilder.getOrDefault(shardRouting.shardId(), -1L)) {
                shardDataSetSizeBuilder.put(shardRouting.shardId(), dataSetSize);
            }
            if (reserved != StoreStats.UNKNOWN_RESERVED_BYTES) {
                final ClusterInfo.ReservedSpace.Builder reservedSpaceBuilder = reservedSpaceByShard.computeIfAbsent(
                    new ClusterInfo.NodeAndPath(shardRouting.currentNodeId(), s.getDataPath()),
                    t -> new ClusterInfo.ReservedSpace.Builder()
                );
                reservedSpaceBuilder.add(shardRouting.shardId(), reserved);
            }
        }
    }

    static void fillDiskUsagePerNode(
        List<NodeStats> nodeStatsArray,
        ImmutableOpenMap.Builder<String, DiskUsage> newLeastAvailableUsages,
        ImmutableOpenMap.Builder<String, DiskUsage> newMostAvailableUsages
    ) {
        for (NodeStats nodeStats : nodeStatsArray) {
            if (nodeStats.getFs() == null) {
                logger.warn("node [{}/{}] did not return any filesystem stats", nodeStats.getNode().getName(), nodeStats.getNode().getId());
                continue;
            }

            FsInfo.Path leastAvailablePath = null;
            FsInfo.Path mostAvailablePath = null;
            for (FsInfo.Path info : nodeStats.getFs()) {
                if (leastAvailablePath == null) {
                    // noinspection ConstantConditions this assertion is for the benefit of readers, it's always true
                    assert mostAvailablePath == null;
                    mostAvailablePath = leastAvailablePath = info;
                } else if (leastAvailablePath.getAvailable().getBytes() > info.getAvailable().getBytes()) {
                    leastAvailablePath = info;
                } else if (mostAvailablePath.getAvailable().getBytes() < info.getAvailable().getBytes()) {
                    mostAvailablePath = info;
                }
            }
            if (leastAvailablePath == null) {
                // noinspection ConstantConditions this assertion is for the benefit of readers, it's always true
                assert mostAvailablePath == null;
                logger.warn("node [{}/{}] did not return any filesystem stats", nodeStats.getNode().getName(), nodeStats.getNode().getId());
                continue;
            }

            final String nodeId = nodeStats.getNode().getId();
            final String nodeName = nodeStats.getNode().getName();
            if (logger.isTraceEnabled()) {
                logger.trace(
                    "node [{}]: most available: total: {}, available: {} / least available: total: {}, available: {}",
                    nodeId,
                    mostAvailablePath.getTotal(),
                    mostAvailablePath.getAvailable(),
                    leastAvailablePath.getTotal(),
                    leastAvailablePath.getAvailable()
                );
            }
            if (leastAvailablePath.getTotal().getBytes() < 0) {
                if (logger.isTraceEnabled()) {
                    logger.trace(
                        "node: [{}] least available path has less than 0 total bytes of disk [{}], skipping",
                        nodeId,
                        leastAvailablePath.getTotal().getBytes()
                    );
                }
            } else {
                newLeastAvailableUsages.put(
                    nodeId,
                    new DiskUsage(
                        nodeId,
                        nodeName,
                        leastAvailablePath.getPath(),
                        leastAvailablePath.getTotal().getBytes(),
                        leastAvailablePath.getAvailable().getBytes()
                    )
                );
            }
            if (mostAvailablePath.getTotal().getBytes() < 0) {
                if (logger.isTraceEnabled()) {
                    logger.trace(
                        "node: [{}] most available path has less than 0 total bytes of disk [{}], skipping",
                        nodeId,
                        mostAvailablePath.getTotal().getBytes()
                    );
                }
            } else {
                newMostAvailableUsages.put(
                    nodeId,
                    new DiskUsage(
                        nodeId,
                        nodeName,
                        mostAvailablePath.getPath(),
                        mostAvailablePath.getTotal().getBytes(),
                        mostAvailablePath.getAvailable().getBytes()
                    )
                );
            }

        }
    }

    private static class IndicesStatsSummary {
        static final IndicesStatsSummary EMPTY = new IndicesStatsSummary(
            ImmutableOpenMap.of(),
            ImmutableOpenMap.of(),
            ImmutableOpenMap.of(),
            ImmutableOpenMap.of()
        );

        final ImmutableOpenMap<String, Long> shardSizes;
        final ImmutableOpenMap<ShardId, Long> shardDataSetSizes;
        final ImmutableOpenMap<ShardRouting, String> shardRoutingToDataPath;
        final ImmutableOpenMap<ClusterInfo.NodeAndPath, ClusterInfo.ReservedSpace> reservedSpace;

        IndicesStatsSummary(
            ImmutableOpenMap<String, Long> shardSizes,
            ImmutableOpenMap<ShardId, Long> shardDataSetSizes,
            ImmutableOpenMap<ShardRouting, String> shardRoutingToDataPath,
            ImmutableOpenMap<ClusterInfo.NodeAndPath, ClusterInfo.ReservedSpace> reservedSpace
        ) {
            this.shardSizes = shardSizes;
            this.shardDataSetSizes = shardDataSetSizes;
            this.shardRoutingToDataPath = shardRoutingToDataPath;
            this.reservedSpace = reservedSpace;
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
package io.seldon.memcache;

import io.seldon.memcache.DogpileHandler;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class DogPileTests {

	@Before
	public void setup()
	{
		new DogpileHandler();
	}

	@Test
	public void basicFunctionalityTest() throws InterruptedException
	{
		final String key = "testKey";
		final int expireSecs = 1;
		Assert.assertTrue(DogpileHandler.get().updateIsRequired(key, new Object(), expireSecs)); // no key set so no need to update
		DogpileHandler.get().updated(key, expireSecs);
		Assert.assertFalse(DogpileHandler.get().updateIsRequired(key, new Object(), expireSecs)); // key set but not expired
		Thread.sleep(expireSecs*1000);
		Assert.assertTrue(DogpileHandler.get().updateIsRequired(key, new Object(), expireSecs)); // key set and expired
		Assert.assertFalse(DogpileHandler.get().updateIsRequired(key, new Object(), expireSecs)); // key set and expired but waiting for update
		DogpileHandler.get().clear(key);
	}

	@Test
	public void noKeyTest() throws InterruptedException
	{
		final String key = "testKey";
		final int expireSecs = 1;
		DogpileHandler.get().clear(key);

		Assert.assertTrue(DogpileHandler.get().updateIsRequired(key, new Object(), expireSecs)); // no key set so no need to update
		DogpileHandler.get().updated(key, expireSecs);
		Assert.assertFalse(DogpileHandler.get().updateIsRequired(key, new Object(), expireSecs)); // key set but not expired
		Thread.sleep(expireSecs*1000);
		Assert.assertTrue(DogpileHandler.get().updateIsRequired(key, new Object(), expireSecs)); // key set and expired
		Assert.assertFalse(DogpileHandler.get().updateIsRequired(key, new Object(), expireSecs)); // key set and expired but waiting for update
		DogpileHandler.get().clear(key);
	}

	public static class UpdaterTester implements Runnable
	{
		int updates = 0;
		int delay;
		String key;
		int keyExpireSecs;
		boolean keepRunning = true;
		public UpdaterTester(int delayMillisecs,String key,int keyExpireSecs)
		{
			this.delay = delayMillisecs;
			this.key = key;
			this.keyExpireSecs = keyExpireSecs;
		}

		@Override
		public void run() {

			while(keepRunning)
			{
				boolean needsUpdate = DogpileHandler.get().updateIsRequired(key, new Object(), 1);
				if (needsUpdate)
				{
					System.out.println("Update "+System.currentTimeMillis());
					updates++;
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					DogpileHandler.get().updated(key, keyExpireSecs);
				}
				try {
					Thread.sleep(this.delay);
				} catch (InterruptedException e) {
					e.printStackTrace();
					return;
				}
			}
		}

		public int getUpdates() {
			return updates;
		}

		public void setKeepRunning(boolean keepRunning) {
			this.keepRunning = keepRunning;
		}

	}

	@Test
	public void multiThreadedTest() throws InterruptedException
	{

		int numThreads = 100;
		final String key = "testKey";
		try
		{
		final int expireSecs = 1;
		final int busyLoopDelayMillisecs = 100;
		List<Thread> threads = new ArrayList<>();
		List<UpdaterTester> testers = new ArrayList<>();
		DogpileHandler.get().updated(key, expireSecs);
		System.out.println("Start test "+System.currentTimeMillis());
		for(int i=0;i<numThreads;i++)
		{
			UpdaterTester ut = new UpdaterTester(busyLoopDelayMillisecs, key, expireSecs);
			Thread t = new Thread(ut);
			threads.add(t);
			testers.add(ut);
			t.start();
		}

		Thread.sleep(expireSecs * 1000);

		for(UpdaterTester t : testers)
			t.setKeepRunning(false);

		System.out.println("End test "+System.currentTimeMillis());

		for(Thread t : threads)
			t.join();

		int sum = 0;
		for(UpdaterTester t : testers)
			sum = sum + t.getUpdates();

		Assert.assertEquals(1, sum);
		}
		finally
		{
			DogpileHandler.get().clear(key);
		}
	}
}


text:
package org.kuali.kfs.module.cam.document.service;

import org.kuali.kfs.module.cam.businessobject.Asset;
import org.kuali.kfs.module.cam.businessobject.AssetDepreciationConvention;
import org.kuali.kfs.module.cam.businessobject.AssetType;

public interface AssetDateService {

    /**
     * Last inventory Date shall be updated whenever changes made to location or tag number
     */
    void checkAndUpdateLastInventoryDate(Asset copyAsset, Asset newAsset);

    /**
     * In Asset Edit, DepreciationDate shall be updated whenever In-service Date changed.
     */
    void checkAndUpdateDepreciationDate(Asset copyAsset, Asset newAsset);

    /**
     * In Asset Edit, Fiscal year and period code shall be updated whenever In-service Date changed.
     */
    void checkAndUpdateFiscalYearAndPeriod(Asset copyAsset, Asset newAsset);

    /**
     * This method computes the depreciation date based on input parameters
     *
     * @param assetType Asset Type Object
     * @param depreciationConvention Depreciation Convention for the asset
     * @param inServiceDate Current in-service date value
     * @return Computed Asset Depreciation Date
     */
    java.sql.Date computeDepreciationDate(AssetType assetType, AssetDepreciationConvention depreciationConvention, java.sql.Date inServiceDate);

}


text:
module RubyPushNotifications
  module WNS
    describe WNSConnection do

      describe '::post' do
        let(:body) { 'abc' }
        let(:headers) {
          {
            'x-wns-notificationstatus' => 'Received',
            'x-wns-deviceconnectionstatus' => 'Connected',
            'x-wns-status' => 'Received'
          }
        }
        let(:push_types) { RubyPushNotifications::WNS::WNSConnection::WP_TARGETS }
        let(:access_token) { 'token' }
        let(:device_urls) { [generate(:wns_device_url)] }
        let(:toast_data) { { title: 'Title', message: 'Hello WNS World!', type: :toast } }
        let(:toast_notification) { build :wns_notification, device_urls: device_urls, data: toast_data }
        let(:wns_connection) { RubyPushNotifications::WNS::WNSConnection }

        before do
          stub_request(:post, %r{hk2.notify.windows.com}).
            to_return status: [200, 'OK'], body: body, headers: headers
        end

        it 'runs the right request' do
          WNSConnection.post toast_notification, access_token
          headers = {
            wns_connection::CONTENT_TYPE_HEADER => wns_connection::CONTENT_TYPE[:toast],
            wns_connection::X_WNS_TYPE_HEADER => wns_connection::WP_TARGETS[:toast],
            wns_connection::CONTENT_LENGTH_HEADER => toast_notification.as_wns_xml.length.to_s,
            wns_connection::AUTHORIZATION_HEADER => "Bearer #{access_token}",
            wns_connection::REQUEST_FOR_STATUS_HEADER => 'true'
          }
          expect(WebMock).
            to have_requested(:post, toast_notification.device_urls[0]).
              with(body: toast_notification.as_wns_xml, headers: headers).
                once
        end

        it 'returns the response encapsulated in a Hash object' do
          responses =  [
            { device_url: toast_notification.device_urls[0],
              headers: headers,
              code: 200
            }
          ]
          expect(WNSConnection.post toast_notification, access_token).to eq WNSResponse.new(responses)
        end
      end
    end
  end
end


text:
#include <gtest/gtest.h>

#include <thread>

#include "socket.h"
#include "sysdeps.h"

class FdeventTest : public ::testing::Test {
  protected:
    int dummy = -1;

    static void SetUpTestCase() {
#if !defined(_WIN32)
        ASSERT_NE(SIG_ERR, signal(SIGPIPE, SIG_IGN));
#endif
    }

    void SetUp() override {
        fdevent_reset();
        ASSERT_EQ(0u, fdevent_installed_count());
    }

    // Register a dummy socket used to wake up the fdevent loop to tell it to die.
    void PrepareThread() {
        int dummy_fds[2];
        if (adb_socketpair(dummy_fds) != 0) {
            FAIL() << "failed to create socketpair: " << strerror(errno);
        }

        asocket* dummy_socket = create_local_socket(dummy_fds[1]);
        if (!dummy_socket) {
            FAIL() << "failed to create local socket: " << strerror(errno);
        }
        dummy_socket->ready(dummy_socket);
        dummy = dummy_fds[0];
    }

    size_t GetAdditionalLocalSocketCount() {
#if ADB_HOST
        // dummy socket installed in PrepareThread()
        return 1;
#else
        // dummy socket and one more socket installed in fdevent_subproc_setup()
        return 2;
#endif
    }

    void TerminateThread(std::thread& thread) {
        fdevent_terminate_loop();
        ASSERT_TRUE(WriteFdExactly(dummy, "", 1));
        thread.join();
        ASSERT_EQ(0, adb_close(dummy));
    }
};


text:
@interface JRCoreTextController : JRBaseViewController

@end


text:
package org.alfresco.repo.lotus.ws;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for ClbLabelType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ClbLabelType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <attribute name="label" type="{http://www.w3.org/2001/XMLSchema}string" />
 *       <attribute name="lang" type="{http://www.w3.org/2001/XMLSchema}string" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ClbLabelType", namespace = "http://model.xsd.clb.content.ibm.com")
public class ClbLabelType {

    @XmlAttribute
    protected String label;
    @XmlAttribute
    protected String lang;

    /**
     * Gets the value of the label property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getLabel() {
        return label;
    }

    /**
     * Sets the value of the label property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setLabel(String value) {
        this.label = value;
    }

    /**
     * Gets the value of the lang property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getLang() {
        return lang;
    }

    /**
     * Sets the value of the lang property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setLang(String value) {
        this.lang = value;
    }

}


text:
/
#define TALLOC_BLOCK_SIZE 4194304 // 4 MB

/**
 * @def Every allocation with pool allocator is rounded up to next multiply of
 * this value. Objects of same size are in same pool.
 */
#define TALLOC_POOL_GROUP_MULT 32

/**
 * @def Count of cells allocated on heap in every pool. When count of
 * per-pool allocations reach this value, new pool block of this size will be
 * allocated on heap.
 */
#define TALLOC_INIT_POOL_SIZE 128

/**
 * @def Objects with size under this value will be allocated in pools, larger
 * objects will be allocated directly on heap.
 */
#define TALLOC_SMALL_TO 2048 // 2KB

/**
 * @def Enable or disable pooling of small objects.
 */
#define TALLOC_USE_POOLS 1

/**
 * @def Every allocation of talloc is aligned using this alignment
 */
#ifdef _MSC_VER
#define TALLOC_ALIGNMENT 16
#else
#define TALLOC_ALIGNMENT alignof(max_align_t)
#endif

/**
 * @def Enable or disable force freeing of system memory and reset of allocator.
 */
#define TALLOC_FORCE_RESET 0

/**
 * @brief Enable checking of freeing unallocated memory.
 */
#define TALLOC_MEM_CHECKING 1

/**
 * @brief Enable error notification system.
 *
 * Mathod talloc_exception(const char *) must be implemented on client side to handle
 * allocator errors. Abort is called after talloc_exception call.
 */
#define TALLOC_EXCEPTION_HANDLING 1

#endif /* end of include guard: CONFIG_HPP_IF6CXWGS */


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

// disable com
[assembly: ComVisible(false)]

// set the default resource language
[assembly: NeutralResourcesLanguage("en-us")]


text:
'use strict';

var _ = require('lodash');
var env = process.env.NODE_ENV || 'development'
/**
 * Load environment configuration
 */
module.exports = _.merge(
    require('./env/all.js'),
    require('./env/' + env + '.js') || {});


text:
from doctest import DocTestSuite, REPORT_NDIFF,ELLIPSIS
from testfixtures import Replacer
from unittest import TestSuite

class TestReplacer:

    def test_function(self): # pragma: no branch
        """
        >>> from testfixtures.tests import sample1
        >>> sample1.z()
        'original z'

        >>> def test_z():
        ...   return 'replacement z'

        >>> r = Replacer()
        >>> r.replace('testfixtures.tests.sample1.z',test_z)

        >>> sample1.z()
        'replacement z'

        >>> r.restore()

        >>> sample1.z()
        'original z'
        """

    def test_class(self): # pragma: no branch
        """
        >>> from testfixtures.tests import sample1
        >>> sample1.X()
        <testfixtures.tests.sample1.X ...>

        >>> class XReplacement(sample1.X): pass

        >>> r = Replacer()
        >>> r.replace('testfixtures.tests.sample1.X',XReplacement)

        >>> sample1.X()
        <testfixtures.tests.test_replacer.XReplacement ...>
        >>> sample1.X().y()
        'original y'

        >>> r.restore()

        >>> sample1.X()
        <testfixtures.tests.sample1.X ...>
        """

    def test_method(self): # pragma: no branch
        """
        >>> from testfixtures.tests import sample1
        >>> sample1.X().y()
        'original y'

        >>> def test_y(self):
        ...   return 'replacement y'

        >>> r = Replacer()
        >>> r.replace('testfixtures.tests.sample1.X.y',test_y)

        >>> sample1.X().y()[:38]
        'replacement y'

        >>> r.restore()

        >>> sample1.X().y()
        'original y'
        """

    def test_class_method(self): # pragma: no branch
        """
        >>> from testfixtures.tests import sample1
        >>> sample1.X.aMethod()
        <class ...testfixtures.tests.sample1.X...>

        >>> def rMethod(cls):
        ...   return (cls,1)

        >>> r = Replacer()
        >>> r.replace('testfixtures.tests.sample1.X.aMethod',rMethod)

        >>> sample1.X.aMethod()
        (<class ...testfixtures.tests.sample1.X...>, 1)

        >>> r.restore()

        >>> sample1.X.aMethod()
        <class ...testfixtures.tests.sample1.X...>
        """

    def test_multiple_replace(self): # pragma: no branch
        """
        >>> from testfixtures.tests import sample1
        >>> sample1.z()
        'original z'
        >>> sample1.X().y()
        'original y'

        >>> def test_y(self):
        ...   return repr(self)
        >>> def test_z():
        ...   return 'replacement z'

        >>> r = Replacer()
        >>> r.replace('testfixtures.tests.sample1.z',test_z)
        >>> r.replace('testfixtures.tests.sample1.X.y',test_y)

        >>> sample1.z()
        'replacement z'
        >>> sample1.X().y()
        '<testfixtures.tests.sample1.X ...>'

        >>> r.restore()

        >>> sample1.z()
        'original z'
        >>> sample1.X().y()
        'original y'
        """

    def test_gotcha(self): # pragma: no branch
        """
        Just because you replace an object in one context:

        >>> from testfixtures.tests import sample1
        >>> from testfixtures.tests import sample2
        >>> sample1.z()
        'original z'

        >>> def test_z():
        ...   return 'replacement z'

        >>> r = Replacer()
        >>> r.replace('testfixtures.tests.sample1.z',test_z)

        >>> sample1.z()
        'replacement z'

        Doesn't meant that it's replaced in all contexts:

        >>> sample2.z()
        'original z'

        >>> r.restore()
        """

    def test_remove_called_twice(self): # pragma: no branch
        """
        >>> from testfixtures.tests import sample1

        >>> def test_z():
        ...   return 'replacement z'

        >>> r = Replacer()
        >>> r.replace('testfixtures.tests.sample1.z',test_z)

        >>> r.restore()
        >>> sample1.z()
        'original z'

        >>> r.restore()
        >>> sample1.z()
        'original z'
        """

    def test_with_statement(self): # pragma: no branch
        """
        >>> from testfixtures.tests import sample1
        >>> sample1.z()
        'original z'

        >>> def test_z():
        ...   return 'replacement z'

        >>> with Replacer() as r:
        ...   r.replace('testfixtures.tests.sample1.z',test_z)
        ...   sample1.z()
        'replacement z'

        >>> sample1.z()
        'original z'
        """

    def test_not_there(self): # pragma: no branch
        """
        >>> def test_bad():
        ...   return 'moo'

        >>> with Replacer() as r:
        ...   r.replace('testfixtures.tests.sample1.bad',test_bad)
        Traceback (most recent call last):
        ...
        AttributeError: Original 'bad' not found
        """

    def test_not_there_ok(self): # pragma: no branch
        """
        >>> from testfixtures.tests import sample1
        >>> sample1.bad()
        Traceback (most recent call last):
        ...
        AttributeError: 'module' object has no attribute 'bad'

        >>> def test_bad():
        ...   return 'moo'

        >>> with Replacer() as r:
        ...   r.replace('testfixtures.tests.sample1.bad',test_bad,strict=False)
        ...   sample1.bad()
        'moo'

        >>> sample1.bad()
        Traceback (most recent call last):
        ...
        AttributeError: 'module' object has no attribute 'bad'
        """

def test_suite():
    return DocTestSuite(optionflags=REPORT_NDIFF|ELLIPSIS)


text:
package co.cask.cdap.etl.api;

/**
 * Utility for obtaining an object which implements a set of validator functions, this object
 * is usually assigned to a variable specified by the
 * {@link co.cask.cdap.etl.api.Validator#getValidatorName} value.
 */
public interface Validator {

  /**
   * Name used as variable name for the Object returned by {@link co.cask.cdap.etl.api.Validator#getValidator}
   */
  String getValidatorName();

  /**
   * get Validator Object, on which the validator function's can be invoked from user-code..
   * @return
   */
  Object getValidator();
}


text:
function initPhysFromOptions( obj, mesh )

% call the superclass methods
initPhysFromOptions@NdgPhysMat( obj, mesh );
obj.matUpdateWetDryState( obj.fphys );

obj.zGrad = cell( obj.Nmesh, 1 );
for m = 1:obj.Nmesh
    mesh = obj.meshUnion(m);
    obj.zGrad{m} = zeros( mesh.cell.Np, mesh.K, 2 );
    zr = mesh.cell.Dr * obj.fphys{m}(:,:,3);
    obj.zGrad{m}(:,:,1) = mesh.rx .* zr;
end

%Friction Term
if obj.option.isKey('FrictionType') % the option exist
    switch obj.getOption('FrictionType')
        case SWEFrictionType.None
            obj.frictionSolver = NonFrictionTermSolver();
        case SWEFrictionType.Linear
            t = obj.getOption('FrictionCoefficient_r');
            obj.frictionSolver = LinearFrictionTermSolver1d(t);
        case SWEFrictionType.Manning
            n = obj.getOption('FrictionCoefficient_n');
            obj.frictionSolver = ManningFrictionSolver1d(n);
    end
else % the option does not exist
    obj.frictionSolver = NonFrictionTermSolver();
end

% Numerical flux
if obj.option.isKey('NumFluxType')
    if obj.getOption('NumFluxType') == SWENumFluxType.HLL
        obj.numfluxSolver = SWEHLLNumFluxSolver1d( );
    elseif( obj.getOption('NumFluxType') == SWENumFluxType.LF )
        obj.numfluxSolver = SWELFNumFluxSolver1d( );
    elseif( obj.getOption('NumFluxType') == SWENumFluxType.ROE )
        obj.numfluxSolver = SWERoeNumFluxSolver1d( );
    end
else
    obj.numfluxSolver = SWEHLLNumFluxSolver1d( );
end

if obj.option.isKey('SWELimiterType')
    switch obj.getOption('SWELimiterType')
        case SWELimiterType.OnDepth
            obj.limiterSolver = SWEDepthLimiter1d();
        case SWELimiterType.OnElevation
            obj.limiterSolver = SWEElevationLimiter1d();
    end
else
    obj.limiterSolver = SWEDepthLimiter1d();
end

end% func


text:
import CopyToClipboard from '../components/CopyToClipboard';

class Example {
  constructor($example) {
    this.$example = $example;
    this.$button = {
      code: $example.querySelector('button.--code'),
      preview: $example.querySelector('button.--preview'),
    };

    this.$code = $example.querySelector('.bd-example-code');
    this.$preview = $example.querySelector('.bd-example-preview');

    this.$button.code.addEventListener('click', (e) => {
      this.toggle(e, false);
    });
    this.$button.preview.addEventListener('click', (e) => {
      this.toggle(e, true);
    });

    let code = '';
    for (const codeElement of this.$example.querySelectorAll('pre')) {
      code = code + codeElement.innerText;
    }

    new CopyToClipboard(this.$code, code);
  }

  toggle(e, force) {
    e.preventDefault();
    this.$button.code.classList.toggle('--active', !force);
    this.$button.preview.classList.toggle('--active', force);

    this.$code.classList.toggle('--hidden', force);
    this.$preview.classList.toggle('--hidden', !force);
  }
}

export default Example;


text:
package com.hutong.supersdk.sdk.handler.iosyy;

import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.hutong.supersdk.common.model.JsonReqObj;
import com.hutong.supersdk.common.util.HttpUtil;
import com.hutong.supersdk.common.util.ParseJson;
import com.hutong.supersdk.sdk.IPayCallBackSDK;
import com.hutong.supersdk.sdk.IPaySuccessHandler;
import com.hutong.supersdk.sdk.IVerifyUserSDK;
import com.hutong.supersdk.sdk.modeltools.SDKVerifyRet;
import com.hutong.supersdk.sdk.modeltools.kuaiyong.KuaiYongSDKInfo;
import com.hutong.supersdk.sdk.utils.MD5Util;
import com.hutong.supersdk.sdk.utils.kuaiyong.Base64;
import com.hutong.supersdk.sdk.utils.kuaiyong.RSAEncrypt;
import com.hutong.supersdk.sdk.utils.kuaiyong.RSASignature;
import com.hutong.supersdk.sdk.utils.kuaiyong.Util;
import org.springframework.util.StringUtils;

@Component("iOSYYKuaiYongSDK")
public class IOSYYKuaiYongSDK implements IVerifyUserSDK, IPayCallBackSDK {

	private static final String SDK_ID = "IOSYYKuaiYong";

	private final static Log logger = LogFactory.getLog(IOSYYKuaiYongSDK.class);

	@Override
	public String getSDKId() {
		return SDK_ID;
	}

	@Override
	public Class<?> getConfigClazz() {
		return KuaiYongSDKInfo.class;
	}

	@Override
	public Object payCallBack(IPaySuccessHandler callback, Map<String, String> paramMap, InputStream servletInputStream,
			String method, Object config) {
		String success = "success";
		String fail = "fail";
		try {
			KuaiYongSDKInfo configInfo = (KuaiYongSDKInfo) config;
			Map<String, String> transformedMap = new HashMap<String, String>();
			String notify_data = paramMap.get("notify_data");
			transformedMap.put("notify_data", notify_data);
			String orderid = paramMap.get("orderid");
			transformedMap.put("orderid", orderid);
			String sign = paramMap.get("sign");
			transformedMap.put("sign", sign);
			String dealseq = paramMap.get("dealseq");
			transformedMap.put("dealseq", dealseq);
			String uid = paramMap.get("uid");
			transformedMap.put("uid", uid);
			String subject = paramMap.get("subject");
			transformedMap.put("subject", subject);
			String v = paramMap.get("v");
			transformedMap.put("v", v);
			logger.debug("transformedMap is : " + transformedMap.toString());
			// 将sign除外的参数按自然升序排序后组装成验签数据
			String signData = Util.getSignData(transformedMap);
			logger.debug("signData is : " + signData);
			String rsaPublicKey = configInfo.getPubKey();
			logger.debug("rsaPublicKey is : " + rsaPublicKey);
			if(!RSASignature.doCheck(signData, sign, rsaPublicKey, "utf-8")){
				logger.error("RSASignature is failed");
				return fail;
			}
			logger.debug("RSASignature is success");
			// "RSA验签成功,数据可信
			RSAEncrypt rsaEncrypt = new RSAEncrypt();
			rsaEncrypt.loadPublicKey(rsaPublicKey);
			byte[] dcDataStr = Base64.decode(notify_data);
			byte[] plainData;
			plainData = rsaEncrypt.decrypt(rsaEncrypt.getPublicKey(), dcDataStr);
			String notifyData = new String(plainData, "UTF-8");
			logger.debug("plainData is " + Arrays.toString(plainData));
			logger.debug("notifyData is " + notifyData);

			Map<String, String> plainMap = new HashMap<String, String>();
			String[] strArray = notifyData.split("&");
			for (String str : strArray) {
				String[] keyValueArray = str.split("=");
				String key = keyValueArray[0];
				String value = "";
				if (keyValueArray.length >= 2) {
					value = keyValueArray[1];
				}
				plainMap.put(key, value);
			}

			logger.debug("plainMap is " + plainMap.toString());
			dealseq = plainMap.get("dealseq");
			String fee = plainMap.get("fee");
			String payresult = plainMap.get("payresult");
			if (!payresult.equals("0")) {
				logger.error("order failed payResult=" + payresult);
				return fail;
			}

			String platformId = orderid;
            platformId = StringUtils.isEmpty(platformId) ? "kuaiyong order id is empty" : platformId;
			// 取得充值人民币
			double CostMoney = Double.parseDouble(fee);
			boolean iResult = callback.succeedPayment(dealseq, platformId, CostMoney, "RMB",
                    payresult, ParseJson.encodeJson(paramMap));
			if(iResult)
				return success;
		} catch (Exception e) {
			logger.error("", e);
		}
        return fail;
    }

	@SuppressWarnings("rawtypes")
	@Override
	public SDKVerifyRet verifyUser(JsonReqObj input, Object config) {
		SDKVerifyRet ret = new SDKVerifyRet();
        try {
            KuaiYongSDKInfo configInfo = (KuaiYongSDKInfo) config;
            String token = input.getSDKAccessToken();
            String appKey = configInfo.getAppKey();
            String content = appKey.toLowerCase() + token.toLowerCase();
            String mySign = MD5Util.MD5(content);
            String url = configInfo.getRequestUrl();
            String getInfo = url + "?tokenKey=" + token + "&sign=" + mySign;
            String result = HttpUtil.get(getInfo);
            Map resultMap = ParseJson.getJsonContentByStr(result, Map.class);
            if (resultMap == null || !"0".equals(String.valueOf(resultMap.get("code")))) {
                ret.setErrorMsg(this.getSDKId() + " verifyUser Error");
                return ret.fail();
            }
            Map dataMap = ParseJson.getJsonContentByStr(ParseJson.encodeJson(resultMap.get("data")), Map.class);
            if (dataMap != null) {
                ret.setSdkUid(String.valueOf(dataMap.get("guid")));
                ret.setExtra("username", String.valueOf(dataMap.get("username")));
                ret.setSdkAccessToken(token);
                return ret.success();
            }
            logger.error("SDK response error. result=" + result);
        } catch (Exception e) {
            logger.error("", e);
        }
        return ret.fail();
    }

}


text:
package group.idealworld.dew.core.cluster;

import group.idealworld.dew.core.cluster.spi.rocket.RocketClusterMQ;
import group.idealworld.dew.core.cluster.test.ClusterMQTest;
import group.idealworld.dew.test.RocketMQExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.testcontainers.junit.jupiter.Testcontainers;

/**
 * Cluster test.
 *
 * @author nipeixuan
 */
@ExtendWith({SpringExtension.class, RocketMQExtension.class})
@ContextConfiguration(initializers = RocketMQExtension.Initializer.class)
@SpringBootApplication
@SpringBootTest
@Testcontainers
public class ClusterTest {

    @Autowired
    private RocketClusterMQ rocketClusterMQ;

    /**
     * Test mq.
     *
     * @throws InterruptedException the interrupted exception
     */
    @Test
    public void testMQ() throws InterruptedException {
        new ClusterMQTest().test(rocketClusterMQ);
    }

}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_66b.c
Label Definition File: CWE195_Signed_to_Unsigned_Conversion_Error.label.xml
Template File: sources-sink-66b.tmpl.c
*/
/*
 * @description
 * CWE: 195 Signed to Unsigned Conversion Error
 * BadSource: fgets Read data from the console using fgets()
 * GoodSource: Positive integer
 * Sinks: malloc
 *    BadSink : Allocate memory using malloc() with the size of data
 * Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)

#ifndef OMITBAD

void CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_66b_badSink(int dataArray[])
{
    /* copy data out of dataArray */
    int data = dataArray[2];
    /* Assume we want to allocate a relatively small buffer */
    if (data < 100)
    {
        /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative,
         * the conversion will cause malloc() to allocate a very large amount of data or fail */
        char * dataBuffer = (char *)malloc(data);
        /* Do something with dataBuffer */
        memset(dataBuffer, 'A', data-1);
        dataBuffer[data-1] = '\0';
        printLine(dataBuffer);
        free(dataBuffer);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_66b_goodG2BSink(int dataArray[])
{
    int data = dataArray[2];
    /* Assume we want to allocate a relatively small buffer */
    if (data < 100)
    {
        /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative,
         * the conversion will cause malloc() to allocate a very large amount of data or fail */
        char * dataBuffer = (char *)malloc(data);
        /* Do something with dataBuffer */
        memset(dataBuffer, 'A', data-1);
        dataBuffer[data-1] = '\0';
        printLine(dataBuffer);
        free(dataBuffer);
    }
}

#endif /* OMITGOOD */


text:
require 'fileutils'
require 'java_buildpack/component/versioned_dependency_component'
require 'java_buildpack/jre'

module JavaBuildpack
  module Jre

    # Encapsulates the detect, compile, and release functionality for the jvmkill agent
    class JvmkillAgent < JavaBuildpack::Component::VersionedDependencyComponent
      include JavaBuildpack::Util

      # (see JavaBuildpack::Component::BaseComponent#compile)
      def compile
        download(@version, @uri) do |file|
          FileUtils.mkdir_p jvmkill_agent.parent
          FileUtils.cp(file.path, jvmkill_agent)
          jvmkill_agent.chmod 0o755
        end

        puts "       Write terminal heap dumps to #{heap_dump_path}" if @application.services.one_volume_service? FILTER
      end

      # (see JavaBuildpack::Component::BaseComponent#release)
      def release
        properties                 = { 'printHeapHistogram' => '1' }
        properties['heapDumpPath'] = heap_dump_path if @application.services.one_volume_service? FILTER

        @droplet.java_opts.add_agentpath_with_props(jvmkill_agent, properties)
      end

      protected

      # (see JavaBuildpack::Component::VersionedDependencyComponent#supports?)
      def supports?
        true
      end

      private

      FILTER = /heap-dump/.freeze

      private_constant :FILTER

      def application_identifier
        "#{@application.details['application_name']}-#{@application.details['application_id'][0...8]}"
      end

      def container_dir
        @application.services.find_volume_service(FILTER)['volume_mounts'].first['container_dir']
      end

      def heap_dump_path
        "#{container_dir}/#{space_identifier}/#{application_identifier}/#{instance_identifier}.hprof"
      end

      def instance_identifier
        '$CF_INSTANCE_INDEX-%FT%T%z-${CF_INSTANCE_GUID:0:8}'
      end

      def jvmkill_agent
        @droplet.sandbox + "bin/jvmkill-#{@version}"
      end

      def space_identifier
        "#{@application.details['space_name']}-#{@application.details['space_id'][0...8]}"
      end

    end

  end
end


text:
title: Pipeline Hooks
---

The build pipeline is composed of a series of hooks that each deploy plugin can optionally implement.

Note:
If multiple plugins implement the same hook they will all be called, if you need to specify the order
you can use the `plugins: [...]` option in the [configuration](../configuration-overview).

## Hooks by command

Depending on the command, different hooks will be called (in order):

### Hooks for `ember deploy`
```
* configure
* setup
* willDeploy
* willBuild, build, didBuild,
* willPrepare, prepare, didPrepare,
* willUpload, upload, didUpload,
* willActivate, activate, didActivate, (only if --activate flag is passed)
* didDeploy,
* teardown
```

#### Detailed description:

```
configure: ---> Runs before anything happens

setup: -------> The first hook for every command

                Runs before anything happens.
willDeploy: --> Good opportunity for plugins to validate
                configuration or other preconditions

           /-- willBuild  confirm environment
          /
build -----------> build  builds app assets, documentation, etc.
          \
           \--- didBuild  manipulate index.html, validate assets

           /--- willPrepare  confirm deployment info
          /
prepare ----------> prepare  information about the deploy,
          \                  eg revisonKey, timestamp, commit message
           \
            \--- didPrepare  notify APIS (slack etc)

           /--- willUpload  confirm remote servers(S3, Redis, Azure, etc.)
          /
upload -----------> upload  puts the assets somewhere
          \                 (S3, Redis, Azure, Rackspace, etc.)
           \
            \--- didUpload  notify APIs (slack, pusher, etc.), warm cache

            /-- willActivate  create backup of assets,
           /                  notify APIs, uninstall earlier versions
          /
activate ---------> activate  make a new version live
          \                   (clear cache, swap Redis values, etc.)
           \
            \-- didActivate  notify APIs, warm cache

didDeploy: --> runs at the end of a full deployment operation.

teardown: ---> always the last hook being run
```

### Hooks for `ember deploy:activate`
```
* configure
* setup
* willActivate, activate, didActivate
* teardown
```

#### Detailed description:

```
configure: ---> Runs before anything happens

setup: -------> The first hook for every command

            /-- willActivate  create backup of assets,
           /                  notify APIs, uninstall earlier versions
          /
activate ---------> activate  make a new version live
          \                   (clear cache, swap Redis values, etc.)
           \
            \-- didActivate  notify APIs, warm cache

teardown: ---> always the last hook being run
```

### Hooks for `ember deploy:list`
```
* configure
* setup
* fetchRevisions
* displayRevisions
* teardown
```

#### Detailed description:

```
configure: ---> Runs before anything happens

setup: -------> The first hook for every command

fetchRevisions: ----> returns an hash (or a promise resolving to one)
                      that has a `revisions` key and an array of revisions
                      objects as its value.  i.e. `{revisions: [...]}
                      Each revision object _must_ have
                      an `revision` key. Each revision _may_ have one
                      or more of the following properties:

                      `version`:     (String) reference of version in SCM
                      `timestamp`:   (Date) when the version was created
                      `deployer`:    (String) name/email address of
                                     developer who deployed the version
                      `active`:      (Boolean) is the revision activated?
                      `description`: (String) summary of the revision

displayRevisions: --> looks up the `revisions` key in the `context`
                      and uses the information to
                      display the list of revisions.

teardown: ---> always the last hook being run
```

See [ember-cli-deploy-display-revisions](https://github.com/ember-cli-deploy/ember-cli-deploy-display-revisions) for a detailed example.

### The `didFail` hook

When a hook invocation rejects, the pipeline aborts execution.
As soon as that happens a special `didFail` hook is invoked on all the registered plugins.

Plugins can optionally implement the `didFail` hook to handle any cleanup that might be needed in this case.

### Return values & Async operations in hooks

The return value of each hook can be used to add information to the [deployment context](../deployment-context).

Hook functions can return a promise to block the deployment pipeline.
Since most deployment involves some sort of IO it makes senses that most
plugins will want an async function to complete before continuing to the
next step.

If a plugin does not return a promise, then ember-cli-deploy proceeds immediately.

If a promise from any of the plugins is rejected then the deployment
pipeline will stop and ember-cli-deploy will exit. Returned promises that are
rejected are treated as unrecoverable errors.


text:
OpenLightInitiative
===================

A collection of code and schematics for making custom/hackable lighting.


text:
//
//  SkywareOtherManager.h
//  SkywareSDK
//
//  Created by 李晓 on 15/12/3.
//  Copyright © 2015年 skyware. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "SkywareHttpTool.h"

@interface SkywareOtherManager : NSObject

/**
 *             天气接口
 *
 *   SkywareWeatherModel *model = [[SkywareWeatherModel alloc] init];
 *   model.province = @"河北省";
 *   model.city = @"沧州市";
 *   model.district = @"吴桥县";
 *  [SkywareOthersManager UserAddressWeatherParamesers:model Success:^(SkywareResult *result) {
 *       SkywareAddressWeatherModel *addressModel = [SkywareAddressWeatherModel objectWithKeyValues:result.result];
 *       NSLog(@"%@",addressModel);
 *     } failure:^(SkywareResult *result) {
 *        NSLog(@"%@",result);
 *   }];
 */
+ (void) UserAddressWeatherParamesers:(SkywareWeatherModel *) model Success:(void(^)(SkywareResult *result)) success failure:(void (^)(SkywareResult *result)) failure;

/**
 *  发送日志信息到服务器  (目前只有配网的日志)
 *
 *  @param params
 NSDictionary *dic =  @{
 @"log":@{
 @"app_id":@"1",
 @"app_version":@"1"
 ...
 }
 };
 *  @param success
 *  @param failure
 */
+ (void) UserSendLogParamesers:(NSDictionary *) params Success:(void(^)(SkywareResult *result)) success failure:(void (^)(SkywareResult *result)) failure;

@end


text:
package com.microsoftopentechnologies.intellij.forms;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.microsoftopentechnologies.intellij.components.MSOpenTechToolsApplication;
import com.microsoftopentechnologies.intellij.components.PluginSettings;
import com.microsoftopentechnologies.intellij.helpers.UIHelper;
import com.microsoftopentechnologies.intellij.helpers.aadauth.AuthenticationContext;
import com.microsoftopentechnologies.intellij.helpers.aadauth.AuthenticationResult;
import com.microsoftopentechnologies.intellij.helpers.aadauth.PromptValue;
import com.microsoftopentechnologies.intellij.helpers.azure.AzureAuthenticationMode;
import com.microsoftopentechnologies.intellij.helpers.azure.AzureCmdException;
import com.microsoftopentechnologies.intellij.helpers.azure.AzureManager;
import com.microsoftopentechnologies.intellij.helpers.azure.AzureRestAPIManager;
import com.microsoftopentechnologies.intellij.model.Subscription;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
import java.util.Vector;

public class ManageSubscriptionForm extends JDialog {
    private JPanel mainPanel;
    private JTable subscriptionTable;
    private JButton signInButton;
    private JButton removeButton;
    private JButton importSubscriptionButton;
    private JButton closeButton;
    private ArrayList<Subscription> subscriptionList;
    private Project project;

    public ManageSubscriptionForm(final Project project) {
        this.project = project;

        this.setTitle("Manage Subscriptions");
        this.setModal(true);
        this.setContentPane(mainPanel);

        this.setResizable(false);

        final DefaultTableModel model = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int col) {
                return (col == 0);
            }

            public Class<?> getColumnClass(int colIndex) {
                return getValueAt(0, colIndex).getClass();
            }
        };

        model.addColumn("");
        model.addColumn("Name");
        model.addColumn("Id");

        subscriptionTable.setModel(model);

        TableColumn column = subscriptionTable.getColumnModel().getColumn(0);
        column.setMinWidth(23);
        column.setMaxWidth(23);

        signInButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    if (AzureRestAPIManager.getManager().getAuthenticationToken() != null) {
                        clearSubscriptions(false);
                    } else {
                        PluginSettings settings = MSOpenTechToolsApplication.getCurrent().getSettings();
                        final AuthenticationContext context = new AuthenticationContext(settings.getAdAuthority());

                        Futures.addCallback(context.acquireTokenInteractiveAsync(
                                settings.getTenantName(),
                                settings.getAzureServiceManagementUri(),
                                settings.getClientId(),
                                settings.getRedirectUri(),
                                project,
                                PromptValue.login), new FutureCallback<AuthenticationResult>() {
                            @Override
                            public void onSuccess(AuthenticationResult authenticationResult) {
                                context.dispose();

                                if (authenticationResult != null) {
                                    final AzureManager apiManager = AzureRestAPIManager.getManager();
                                    apiManager.setAuthenticationMode(AzureAuthenticationMode.ActiveDirectory);
                                    apiManager.setAuthenticationToken(authenticationResult);

                                    // load list of subscriptions
                                    ApplicationManager.getApplication().invokeAndWait(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                apiManager.clearSubscriptions();

                                                refreshSignInCaption();
                                            } catch (AzureCmdException e1) {
                                                UIHelper.showException("An error occurred while attempting to " +
                                                        "clear your old subscriptions.", e1);
                                            }

                                            loadList();
                                        }
                                    }, ModalityState.any());
                                }
                            }

                            @Override
                            public void onFailure(Throwable throwable) {
                                context.dispose();
                                UIHelper.showException("An error occurred while attempting to sign in to your account.", throwable);
                            }
                        });
                    }
                } catch (IOException e1) {
                    UIHelper.showException("An error occurred while attempting to sign in to your account.", e1);
                }
            }
        });

        removeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                clearSubscriptions(true);
            }
        });

        removeButton.setEnabled(false);

        importSubscriptionButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ImportSubscriptionForm isf = new ImportSubscriptionForm();
                isf.setOnSubscriptionLoaded(new Runnable() {
                    @Override
                    public void run() {
                        loadList();
                    }
                });
                UIHelper.packAndCenterJDialog(isf);
                isf.setVisible(true);
            }
        });

        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
                loadList();
            }
        });
    }

    private void refreshSignInCaption() {
        boolean isNotSigned = (AzureRestAPIManager.getManager().getAuthenticationToken() == null);

        signInButton.setText(isNotSigned ? "Sign In ..." : "Sign Out");
    }

    private void clearSubscriptions(boolean isSigningOut) {
        int res = JOptionPane.showConfirmDialog(this, (isSigningOut
                        ? "Are you sure you would like to clear all subscriptions?"
                        : "Are you sure you would like to sign out?"),
                (isSigningOut
                        ? "Clear Subscriptions"
                        : "Sign out"),
                JOptionPane.YES_NO_OPTION,
                JOptionPane.INFORMATION_MESSAGE);

        if (res == JOptionPane.YES_OPTION) {
            try {
                AzureManager apiManager = AzureRestAPIManager.getManager();
                apiManager.clearAuthenticationTokens();
                apiManager.clearSubscriptions();
                apiManager.setAuthenticationMode(AzureAuthenticationMode.Unknown);
            } catch (AzureCmdException t) {
                UIHelper.showException("Error clearing user subscriptions", t);
            }

            DefaultTableModel model = (DefaultTableModel) subscriptionTable.getModel();

            while (model.getRowCount() > 0) {
                model.removeRow(0);
            }

            PropertiesComponent.getInstance().unsetValue(MSOpenTechToolsApplication.AppSettingsNames.SELECTED_SUBSCRIPTIONS);
            ApplicationManager.getApplication().saveSettings();

            removeButton.setEnabled(false);

            refreshSignInCaption();
        }
    }

    private void onCancel() {
        try {
            ArrayList<UUID> selectedList = new ArrayList<UUID>();

            TableModel model = subscriptionTable.getModel();

            for (int i = 0; i < model.getRowCount(); i++) {
                Boolean selected = (Boolean) model.getValueAt(i, 0);

                if (selected) {
                    selectedList.add(UUID.fromString(model.getValueAt(i, 2).toString()));
                }
            }

            AzureRestAPIManager.getManager().setSelectedSubscriptions(selectedList);

            //Saving the project is necessary to save the changes on the PropertiesComponent
            if (project != null) {
                project.save();
            }

            dispose();
        } catch (AzureCmdException e) {
            UIHelper.showException("Error setting selected subscriptions", e);
        }
    }

    private void loadList() {
        final JDialog form = this;
        final DefaultTableModel model = (DefaultTableModel) subscriptionTable.getModel();

        refreshSignInCaption();

        while (model.getRowCount() > 0) {
            model.removeRow(0);
        }

        form.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        Vector<Object> vector = new Vector<Object>();
        vector.add("");
        vector.add("(loading... )");
        vector.add("");
        model.addRow(vector);

        ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    while (model.getRowCount() > 0) {
                        model.removeRow(0);
                    }

                    subscriptionList = AzureRestAPIManager.getManager().getFullSubscriptionList();

                    if (subscriptionList != null && subscriptionList.size() > 0) {
                        for (Subscription subs : subscriptionList) {
                            Vector<Object> row = new Vector<Object>();
                            row.add(subs.isSelected());
                            row.add(subs.getName());
                            row.add(subs.getId().toString());
                            model.addRow(row);
                        }

                        removeButton.setEnabled(true);
                    } else {
                        removeButton.setEnabled(false);
                    }

                    form.setCursor(Cursor.getDefaultCursor());
                } catch (AzureCmdException e) {
                    form.setCursor(Cursor.getDefaultCursor());
                    UIHelper.showException("Error getting subscription list", e);
                }
            }
        });
    }
}


text:
<?php
namespace Cerad\Bundle\PersonBundle\Tests\Model;

use Cerad\Bundle\PersonBundle\Model\Person;
use Cerad\Bundle\PersonBundle\Model\PersonAddress;

class PersonAddressTest extends \PHPUnit_Framework_TestCase
{
    public function testPersonAddress()
    {
        $person = new Person();

        // Getting back a value object created with the constructor
        $address1 = $person->getAddress();
        $this->assertTrue($address1 instanceOf PersonAddress);

        $address2 = new PersonAddress(null,null,'Huntsville','AL');
        $person->setAddress($address2);

        // New PersonName object was created because values changed
        $address3 = $person->getAddress();
        $this->assertFalse($address2 === $address3);

        $this->assertEquals('Huntsville',$address3->city);
        $this->assertEquals('AL',        $address3->state);

    }
}


text: /*# sourceMappingURL=static_pages.css.map */


text:
module Africastalking
  class Talk < Connection
    base_uri 'https://voice.africastalking.com'

    class << self
      def make_call(from, to)
        post(
          '/call',
          'username' => Africastalking.config.username,
          'from' => from,
          'to' => to
        )
      end

      def fetch_queued_calls(phone_number, queue_name = nil)
        post(
          '/queueStatus',
          'username' => Africastalking.config.username,
          'phoneNumbers' => phone_number,
          'queueName' => queue_name
        )
      end

      def upload_file(url)
        post(
          '/mediaUpload',
          'username' => Africastalking.config.username,
          'url' => url
        )
      end
    end
  end
end


text:
 * Minor bugfix for jsDoc handling

## 0.2.11

 * Change sidebar loading in produced output to fire on DOMContentLoaded - thanks [hhelwich](//github.com/hhelwich)
 * LiveScript syntax support, thanks to [qgustavor](//github.com/qgustavor).
 * Add option to ignore inline comments and only process multiline comments - thanks to [jasonseney](//github.com/jasonseney)
 * Big pile of updates to jsDoc tag handling: alias some types, add default handler for unknown types, and escape HTML properly. Thanks [ErisDS](//github.com/ErisDS)!

## 0.2.10

 * Purely a version bump because npm was having issues publishing 0.2.9

## 0.2.9

 * Use bundled version of Pygments (via [pygmentize-bundled](https://github.com/rvagg/node-pygmentize-bundled)) and remove the setup scripts (thanks [alexindigo](//github.com/alexindigo))
 * Add `cakefile` filename parsed as CoffeeScript, and tweak Jade comments (thanks [alinex](//github.com/alinex))
 * Fix up section separators in languages without multiline comments (thanks [tjbaron](//github.com/tjbaron))

## 0.2.8

 * Warn if Pygments isn't installed
 * Changes to ID generation for headings to support extra characters and ensure IDs are unique (thanks to [justan](//github.com/justan))

## 0.2.7

 * Add support for styl, jade, groove and gsp (thanks to [mikkel](//github.com/mikkel))
 * Add support for languages without single-line comments (currently CSS and HTML)
 * Change white-space to pre-wrap

## 0.2.6

 * Fix a weird bug in SCSS parsing

## 0.2.5

 * Fix for file paths in windows (`\` as a path separator broke things)
 * Throw errors on filesystem exceptions

## 0.2.4

 * Update watchr dependency
 * Tweaks to fileSearch extra

## 0.2.3

 * Lots of minor tweaks and improvements

## 0.2.2

 * Fixes for indented multiline comments and indented comments in CoffeeScript

## 0.2.1

 * Temporarily disable multiline comments in SASS and SCSS as `/*` can be used to open a single-line comment. Will reinstate when I have time to figure it out properly

## 0.2.0

 * Added `--js` and `--css` options to specify extra CSS and JavaScript files to include
 * Added optional `-n` flag to enable line numbers in output
 * Added "disable" value for sidebar to hide it completely
 * Added support for matching files by name rather than just extension (e.g. Makefile)
 * Added first two "extras" - optionally enable-able extras for the output
   - **fileSearch**: performs fuzzy-matching on file names to quickly jump to a file
   - **goToLine**: quickly jump to a line in the source. Currently only works if line numbers are enabled
 * Fixed some bugs in Markdown parsing
 * Improvements to indentation detection
 * Fixed bug where processing only updated files would result in an empty tree

## 0.1.8

 * Removed dependency on dox; wrote more concise version of jsDoc parser based on dox, but which handles headings correctly
 * Bugfixes for watch mode.

## 0.1.7

 * Bugfix: indented jsDoc was breaking.

## 0.1.6

 * Added support for VB.NET, ASP C# and ASP VB courtesy of [peterhost](https://github.com/peterhost)

## 0.1.5

 * Added smarter handling of symbolic links, allowing for handling of dead links

## 0.1.4

 * Added language type detection from shebangs

## 0.1.3

 * Added `-s` option to specify default state of the sidebar
 * Added `-x` option to specify paths to exclude
 * Renamed `tree` to `sidebar` in some of the markup.

## 0.1.2

 * Windows compatibility
 * Resolve infinite loop problem when files aren't actually inside the source dir
 * A few minor typos

## 0.1.1

 * Fixed problem with comment delimiters being matched inside string literals

## 0.1.0

 * Added `-w` flag to watch a directory for changes (experimental). Not sure how useful it'll actually be, but it's cool.
 * Added `-I` switch to ignore hidden files
 * Fixed some rendering bugs for code blocks
 * Added automatic title generation for empty-looking files
 * Various styling tweaks

## 0.0.9

 * Added support for another pile more languages (added perl, php, actionscript, sh and yaml)
 * Ran embedded arrow images through pngcrush.  Saved a load of bytes

## 0.0.8

 * Added support for different colour schemes
 * A few more improvements to showdown for GFM-style bits.

## 0.0.7

 * Minor improvements to code structure
 * Full comments on public script file

## 0.0.6

 * Added support for a pile more languages (now JS, coffeescript, ruby, python, C, C++, C#, Java and Markdown)
 * Tweaks to markdown (particularly, automatic linking of URLs and email addresses)

## 0.0.5

 * Added heading navigation within files

## 0.0.4

 * Added syntax highlighting to fenced code blocks that have a language specified

## 0.0.3

 * Minor improvements to store the scroll position of the folder tree

## 0.0.2

 * Added `-u` flag to only process files that have been updated

## 0.0.1

Initial version indcluded (among other things):

 * Folder tree
 * Syntax highlighting of javascript files
 * Markdown processing of `.md` files and extracted code comments