text:
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Library providing basic test framework functionality.
 */

/* eslint-disable no-console */

/**
 * See assert.js for where this is used.
 * @suppress {globalThis}
 */
this.traceAssertionsForTesting = true;

/** @suppress {globalThis} */
// eslint-disable-next-line no-var
var hasWindow = !!this.window;

/**
 * Namespace for |Test|.
 * @type {Object}
 */
// eslint-disable-next-line no-var
var testing = {};
(function(exports) {
/**
 * Hold the currentTestCase across between preLoad and run.
 * @type {TestCase}
 */
let currentTestCase = null;

/**
 * Value set to true by WebUIBrowserTest if test harness should wait for user to
 * attach a debugger.
 *
 * @type {boolean}
 */
let waitUser = false;

/**
 * The string representation of the currently running test function.
 * @type {?string}
 */
let currentTestFunction = null;

/**
 * The arguments of the currently running test.
 * @type {Array}
 */
let currentTestArguments = [];

/**
 * This class will be exported as testing.Test, and is provided to hold the
 * fixture's configuration and callback methods for the various phases of
 * invoking a test. It is called "Test" rather than TestFixture to roughly
 * mimic the gtest's class names.
 * @constructor
 */
function Test() {}

/**
 * Make all transitions and animations take 0ms. NOTE: this will completely
 * disable webkitTransitionEnd events. If your code relies on them firing, it
 * will break. animationend events should still work.
 */
Test.disableAnimationsAndTransitions = function() {
  const all = document.body.querySelectorAll('*');
  const ZERO_MS_IMPORTANT = '0ms !important';
  for (let i = 0, l = all.length; i < l; ++i) {
    const style = all[i].style;
    style.animationDelay = ZERO_MS_IMPORTANT;
    style.animationDuration = ZERO_MS_IMPORTANT;
    style.transitionDelay = ZERO_MS_IMPORTANT;
    style.transitionDuration = ZERO_MS_IMPORTANT;
  }

  const realElementAnimate = Element.prototype.animate;
  Element.prototype.animate = function(keyframes, opt_options) {
    if (typeof opt_options === 'object') {
      opt_options.duration = 0;
    } else {
      opt_options = 0;
    }
    return realElementAnimate.call(this, keyframes, opt_options);
  };
  if (document.timeline && document.timeline.play) {
    const realTimelinePlay = document.timeline.play;
    document.timeline.play = function(a) {
      a.timing.duration = 0;
      return realTimelinePlay.call(document.timeline, a);
    };
  }
};

Test.prototype = {
  /**
   * The name of the test.
   */
  name: null,

  /**
   * When set to a string value representing a url, generate BrowsePreload
   * call, which will browse to the url and call fixture.preLoad of the
   * currentTestCase.
   * @type {?string}
   */
  browsePreload: null,

  /** @type {?string} */
  webuiHost: null,

  /**
   * When set to a function, will be called in the context of the test
   * generation inside the function, after AddLibrary calls and before
   * generated C++.
   * @type {?function(string,string)}
   */
  testGenPreamble: null,

  /**
   * When set to a function, will be called in the context of the test
   * generation inside the function, and after any generated C++.
   * @type {?function(string,string)}
   */
  testGenPostamble: null,

  /** @type {?function()} */
  testGenCppIncludes: null,

  /**
   * When set to a non-null string, auto-generate typedef before generating
   * TEST*: {@code typedef typedefCppFixture testFixture}.
   * @type {string}
   */
  typedefCppFixture: 'WebUIBrowserTest',

  /** @type {?Array<{switchName: string, switchValue: string}>} */
  commandLineSwitches: null,

  /** @type {?{enabled: !Array<string>, disabled: !Array<string>}} */
  featureList: null,

  /**
   * @type {?Array<!{
   *    featureName: string,
   *    parameters: !Array<{name: string, value: string}>}>}
   */
  featuresWithParameters: null,

  /**
   * Value is passed through call to C++ RunJavascriptF to invoke this test.
   * @type {boolean}
   */
  isAsync: false,

  /**
   * True when the test is expected to fail for testing the test framework.
   * @type {boolean}
   */
  testShouldFail: false,

  /**
   * Starts a local test server if true and injects the server's base url to
   * each test. The url can be accessed from
   * |testRunnerParams.testServerBaseUrl|.
   * @type {boolean}
   */
  testServer: false,

  /**
   * Extra libraries to add before loading this test file.
   * @type {Array<string>}
   */
  extraLibraries: [],

  /**
   * Extra libraries to add before loading this test file.
   * This list is in the form of Closure library style object
   * names.  To support this, a closure deps.js file must
   * be specified when generating the test C++ source.
   * The specified libraries will be included with their transitive
   * dependencies according to the deps file.
   * @type {Array<string>}
   */
  closureModuleDeps: [],

  /**
   * Override this method to perform initialization during preload (such as
   * creating mocks and registering handlers).
   * @type {Function}
   */
  preLoad: function() {},

  /**
   * Override this method to perform tasks before running your test.
   * @type {Function}
   */
  setUp: function() {},

  /**
   * Override this method to perform tasks after running your test.
   * @type {Function}
   */
  tearDown: function() {
    if (typeof document !== 'undefined') {
      const noAnimationStyle = document.getElementById('no-animation');
      if (noAnimationStyle) {
        noAnimationStyle.parentNode.removeChild(noAnimationStyle);
      }
    }
  },

  /**
   * Called to run the body from the perspective of this fixture.
   * @type {Function}
   */
  runTest: function(testBody) {
    testBody.call(this);
  },

  /**
   * Create a closure function for continuing the test at a later time. May be
   * used as a listener function.
   * @param {WhenTestDone} whenTestDone Call testDone() at the appropriate
   *     time.
   * @param {!Function} completion The function to call to complete the test.
   * @param {...*} var_args Arguments to pass when calling completionAction.
   * @return {function(): void} Return a function, bound to this test fixture,
   *     which continues the test.
   */
  continueTest: function(whenTestDone, completion, var_args) {
    const savedArgs = new SaveMockArguments();
    const completionAction = new CallFunctionAction(
        this, savedArgs, completion, Array.prototype.slice.call(arguments, 2));
    if (whenTestDone === WhenTestDone.DEFAULT) {
      whenTestDone = WhenTestDone.ASSERT;
    }
    const runAll = new RunAllAction(true, whenTestDone, [completionAction]);
    return function() {
      savedArgs.arguments = Array.prototype.slice.call(arguments);
      runAll.invoke();
    };
  },

  /**
   * Call this during setUp to defer the call to runTest() until later. The
   * caller must call the returned function at some point to run the test.
   * @param {WhenTestDone} whenTestDone Call testDone() at the appropriate
   *     time.
   * @param {...*} var_args Arguments to pass when running the
   *     |currentTestCase|.
   * @return {function(): void} A function which will run the current body of
   *     the currentTestCase.
   */
  deferRunTest: function(whenTestDone, var_args) {
    if (whenTestDone === WhenTestDone.DEFAULT) {
      whenTestDone = WhenTestDone.ALWAYS;
    }

    return currentTestCase.deferRunTest.apply(
        currentTestCase,
        [whenTestDone].concat(Array.prototype.slice.call(arguments, 1)));
  },
};

/**
 * This class is not exported and is available to hold the state of the
 * |currentTestCase| throughout preload and test run.
 * @param {string} name The name of the test case.
 * @param {Test} fixture The fixture object for this test case.
 * @param {Function} body The code to run for the test.
 * @constructor
 */
function TestCase(name, fixture, body) {
  this.name = name;
  this.fixture = fixture;
  this.body = body;
}

TestCase.prototype = {
  /**
   * The name of this test.
   * @type {?string}
   */
  name: null,

  /**
   * The test fixture to set |this| to when running the test |body|.
   * @type {Test}
   */
  fixture: null,

  /**
   * The test body to execute in runTest().
   * @type {Function}
   */
  body: null,

  /**
   * True when the test fixture will run the test later.
   * @type {boolean}
   * @private
   */
  deferred_: false,

  /**
   * Called at preload time, proxies to the fixture.
   * @type {Function}
   */
  preLoad: function(name) {
    if (this.fixture) {
      this.fixture.preLoad();
    }
  },

  /**
   * Called before a test runs.
   */
  setUp: function() {
    if (this.fixture) {
      this.fixture.setUp();
    }
  },

  /**
   * Called before a test is torn down (by testDone()).
   */
  tearDown: function() {
    if (this.fixture) {
      this.fixture.tearDown();
    }
  },

  /**
   * Called to run this test's body.
   */
  runTest: function() {
    if (this.body && this.fixture) {
      this.fixture.runTest(this.body);
    }
  },

  /**
   * Runs this test case with |this| set to the |fixture|.
   *
   * Note: Tests created with TEST_F may depend upon |this| being set to an
   * instance of this.fixture. The current implementation of TEST creates a
   * dummy constructor, but tests created with TEST should not rely on |this|
   * being set.
   * @type {Function}
   */
  run: function() {
    try {
      this.setUp();
    } catch (e) {
      // Mock4JSException doesn't inherit from Error, so fall back on
      // toString().
      console.error(e.stack || e.toString());
    }

    if (!this.deferred_) {
      this.runTest();
    }

    // tearDown called by testDone().
  },

  /**
   * Cause this TestCase to be deferred (don't call runTest()) until the
   * returned function is called.
   * @param {WhenTestDone} whenTestDone Call testDone() at the appropriate
   *     time.
   * @param {...*} var_args Arguments to pass when running the
   *     |currentTestCase|.
   * @return {function(): void} A function that will run this TestCase when
   *     called.
   */
  deferRunTest: function(whenTestDone, var_args) {
    this.deferred_ = true;
    const savedArgs = new SaveMockArguments();
    const completionAction = new CallFunctionAction(
        this, savedArgs, this.runTest,
        Array.prototype.slice.call(arguments, 1));
    const runAll = new RunAllAction(true, whenTestDone, [completionAction]);
    return function() {
      savedArgs.arguments = Array.prototype.slice.call(arguments);
      runAll.invoke();
    };
  },

};

/**
 * true when testDone has been called.
 * @type {boolean}
 */
let testIsDone = false;

/**
 * Holds the errors, if any, caught by expects so that the test case can
 * fail. Cleared when results are reported from runTest() or testDone().
 * @type {Array<Error>}
 */
const errors = [];

/**
 * URL to dummy WebUI page for testing framework.
 * @type {string}
 */
const DUMMY_URL = 'chrome://DummyURL';

/**
 * Resets test state by clearing |errors| and |testIsDone| flags.
 */
function resetTestState() {
  errors.splice(0, errors.length);
  testIsDone = false;
}

/**
 * Notifies the running browser test of the test results. Clears |errors|.
 * No tuple type: b/131114945 (result should be {[boolean, string]}).
 * @param {Array=} result When passed, this is used for the testResult message.
 */
function testDone(result) {
  if (!testIsDone) {
    testIsDone = true;
    if (currentTestCase) {
      let ok = true;
      ok = createExpect(currentTestCase.tearDown.bind(currentTestCase))
               .call(null) &&
          ok;

      if (!ok && result) {
        result = [false, errorsToMessage(errors, result[1])];
      }

      currentTestCase = null;
    }
    if (!result) {
      result = testResult();
    }

    const [success, errorMessage] = /** @type {!Array} */ (result);
    if (hasWindow && window.reportMojoWebUITestResult) {
      // For "mojo_webui" test types, reportMojoWebUITestResult should already
      // be defined globally, because such tests must manually import the
      // mojo_webui_test_support.js module which defines it.
      if (success) {
        window.reportMojoWebUITestResult();
      } else {
        window.reportMojoWebUITestResult(errorMessage);
      }
    } else if (hasWindow && window.webUiTest) {
      let testRunner;
      if (webUiTest.mojom.TestRunnerRemote) {
        // For mojo-lite WebUI tests.
        testRunner = webUiTest.mojom.TestRunner.getRemote();
      } else {
        assertNotReached(
            'Mojo bindings found, but no valid test interface loaded');
      }
      if (success) {
        testRunner.testComplete(null);
      } else {
        testRunner.testComplete(errorMessage);
      }
    } else if (chrome.send) {
      // For WebUI and v8 unit tests.
      chrome.send('testResult', result);
    } else if (chrome.test.sendScriptResult) {
      // For extension tests.
      const valueResult = {'result': success, message: errorMessage};
      chrome.test.sendScriptResult(JSON.stringify(valueResult));
    } else {
      assertNotReached('No test framework available');
    }
    errors.splice(0, errors.length);
  } else {
    console.warn('testIsDone already');
  }
}

/**
 * Converts each Error in |errors| to a suitable message, adding them to
 * |message|, and returns the message string.
 * @param {Array<Error>} errors Array of errors to add to |message|.
 * @param {string=} opt_message Message to append error messages to.
 * @return {string} |opt_message| + messages of all |errors|.
 */
function errorsToMessage(errors, opt_message) {
  let message = '';
  if (opt_message) {
    message += opt_message + '\n';
  }

  for (let i = 0; i < errors.length; ++i) {
    const errorMessage = errors[i].stack || errors[i].message;
    // Cast JSON.stringify to Function to avoid formal parameter mismatch.
    message += 'Failed: ' + currentTestFunction + '(' +
        currentTestArguments.map(/** @type{Function} */ (JSON.stringify)) +
        ')\n' + errorMessage;
  }
  return message;
}

/**
 * Returns [success, message] & clears |errors|.
 * @param {boolean=} errorsOk When true, errors are ok.
 *
 * No tuple type: b/131114945 (result should be {[boolean, string]}).
 * @return {Array}
 */
function testResult(errorsOk) {
  let result = [true, ''];
  if (errors.length) {
    result = [!!errorsOk, errorsToMessage(errors)];
  }

  return result;
}

// Asserts.
// Use the following assertions to verify a condition within a test.

/**
 * @param {boolean} value The value to check.
 * @param {string=} opt_message Additional error message.
 * @throws {Error}
 */
function assertTrue(value, opt_message) {
  chai.assert.isTrue(value, opt_message);
}

/**
 * @param {boolean} value The value to check.
 * @param {string=} opt_message Additional error message.
 * @throws {Error}
 */
function assertFalse(value, opt_message) {
  chai.assert.isFalse(value, opt_message);
}

/**
 * @param {number} value1 The first operand.
 * @param {number} value2 The second operand.
 * @param {string=} opt_message Additional error message.
 * @throws {Error}
 */
function assertGE(value1, value2, opt_message) {
  chai.expect(value1).to.be.at.least(value2, opt_message);
}

/**
 * @param {number} value1 The first operand.
 * @param {number} value2 The second operand.
 * @param {string=} opt_message Additional error message.
 * @throws {Error}
 */
function assertGT(value1, value2, opt_message) {
  chai.assert.isAbove(value1, value2, opt_message);
}

/**
 * @param {*} expected The expected value.
 * @param {*} actual The actual value.
 * @param {string=} opt_message Additional error message.
 * @throws {Error}
 */
function assertEquals(expected, actual, opt_message) {
  chai.assert.strictEqual(actual, expected, opt_message);
}

/**
 * @param {*} expected
 * @param {*} actual
 * {string=} opt_message
 * @throws {Error}
 */
function assertDeepEquals(expected, actual, opt_message) {
  chai.assert.deepEqual(actual, expected, opt_message);
}

/**
 * @param {number} value1 The first operand.
 * @param {number} value2 The second operand.
 * @param {string=} opt_message Additional error message.
 * @throws {Error}
 */
function assertLE(value1, value2, opt_message) {
  chai.expect(value1).to.be.at.most(value2, opt_message);
}

/**
 * @param {number} value1 The first operand.
 * @param {number} value2 The second operand.
 * @param {string=} opt_message Additional error message.
 * @throws {Error}
 */
function assertLT(value1, value2, opt_message) {
  chai.assert.isBelow(value1, value2, opt_message);
}

/**
 * @param {*} expected The expected value.
 * @param {*} actual The actual value.
 * @param {string=} opt_message Additional error message.
 * @throws {Error}
 */
function assertNotEquals(expected, actual, opt_message) {
  chai.assert.notStrictEqual(actual, expected, opt_message);
}

/**
 * @param {string=} opt_message Additional error message.
 * @throws {Error}
 */
function assertNotReached(opt_message) {
  chai.assert.fail(null, null, opt_message);
}

/**
 * @param {function()} testFunction
 * @param {(Function|string|RegExp)=} opt_expected_or_constructor The expected
 *     Error constructor, partial or complete error message string, or RegExp to
 *     test the error message.
 * @param {string=} opt_message Additional error message.
 * @throws {Error}
 */
function assertThrows(testFunction, opt_expected_or_constructor, opt_message) {
  // The implementation of assert.throws goes like:
  //  function (fn, errt, errs, msg) {
  //    if ('string' === typeof errt || errt instanceof RegExp) {
  //      errs = errt;
  //      errt = null;
  //    }
  //    ...
  // That is, if the second argument is string or RegExp, the type of the
  // exception is not checked: only the error message. This is achieved by
  // partially "shifting" parameters (the "additional error message" is not
  // shifted and will be lost). "Shifting" isn't a thing Closure understands, so
  // just cast to string.
  // TODO(crbug/1000989): Refactor this into something that makes sense when
  // tests are actually compiled and we can do that safely.
  chai.assert.throws(
      testFunction,
      /** @type{string} */ (opt_expected_or_constructor), opt_message);
}

/**
 * Creates a function based upon a function that throws an exception on
 * failure. The new function stuffs any errors into the |errors| array for
 * checking by runTest. This allows tests to continue running other checks,
 * while failing the overall test if any errors occurred.
 * @param {Function} assertFunc The function which may throw an Error.
 * @return {function(...*):boolean} A function that applies its arguments to
 *     |assertFunc| and returns true if |assertFunc| passes.
 * @see errors
 * @see runTestFunction
 */
function createExpect(assertFunc) {
  return function() {
    try {
      assertFunc.apply(null, arguments);
    } catch (e) {
      errors.push(e);
      return false;
    }
    return true;
  };
}

/**
 * This is the starting point for tests run by WebUIBrowserTest.  If an error
 * occurs, it reports a failure and a message created by joining individual
 * error messages. This supports sync tests and async tests by calling
 * testDone() when |isAsync| is not true, relying on async tests to call
 * testDone() when they complete.
 * @param {boolean} isAsync When false, call testDone() with the test result
 *     otherwise only when assertions are caught.
 * @param {string} testFunction The function name to call.
 * @param {Array} testArguments The arguments to call |testFunction| with.
 * @return {boolean} true always to signal successful execution (but not
 *     necessarily successful results) of this test.
 * @see errors
 * @see runTestFunction
 */
function runTest(isAsync, testFunction, testArguments) {
  // If waiting for user to attach a debugger, retry in 1 second.
  if (waitUser) {
    setTimeout(runTest, 1000, isAsync, testFunction, testArguments);
    return true;
  }

  // Avoid eval() if at all possible, since it will not work on pages
  // that have enabled content-security-policy.
  /** @type {?Function} */
  let testBody = this[testFunction];  // global object -- not a method.
  let testName = testFunction;

  // Depending on how we were called, |this| might not resolve to the global
  // context.
  if (testName === 'RUN_TEST_F' && testBody === undefined) {
    testBody = RUN_TEST_F;
  }

  if (typeof testBody === 'undefined') {
    testBody = /** @type{Function} */ (eval(testFunction));
    testName = testBody.toString();
  }
  if (testBody !== RUN_TEST_F) {
    console.log('Running test ' + testName);
  }

  // Async allow expect errors, but not assert errors.
  const result =
      runTestFunction(testFunction, testBody, testArguments, isAsync);
  if (!isAsync || !result[0]) {
    testDone(result);
  }
  return true;
}

/**
 * This is the guts of WebUIBrowserTest. It runs the test surrounded by an
 * expect to catch Errors. If |errors| is non-empty, it reports a failure and
 * a message by joining |errors|. Consumers can use this to use assert/expect
 * functions asynchronously, but are then responsible for reporting errors to
 * the browser themselves through testDone().
 * @param {string} testFunction The function name to report on failure.
 * @param {Function} testBody The function to call.
 * @param {Array} testArguments The arguments to call |testBody| with.
 * @param {boolean} onlyAssertFails When true, only assertions cause failing
 *     testResult.
 *
 * No tuple type: b/131114945 (result should be {[boolean, string]}).
 * @return {Array} [test-succeeded, message-if-failed]
 * @see createExpect
 * @see testResult
 */
function runTestFunction(
    testFunction, testBody, testArguments, onlyAssertFails) {
  currentTestFunction = testFunction;
  currentTestArguments = testArguments;
  const ok = createExpect(testBody).apply(null, testArguments);
  return testResult(onlyAssertFails && ok);
}

/**
 * Creates a new test case for the given |testFixture| and |testName|. Assumes
 * |testFixture| describes a globally available subclass of type Test.
 * @param {string} testFixture The fixture for this test case.
 * @param {string} testName The name for this test case.
 * @return {TestCase} A newly created TestCase.
 */
function createTestCase(testFixture, testName) {
  const fixtureConstructor = this[testFixture];
  assertTrue(
      !!fixtureConstructor,
      `The testFixture \'${testFixture}\' was not found.`);
  const testBody = fixtureConstructor.testCaseBodies[testName];
  assertTrue(
      !!testBody, `Test \'${testName} was not found in \'${testFixture}\'.`);
  const fixture = new fixtureConstructor();
  fixture.name = testFixture;
  return new TestCase(testName, fixture, testBody);
}

/**
 * Used by WebUIBrowserTest to preload the javascript libraries at the
 * appropriate time for javascript injection into the current page. This
 * creates a test case and calls its preLoad for any early initialization such
 * as registering handlers before the page's javascript runs it's OnLoad
 * method. This is called before the page is loaded.
 * @param {string} testFixture The test fixture name.
 * @param {string} testName The test name.
 */
function preloadJavascriptLibraries(testFixture, testName) {
  currentTestCase = createTestCase(testFixture, testName);
  currentTestCase.preLoad();
}

/**
 * Sets |waitUser| to true so |runTest| function waits for user to attach a
 * debugger.
 */
function setWaitUser() {
  waitUser = true;
  exports.go = () => waitUser = false;
  console.log('Waiting for debugger...');
  console.log('Run: go() in the JS console when you are ready.');
}

/**
 * During generation phase, this outputs; do nothing at runtime.
 */
function GEN() {}

/**
 * During generation phase, this outputs; do nothing at runtime.
 */
function GEN_INCLUDE() {}

/**
 * At runtime, register the testName with its fixture. Stuff the |name| into
 * the |testFixture|'s prototype, if needed, and the |testCaseBodies| into its
 * constructor.
 * @param {string} testFixture The name of the test fixture class.
 * @param {string} testName The name of the test function.
 * @param {Function} testBody The body to execute when running this test.
 * @param {string=} opt_preamble C++ code to be generated before the test. Does
 * nothing here in the runtime phase.
 */
function TEST_F(testFixture, testName, testBody, opt_preamble) {
  const fixtureConstructor = this[testFixture];
  if (!fixtureConstructor.prototype.name) {
    fixtureConstructor.prototype.name = testFixture;
  }
  if (!fixtureConstructor.hasOwnProperty('testCaseBodies')) {
    fixtureConstructor.testCaseBodies = {};
  }
  fixtureConstructor.testCaseBodies[testName] = testBody;
}

/**
 * Similar to TEST_F above but with a mandatory |preamble|.
 * @param {string} preamble C++ code to be generated before the test. Does
 *                 nothing here in the runtime phase.
 * @param {string} testFixture The name of the test fixture class.
 * @param {string} testName The name of the test function.
 * @param {Function} testBody The body to execute when running this test.
 */
function TEST_F_WITH_PREAMBLE(preamble, testFixture, testName, testBody) {
  TEST_F(testFixture, testName, testBody);
}

/**
 * RunJavascriptTestF uses this as the |testFunction| when invoking
 * runTest. If |currentTestCase| is non-null at this point, verify that
 * |testFixture| and |testName| agree with the preloaded values. Create
 * |currentTestCase|, if needed, run it, and clear the |currentTestCase|.
 * @param {string} testFixture The name of the test fixture class.
 * @param {string} testName The name of the test function.
 * @see preloadJavascriptLibraries
 * @see runTest
 */
function RUN_TEST_F(testFixture, testName) {
  if (!currentTestCase) {
    currentTestCase = createTestCase(testFixture, testName);
  }
  assertEquals(currentTestCase.name, testName);
  assertEquals(currentTestCase.fixture.name, testFixture);
  console.log('Running TestCase ' + testFixture + '.' + testName);
  currentTestCase.run();
}

/**
 * This Mock4JS matcher object pushes each |actualArgument| parameter to
 * match() calls onto |args|.
 * @param {Array} args The array to push |actualArgument| onto.
 * @param {Object} realMatcher The real matcher check arguments with.
 * @constructor
 */
function SaveMockArgumentMatcher(args, realMatcher) {
  this.arguments_ = args;
  this.realMatcher_ = realMatcher;
}

SaveMockArgumentMatcher.prototype = {
  /**
   * Holds the arguments to push each |actualArgument| onto.
   * @type {Array}
   * @private
   */
  arguments_: null,

  /**
   * The real Mock4JS matcher object to check arguments with.
   * @type {Object}
   */
  realMatcher_: null,

  /**
   * Pushes |actualArgument| onto |arguments_| and call |realMatcher_|. Clears
   * |arguments_| on non-match.
   * @param {*} actualArgument The argument to match and save.
   * @return {boolean} Result of calling the |realMatcher|.
   */
  argumentMatches: function(actualArgument) {
    this.arguments_.push(actualArgument);
    const match = this.realMatcher_.argumentMatches(actualArgument);
    if (!match) {
      this.arguments_.splice(0, this.arguments_.length);
    }

    return match;
  },

  /**
   * Proxy to |realMatcher_| for description.
   * @return {string} Description of this Mock4JS matcher.
   */
  describe: function() {
    return this.realMatcher_.describe();
  },
};

/**
 * Actions invoked by Mock4JS's "will()" syntax do not receive arguments from
 * the mocked method. This class works with SaveMockArgumentMatcher to save
 * arguments so that the invoked Action can pass arguments through to the
 * invoked function.
 * @constructor
 */
function SaveMockArguments() {
  this.arguments = [];
}

SaveMockArguments.prototype = {
  /**
   * Wraps the |realMatcher| with an object which will push its argument onto
   * |arguments| and call realMatcher.
   * @param {Object} realMatcher A Mock4JS matcher object for this argument.
   * @return {SaveMockArgumentMatcher} A new matcher which will push its
   *     argument onto |arguments|.
   */
  match: function(realMatcher) {
    return new SaveMockArgumentMatcher(this.arguments, realMatcher);
  },

  /**
   * Remember the argument passed to this stub invocation.
   * @type {Array}
   */
  arguments: null,
};

/**
 * CallFunctionAction is provided to allow mocks to have side effects.
 * @param {Object} obj The object to set |this| to when calling |func_|.
 * @param {?SaveMockArguments} savedArgs when non-null, saved arguments are
 *     passed to |func|.
 * @param {!Function} func The function to call.
 * @param {Array=} args Any arguments to pass to func.
 * @constructor
 */
function CallFunctionAction(obj, savedArgs, func, args) {
  /**
   * Set |this| to |obj_| when calling |func_|.
   * @type {?Object}
   */
  this.obj_ = obj;

  /**
   * The SaveMockArguments to hold arguments when invoking |func_|.
   * @type {?SaveMockArguments}
   * @private
   */
  this.savedArgs_ = savedArgs;

  /**
   * The function to call when invoked.
   * @type {!Function}
   * @private
   */
  this.func_ = func;

  /**
   * Arguments to pass to |func_| when invoked.
   * @type {!Array}
   */
  this.args_ = args || [];
}

CallFunctionAction.prototype = {
  /**
   * Accessor for |func_|.
   * @return {Function} The function to invoke.
   */
  get func() {
    return this.func_;
  },

  /**
   * Called by Mock4JS when using .will() to specify actions for stubs() or
   * expects(). Clears |savedArgs_| so it can be reused.
   * @return The results of calling |func_| with the concatenation of
   *     |savedArgs_| and |args_|.
   */
  invoke: function() {
    let prependArgs = [];
    if (this.savedArgs_) {
      prependArgs =
          this.savedArgs_.arguments.splice(0, this.savedArgs_.arguments.length);
    }
    return this.func.apply(this.obj_, prependArgs.concat(this.args_));
  },

  /**
   * Describe this action to Mock4JS.
   * @return {string} A description of this action.
   */
  describe: function() {
    return 'calls the given function with saved arguments and ' + this.args_;
  },
};

/**
 * Syntactic sugar for use with will() on a Mock4JS.Mock.
 * @param {SaveMockArguments} savedArgs Arguments saved with this object
 *     are passed to |func|.
 * @param {!Function} func The function to call when the method is invoked.
 * @param {...*} var_args Arguments to pass when calling func.
 * @return {CallFunctionAction} Action for use in will.
 */
function callFunctionWithSavedArgs(savedArgs, func, var_args) {
  return new CallFunctionAction(
      null, savedArgs, func, Array.prototype.slice.call(arguments, 2));
}

/**
 * When to call testDone().
 * @enum {number}
 */
const WhenTestDone = {
  /**
   * Default for the method called.
   */
  DEFAULT: -1,

  /**
   * Never call testDone().
   */
  NEVER: 0,

  /**
   * Call testDone() on assert failure.
   */
  ASSERT: 1,

  /**
   * Call testDone() if there are any assert or expect failures.
   */
  EXPECT: 2,

  /**
   * Always call testDone().
   */
  ALWAYS: 3,
};

/**
 * Runs all |actions|.
 * @param {boolean} isAsync When true, call testDone() on Errors.
 * @param {WhenTestDone} whenTestDone Call testDone() at the appropriate
 *     time.
 * @param {Array<Object>} actions Actions to run.
 * @constructor
 */
function RunAllAction(isAsync, whenTestDone, actions) {
  this.isAsync_ = isAsync;
  this.whenTestDone_ = whenTestDone;
  this.actions_ = actions;
}

RunAllAction.prototype = {
  /**
   * When true, call testDone() on Errors.
   * @type {boolean}
   * @private
   */
  isAsync_: false,

  /**
   * Call testDone() at appropriate time.
   * @type {WhenTestDone}
   * @private
   * @see WhenTestDone
   */
  whenTestDone_: WhenTestDone.ASSERT,

  /**
   * Holds the actions to execute when invoked.
   * @type {Array}
   * @private
   */
  actions_: null,

  /**
   * Runs all |actions_|, returning the last one. When running in sync mode,
   * throws any exceptions to be caught by runTest() or
   * runTestFunction(). Call testDone() according to |whenTestDone_| setting.
   */
  invoke: function() {
    try {
      let result;
      for (let i = 0; i < this.actions_.length; ++i) {
        result = this.actions_[i].invoke();
      }

      if ((this.whenTestDone_ === WhenTestDone.EXPECT && errors.length) ||
          this.whenTestDone_ === WhenTestDone.ALWAYS) {
        testDone();
      }

      return result;
    } catch (e) {
      if (!(e instanceof Error)) {
        e = new Error(e.toString());
      }

      if (!this.isAsync_) {
        throw e;
      }

      errors.push(e);
      if (this.whenTestDone_ !== WhenTestDone.NEVER) {
        testDone();
      }
    }
  },

  /**
   * Describe this action to Mock4JS.
   * @return {string} A description of this action.
   */
  describe: function() {
    return 'Calls all actions: ' + this.actions_;
  },
};

/**
 * Syntactic sugar for use with will() on a Mock4JS.Mock.
 * @param {...*} var_args Actions to run.
 * @return {RunAllAction} Action for use in will.
 */
function runAllActions(var_args) {
  return new RunAllAction(
      false, WhenTestDone.NEVER, Array.prototype.slice.call(arguments));
}

/**
 * Syntactic sugar for use with will() on a Mock4JS.Mock.
 * @param {WhenTestDone} whenTestDone Call testDone() at the appropriate
 *     time.
 * @param {...*} var_args Actions to run.
 * @return {RunAllAction} Action for use in will.
 */
function runAllActionsAsync(whenTestDone, var_args) {
  return new RunAllAction(
      true, whenTestDone, Array.prototype.slice.call(arguments, 1));
}

/**
 * Exports assertion methods. All assertion methods delegate to the chai.js
 * assertion library.
 */
function exportChaiAsserts() {
  exports.assertTrue = assertTrue;
  exports.assertFalse = assertFalse;
  exports.assertGE = assertGE;
  exports.assertGT = assertGT;
  exports.assertEquals = assertEquals;
  exports.assertDeepEquals = assertDeepEquals;
  exports.assertLE = assertLE;
  exports.assertLT = assertLT;
  exports.assertNotEquals = assertNotEquals;
  exports.assertNotReached = assertNotReached;
  exports.assertThrows = assertThrows;
}

/**
 * Exports methods related to Mock4JS mocking.
 */
function exportMock4JsHelpers() {
  exports.callFunctionWithSavedArgs = callFunctionWithSavedArgs;
  exports.SaveMockArguments = SaveMockArguments;
}

// Exports.
testing.Test = Test;
exports.testDone = testDone;
exportChaiAsserts();
exportMock4JsHelpers();
exports.preloadJavascriptLibraries = preloadJavascriptLibraries;
exports.setWaitUser = setWaitUser;
exports.resetTestState = resetTestState;
exports.runAllActions = runAllActions;
exports.runAllActionsAsync = runAllActionsAsync;
exports.runTest = runTest;
exports.runTestFunction = runTestFunction;
exports.DUMMY_URL = DUMMY_URL;
exports.TEST_F = TEST_F;
exports.TEST_F_WITH_PREAMBLE = TEST_F_WITH_PREAMBLE;
exports.RUNTIME_TEST_F = TEST_F;
exports.GEN = GEN;
exports.GEN_INCLUDE = GEN_INCLUDE;
exports.WhenTestDone = WhenTestDone;
})(this);


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.mule.modules</groupId>
    <artifactId>mule-module-cloudhub</artifactId>
    <version>2.0.0-SNAPSHOT</version>
    <packaging>mule-module</packaging>
    <name>Mule CloudHub Connector</name>

    <parent>
        <groupId>org.mule.tools.devkit</groupId>
        <artifactId>mule-devkit-parent</artifactId>
        <version>3.7.0</version>
    </parent>

    <properties>
        <junit.version>4.9</junit.version>
        <mockito.version>1.8.2</mockito.version>
        <jdk.version>1.7</jdk.version>
        <category>Premium</category>
        <licensePath>LICENSE.md</licensePath>
        <devkit.studio.package.skip>false</devkit.studio.package.skip>
    </properties>

    <build>
        <testResources>
            <testResource>
                <filtering>false</filtering>
                <directory>${project.basedir}/src/test/resources</directory>
            </testResource>
        </testResources>
    </build>
    <profiles>
        <profile>
            <id>functionalTestingOutputDir</id>
            <build>
                <directory>${project.basedir}/target/functionalTesting</directory>
            </build>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>com.mulesoft.cloudhub</groupId>
            <artifactId>cloudhub-client-api</artifactId>
            <version>1.7.0-HYDRA</version>
        </dependency>
        <!-- test dependencies -->
        <dependency>
            <groupId>org.mule.modules</groupId>
            <artifactId>mule-module-scripting</artifactId>
            <version>${mule.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>mulesoft-releases</id>
            <name>MuleSoft Releases Repository</name>
            <url>http://repository.mulesoft.org/releases/</url>
            <layout>default</layout>
        </repository>
        <repository>
            <id>mulesoft-snapshots</id>
            <name>MuleSoft Snapshots Repository</name>
            <url>http://repository.mulesoft.org/snapshots/</url>
            <layout>default</layout>
        </repository>
        <repository>
            <id>ee-customer</id>
            <url>https://repository.mulesoft.org/nexus-ee/content/repositories/releases-ee/</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <releases>
                <enabled>true</enabled>
            </releases>
        </repository>
    </repositories>

    <distributionManagement>
        <repository>
            <id>mule-ee-releases</id>
            <name>MuleEE Releases Repository</name>
            <url>https://repository-master.mulesoft.org/nexus/content/repositories/releases-ee/</url>
        </repository>
        <snapshotRepository>
            <id>mule-ee-snapshots</id>
            <name>MuleEE Snapshots Repository</name>
            <url>https://repository-master.mulesoft.org/nexus/content/repositories/ci-snapshots/</url>
            <uniqueVersion>false</uniqueVersion>
        </snapshotRepository>
    </distributionManagement>

    <scm>
        <connection>scm:git:git://github.com:mulesoft/cloudhub-connector.git</connection>
        <developerConnection>scm:git:git@github.com:mulesoft/cloudhub-connector.git</developerConnection>
        <url>http://github.com/mulesoft/cloudhub-connector</url>
    </scm>
</project>

redpajama_set_name: RedPajamaGithub


text:
.class public Landroid/hardware/scontext/SContextExercise;
.super Landroid/hardware/scontext/SContextEventContext;
.source "SContextExercise.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/hardware/scontext/SContextExercise$1;
    }
.end annotation

.annotation runtime Ljava/lang/Deprecated;
.end annotation

# static fields
.field public static final CREATOR:Landroid/os/Parcelable$Creator;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Landroid/os/Parcelable$Creator",
            "<",
            "Landroid/hardware/scontext/SContextExercise;",
            ">;"
        }
    .end annotation
.end field

# instance fields
.field private mContext:Landroid/os/Bundle;

.field private mMode:I

# direct methods
.method static constructor <clinit>()V
    .locals 1

    new-instance v0, Landroid/hardware/scontext/SContextExercise$1;

    invoke-direct {v0}, Landroid/hardware/scontext/SContextExercise$1;-><init>()V

    sput-object v0, Landroid/hardware/scontext/SContextExercise;->CREATOR:Landroid/os/Parcelable$Creator;

    return-void
.end method

.method constructor <init>()V
    .locals 1

    invoke-direct {p0}, Landroid/hardware/scontext/SContextEventContext;-><init>()V

    new-instance v0, Landroid/os/Bundle;

    invoke-direct {v0}, Landroid/os/Bundle;-><init>()V

    iput-object v0, p0, Landroid/hardware/scontext/SContextExercise;->mContext:Landroid/os/Bundle;

    const/4 v0, 0x0

    iput v0, p0, Landroid/hardware/scontext/SContextExercise;->mMode:I

    return-void
.end method

.method constructor <init>(Landroid/os/Parcel;)V
    .locals 0

    invoke-direct {p0}, Landroid/hardware/scontext/SContextEventContext;-><init>()V

    invoke-direct {p0, p1}, Landroid/hardware/scontext/SContextExercise;->readFromParcel(Landroid/os/Parcel;)V

    return-void
.end method

.method private readFromParcel(Landroid/os/Parcel;)V
    .locals 1

    invoke-virtual {p1}, Landroid/os/Parcel;->readBundle()Landroid/os/Bundle;

    move-result-object v0

    iput-object v0, p0, Landroid/hardware/scontext/SContextExercise;->mContext:Landroid/os/Bundle;

    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v0

    iput v0, p0, Landroid/hardware/scontext/SContextExercise;->mMode:I

    return-void
.end method

# virtual methods
.method public getAltitude()[F
    .locals 3

    const/4 v0, 0x0

    iget v1, p0, Landroid/hardware/scontext/SContextExercise;->mMode:I

    if-nez v1, :cond_0

    iget-object v1, p0, Landroid/hardware/scontext/SContextExercise;->mContext:Landroid/os/Bundle;

    const-string/jumbo v2, "AltitudeArray"

    invoke-virtual {v1, v2}, Landroid/os/Bundle;->getFloatArray(Ljava/lang/String;)[F

    move-result-object v0

    :cond_0
    return-object v0
.end method

.method public getLatitude()[D
    .locals 3

    const/4 v0, 0x0

    iget v1, p0, Landroid/hardware/scontext/SContextExercise;->mMode:I

    if-nez v1, :cond_0

    iget-object v1, p0, Landroid/hardware/scontext/SContextExercise;->mContext:Landroid/os/Bundle;

    const-string/jumbo v2, "LatitudeArray"

    invoke-virtual {v1, v2}, Landroid/os/Bundle;->getDoubleArray(Ljava/lang/String;)[D

    move-result-object v0

    :cond_0
    return-object v0
.end method

.method public getLoggingSize()I
    .locals 3

    const/4 v0, 0x0

    iget v1, p0, Landroid/hardware/scontext/SContextExercise;->mMode:I

    if-nez v1, :cond_0

    iget-object v1, p0, Landroid/hardware/scontext/SContextExercise;->mContext:Landroid/os/Bundle;

    const-string/jumbo v2, "DataCount"

    invoke-virtual {v1, v2}, Landroid/os/Bundle;->getInt(Ljava/lang/String;)I

    move-result v0

    :cond_0
    return v0
.end method

.method public getLongitude()[D
    .locals 3

    const/4 v0, 0x0

    iget v1, p0, Landroid/hardware/scontext/SContextExercise;->mMode:I

    if-nez v1, :cond_0

    iget-object v1, p0, Landroid/hardware/scontext/SContextExercise;->mContext:Landroid/os/Bundle;

    const-string/jumbo v2, "LongitudeArray"

    invoke-virtual {v1, v2}, Landroid/os/Bundle;->getDoubleArray(Ljava/lang/String;)[D

    move-result-object v0

    :cond_0
    return-object v0
.end method

.method public getMode()I
    .locals 2

    iget-object v0, p0, Landroid/hardware/scontext/SContextExercise;->mContext:Landroid/os/Bundle;

    const-string/jumbo v1, "Mode"

    invoke-virtual {v0, v1}, Landroid/os/Bundle;->getInt(Ljava/lang/String;)I

    move-result v0

    return v0
.end method

.method public getPedoDistance()[D
    .locals 3

    const/4 v0, 0x0

    iget v1, p0, Landroid/hardware/scontext/SContextExercise;->mMode:I

    if-nez v1, :cond_0

    iget-object v1, p0, Landroid/hardware/scontext/SContextExercise;->mContext:Landroid/os/Bundle;

    const-string/jumbo v2, "PedoDistanceDiffArray"

    invoke-virtual {v1, v2}, Landroid/os/Bundle;->getDoubleArray(Ljava/lang/String;)[D

    move-result-object v0

    :cond_0
    return-object v0
.end method

.method public getPedoSpeed()[D
    .locals 3

    const/4 v0, 0x0

    iget v1, p0, Landroid/hardware/scontext/SContextExercise;->mMode:I

    if-nez v1, :cond_0

    iget-object v1, p0, Landroid/hardware/scontext/SContextExercise;->mContext:Landroid/os/Bundle;

    const-string/jumbo v2, "PedoSpeedArray"

    invoke-virtual {v1, v2}, Landroid/os/Bundle;->getDoubleArray(Ljava/lang/String;)[D

    move-result-object v0

    :cond_0
    return-object v0
.end method

.method public getPressure()[F
    .locals 3

    const/4 v0, 0x0

    iget v1, p0, Landroid/hardware/scontext/SContextExercise;->mMode:I

    if-nez v1, :cond_0

    iget-object v1, p0, Landroid/hardware/scontext/SContextExercise;->mContext:Landroid/os/Bundle;

    const-string/jumbo v2, "PressureArray"

    invoke-virtual {v1, v2}, Landroid/os/Bundle;->getFloatArray(Ljava/lang/String;)[F

    move-result-object v0

    :cond_0
    return-object v0
.end method

.method public getSpeed()[F
    .locals 3

    const/4 v0, 0x0

    iget v1, p0, Landroid/hardware/scontext/SContextExercise;->mMode:I

    if-nez v1, :cond_0

    iget-object v1, p0, Landroid/hardware/scontext/SContextExercise;->mContext:Landroid/os/Bundle;

    const-string/jumbo v2, "SpeedArray"

    invoke-virtual {v1, v2}, Landroid/os/Bundle;->getFloatArray(Ljava/lang/String;)[F

    move-result-object v0

    :cond_0
    return-object v0
.end method

.method public getStatus()I
    .locals 3

    const/4 v0, 0x0

    iget v1, p0, Landroid/hardware/scontext/SContextExercise;->mMode:I

    const/4 v2, 0x1

    if-ne v1, v2, :cond_0

    iget-object v1, p0, Landroid/hardware/scontext/SContextExercise;->mContext:Landroid/os/Bundle;

    const-string/jumbo v2, "GpsStatus"

    invoke-virtual {v1, v2}, Landroid/os/Bundle;->getInt(Ljava/lang/String;)I

    move-result v0

    :cond_0
    return v0
.end method

.method public getStepCount()[J
    .locals 3

    const/4 v0, 0x0

    iget v1, p0, Landroid/hardware/scontext/SContextExercise;->mMode:I

    if-nez v1, :cond_0

    iget-object v1, p0, Landroid/hardware/scontext/SContextExercise;->mContext:Landroid/os/Bundle;

    const-string/jumbo v2, "StepCountDiffArray"

    invoke-virtual {v1, v2}, Landroid/os/Bundle;->getLongArray(Ljava/lang/String;)[J

    move-result-object v0

    :cond_0
    return-object v0
.end method

.method public getTimeStamp()[J
    .locals 3

    const/4 v0, 0x0

    iget v1, p0, Landroid/hardware/scontext/SContextExercise;->mMode:I

    if-nez v1, :cond_0

    iget-object v1, p0, Landroid/hardware/scontext/SContextExercise;->mContext:Landroid/os/Bundle;

    const-string/jumbo v2, "TimeStampArray"

    invoke-virtual {v1, v2}, Landroid/os/Bundle;->getLongArray(Ljava/lang/String;)[J

    move-result-object v0

    :cond_0
    return-object v0
.end method

.method public setValues(Landroid/os/Bundle;)V
    .locals 1

    iput-object p1, p0, Landroid/hardware/scontext/SContextExercise;->mContext:Landroid/os/Bundle;

    const-string/jumbo v0, "Mode"

    invoke-virtual {p1, v0}, Landroid/os/Bundle;->getInt(Ljava/lang/String;)I

    move-result v0

    iput v0, p0, Landroid/hardware/scontext/SContextExercise;->mMode:I

    return-void
.end method

.method public writeToParcel(Landroid/os/Parcel;I)V
    .locals 1

    iget-object v0, p0, Landroid/hardware/scontext/SContextExercise;->mContext:Landroid/os/Bundle;

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeBundle(Landroid/os/Bundle;)V

    iget v0, p0, Landroid/hardware/scontext/SContextExercise;->mMode:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    return-void
.end method


text:
using ::testing::_;
using ::testing::SaveArg;

namespace proximity_auth {

namespace {

const char kCryptAuthGCMAppId[] = "com.google.chrome.cryptauth";
const char kCryptAuthGCMSenderId[] = "381449029288";
const char kExistingGCMRegistrationId[] = "cirrus";
const char kNewGCMRegistrationId[] = "stratus";
const char kCryptAuthMessageCollapseKey[] =
    "collapse_cryptauth_sync_DEVICES_SYNC";

// Mock GCMDriver implementation for testing.
class MockGCMDriver : public gcm::FakeGCMDriver {
 public:
  MockGCMDriver() {}
  ~MockGCMDriver() override {}

  MOCK_METHOD2(AddAppHandler,
               void(const std::string& app_id, gcm::GCMAppHandler* handler));

  MOCK_METHOD2(RegisterImpl,
               void(const std::string& app_id,
                    const std::vector<std::string>& sender_ids));

  using gcm::GCMDriver::RegisterFinished;

 private:
  DISALLOW_COPY_AND_ASSIGN(MockGCMDriver);
};

}  // namespace

class ProximityAuthCryptAuthGCMManagerImplTest
    : public testing::Test,
      public CryptAuthGCMManager::Observer {
 protected:
  ProximityAuthCryptAuthGCMManagerImplTest()
      : gcm_manager_(&gcm_driver_, &pref_service_) {}

  // testing::Test:
  void SetUp() override {
    CryptAuthGCMManager::RegisterPrefs(pref_service_.registry());
    gcm_manager_.AddObserver(this);
    EXPECT_CALL(gcm_driver_, AddAppHandler(kCryptAuthGCMAppId, &gcm_manager_));
    gcm_manager_.StartListening();
  }

  void TearDown() override { gcm_manager_.RemoveObserver(this); }

  void RegisterWithGCM(gcm::GCMClient::Result registration_result) {
    std::vector<std::string> sender_ids;
    EXPECT_CALL(gcm_driver_, RegisterImpl(kCryptAuthGCMAppId, _))
        .WillOnce(SaveArg<1>(&sender_ids));
    gcm_manager_.RegisterWithGCM();

    ASSERT_EQ(1u, sender_ids.size());
    EXPECT_EQ(kCryptAuthGCMSenderId, sender_ids[0]);

    bool success = (registration_result == gcm::GCMClient::SUCCESS);
    EXPECT_CALL(*this, OnGCMRegistrationResultProxy(success));
    gcm_driver_.RegisterFinished(kCryptAuthGCMAppId, kNewGCMRegistrationId,
                                 registration_result);
  }

  // CryptAuthGCMManager::Observer:
  void OnGCMRegistrationResult(bool success) override {
    OnGCMRegistrationResultProxy(success);
  }

  void OnReenrollMessage() override { OnReenrollMessageProxy(); }

  void OnResyncMessage() override { OnResyncMessageProxy(); }

  MOCK_METHOD1(OnGCMRegistrationResultProxy, void(bool));
  MOCK_METHOD0(OnReenrollMessageProxy, void());
  MOCK_METHOD0(OnResyncMessageProxy, void());

  testing::StrictMock<MockGCMDriver> gcm_driver_;

  TestingPrefServiceSimple pref_service_;

  CryptAuthGCMManagerImpl gcm_manager_;

  DISALLOW_COPY_AND_ASSIGN(ProximityAuthCryptAuthGCMManagerImplTest);
};

TEST_F(ProximityAuthCryptAuthGCMManagerImplTest, RegisterPrefs) {
  TestingPrefServiceSimple pref_service;
  CryptAuthGCMManager::RegisterPrefs(pref_service.registry());
  EXPECT_TRUE(pref_service.FindPreference(prefs::kCryptAuthGCMRegistrationId));
}

TEST_F(ProximityAuthCryptAuthGCMManagerImplTest, RegistrationSucceeds) {
  EXPECT_EQ(std::string(), gcm_manager_.GetRegistrationId());
  RegisterWithGCM(gcm::GCMClient::SUCCESS);
  EXPECT_EQ(kNewGCMRegistrationId, gcm_manager_.GetRegistrationId());
}

TEST_F(ProximityAuthCryptAuthGCMManagerImplTest,
       RegistrationSucceedsWithExistingRegistration) {
  pref_service_.SetString(prefs::kCryptAuthGCMRegistrationId,
                          kExistingGCMRegistrationId);
  EXPECT_EQ(kExistingGCMRegistrationId, gcm_manager_.GetRegistrationId());
  RegisterWithGCM(gcm::GCMClient::SUCCESS);
  EXPECT_EQ(kNewGCMRegistrationId, gcm_manager_.GetRegistrationId());
  EXPECT_EQ(kNewGCMRegistrationId,
            pref_service_.GetString(prefs::kCryptAuthGCMRegistrationId));
}

TEST_F(ProximityAuthCryptAuthGCMManagerImplTest, RegisterWithGCMFails) {
  EXPECT_EQ(std::string(), gcm_manager_.GetRegistrationId());
  RegisterWithGCM(gcm::GCMClient::SERVER_ERROR);
  EXPECT_EQ(std::string(), gcm_manager_.GetRegistrationId());
  EXPECT_EQ(std::string(),
            pref_service_.GetString(prefs::kCryptAuthGCMRegistrationId));
}

TEST_F(ProximityAuthCryptAuthGCMManagerImplTest,
       RegisterWithGCMFailsWithExistingRegistration) {
  pref_service_.SetString(prefs::kCryptAuthGCMRegistrationId,
                          kExistingGCMRegistrationId);
  EXPECT_EQ(kExistingGCMRegistrationId, gcm_manager_.GetRegistrationId());
  RegisterWithGCM(gcm::GCMClient::SERVER_ERROR);
  EXPECT_EQ(kExistingGCMRegistrationId, gcm_manager_.GetRegistrationId());
  EXPECT_EQ(kExistingGCMRegistrationId,
            pref_service_.GetString(prefs::kCryptAuthGCMRegistrationId));
}

TEST_F(ProximityAuthCryptAuthGCMManagerImplTest,
       RegistrationFailsThenSucceeds) {
  EXPECT_EQ(std::string(), gcm_manager_.GetRegistrationId());
  RegisterWithGCM(gcm::GCMClient::NETWORK_ERROR);
  EXPECT_EQ(std::string(), gcm_manager_.GetRegistrationId());
  RegisterWithGCM(gcm::GCMClient::SUCCESS);
  EXPECT_EQ(kNewGCMRegistrationId, gcm_manager_.GetRegistrationId());
}

TEST_F(ProximityAuthCryptAuthGCMManagerImplTest, ConcurrentRegistrations) {
  // If multiple RegisterWithGCM() calls are made concurrently, only one
  // registration attempt should actually be made.
  EXPECT_CALL(gcm_driver_, RegisterImpl(kCryptAuthGCMAppId, _));
  gcm_manager_.RegisterWithGCM();
  gcm_manager_.RegisterWithGCM();
  gcm_manager_.RegisterWithGCM();

  EXPECT_CALL(*this, OnGCMRegistrationResultProxy(true));
  gcm_driver_.RegisterFinished(kCryptAuthGCMAppId, kNewGCMRegistrationId,
                               gcm::GCMClient::SUCCESS);
  EXPECT_EQ(kNewGCMRegistrationId, gcm_manager_.GetRegistrationId());
}

TEST_F(ProximityAuthCryptAuthGCMManagerImplTest, ReenrollmentMessagesReceived) {
  EXPECT_CALL(*this, OnReenrollMessageProxy()).Times(2);

  gcm::IncomingMessage message;
  message.data["registrationTickleType"] = "1";  // FORCE_ENROLLMENT
  message.collapse_key = kCryptAuthMessageCollapseKey;
  message.sender_id = kCryptAuthGCMSenderId;

  gcm::GCMAppHandler* gcm_app_handler =
      static_cast<gcm::GCMAppHandler*>(&gcm_manager_);
  gcm_app_handler->OnMessage(kCryptAuthGCMAppId, message);
  message.data["registrationTickleType"] = "2";  // UPDATE_ENROLLMENT
  gcm_app_handler->OnMessage(kCryptAuthGCMAppId, message);
}

TEST_F(ProximityAuthCryptAuthGCMManagerImplTest, ResyncMessagesReceived) {
  EXPECT_CALL(*this, OnResyncMessageProxy()).Times(2);

  gcm::IncomingMessage message;
  message.data["registrationTickleType"] = "3";  // DEVICES_SYNC
  message.collapse_key = kCryptAuthMessageCollapseKey;
  message.sender_id = kCryptAuthGCMSenderId;

  gcm::GCMAppHandler* gcm_app_handler =
      static_cast<gcm::GCMAppHandler*>(&gcm_manager_);
  gcm_app_handler->OnMessage(kCryptAuthGCMAppId, message);
  gcm_app_handler->OnMessage(kCryptAuthGCMAppId, message);
}

}  // namespace proximity_auth


text:
package com.amazonaws.services.healthlake.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListFHIRDatastoresRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * Lists all filters associated with a FHIR Data Store request.
     *

     */
    private DatastoreFilter filter;
    /**
     *

     * Fetches the next page of Data Stores when results are paginated.
     *

     */
    private String nextToken;
    /**
     *

     * The maximum number of Data Stores returned in a single page of a ListFHIRDatastoresRequest call.
     *

     */
    private Integer maxResults;

    /**
     *

     * Lists all filters associated with a FHIR Data Store request.
     *

     *
     * @param filter
     *        Lists all filters associated with a FHIR Data Store request.
     */

    public void setFilter(DatastoreFilter filter) {
        this.filter = filter;
    }

    /**
     *

     * Lists all filters associated with a FHIR Data Store request.
     *

     *
     * @return Lists all filters associated with a FHIR Data Store request.
     */

    public DatastoreFilter getFilter() {
        return this.filter;
    }

    /**
     *

     * Lists all filters associated with a FHIR Data Store request.
     *

     *
     * @param filter
     *        Lists all filters associated with a FHIR Data Store request.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListFHIRDatastoresRequest withFilter(DatastoreFilter filter) {
        setFilter(filter);
        return this;
    }

    /**
     *

     * Fetches the next page of Data Stores when results are paginated.
     *

     *
     * @param nextToken
     *        Fetches the next page of Data Stores when results are paginated.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * Fetches the next page of Data Stores when results are paginated.
     *

     *
     * @return Fetches the next page of Data Stores when results are paginated.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * Fetches the next page of Data Stores when results are paginated.
     *

     *
     * @param nextToken
     *        Fetches the next page of Data Stores when results are paginated.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListFHIRDatastoresRequest withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     *

     * The maximum number of Data Stores returned in a single page of a ListFHIRDatastoresRequest call.
     *

     *
     * @param maxResults
     *        The maximum number of Data Stores returned in a single page of a ListFHIRDatastoresRequest call.
     */

    public void setMaxResults(Integer maxResults) {
        this.maxResults = maxResults;
    }

    /**
     *

     * The maximum number of Data Stores returned in a single page of a ListFHIRDatastoresRequest call.
     *

     *
     * @return The maximum number of Data Stores returned in a single page of a ListFHIRDatastoresRequest call.
     */

    public Integer getMaxResults() {
        return this.maxResults;
    }

    /**
     *

     * The maximum number of Data Stores returned in a single page of a ListFHIRDatastoresRequest call.
     *

     *
     * @param maxResults
     *        The maximum number of Data Stores returned in a single page of a ListFHIRDatastoresRequest call.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListFHIRDatastoresRequest withMaxResults(Integer maxResults) {
        setMaxResults(maxResults);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getFilter() != null)
            sb.append("Filter: ").append(getFilter()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken()).append(",");
        if (getMaxResults() != null)
            sb.append("MaxResults: ").append(getMaxResults());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ListFHIRDatastoresRequest == false)
            return false;
        ListFHIRDatastoresRequest other = (ListFHIRDatastoresRequest) obj;
        if (other.getFilter() == null ^ this.getFilter() == null)
            return false;
        if (other.getFilter() != null && other.getFilter().equals(this.getFilter()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        if (other.getMaxResults() == null ^ this.getMaxResults() == null)
            return false;
        if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getFilter() == null) ? 0 : getFilter().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
        return hashCode;
    }

    @Override
    public ListFHIRDatastoresRequest clone() {
        return (ListFHIRDatastoresRequest) super.clone();
    }

}


text:
#ifndef CATALANTREE_NODE_H
#define CATALANTREE_NODE_H

#include <gmpxx.h>

/**
 * @class Binary tree node
 */
class Node {
public:
  typedef size_t size_type;
  Node();
  Node(const Node* other);
  Node(const Node& other);
  virtual ~Node();
  Node& operator=(const Node& rhs);
  bool operator==(const Node& rhs) const;
  bool operator!=(const Node& rhs) const;
  //! left subtree
  Node* llink() const;
  //! right subtree
  Node* rlink() const;
  //! parent node
  Node* plink() const;
  //! find root node
  const Node* root() const;
  //! set right subtree (this node will become parent of "n")
  void setRlink(Node* n);
  //! set left subtree (this node will become parent of "n")
  void setLlink(Node* n);
  //! set n as parent node
  void setPlink(Node* n);
  /**
   * @brief Tree nodes count (including root node)
   */
  size_type size() const;
  /**
   * @brief Maximum tree depth
   */
  size_type depth() const;
  /**
   * @brief Width of left subtree
   */
  size_type lwidth() const;
  /**
   * @brief Width of right subtree
   */
  size_type rwidth() const;
  /**
   * @brief Width of tree
   */
  size_type width() const;
  /**
   * @brief Decode index "I" into binary tree with "N" nodes and return pointer to root node
   */
  static Node* decode(mpz_class I, size_type N);
  /**
   * @brief Encode tree "root" and return its index
   */
  static mpz_class encode(Node* root);
  /**
   * @brief Search next node in DFS order
   */
  Node* dfs_next() const;
protected:
  //! Left subtree
  Node* llink_;
  //! Right subtree
  Node* rlink_;
  //! Parent node
  Node* plink_;
};

#endif //CATALANTREE_NODE_H


text:
package net.sf.beep4j.internal.tcp;

import junit.framework.TestCase;
import net.sf.beep4j.Message;
import net.sf.beep4j.MessageStub;
import net.sf.beep4j.internal.TransportMapping;
import net.sf.beep4j.transport.Transport;

import org.easymock.MockControl;

public class TCPMappingTest extends TestCase {

	private MockControl transportCtrl;

	private Transport transport;

	private MockControl controllerCtrl;

	private ChannelController controller;

	private MockControl factoryCtrl;

	private ChannelControllerFactory factory;

	@Override
	protected void setUp() throws Exception {
		transportCtrl = MockControl.createControl(Transport.class);
		transport = (Transport) transportCtrl.getMock();
		factoryCtrl = MockControl.createControl(ChannelControllerFactory.class);
		factory = (ChannelControllerFactory) factoryCtrl.getMock();
		controllerCtrl = MockControl.createControl(ChannelController.class);
		controller = (ChannelController) controllerCtrl.getMock();

		factory.createChannelController(0, transport);
		factoryCtrl.setReturnValue(controller);
	}

	private void replay() {
		transportCtrl.replay();
		factoryCtrl.replay();
		controllerCtrl.replay();
	}

	private void verify() {
		transportCtrl.verify();
		factoryCtrl.verify();
		controllerCtrl.verify();
	}

	public void testReceiveFrame() throws Exception {
		TransportMapping mapping = new TCPMapping(transport, factory);

		// define expectations
		controller.checkFrame(0, 50);
		controller.frameReceived(0, 50);

		replay();

		mapping.channelStarted(0);
		mapping.checkFrame(0, 0, 50);
		mapping.frameReceived(0, 0, 50);

		verify();
	}

	public void testProcessMappingFrame() throws Exception {
		TransportMapping mapping = new TCPMapping(transport, factory, 50);

		// define expectations
		controller.updateSendWindow(0, 4096);

		replay();

		mapping.channelStarted(0);
		mapping.processMappingFrame("SEQ 0 0 4096".split(" "));

		verify();
	}

	public void testStartCloseChannel() throws Exception {
		TransportMapping mapping = new TCPMapping(transport, factory);

		// define expectations
		replay();

		// test
		mapping.channelStarted(0);
		mapping.channelClosed(0);

		try {
			mapping.checkFrame(0, 0, 50);
			fail("channel 0 is closed, does not have a controller");
		} catch (Exception e) {
			// expected
			// TODO: catch proper exception
		}

		// verify
		verify();
	}

	public void testSendANS() throws Exception {
		TransportMapping mapping = new TCPMapping(transport, factory);
		Message message = new MessageStub();

		// define expectations
		controller.sendANS(0, 0, message);
		replay();

		// test
		mapping.channelStarted(0);
		mapping.sendANS(0, 0, 0, message);

		// verify
		verify();
	}

	public void testSendNUL() throws Exception {
		TransportMapping mapping = new TCPMapping(transport, factory);

		// define expectations
		controller.sendNUL(0);
		replay();

		// test
		mapping.channelStarted(0);
		mapping.sendNUL(0, 0);

		// verify
		verify();
	}

	public void testSendERR() throws Exception {
		TransportMapping mapping = new TCPMapping(transport, factory);
		Message message = new MessageStub();

		// define expectations
		controller.sendERR(0, message);
		replay();

		// test
		mapping.channelStarted(0);
		mapping.sendERR(0, 0, message);

		// verify
		verify();
	}

	public void testSendMSG() throws Exception {
		TransportMapping mapping = new TCPMapping(transport, factory);
		Message message = new MessageStub();

		// define expectations
		controller.sendMSG(0, message);
		replay();

		// test
		mapping.channelStarted(0);
		mapping.sendMSG(0, 0, message);

		// verify
		verify();
	}

	public void testSendRPY() throws Exception {
		TransportMapping mapping = new TCPMapping(transport, factory);
		Message message = new MessageStub();

		// define expectations
		controller.sendRPY(0, message);
		replay();

		// test
		mapping.channelStarted(0);
		mapping.sendRPY(0, 0, message);

		// verify
		verify();
	}

	public void testCloseTransport() throws Exception {
		TransportMapping mapping = new TCPMapping(transport, factory);

		// define expectations
		transport.closeTransport();
		replay();

		// test
		mapping.channelStarted(0);
		mapping.closeTransport();

		// verify
		verify();
	}

}


text:
package mwvdev.brt.service.mapper;

import mwvdev.brt.entity.LocationEntity;
import mwvdev.brt.model.Location;

public interface LocationMapper {

    LocationEntity toEntity(long tripId, Location location);

    Location toLocation(LocationEntity locationEntity);

}


text:
This sample app consists of a chunk-type step with a reader and writer that reads and writes a series of numbers.
This job also uses one custom class for checkpoint info, and another custom class for step persistent data, to
verify that they can be properly serialized and deserialized between job restart.

The test class performs the following:

* starts a new job that will fail when the number in the reader reaches ${fail.on};
* in a separate test method, restart the same job that should continue from where it left in the previous run.

Various info is printed on the client side, and in server log to verify the progress of the job.

To more thoroughly verify serialization and deserialization behavior, configure WildFly to use jdbc job repository,
instead of the default in-memory job repository, through WildFly CLI.  The standalone.xml (or other server configuration
file) should look like:

    <subsystem xmlns="urn:jboss:domain:batch:1.0">
        <job-repository>
            <jdbc jndi-name="java:/jdbc/orderDB"/>
        </job-repository>
        <thread-pool>
            <max-threads count="50"/>
            <keepalive-time time="100" unit="milliseconds"/>
        </thread-pool>
    </subsystem>

The following is the detailed steps for running such test:

* start database server
* start WildFly
* mvn package
* deploy to WildFly
* run org.jberet.testapps.deserialization.DeserializationIT.startJob test, and the job execution will fail
* restart WildFly
* run org.jberet.testapps.deserialization.DeserializationIT.restartJob test, and the job execution will complete

This test app can also verify the restartable job attribute. The value of restartable attribute in job xml is controlled
by the job parameter named "restartable". When a job is initially started with job parameter restartable=false, it cannot
be restarted after the initial execution failed or stopped.

* deploy to WildFly
* run startNotRestartable, the job execution will fail as the test app
throws exception, and the test will pass with the expected job failure.
* restart WildFly to make sure the previous decision to ban restart was persisted and retrieved upon the next restart.
* run org.jberet.testapps.deserialization.DeserializationIT.restartNotRestartable, the restart will fail with JobRestartException,
since the initial job execution was configured not restartable.

This test app can also verify that a job whose job id differs from job xml file name can be started and restarted.
When the job is first started, it is started with job xml name, and is configured to fail. When it is restarted with
the previous job execution id after WildFly server restart, the batch runtime should be able to correctly load job
from job xml name (the job cache is gone after WildFly restart), even though job id differs from job xml name.

* deploy to WildFly
* run org.jberet.testapps.deserialization.DeserializationIT.startJobNameDifferent, the job execution will fail as the test app
throws exception, and the test will pass with the expected job failure.
* restart WildFly
* run org.jberet.testapps.deserialization.DeserializationIT.restartJobNameDifferent, which should complete successfully.


text:
namespace tensorflow {

using tensorforest::CheckTensorBounds;
using tensorforest::Initialize;

int64 Convert(const string& in, int32 offset_bits) {
  std::size_t hashed = std::hash<string>()(in);
  // Mask off the offset_bits msb's
  int64 mask = static_cast<int64>(pow(2, offset_bits) - 1)
               << (32 - offset_bits);
  // TODO(gilberth): Use int64 to store feature indices in tensor_forest.
  // Only use the lower 31 bits because that's what we currently store as
  // feature indices.
  mask = ~mask & 0x7FFFFFFF;
  return static_cast<int64>(hashed & mask);
}

void Evaluate(const Tensor& sparse_indices, const Tensor& sparse_values,
              Tensor output_data, int64 offset, int32 offset_bits, int32 start,
              int32 end) {
  auto out_data = output_data.tensor<int64, 2>();
  const auto indices = sparse_indices.tensor<int64, 2>();
  const auto values = sparse_values.unaligned_flat<string>();

  for (int32 i = start; i < end; ++i) {
    out_data(i, 0) = indices(i, 0);
    out_data(i, 1) = Convert(values(i), offset_bits) + offset;
  }
}

REGISTER_OP("SparseValuesToIndices")
    .Attr("offset_bits: int")
    .Input("sparse_indices: int64")
    .Input("sparse_values: string")
    .Input("offset: int64")
    .Output("output_indices: int64")
    .Output("output_values: float")

    .Doc(R"doc(
   Converts string values to sparse indices in a bit vector.

   offset_bits: The number of bits being used for offsets, which tells us
     how many bits we can use to represent the string values.
   sparse_indices: The original sparse indices (2-d tensor).
   sparse_values: A batch of string values as a 1-d tensor.
   offset: An offset value to apply to the feature index.
   output_indices: A tensor of the same shape as sparse_indices where
     output_indices[i][0] is the same as sparse_indices and output_indices[i][1]
     is the integer value of the corresponding sparse_values.

)doc");

class SparseValuesToIndices : public OpKernel {
 public:
  explicit SparseValuesToIndices(OpKernelConstruction* context)
      : OpKernel(context) {
    OP_REQUIRES_OK(context, context->GetAttr("offset_bits", &offset_bits_));
  }

  void Compute(OpKernelContext* context) override {
    const Tensor& sparse_indices = context->input(0);
    const Tensor& sparse_values = context->input(1);
    const Tensor& offset_tensor = context->input(2);

    // Check inputs.
    OP_REQUIRES(
        context, sparse_indices.shape().dims() == 2,
        errors::InvalidArgument("sparse_indices should be two-dimensional"));
    OP_REQUIRES(
        context, sparse_values.shape().dims() == 1,
        errors::InvalidArgument("sparse_values should be one-dimensional"));

    // Check tensor bounds.
    if (!CheckTensorBounds(context, sparse_indices)) return;
    if (!CheckTensorBounds(context, sparse_values)) return;
    if (!CheckTensorBounds(context, offset_tensor)) return;

    Tensor* output_indices = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(0, sparse_indices.shape(),
                                                     &output_indices));
    Tensor* output_values = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(1, sparse_values.shape(),
                                                     &output_values));
    // There doesn't seem to be a great way to get a tensor of 1's with the same
    // shape as a string tensor with unknown dimensions, so we just do it here
    // in this op.
    Initialize<float>(*output_values, 1.0);

    const int64 offset = offset_tensor.unaligned_flat<int64>()(0);

    // Evaluate input data in parallel.
    const int32 num_data =
        static_cast<int32>(sparse_values.shape().dim_size(0));
    auto worker_threads = context->device()->tensorflow_cpu_worker_threads();
    int num_threads = worker_threads->num_threads;
    if (num_threads <= 1) {
      Evaluate(sparse_indices, sparse_values, *output_indices, offset, 0,
               offset_bits_, num_data);
    } else {
      auto work = [this, &sparse_indices, sparse_values, output_indices, offset,
                   num_data](int64 start, int64 end) {
        CHECK(start <= end);
        CHECK(end <= num_data);
        Evaluate(sparse_indices, sparse_values, *output_indices, offset,
                 offset_bits_, static_cast<int32>(start),
                 static_cast<int32>(end));
      };
      Shard(num_threads, worker_threads->workers, num_data, 100, work);
    }
  }

 private:
  int32 offset_bits_;
};

REGISTER_KERNEL_BUILDER(Name("SparseValuesToIndices").Device(DEVICE_CPU),
                        SparseValuesToIndices);

}  // namespace tensorflow


text:
import React, { Component } from 'react'

import Card from 'material-ui/lib/card/card'
import CardText from 'material-ui/lib/card/card-text'
import Tabs from 'material-ui/lib/tabs/tabs'
import Tab from 'material-ui/lib/tabs/tab'

import ProfitAndLoss from './ProfitAndLoss'
import BalanceSheet from './BalanceSheet'
import Cashflow from './Cashflow'

const styles = {
  container: {
    width: '100%',
    display: 'inline-flex'
  },
  cardText: {
    padding: 0
  },
  inkBar: {
    height: 6,
    marginTop: -6
  },
  tabContents: {
    padding: 16,
    paddingBottom: 50,
    overflow: 'auto'
  }
}

export default class Outputs extends Component {
  render () {
    return <div style={styles.container} >
      <Card className="card">
        <CardText style={styles.cardText}>
          <Tabs
              value={this.props.tab}
              onChange={tab => {
                if (typeof tab === 'string') { // filter events triggered by input fields in the tabs
                  this.props.onChangeTab(tab)
                }
              }}
              inkBarStyle={styles.inkBar}
              contentContainerStyle={styles.tabContents}>
            <Tab value="profitAndLoss" label="Profit & Loss">
              <ProfitAndLoss data={this.props.data} />
            </Tab>
            <Tab value="balanceSheet" label="Balance sheet">
              <BalanceSheet data={this.props.data} />
            </Tab>
            <Tab value="cashFlow" label="Cashflow">
              <Cashflow data={this.props.data} />
            </Tab>
          </Tabs>
        </CardText>
      </Card>
    </div>
  }

}


text:
#include "WebSocketLibJoynrMessagingSkeleton.h"

#include <stdexcept>
#include <string>
#include <utility>

#include <smrf/ByteVector.h>
#include <smrf/exceptions.h>

#include "joynr/IMessageRouter.h"
#include "joynr/ImmutableMessage.h"
#include "joynr/Message.h"
#include "joynr/exceptions/JoynrException.h"
#include "joynr/serializer/Serializer.h"

namespace joynr
{

WebSocketLibJoynrMessagingSkeleton::WebSocketLibJoynrMessagingSkeleton(
        std::weak_ptr<IMessageRouter> messageRouter)
        : _messageRouter(std::move(messageRouter))
{
}

void WebSocketLibJoynrMessagingSkeleton::transmit(
        std::shared_ptr<ImmutableMessage> message,
        const std::function<void(const exceptions::JoynrRuntimeException&)>& onFailure)
{
    try {
        if (auto ptr = _messageRouter.lock()) {
            ptr->route(message);
        }
    } catch (const exceptions::JoynrRuntimeException& e) {
        onFailure(e);
    }
}

void WebSocketLibJoynrMessagingSkeleton::onMessageReceived(smrf::ByteVector&& message)
{
    // deserialize message and transmit
    std::shared_ptr<ImmutableMessage> immutableMessage;
    try {
        immutableMessage = std::make_shared<ImmutableMessage>(std::move(message));
    } catch (const smrf::EncodingException& e) {
        JOYNR_LOG_ERROR(logger(), "Unable to deserialize message - error: {}", e.what());
        return;
    } catch (const std::invalid_argument& e) {
        JOYNR_LOG_ERROR(logger(), "deserialized message is not valid - error: {}", e.what());
        return;
    }

    if (immutableMessage->getType() == Message::VALUE_MESSAGE_TYPE_MULTICAST()) {
        immutableMessage->setReceivedFromGlobal(true);
    }

    if (logger().getLogLevel() == LogLevel::Debug) {
        JOYNR_LOG_DEBUG(logger(), "<<< INCOMING <<< {}", immutableMessage->getTrackingInfo());
    } else {
        JOYNR_LOG_TRACE(logger(), "<<< INCOMING <<< {}", immutableMessage->toLogMessage());
    }

    auto onFailure =
            [messageId = immutableMessage->getId()](const exceptions::JoynrRuntimeException& e) {
                JOYNR_LOG_ERROR(logger(),
                                "Incoming Message with ID {} could not be sent! reason: {}",
                                messageId,
                                e.getMessage());
            };
    transmit(std::move(immutableMessage), onFailure);
}

} // namespace joynr


text:
import {FormControl, FormLabel} from '@chakra-ui/react'
import fpGet from 'lodash/fp/get'
import {useState} from 'react'

import useRouteTo from 'lib/hooks/use-route-to'
import message from 'lib/message'

import Select from './select'

const getLabel = fpGet('name')
const getValue = fpGet('_id')

export default function SelectBundle({
  bundles,
  query
}: {
  bundles: CL.Bundle[]
  query: CL.Query
}) {
  const [bundleId, setBundleId] = useState(query.bundleId)
  const goToBundleEdit = useRouteTo('bundle', {regionId: query.regionId})
  return (
    <FormControl>
      <FormLabel htmlFor='selectBundle' textAlign='center'>
        {message('bundle.select')}
      </FormLabel>
      <div>
        <Select
          inputId='selectBundle'
          options={bundles}
          getOptionLabel={getLabel}
          getOptionValue={getValue}
          onChange={(result: CL.Bundle) => {
            setBundleId(result._id)
            goToBundleEdit({bundleId: result._id})
          }}
          value={bundles.find((b) => b._id === bundleId)}
        />
      </div>
    </FormControl>
  )
}


text:
import unittest

from pymatgen.analysis.hhi import HHIModel

class HHIModelTest(unittest.TestCase):
    def test_hhi(self):
        hhi = HHIModel()
        self.assertEqual(hhi.get_hhi("He"), (3200, 3900))
        self.assertEqual(hhi.get_hhi_production("He"), 3200)
        self.assertEqual(hhi.get_hhi_reserve("He"), 3900)

        self.assertAlmostEqual(hhi.get_hhi_production("Li2O"), 1614.96, 1)
        self.assertAlmostEqual(hhi.get_hhi_reserve("Li2O"), 2218.90, 1)

        self.assertEqual(hhi.get_hhi_designation(1400), "low")
        self.assertEqual(hhi.get_hhi_designation(1800), "medium")
        self.assertEqual(hhi.get_hhi_designation(3000), "high")
        self.assertEqual(hhi.get_hhi_designation(None), None)

if __name__ == "__main__":
    unittest.main()


text:
package io.siddhi.core.util.transport;

/**
 * Exception class to be used when a Subscriber is not available for the given topic in In-memory Broker.
 */
public class SubscriberUnAvailableException extends Exception {
    public SubscriberUnAvailableException() {
        super();
    }

    public SubscriberUnAvailableException(String message) {
        super(message);
    }

    public SubscriberUnAvailableException(String message, Throwable throwable) {
        super(message, throwable);
    }

    public SubscriberUnAvailableException(Throwable throwable) {
        super(throwable);
    }
}


text:
'use strict';

import * as vscode from 'vscode'
import * as events from 'events';
import {Logger} from './logger';
import {HubClient} from './hubclient';
import View from './view';
import DocumentManager from './document-manager';

export default class Controller implements vscode.Disposable {

	private _logger: Logger;
	private _view: View;
	private _documentManager: DocumentManager;

	private _extensionContext: vscode.ExtensionContext;
	private _eventEmitter: events.EventEmitter = new events.EventEmitter();
	private _hubClient: HubClient;

	static StartBroadcastCommand: string = "vsshare.startBroadcast";
	static StopBroadcastCommand: string = "vsshare.stopBroadcast";
	static RestartBroadcastCommand: string = "vsshare.restartBroadcast";
	static RefreshBroadcastCommand: string = "vsshare.refreshBroadcast";
	static ShowLogWindowCommand: string = "vsshare.showLogWindow";

	static DefaultEndpointUrl: string = "http://vsshare.net/signalr";
	static DefaultHubName: string = "broadcast";

	private registerCommand(command: string) {
		const self = this;
		this._extensionContext.subscriptions.push(vscode.commands.registerCommand(command, () => {
			self._eventEmitter.emit(command);
		}));
	}

	private startBroadcast() {
		if (this._hubClient.isConnected()) {
			vscode.window.showErrorMessage('You need to stop current connection.');
			return;
		}

		let config = vscode.workspace.getConfiguration('vsshare');

		var endpointUrl = config['url'] || Controller.DefaultEndpointUrl;
		var hubName = config['hubName'] || Controller.DefaultHubName;

		var userName: string = config['userName'] || null;
		var userToken: string = config['userToken'] || null;
		var roomName: string = config['roomName'] || null;
		var roomToken: string = config['roomToken'] || null;

		if (!userName || !userToken || !roomName || !roomToken) {
			vscode.window.showErrorMessage('You need to set preference field before using VSShare.');
			return;
		}

		this._hubClient.startBroadcast(endpointUrl, hubName, userName, userToken, roomName, roomToken);
	}

	private stopBroadcast() {
		this._hubClient.stopBroadcast();
	}

	constructor(context: vscode.ExtensionContext, logger: Logger, view: View) {
		this._extensionContext = context;
		this._logger = logger;
		this._view = view;
	}

	activate() {
		const self = this;

		this._hubClient = new HubClient(this._logger, this._view, this);
		this._documentManager = new DocumentManager(this._hubClient, this._logger);
		this._hubClient.activate();
		this._documentManager.activate();

		this.registerCommand(Controller.StartBroadcastCommand);
		this.registerCommand(Controller.StopBroadcastCommand);
		this.registerCommand(Controller.RestartBroadcastCommand);
		this.registerCommand(Controller.RefreshBroadcastCommand);
		this.registerCommand(Controller.ShowLogWindowCommand);

		this._eventEmitter.on(Controller.StartBroadcastCommand, () => { self.startBroadcast(); });
		this._eventEmitter.on(Controller.StopBroadcastCommand, () => { self.stopBroadcast(); });
		this._eventEmitter.on(Controller.RestartBroadcastCommand, () => { self.stopBroadcast(); self.startBroadcast(); });
		this._eventEmitter.on(Controller.RefreshBroadcastCommand, () => { self.refreshBroadcast(); });
		this._eventEmitter.on(Controller.ShowLogWindowCommand, () => { self._logger.showWindow(); });
	}

	refreshBroadcast() {
		this._documentManager.resendActiveDocument();
	}

	dispose() {
		this._hubClient.dispose();
		this._documentManager.dispose();
	}
}


text:
describe('Unit: eCommercePluginWidget widget app', function () {
  describe('Unit: app routes', function () {
    beforeEach(module('eCommercePluginWidget'));
    var location, route, rootScope, compile, scope;
    beforeEach(inject(function (_$rootScope_, _$compile_, $rootScope) {
     // route = _$route_;
      rootScope = _$rootScope_;
        compile= _$compile_;
        scope = $rootScope.$new();
        directiveElem = getCompiledElement();
    }));

    describe('Home route', function () {
      beforeEach(inject(
          function ($httpBackend) {
            $httpBackend.expectGET('/')
                .respond(200);
            $httpBackend.expectGET('/')
                .respond(200);
          }));
      it('should load the home page on successful load of location path /', function () {

      });

    });

      function getCompiledElement(){
          var element = angular.element('

');
          var compiledElement = compile(element)(scope);
          scope.$digest();
          return compiledElement;
      }
      it('should call if build-fire-carousel is defined', function () {
          expect(directiveElem.find('build-fire-carousel')).toBeDefined();
      });
      it('should call if build-fire-carousel2 is defined', function () {
          expect(directiveElem.find('build-fire-carousel2')).toBeDefined();
      });
      it('should call if build-fire-carousel3 is defined', function () {
          expect(directiveElem.find('build-fire-carousel3')).toBeDefined();
      });
  });

    describe('View Switcher directive with PUSH call', function () {
        var $compile, $rootScope, viewSwitcher, $scope;
        beforeEach(module('eCommercePluginWidget'));
        beforeEach(inject(function (_$compile_, _$rootScope_) {
            $compile = _$compile_;
            $rootScope = _$rootScope_;
            $scope = _$rootScope_.$new();
        }));
        beforeEach(function () {
            var view = {
                template:['Item_Details'],
                params:{
                    controller:"test",
                    shouldUpdateTemplate:true
                }
            }
            viewSwitcher = $compile('

')($scope);
            $rootScope.$broadcast('VIEW_CHANGED','PUSH',view);
            //$rootScope.$digest();
        });

        it('it should pass and view switcher of div should be 1', function () {
            expect(viewSwitcher.length).toEqual(1);
        });

        it('it should be defined', function () {
            expect(viewSwitcher).toBeDefined();
        });
    });

    describe('view switcher directive with POP call', function () {
        var $compile, $rootScope, viewSwitcher, $scope;
        beforeEach(module('eCommercePluginWidget'));
        beforeEach(inject(function (_$compile_, _$rootScope_) {
            $compile = _$compile_;
            $rootScope = _$rootScope_;
            $scope = _$rootScope_.$new();
        }));
        beforeEach(function () {
            var view = {
                template:['Item_Details']
            }
            viewSwitcher = $compile('

')($scope);
            $rootScope.$broadcast('VIEW_CHANGED','POP',view);
            //$rootScope.$digest();
        });

        it('it should pass and view switcher of div should be 1', function () {
            expect(viewSwitcher.length).toEqual(1);
        });

        it('it should be defined', function () {
            expect(viewSwitcher).toBeDefined();
        });
    });
    describe('view switcher directive with POPALL call', function () {
        var $compile, $rootScope, viewSwitcher, $scope;
        beforeEach(module('eCommercePluginWidget'));
        beforeEach(inject(function (_$compile_, _$rootScope_) {
            $compile = _$compile_;
            $rootScope = _$rootScope_;
            $scope = _$rootScope_.$new();
        }));
        beforeEach(function () {
            var view = {
                template:['Item_Details']
            }
            viewSwitcher = $compile('

')($scope);
            $rootScope.$broadcast('VIEW_CHANGED','POPALL',view);
            $rootScope.$digest();
        });

        it('it should pass and view switcher of div should be 1', function () {
            expect(viewSwitcher.length).toEqual(1);
        });

        it('it should be defined', function () {
            expect(viewSwitcher).toBeDefined();
        });
    });

    describe('buildFireCarousel directive test', function () {
        var $compile, $rootScope, buildFireCarousel, $scope;
        beforeEach(module('eCommercePluginWidget'));
        beforeEach(inject(function (_$compile_, _$rootScope_) {
            $compile = _$compile_;
            $rootScope = _$rootScope_;
            $scope = _$rootScope_.$new();
        }));
        beforeEach(function () {
            buildFireCarousel = $compile('

')($scope);
            $rootScope.$digest();
        });

        it('it should pass and view switcher of div should be 1', function () {
            expect(buildFireCarousel.length).toEqual(1);
            buildfire.messaging.onReceivedMessage("aa")
        });
    });
    describe('buildFireCarousel2 directive test', function () {
        var $compile, $rootScope, buildFireCarousel2, $scope;
        beforeEach(module('eCommercePluginWidget'));
        beforeEach(inject(function (_$compile_, _$rootScope_) {
            $compile = _$compile_;
            $rootScope = _$rootScope_;
            $scope = _$rootScope_.$new();
        }));
        beforeEach(function () {
            buildFireCarousel2 = $compile('

')($scope);
            $rootScope.$digest();
        });

        it('it should pass and view switcher of div should be 1', function () {
            expect(buildFireCarousel2.length).toEqual(1);
            buildfire.messaging.onReceivedMessage("aa")
        });
    });
    describe('buildFireCarousel3 directive test', function () {
        var $compile, $rootScope, buildFireCarousel3, $scope;
        beforeEach(module('eCommercePluginWidget'));
        beforeEach(inject(function (_$compile_, _$rootScope_) {
            $compile = _$compile_;
            $rootScope = _$rootScope_;
            $scope = _$rootScope_.$new();
        }));
        beforeEach(function () {
            buildFireCarousel3 = $compile('

')($scope);
            $rootScope.$digest();
        });

        it('it should pass and view switcher of div should be 1', function () {
            expect(buildFireCarousel3.length).toEqual(1);
            buildfire.messaging.onReceivedMessage("aa")
        });
    });
    describe('Test the filter', function () {
        'use strict';

        var $filter;

        beforeEach(function () {
            module('eCommercePluginWidget');

            inject(function (_$filter_) {
                $filter = _$filter_;
            });
        });

        it('should Crop the Image', function () {
            // Arrange.
            var url = 'https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150', result;
            var updatedUrl = 'http://s7obnu.cloudimage.io/s/crop/250x250/https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150';
            // Act.
            result = $filter('getImageUrl')(url, '250','250','no');

            // Assert.
            expect(result).toEqual(updatedUrl);
        });
        it('should Crop the Image when url', function () {
            // Arrange.
            var url = 'http://s7obnu.cloudimage.io/s/resizenp/250x250', result,
                updatedUrl = 'http://s7obnu.cloudimage.io/s/resizenp/250x250/http://s7obnu.cloudimage.io/s/resizenp/250x250';
            // Act.
            result = $filter('getImageUrl')(url, '250','250','resize');

            // Assert.
            expect(result).toEqual(updatedUrl);
        });

        it('should change the currency with moneyWithoutTrailingZeros (with value)', function () {
             var url = '50000.000', result,
                updatedUrl = 500;
           result = $filter('moneyWithoutTrailingZeros')(url);
           expect(result).toEqual(updatedUrl);
        });

        it('should change the currency with moneyWithoutTrailingZeros (Without value)', function () {
            var url = '', result,
                updatedUrl = "";
            result = $filter('moneyWithoutTrailingZeros')(url);
            expect(result).toEqual(updatedUrl);
        });
    });

    describe('backImg directive test with background Image URL', function () {
        var $compile, $rootScope, backImg, $scope;
        beforeEach(module('eCommercePluginWidget'));
        beforeEach(inject(function (_$compile_, _$rootScope_) {
            $compile = _$compile_;
            $rootScope = _$rootScope_;
            $scope = _$rootScope_.$new();
        }));
        beforeEach(function () {
            backImg = $compile('

')($scope);
            // $rootScope.$broadcast('VIEW_CHANGED');
            $rootScope.$digest();
        });

        it('it should pass and view switcher of div should be 1', function () {
            expect(backImg.length).toEqual(1);
        });

    });
    describe('backImg directive test without background Image URL', function () {
        var $compile, $rootScope, backImg, $scope;
        beforeEach(module('eCommercePluginWidget'));
        beforeEach(inject(function (_$compile_, _$rootScope_) {
            $compile = _$compile_;
            $rootScope = _$rootScope_;
            $scope = _$rootScope_.$new();
        }));
        beforeEach(function () {
            backImg = $compile('

')($scope);
            $rootScope.$digest();
        });

        it('it should pass and view switcher of div should be 1', function () {
            expect(backImg.length).toEqual(1);
        });

    });

    describe('customBindHtml directive test', function () {
        var $compile, $rootScope, customBindHtml, $scope;
        beforeEach(module('eCommercePluginWidget'));
        beforeEach(inject(function (_$compile_, _$rootScope_) {
            $compile = _$compile_;
            $rootScope = _$rootScope_;
            $scope = _$rootScope_.$new();
        }));
        beforeEach(function () {
                customBindHtml = $compile('

')($scope);
            $rootScope.$digest();
        });

        it('it should pass and view switcher of div should be 1', function () {
            expect(customBindHtml.length).toEqual(1);
        });

    });

    describe('loadImage directive test with background Image URL', function () {
        var $compile, $rootScope, backImg, $scope;
        beforeEach(module('eCommercePluginWidget'));
        beforeEach(inject(function (_$compile_, _$rootScope_) {
            $compile = _$compile_;
            $rootScope = _$rootScope_;
            $scope = _$rootScope_.$new();
        }));
        beforeEach(function () {
            backImg = $compile('

')($scope);
            // $rootScope.$broadcast('VIEW_CHANGED');
            $rootScope.$digest();
        });

        it('it should pass and view switcher of div should be 1', function () {
            expect(backImg.length).toEqual(1);
        });

    });

    describe('calling the buildfire.navigation.onBackButtonClick', function () {
        var ViewStack, $rootScope;
        beforeEach(module('eCommercePluginWidget'));
        beforeEach(inject(function (_ViewStack_, _$rootScope_) {
            ViewStack =_ViewStack_;
            $rootScope = _$rootScope_;
        }));
        var msg = {
            type:'UpdateItem',
            data:{
                pointsToRedeem:5
            }
        };
        it('it should pass when buildfire.messaging.onReceivedMessage', function () {
            buildfire.navigation.onBackButtonClick()
            $rootScope.$apply();
        });
    });
});