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

import * as Common from '../common/common.js';  // eslint-disable-line no-unused-vars
import * as ProtocolClientModule from '../protocol_client/protocol_client.js';
import * as Workspace from '../workspace/workspace.js';

/**
 * @fileoverview using private properties isn't a Closure violation in tests.
 * @suppress {accessControls}
 */

/* eslint-disable no-console */

/**
 * @return {boolean}
 */
export function isDebugTest() {
  return !self.testRunner || !!Root.Runtime.queryParam('debugFrontend');
}

/**
 * This monkey patches console functions in DevTools context so the console
 * messages are shown in the right places, instead of having all of the console
 * messages printed at the top of the test expectation file (default behavior).
 */
export function _printDevToolsConsole() {
  if (isDebugTest()) {
    return;
  }
  console.log = (...args) => {
    addResult(`log: ${args}`);
  };
  console.error = (...args) => {
    addResult(`error: ${args}`);
  };
  console.info = (...args) => {
    addResult(`info: ${args}`);
  };
  console.assert = (assertionCondition, ...args) => {
    if (!assertionCondition) {
      addResult(`ASSERTION FAILURE: ${args.join(' ')}`);
    }
  };
}

self['onerror'] = (message, source, lineno, colno, error) => {
  addResult('TEST ENDED IN ERROR: ' + error.stack);
  completeTest();
};
/** @suppressGlobalPropertiesCheck @suppress {checkTypes} */
(() => {
  self.addEventListener('unhandledrejection', event => {
    addResult(`PROMISE FAILURE: ${event.reason.stack}`);
    completeTest();
  });
})();
_printDevToolsConsole();

// TODO(crbug.com/1032477): Re-enable once test timeouts are handled in Chromium
// setTimeout(() => {
//   addResult('TEST TIMED OUT!');
//   completeTest();
// }, 6000);

/** @type {!Array<string>} */
let _results = [];

let _innerAddResult = text => {
  _results.push(String(text));
};

export function setInnerResult(updatedInnerResult) {
  _innerAddResult = updatedInnerResult;
}

/**
 * @param {*} text
 */
export function addResult(text) {
  _innerAddResult(text);
}

let completed = false;

let _innerCompleteTest = () => {
  if (completed) {
    return;
  }
  completed = true;
  flushResults();
  self.testRunner.notifyDone();
};

export function setInnerCompleteTest(updatedInnerCompleteTest) {
  _innerCompleteTest = updatedInnerCompleteTest;
}

export function completeTest() {
  _innerCompleteTest();
}

self.TestRunner = self.TestRunner || {};

/**
 * @suppressGlobalPropertiesCheck
 */
export function flushResults() {
  Array.prototype.forEach.call(document.documentElement.childNodes, x => x.remove());
  const outputElement = document.createElement('div');
  // Support for svg - add to document, not body, check for style.
  if (outputElement.style) {
    outputElement.style.whiteSpace = 'pre';
    outputElement.style.height = '10px';
    outputElement.style.overflow = 'hidden';
  }
  document.documentElement.appendChild(outputElement);
  for (let i = 0; i < _results.length; i++) {
    outputElement.appendChild(document.createTextNode(_results[i]));
    outputElement.appendChild(document.createElement('br'));
  }
  _results = [];
}

/**
 * @param {!Array<string>} textArray
 */
export function addResults(textArray) {
  if (!textArray) {
    return;
  }
  for (let i = 0, size = textArray.length; i < size; ++i) {
    addResult(textArray[i]);
  }
}

/**
 * @param {!Array<function()>} tests
 */
export function runTests(tests) {
  nextTest();

  function nextTest() {
    const test = tests.shift();
    if (!test) {
      completeTest();
      return;
    }
    addResult('\ntest: ' + test.name);
    let testPromise = test();
    if (!(testPromise instanceof Promise)) {
      testPromise = Promise.resolve();
    }
    testPromise.then(nextTest);
  }
}

/**
 * @param {!Object} receiver
 * @param {string} methodName
 * @param {!Function} override
 * @param {boolean=} opt_sticky
 */
export function addSniffer(receiver, methodName, override, opt_sticky) {
  override = safeWrap(override);

  const original = receiver[methodName];
  if (typeof original !== 'function') {
    throw new Error('Cannot find method to override: ' + methodName);
  }

  receiver[methodName] = function(var_args) {
    let result;
    try {
      result = original.apply(this, arguments);
    } finally {
      if (!opt_sticky) {
        receiver[methodName] = original;
      }
    }
    // In case of exception the override won't be called.
    try {
      Array.prototype.push.call(arguments, result);
      override.apply(this, arguments);
    } catch (e) {
      throw new Error('Exception in overriden method \'' + methodName + '\': ' + e);
    }
    return result;
  };
}

/**
 * @param {!Object} receiver
 * @param {string} methodName
 * @return {!Promise<*>}
 */
export function addSnifferPromise(receiver, methodName) {
  return new Promise(function(resolve, reject) {
    const original = receiver[methodName];
    if (typeof original !== 'function') {
      reject('Cannot find method to override: ' + methodName);
      return;
    }

    receiver[methodName] = function(var_args) {
      let result;
      try {
        result = original.apply(this, arguments);
      } finally {
        receiver[methodName] = original;
      }
      // In case of exception the override won't be called.
      try {
        Array.prototype.push.call(arguments, result);
        resolve.apply(this, arguments);
      } catch (e) {
        reject('Exception in overridden method \'' + methodName + '\': ' + e);
        completeTest();
      }
      return result;
    };
  });
}

/** @type {function():void} */
let _resolveOnFinishInits;

/**
 * @param {string} module
 * @return {!Promise<undefined>}
 */
export async function loadModule(module) {
  const promise = new Promise(resolve => _resolveOnFinishInits = resolve);
  await self.runtime.loadModulePromise(module);
  if (!_pendingInits) {
    return;
  }
  return promise;
}

/**
 * @param {string} panel
 * @return {!Promise.<?UI.Panel>}
 */
export function showPanel(panel) {
  return self.UI.viewManager.showView(panel);
}

/**
 * @param {string} key
 * @param {boolean=} ctrlKey
 * @param {boolean=} altKey
 * @param {boolean=} shiftKey
 * @param {boolean=} metaKey
 * @return {!KeyboardEvent}
 */
export function createKeyEvent(key, ctrlKey, altKey, shiftKey, metaKey) {
  return new KeyboardEvent('keydown', {
    key: key,
    bubbles: true,
    cancelable: true,
    ctrlKey: !!ctrlKey,
    altKey: !!altKey,
    shiftKey: !!shiftKey,
    metaKey: !!metaKey
  });
}

/**
 * Wraps a test function with an exception filter. Does not work
 * correctly for async functions; use safeAsyncWrap instead.
 * @param {!Function|undefined} func
 * @param {!Function=} onexception
 * @return {!Function}
 */
export function safeWrap(func, onexception) {
  /**
   * @this {*}
   */
  function result() {
    if (!func) {
      return;
    }
    const wrapThis = this;
    try {
      return func.apply(wrapThis, arguments);
    } catch (e) {
      addResult('Exception while running: ' + func + '\n' + (e.stack || e));
      if (onexception) {
        safeWrap(onexception)();
      } else {
        completeTest();
      }
    }
  }
  return result;
}

/**
 * Wraps a test function that returns a Promise with an exception
 * filter. Does not work correctly for functions which don't return
 * a Promise; use safeWrap instead.
 * @param {function(...):Promise<*>} func
 * @return {function(...):Promise<*>}
 */
export function safeAsyncWrap(func) {
  /**
   * @this {*}
   */
  async function result() {
    if (!func) {
      return;
    }
    const wrapThis = this;
    try {
      return await func.apply(wrapThis, arguments);
    } catch (e) {
      addResult('Exception while running: ' + func + '\n' + (e.stack || e));
      completeTest();
    }
  }
  return result;
}

/**
 * @param {!Node} node
 * @return {string}
 */
export function textContentWithLineBreaks(node) {
  function padding(currentNode) {
    let result = 0;
    while (currentNode && currentNode !== node) {
      if (currentNode.nodeName === 'OL' &&
          !(currentNode.classList && currentNode.classList.contains('object-properties-section'))) {
        ++result;
      }
      currentNode = currentNode.parentNode;
    }
    return Array(result * 4 + 1).join(' ');
  }

  let buffer = '';
  let currentNode = node;
  let ignoreFirst = false;
  while (currentNode.traverseNextNode(node)) {
    currentNode = currentNode.traverseNextNode(node);
    if (currentNode.nodeType === Node.TEXT_NODE) {
      buffer += currentNode.nodeValue;
    } else if (currentNode.nodeName === 'LI' || currentNode.nodeName === 'TR') {
      if (!ignoreFirst) {
        buffer += '\n' + padding(currentNode);
      } else {
        ignoreFirst = false;
      }
    } else if (currentNode.nodeName === 'STYLE') {
      currentNode = currentNode.traverseNextNode(node);
      continue;
    } else if (currentNode.classList && currentNode.classList.contains('object-properties-section')) {
      ignoreFirst = true;
    }
  }
  return buffer;
}

/**
 * @param {!Node} node
 * @return {string}
 */
export function textContentWithoutStyles(node) {
  let buffer = '';
  let currentNode = node;
  while (currentNode.traverseNextNode(node)) {
    currentNode = currentNode.traverseNextNode(node);
    if (currentNode.nodeType === Node.TEXT_NODE) {
      buffer += currentNode.nodeValue;
    } else if (currentNode.nodeName === 'STYLE') {
      currentNode = currentNode.traverseNextNode(node);
    }
  }
  return buffer;
}

/**
 * @param {string} code
 * @return {!Promise<*>}
 */
export async function evaluateInPageRemoteObject(code) {
  const response = await _evaluateInPage(code);
  return TestRunner.runtimeModel.createRemoteObject(response.result);
}

/**
 * @param {string} code
 * @param {function(*, !Protocol.Runtime.ExceptionDetails=):void} callback
 */
export async function evaluateInPage(code, callback) {
  const response = await _evaluateInPage(code);
  safeWrap(callback)(response.result.value, response.exceptionDetails);
}

/** @type {number} */
let _evaluateInPageCounter = 0;

/**
 * @param {string} code
 * @return {!Promise<undefined|{response: (!SDK.RemoteObject|undefined),
 *   exceptionDetails: (!Protocol.Runtime.ExceptionDetails|undefined)}>}
 */
export async function _evaluateInPage(code) {
  const lines = new Error().stack.split('at ');

  // Handles cases where the function is safe wrapped
  const testScriptURL = /** @type {string} */ (Root.Runtime.queryParam('test'));
  const functionLine = lines.reduce((acc, line) => line.includes(testScriptURL) ? line : acc, lines[lines.length - 2]);

  const components = functionLine.trim().split('/');
  const source = components[components.length - 1].slice(0, -1).split(':');
  const fileName = source[0];
  const sourceURL = `test://evaluations/${_evaluateInPageCounter++}/` + fileName;
  const lineOffset = parseInt(source[1], 10);
  code = '\n'.repeat(lineOffset - 1) + code;
  if (code.indexOf('sourceURL=') === -1) {
    code += `//# sourceURL=${sourceURL}`;
  }
  const response = await TestRunner.RuntimeAgent.invoke_evaluate({expression: code, objectGroup: 'console'});
  const error = response[ProtocolClientModule.InspectorBackend.ProtocolError];
  if (error) {
    addResult('Error: ' + error);
    completeTest();
    return;
  }
  return response;
}

/**
 * Doesn't append sourceURL to snippets evaluated in inspected page
 * to avoid churning test expectations
 * @param {string} code
 * @param {boolean=} userGesture
 * @return {!Promise<*>}
 */
export async function evaluateInPageAnonymously(code, userGesture) {
  const response =
      await TestRunner.RuntimeAgent.invoke_evaluate({expression: code, objectGroup: 'console', userGesture});
  if (!response[ProtocolClientModule.InspectorBackend.ProtocolError]) {
    return response.result.value;
  }
  addResult(
      'Error: ' +
      (response.exceptionDetails && response.exceptionDetails.text || 'exception from evaluateInPageAnonymously.'));
  completeTest();
}

/**
 * @param {string} code
 * @return {!Promise<*>}
 */
export function evaluateInPagePromise(code) {
  return new Promise(success => evaluateInPage(code, success));
}

/**
 * @param {string} code
 * @return {!Promise<*>}
 */
export async function evaluateInPageAsync(code) {
  const response = await TestRunner.RuntimeAgent.invoke_evaluate(
      {expression: code, objectGroup: 'console', includeCommandLineAPI: false, awaitPromise: true});

  const error = response[ProtocolClientModule.InspectorBackend.ProtocolError];
  if (!error && !response.exceptionDetails) {
    return response.result.value;
  }
  addResult(
      'Error: ' +
      (error || response.exceptionDetails && response.exceptionDetails.text || 'exception while evaluation in page.'));
  completeTest();
}

/**
 * @param {string} name
 * @param {!Array<*>} args
 * @return {!Promise<*>}
 */
export function callFunctionInPageAsync(name, args) {
  args = args || [];
  return evaluateInPageAsync(name + '(' + args.map(a => JSON.stringify(a)).join(',') + ')');
}

/**
 * @param {string} code
 * @param {boolean=} userGesture
 */
export function evaluateInPageWithTimeout(code, userGesture) {
  // FIXME: we need a better way of waiting for chromium events to happen
  evaluateInPageAnonymously('setTimeout(unescape(\'' + escape(code) + '\'), 1)', userGesture);
}

/**
 * @param {function():*} func
 * @param {function(*):void} callback
 */
export function evaluateFunctionInOverlay(func, callback) {
  const expression = 'internals.evaluateInInspectorOverlay("(" + ' + func + ' + ")()")';
  const mainContext = TestRunner.runtimeModel.executionContexts()[0];
  mainContext
      .evaluate(
          {
            expression: expression,
            objectGroup: '',
            includeCommandLineAPI: false,
            silent: false,
            returnByValue: true,
            generatePreview: false
          },
          /* userGesture */ false, /* awaitPromise*/ false)
      .then(result => void callback(result.object.value));
}

/**
 * @param {boolean} passCondition
 * @param {string} failureText
 */
export function check(passCondition, failureText) {
  if (!passCondition) {
    addResult('FAIL: ' + failureText);
  }
}

/**
 * @param {!Function} callback
 */
export function deprecatedRunAfterPendingDispatches(callback) {
  ProtocolClient.test.deprecatedRunAfterPendingDispatches(callback);
}

/**
 * This ensures a base tag is set so all DOM references
 * are relative to the test file and not the inspected page
 * (i.e. http/tests/devtools/resources/inspected-page.html).
 * @param {string} html
 * @return {!Promise<*>}
 */
export function loadHTML(html) {
  if (!html.includes('<base')) {
    // <!DOCTYPE...> tag needs to be first
    const doctypeRegex = /(<!DOCTYPE.*?>)/i;
    const baseTag = `<base href="${url()}">`;
    if (html.match(doctypeRegex)) {
      html = html.replace(doctypeRegex, '$1' + baseTag);
    } else {
      html = baseTag + html;
    }
  }
  html = html.replace(/'/g, '\\\'').replace(/\n/g, '\\n');
  return evaluateInPageAnonymously(`document.write(\`${html}\`);document.close();`);
}

/**
 * @param {string} path
 * @return {!Promise<*>}
 */
export function addScriptTag(path) {
  return evaluateInPageAsync(`
    (function(){
      let script = document.createElement('script');
      script.src = '${path}';
      document.head.append(script);
      return new Promise(f => script.onload = f);
    })();
  `);
}

/**
 * @param {string} path
 * @return {!Promise<*>}
 */
export function addStylesheetTag(path) {
  return evaluateInPageAsync(`
    (function(){
      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.href = '${path}';
      link.onload = onload;
      document.head.append(link);
      let resolve;
      const promise = new Promise(r => resolve = r);
      function onload() {
        // TODO(chenwilliam): It shouldn't be necessary to force
        // style recalc here but some tests rely on it.
        window.getComputedStyle(document.body).color;
        resolve();
      }
      return promise;
    })();
  `);
}

/**
 * @param {string} path
 * @return {!Promise<*>}
 */
export function addHTMLImport(path) {
  return evaluateInPageAsync(`
    (function(){
      const link = document.createElement('link');
      link.rel = 'import';
      link.href = '${path}';
      const promise = new Promise(r => link.onload = r);
      document.body.append(link);
      return promise;
    })();
  `);
}

/**
 * NOTE you should manually ensure the path is correct. There
 * is no error event triggered if it is incorrect, and this is
 * in line with the standard (crbug 365457).
 * @param {string} path
 * @param {!Object|undefined} options
 * @return {!Promise<*>}
 */
export function addIframe(path, options = {}) {
  options.id = options.id || '';
  options.name = options.name || '';
  return evaluateInPageAsync(`
    (function(){
      const iframe = document.createElement('iframe');
      iframe.src = '${path}';
      iframe.id = '${options.id}';
      iframe.name = '${options.name}';
      document.body.appendChild(iframe);
      return new Promise(f => iframe.onload = f);
    })();
  `);
}

/** @type {number} */
let _pendingInits = 0;

/**
 * The old test framework executed certain snippets in the inspected page
 * context as part of loading a test helper file.
 *
 * This is deprecated because:
 * 1) it makes the testing API less intuitive (need to read the various *TestRunner.js
 * files to know which helper functions are available in the inspected page).
 * 2) it complicates the test framework's module loading process.
 *
 * In most cases, this is used to set up inspected page functions (e.g. makeSimpleXHR)
 * which should become a *TestRunner method (e.g. NetworkTestRunner.makeSimpleXHR)
 * that calls evaluateInPageAnonymously(...).
 * @param {string} code
 */
export async function deprecatedInitAsync(code) {
  _pendingInits++;
  await TestRunner.RuntimeAgent.invoke_evaluate({expression: code, objectGroup: 'console'});
  _pendingInits--;
  if (!_pendingInits) {
    _resolveOnFinishInits();
  }
}

/**
 * @param {string} title
 */
export function markStep(title) {
  addResult('\nRunning: ' + title);
}

export function startDumpingProtocolMessages() {
  ProtocolClient.test.dumpProtocol = self.testRunner.logToStderr.bind(self.testRunner);
}

/**
 * @param {string} url
 * @param {string} content
 * @param {!SDK.ResourceTreeFrame} frame
 */
export function addScriptForFrame(url, content, frame) {
  content += '\n//# sourceURL=' + url;
  const executionContext = TestRunner.runtimeModel.executionContexts().find(context => context.frameId === frame.id);
  TestRunner.RuntimeAgent.evaluate(content, 'console', false, false, executionContext.id);
}

export const formatters = {

  /**
 * @param {*} value
 * @return {string}
 */
  formatAsTypeName(value) {
    return '<' + typeof value + '>';
  },

  /**
 * @param {*} value
 * @return {string}
 */
  formatAsTypeNameOrNull(value) {
    if (value === null) {
      return 'null';
    }
    return formatters.formatAsTypeName(value);
  },

  /**
 * @param {*} value
 * @return {string|!Date}
 */
  formatAsRecentTime(value) {
    if (typeof value !== 'object' || !(value instanceof Date)) {
      return formatters.formatAsTypeName(value);
    }
    const delta = Date.now() - value;
    return 0 <= delta && delta < 30 * 60 * 1000 ? '<plausible>' : value;
  },

  /**
 * @param {string} value
 * @return {string}
 */
  formatAsURL(value) {
    if (!value) {
      return value;
    }
    const lastIndex = value.lastIndexOf('devtools/');
    if (lastIndex < 0) {
      return value;
    }
    return '.../' + value.substr(lastIndex);
  },

  /**
 * @param {string} value
 * @return {string}
 */
  formatAsDescription(value) {
    if (!value) {
      return value;
    }
    return '"' + value.replace(/^function [gs]et /, 'function ') + '"';
  },
};

/**
 * @param {!Object} object
 * @param {!TestRunner.CustomFormatters=} customFormatters
 * @param {string=} prefix
 * @param {string=} firstLinePrefix
 */
export function addObject(object, customFormatters, prefix, firstLinePrefix) {
  prefix = prefix || '';
  firstLinePrefix = firstLinePrefix || prefix;
  addResult(firstLinePrefix + '{');
  const propertyNames = Object.keys(object);
  propertyNames.sort();
  for (let i = 0; i < propertyNames.length; ++i) {
    const prop = propertyNames[i];
    if (!object.hasOwnProperty(prop)) {
      continue;
    }
    const prefixWithName = '    ' + prefix + prop + ' : ';
    const propValue = object[prop];
    if (customFormatters && customFormatters[prop]) {
      const formatterName = customFormatters[prop];
      if (formatterName !== 'skip') {
        const formatter = formatters[formatterName];
        addResult(prefixWithName + formatter(propValue));
      }
    } else {
      dump(propValue, customFormatters, '    ' + prefix, prefixWithName);
    }
  }
  addResult(prefix + '}');
}

/**
 * @param {!Array} array
 * @param {!TestRunner.CustomFormatters=} customFormatters
 * @param {string=} prefix
 * @param {string=} firstLinePrefix
 */
export function addArray(array, customFormatters, prefix, firstLinePrefix) {
  prefix = prefix || '';
  firstLinePrefix = firstLinePrefix || prefix;
  addResult(firstLinePrefix + '[');
  for (let i = 0; i < array.length; ++i) {
    dump(array[i], customFormatters, prefix + '    ');
  }
  addResult(prefix + ']');
}

/**
 * @param {!Node} node
 */
export function dumpDeepInnerHTML(node) {
  /**
   * @param {string} prefix
   * @param {!Node} node
   */
  function innerHTML(prefix, node) {
    const openTag = [];
    if (node.nodeType === Node.TEXT_NODE) {
      if (!node.parentElement || node.parentElement.nodeName !== 'STYLE') {
        addResult(node.nodeValue);
      }
      return;
    }
    openTag.push('<' + node.nodeName);
    const attrs = node.attributes;
    for (let i = 0; attrs && i < attrs.length; ++i) {
      openTag.push(attrs[i].name + '=' + attrs[i].value);
    }

    openTag.push('>');
    addResult(prefix + openTag.join(' '));
    for (let child = node.firstChild; child; child = child.nextSibling) {
      innerHTML(prefix + '    ', child);
    }
    if (node.shadowRoot) {
      innerHTML(prefix + '    ', node.shadowRoot);
    }
    addResult(prefix + '</' + node.nodeName + '>');
  }
  innerHTML('', node);
}

/**
 * @param {!Node} node
 * @return {string}
 */
export function deepTextContent(node) {
  if (!node) {
    return '';
  }
  if (node.nodeType === Node.TEXT_NODE && node.nodeValue) {
    return !node.parentElement || node.parentElement.nodeName !== 'STYLE' ? node.nodeValue : '';
  }
  let res = '';
  const children = node.childNodes;
  for (let i = 0; i < children.length; ++i) {
    res += deepTextContent(children[i]);
  }
  if (node.shadowRoot) {
    res += deepTextContent(node.shadowRoot);
  }
  return res;
}

/**
 * @param {*} value
 * @param {!TestRunner.CustomFormatters=} customFormatters
 * @param {string=} prefix
 * @param {string=} prefixWithName
 */
export function dump(value, customFormatters, prefix, prefixWithName) {
  prefixWithName = prefixWithName || prefix;
  if (prefixWithName && prefixWithName.length > 80) {
    addResult(prefixWithName + 'was skipped due to prefix length limit');
    return;
  }
  if (value === null) {
    addResult(prefixWithName + 'null');
  } else if (value && value.constructor && value.constructor.name === 'Array') {
    addArray(/** @type {!Array} */ (value), customFormatters, prefix, prefixWithName);
  } else if (typeof value === 'object') {
    addObject(/** @type {!Object} */ (value), customFormatters, prefix, prefixWithName);
  } else if (typeof value === 'string') {
    addResult(prefixWithName + '"' + value + '"');
  } else {
    addResult(prefixWithName + value);
  }
}

/**
 * @param {!UI.TreeElement} treeElement
 */
export function dumpObjectPropertyTreeElement(treeElement) {
  const expandedSubstring = treeElement.expanded ? '[expanded]' : '[collapsed]';
  addResult(expandedSubstring + ' ' + treeElement.listItemElement.deepTextContent());

  for (let i = 0; i < treeElement.childCount(); ++i) {
    const property = treeElement.childAt(i).property;
    const key = property.name;
    const value = property.value._description;
    addResult('    ' + key + ': ' + value);
  }
}

/**
 * @param {symbol} eventName
 * @param {!Common.ObjectWrapper.ObjectWrapper} obj
 * @param {function(?):boolean=} condition
 * @return {!Promise}
 */
export function waitForEvent(eventName, obj, condition) {
  condition = condition || function() {
    return true;
  };
  return new Promise(resolve => {
    obj.addEventListener(eventName, onEventFired);

    /**
     * @param {!Common.EventTarget.EventTargetEvent} event
     */
    function onEventFired(event) {
      if (!condition(event.data)) {
        return;
      }
      obj.removeEventListener(eventName, onEventFired);
      resolve(event.data);
    }
  });
}

/**
 * @param {function(!SDK.Target):boolean} filter
 * @return {!Promise<!SDK.Target>}
 */
export function waitForTarget(filter) {
  filter = filter || (target => true);
  for (const target of self.SDK.targetManager.targets()) {
    if (filter(target)) {
      return Promise.resolve(target);
    }
  }
  return new Promise(fulfill => {
    const observer = /** @type {!SDK.TargetManager.Observer} */ ({
      targetAdded: function(target) {
        if (filter(target)) {
          self.SDK.targetManager.unobserveTargets(observer);
          fulfill(target);
        }
      },
      targetRemoved: function() {},
    });
    self.SDK.targetManager.observeTargets(observer);
  });
}

/**
 * @param {!SDK.Target} targetToRemove
 * @return {!Promise<!SDK.Target>}
 */
export function waitForTargetRemoved(targetToRemove) {
  return new Promise(fulfill => {
    const observer = /** @type {!SDK.TargetManager.Observer} */ ({
      targetRemoved: function(target) {
        if (target === targetToRemove) {
          self.SDK.targetManager.unobserveTargets(observer);
          fulfill(target);
        }
      },
      targetAdded: function() {},
    });
    self.SDK.targetManager.observeTargets(observer);
  });
}

/**
 * @param {!SDK.RuntimeModel} runtimeModel
 * @return {!Promise}
 */
export function waitForExecutionContext(runtimeModel) {
  if (runtimeModel.executionContexts().length) {
    return Promise.resolve(runtimeModel.executionContexts()[0]);
  }
  return runtimeModel.once(SDK.RuntimeModel.Events.ExecutionContextCreated);
}

/**
 * @param {!SDK.ExecutionContext} context
 * @return {!Promise}
 */
export function waitForExecutionContextDestroyed(context) {
  const runtimeModel = context.runtimeModel;
  if (runtimeModel.executionContexts().indexOf(context) === -1) {
    return Promise.resolve();
  }
  return waitForEvent(
      SDK.RuntimeModel.Events.ExecutionContextDestroyed, runtimeModel,
      destroyedContext => destroyedContext === context);
}

/**
 * @param {number} a
 * @param {number} b
 * @param {string=} message
 */
export function assertGreaterOrEqual(a, b, message) {
  if (a < b) {
    addResult('FAILED: ' + (message ? message + ': ' : '') + a + ' < ' + b);
  }
}

let _pageLoadedCallback;

/**
 * @param {string} url
 * @param {function():void} callback
 */
export function navigate(url, callback) {
  _pageLoadedCallback = safeWrap(callback);
  TestRunner.resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.Load, _pageNavigated);
  // Note: injected <base> means that url is relative to test
  // and not the inspected page
  evaluateInPageAnonymously('window.location.replace(\'' + url + '\')');
}

/**
 * @return {!Promise}
 */
export function navigatePromise(url) {
  return new Promise(fulfill => navigate(url, fulfill));
}

export function _pageNavigated() {
  TestRunner.resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.Load, _pageNavigated);
  _handlePageLoaded();
}

/**
 * @param {function():void} callback
 */
export function hardReloadPage(callback) {
  _innerReloadPage(true, undefined, callback);
}

/**
 * @param {function():void} callback
 */
export function reloadPage(callback) {
  _innerReloadPage(false, undefined, callback);
}

/**
 * @param {(string|undefined)} injectedScript
 * @param {function():void} callback
 */
export function reloadPageWithInjectedScript(injectedScript, callback) {
  _innerReloadPage(false, injectedScript, callback);
}

/**
 * @return {!Promise}
 */
export function reloadPagePromise() {
  return new Promise(fulfill => reloadPage(fulfill));
}

/**
 * @param {boolean} hardReload
 * @param {(string|undefined)} injectedScript
 * @param {function():void} callback
 */
export function _innerReloadPage(hardReload, injectedScript, callback) {
  _pageLoadedCallback = safeWrap(callback);
  TestRunner.resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.Load, pageLoaded);
  TestRunner.resourceTreeModel.reloadPage(hardReload, injectedScript);
}

export function pageLoaded() {
  TestRunner.resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.Load, pageLoaded);
  addResult('Page reloaded.');
  _handlePageLoaded();
}

export async function _handlePageLoaded() {
  await waitForExecutionContext(/** @type {!SDK.RuntimeModel} */ (TestRunner.runtimeModel));
  if (_pageLoadedCallback) {
    const callback = _pageLoadedCallback;
    _pageLoadedCallback = undefined;
    callback();
  }
}

/**
 * @param {function():void} callback
 */
export function waitForPageLoad(callback) {
  TestRunner.resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.Load, onLoaded);

  function onLoaded() {
    TestRunner.resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.Load, onLoaded);
    callback();
  }
}

/**
 * @param {function():void} callback
 */
export function runWhenPageLoads(callback) {
  const oldCallback = _pageLoadedCallback;
  function chainedCallback() {
    if (oldCallback) {
      oldCallback();
    }
    callback();
  }
  _pageLoadedCallback = safeWrap(chainedCallback);
}

/**
 * @param {!Array<function(function():void)>} testSuite
 */
export function runTestSuite(testSuite) {
  const testSuiteTests = testSuite.slice();

  function runner() {
    if (!testSuiteTests.length) {
      completeTest();
      return;
    }
    const nextTest = testSuiteTests.shift();
    addResult('');
    addResult(
        'Running: ' +
        /function\s([^(]*)/.exec(nextTest)[1]);
    safeWrap(nextTest)(runner);
  }
  runner();
}

/**
 * @param {!Array<function():Promise<*>>} testSuite
 */
export async function runAsyncTestSuite(testSuite) {
  for (const nextTest of testSuite) {
    addResult('');
    addResult(
        'Running: ' +
        /function\s([^(]*)/.exec(nextTest)[1]);
    await safeAsyncWrap(nextTest)();
  }

  completeTest();
}

/**
 * @param {*} expected
 * @param {*} found
 * @param {string} message
 */
export function assertEquals(expected, found, message) {
  if (expected === found) {
    return;
  }

  let error;
  if (message) {
    error = 'Failure (' + message + '):';
  } else {
    error = 'Failure:';
  }
  throw new Error(error + ' expected <' + expected + '> found <' + found + '>');
}

/**
 * @param {*} found
 * @param {string} message
 */
export function assertTrue(found, message) {
  assertEquals(true, !!found, message);
}

/**
 * @param {!Object} receiver
 * @param {string} methodName
 * @param {!Function} override
 * @param {boolean=} opt_sticky
 * @return {!Function}
 */
export function override(receiver, methodName, override, opt_sticky) {
  override = safeWrap(override);

  const original = receiver[methodName];
  if (typeof original !== 'function') {
    throw new Error('Cannot find method to override: ' + methodName);
  }

  receiver[methodName] = function(var_args) {
    try {
      return override.apply(this, arguments);
    } catch (e) {
      throw new Error('Exception in overriden method \'' + methodName + '\': ' + e);
    } finally {
      if (!opt_sticky) {
        receiver[methodName] = original;
      }
    }
  };

  return original;
}

/**
 * @param {string} text
 * @return {string}
 */
export function clearSpecificInfoFromStackFrames(text) {
  let buffer = text.replace(/\(file:\/\/\/(?:[^)]+\)|[\w\/:-]+)/g, '(...)');
  buffer = buffer.replace(/\(http:\/\/(?:[^)]+\)|[\w\/:-]+)/g, '(...)');
  buffer = buffer.replace(/\(test:\/\/(?:[^)]+\)|[\w\/:-]+)/g, '(...)');
  buffer = buffer.replace(/\(<anonymous>:[^)]+\)/g, '(...)');
  buffer = buffer.replace(/VM\d+/g, 'VM');
  return buffer.replace(/\s*at[^()]+\(native\)/g, '');
}

export function hideInspectorView() {
  self.UI.inspectorView.element.setAttribute('style', 'display:none !important');
}

/**
 * @return {?SDK.ResourceTreeFrame}
 */
export function mainFrame() {
  return TestRunner.resourceTreeModel.mainFrame;
}

export class StringOutputStream {
  /**
   * @param {function(string):void} callback
   */
  constructor(callback) {
    this._callback = callback;
    this._buffer = '';
  }

  /**
   * @param {string} fileName
   * @return {!Promise<boolean>}
   */
  async open(fileName) {
    return true;
  }

  /**
   * @param {string} chunk
   */
  async write(chunk) {
    this._buffer += chunk;
  }

  async close() {
    this._callback(this._buffer);
  }
}

/**
 * @template V
 */
export class MockSetting {
  /**
   * @param {V} value
   */
  constructor(value) {
    this._value = value;
  }

  /**
   * @return {V}
   */
  get() {
    return this._value;
  }

  /**
   * @param {V} value
   */
  set(value) {
    this._value = value;
  }
}

/**
 * @return {!Array<!Root.Runtime.Module>}
 */
export function loadedModules() {
  return self.runtime._modules.filter(module => module._loadedForTest)
      .filter(module => module.name() !== 'help')
      .filter(module => module.name().indexOf('test_runner') === -1);
}

/**
 * @param {!Array<!Root.Runtime.Module>} relativeTo
 * @return {!Array<!Root.Runtime.Module>}
 */
export function dumpLoadedModules(relativeTo) {
  const previous = new Set(relativeTo || []);
  function moduleSorter(left, right) {
    return String.naturalOrderComparator(left._descriptor.name, right._descriptor.name);
  }

  addResult('Loaded modules:');
  const sortedLoadedModules = loadedModules().sort(moduleSorter);
  for (const module of sortedLoadedModules) {
    if (previous.has(module)) {
      continue;
    }
    addResult('    ' + module._descriptor.name);
  }
  return sortedLoadedModules;
}

/**
 * @param {string} urlSuffix
 * @param {!Workspace.Workspace.projectTypes=} projectType
 * @return {!Promise}
 */
export function waitForUISourceCode(urlSuffix, projectType) {
  /**
   * @param {!Workspace.UISourceCode.UISourceCode} uiSourceCode
   * @return {boolean}
   */
  function matches(uiSourceCode) {
    if (projectType && uiSourceCode.project().type() !== projectType) {
      return false;
    }
    if (!projectType && uiSourceCode.project().type() === Workspace.Workspace.projectTypes.Service) {
      return false;
    }
    if (urlSuffix && !uiSourceCode.url().endsWith(urlSuffix)) {
      return false;
    }
    return true;
  }

  for (const uiSourceCode of self.Workspace.workspace.uiSourceCodes()) {
    if (urlSuffix && matches(uiSourceCode)) {
      return Promise.resolve(uiSourceCode);
    }
  }

  return waitForEvent(Workspace.Workspace.Events.UISourceCodeAdded, self.Workspace.workspace, matches);
}

/**
 * @param {!Function} callback
 */
export function waitForUISourceCodeRemoved(callback) {
  self.Workspace.workspace.once(Workspace.Workspace.Events.UISourceCodeRemoved).then(callback);
}

/**
 * @param {string=} url
 * @return {string}
 */
export function url(url = '') {
  const testScriptURL = /** @type {string} */ (Root.Runtime.queryParam('test'));

  // This handles relative (e.g. "../file"), root (e.g. "/resource"),
  // absolute (e.g. "http://", "data:") and empty (e.g. "") paths
  return new URL(url, testScriptURL + '/../').href;
}

/**
 * @param {string} str
 * @param {string} mimeType
 * @return {!Promise.<undefined>}
 * @suppressGlobalPropertiesCheck
 */
export function dumpSyntaxHighlight(str, mimeType) {
  const node = document.createElement('span');
  node.textContent = str;
  const javascriptSyntaxHighlighter = new UI.SyntaxHighlighter(mimeType, false);
  return javascriptSyntaxHighlighter.syntaxHighlightNode(node).then(dumpSyntax);

  function dumpSyntax() {
    const node_parts = [];

    for (let i = 0; i < node.childNodes.length; i++) {
      if (node.childNodes[i].getAttribute) {
        node_parts.push(node.childNodes[i].getAttribute('class'));
      } else {
        node_parts.push('*');
      }
    }

    addResult(str + ': ' + node_parts.join(', '));
  }
}

/* this code exists in Platform.StringUtilities but these layout tests
* cannot import ES modules so we copy the required code in directly as
* these layout tests are going to be removed in favour of e2e so it's
* not worth adding ESM support here
*/

/**
 *
 * @param {string} inputString
 * @param {string} searchString
 * @return {!Array.<number>}
 */
const findIndexesOfSubString = function(inputString, searchString) {
  const matches = [];
  let i = inputString.indexOf(searchString);
  while (i !== -1) {
    matches.push(i);
    i = inputString.indexOf(searchString, i + searchString.length);
  }
  return matches;
};

/**
 *
 * @param {string} inputString
 * @return {!Array.<number>}
 */
export const findLineEndingIndexes = function(inputString) {
  const endings = findIndexesOfSubString(inputString, '\n');
  endings.push(inputString.length);
  return endings;
};

/**
 * @param {string} querySelector
 */
export async function dumpInspectedPageElementText(querySelector) {
  const value = await evaluateInPageAsync(`document.querySelector('${querySelector}').innerText`);
  addResult(value);
}

/**
 * This method blocks until all currently queued live location update handlers are done.
 *
 * Creating and updating live locations causes the update handler of each live location
 * to run. These update handlers are potentially asynchronous and usually cause re-rendering or
 * UI updates. Web tests then check for these updates.
 * To give tests more control, waitForPendingLiveLocationUpdates returns a promise that resolves
 * once all currently-pending updates (at call time) are completed.
 */
export async function waitForPendingLiveLocationUpdates() {
  await self.Bindings.debuggerWorkspaceBinding.pendingLiveLocationChangesPromise();
  await self.Bindings.cssWorkspaceBinding.pendingLiveLocationChangesPromise();
}

/** @type {!{logToStderr: function(), navigateSecondaryWindow: function(string), notifyDone: function()}|undefined} */
self.testRunner;

TestRunner.StringOutputStream = StringOutputStream;
TestRunner.MockSetting = MockSetting;

TestRunner.formatters = formatters;

TestRunner.flushResults = flushResults;
TestRunner.completeTest = completeTest;
TestRunner.addResult = addResult;
TestRunner.addResults = addResults;
TestRunner.runTests = runTests;
TestRunner.addSniffer = addSniffer;
TestRunner.addSnifferPromise = addSnifferPromise;
TestRunner.showPanel = showPanel;
TestRunner.createKeyEvent = createKeyEvent;
TestRunner.safeWrap = safeWrap;
TestRunner.safeAsyncWrap = safeAsyncWrap;
TestRunner.textContentWithLineBreaks = textContentWithLineBreaks;
TestRunner.textContentWithoutStyles = textContentWithoutStyles;
TestRunner.evaluateInPagePromise = evaluateInPagePromise;
TestRunner.callFunctionInPageAsync = callFunctionInPageAsync;
TestRunner.evaluateInPageWithTimeout = evaluateInPageWithTimeout;
TestRunner.evaluateFunctionInOverlay = evaluateFunctionInOverlay;
TestRunner.check = check;
TestRunner.deprecatedRunAfterPendingDispatches = deprecatedRunAfterPendingDispatches;
TestRunner.loadHTML = loadHTML;
TestRunner.addScriptTag = addScriptTag;
TestRunner.addStylesheetTag = addStylesheetTag;
TestRunner.addHTMLImport = addHTMLImport;
TestRunner.addIframe = addIframe;
TestRunner.markStep = markStep;
TestRunner.startDumpingProtocolMessages = startDumpingProtocolMessages;
TestRunner.addScriptForFrame = addScriptForFrame;
TestRunner.addObject = addObject;
TestRunner.addArray = addArray;
TestRunner.dumpDeepInnerHTML = dumpDeepInnerHTML;
TestRunner.deepTextContent = deepTextContent;
TestRunner.dump = dump;
TestRunner.dumpObjectPropertyTreeElement = dumpObjectPropertyTreeElement;
TestRunner.waitForEvent = waitForEvent;
TestRunner.waitForTarget = waitForTarget;
TestRunner.waitForTargetRemoved = waitForTargetRemoved;
TestRunner.waitForExecutionContext = waitForExecutionContext;
TestRunner.waitForExecutionContextDestroyed = waitForExecutionContextDestroyed;
TestRunner.assertGreaterOrEqual = assertGreaterOrEqual;
TestRunner.navigate = navigate;
TestRunner.navigatePromise = navigatePromise;
TestRunner.hardReloadPage = hardReloadPage;
TestRunner.reloadPage = reloadPage;
TestRunner.reloadPageWithInjectedScript = reloadPageWithInjectedScript;
TestRunner.reloadPagePromise = reloadPagePromise;
TestRunner.pageLoaded = pageLoaded;
TestRunner.waitForPageLoad = waitForPageLoad;
TestRunner.runWhenPageLoads = runWhenPageLoads;
TestRunner.runTestSuite = runTestSuite;
TestRunner.assertEquals = assertEquals;
TestRunner.assertTrue = assertTrue;
TestRunner.override = override;
TestRunner.clearSpecificInfoFromStackFrames = clearSpecificInfoFromStackFrames;
TestRunner.hideInspectorView = hideInspectorView;
TestRunner.mainFrame = mainFrame;
TestRunner.loadedModules = loadedModules;
TestRunner.dumpLoadedModules = dumpLoadedModules;
TestRunner.waitForUISourceCode = waitForUISourceCode;
TestRunner.waitForUISourceCodeRemoved = waitForUISourceCodeRemoved;
TestRunner.url = url;
TestRunner.dumpSyntaxHighlight = dumpSyntaxHighlight;
TestRunner.loadModule = loadModule;
TestRunner.evaluateInPageRemoteObject = evaluateInPageRemoteObject;
TestRunner.evaluateInPage = evaluateInPage;
TestRunner.evaluateInPageAnonymously = evaluateInPageAnonymously;
TestRunner.evaluateInPageAsync = evaluateInPageAsync;
TestRunner.deprecatedInitAsync = deprecatedInitAsync;
TestRunner.runAsyncTestSuite = runAsyncTestSuite;
TestRunner.dumpInspectedPageElementText = dumpInspectedPageElementText;
TestRunner.waitForPendingLiveLocationUpdates = waitForPendingLiveLocationUpdates;
TestRunner.findLineEndingIndexes = findLineEndingIndexes;

/**
 * @typedef {!Object<string, string>}
 */
TestRunner.CustomFormatters;


text:
import template from './edit-bbi-assistance.html';
import bbiRecordsDialog from './bbi-records-dialog.html';
import bbiFirstRequestDialog from './first-request-dialog.html';
import app from '~/app';
import angular from 'angular';
import _ from 'lodash';
import '~/authentication';
import 'ngSmoothScroll';
import '~/services/editFormUtility';
import '~/services/mongo-storage';
import '~/services/storage';
import '~/services/workflows';
import '~/services/user-settings';
import '~/directives/bbi/controls/km-form-languages';
import '~/directives/bbi/controls/km-form-std-buttons';
import '~/directives/bbi/controls/km-control-group';
import '~/directives/bbi/select-contact';
import '~/directives/bbi/controls/km-select';
import '~/directives/bbi/controls/km-link';
import '~/directives/bbi/controls/km-date';
import '~/directives/bbi/controls/km-inputtext-ml';
import '~/directives/bbi/controls/km-inputtext-list';
import '~/directives/bbi/controls/mongo-form-std-buttons';
import '~/directives/bbi/controls/km-document-validation';
import '~/providers/locale';
import '../views/view-bbi-request';

	app.directive('editBbiAssistance', ['$http', "$rootScope", "Enumerable", "$filter", "$q", "guid", "$location", "Thesaurus", 'authentication', '$route', '$timeout', 'locale', 'mongoStorage', 'smoothScroll', 'IStorage', 'ngDialog', 'userSettings', function($http, $rootScope, Enumerable, $filter, $q, guid, $location, thesaurus, authentication, $route, $timeout, locale, mongoStorage, smoothScroll, storage, ngDialog, userSettings) {
		return {
			restrict: 'E',
			template: template,
			replace: true,
			transclude: false,
			scope: {
				user: '='
			},
			link: function($scope) {
				$scope.schema = 'bbi-requests';
				$scope.status = "";
				$scope.error = null;
				$scope.document = null;
				$scope.tab = 'org';
				$scope.review = {
					locale: "en"
				};
				$scope.loading = {};
				$scope.loading.contact = false;
				$scope.loading.org = false;
				// $scope.user=user;
				$scope.options = { //5FF88869-FD8C-438F-9F77-66AB1CFB3BD4

					organizationTypes: function() {
						return $http.get("/api/v2013/thesaurus/domains/Organization%20Types/terms", {
							cache: true
						}).then(function(o) {
							return $filter('orderBy')(o.data, 'name');
						});
					},
					aichiTargets: function() {
						return $http.get("/api/v2013/thesaurus/domains/AICHI-TARGETS/terms", {
							cache: true
						}).then(function(o) {
							return o.data;
						});
					},

					jurisdictions: function() {
						return $http.get("/api/v2013/thesaurus/domains/50AC1489-92B8-4D99-965A-AAE97A80F38E/terms", {
							cache: true
						}).then(function(o) {
							return o.data;
						});
					},
					languages: function() {
						return $http.get("/api/v2013/thesaurus/domains/52AFC0EE-7A02-4EFA-9277-8B6C327CE21F/terms", {
							cache: true
						}).then(function(o) {
							return $filter('orderBy')(o.data, 'name');
						});
					},
					countries: function() {
						return $http.get("/api/v2013/thesaurus/domains/countries/terms", {
							cache: true
						}).then(function(o) {
							return $filter('orderBy')(o.data, 'name');
						});
					},
					assistanceTypes: function() {
						return $http.get("/api/v2013/thesaurus/domains/441381DA-856A-4E89-8568-9EBE7145FA50/terms", {
							cache: true
						}).then(function(o) {
							var data = _.filter(o.data, function(term){
									return term.identifier !="2DB66EA6-F4D1-4103-8BA1-55626DD42290"
									&& !_.contains(term.broaderTerms, "2DB66EA6-F4D1-4103-8BA1-55626DD42290")
								});
							return thesaurus.buildTree(data);
						});
					},
					regions: function() {
						return $q.all([$http.get("/api/v2013/thesaurus/domains/countries/terms", {
								cache: true
							}),
							$http.get("/api/v2013/thesaurus/domains/regions/terms", {
								cache: true
							})
						]).then(function(o) {
							return $filter('orderBy')(_.union(o[0].data, o[1].data), 'name');
						});
					},
					cbdSubjects: function() {
						return $http.get("/api/v2013/thesaurus/domains/CBD-SUBJECTS/terms", {
							cache: true
						}).then(function(o) {

							var subjects = ['CBD-SUBJECT-BIOMES', 'CBD-SUBJECT-CROSS-CUTTING'];
							var items = [];

							_.forEach(subjects, function(subject) {
								var term = _.findWhere(o.data, {
									'identifier': subject
								});

								items.push(term);

								_(term.narrowerTerms).forEach(function(term) {
									items.push(_.findWhere(o.data, {
										'identifier': term
									}));
								}).value();

							});

							return items;
						});
					}
				};

				userSettings.ready.then(bbiRecords).then(function() {
					$timeout(firstRequest, 1000);
				});
				//============================================================
				//
				//
				//============================================================
				function bbiRecords() {

					if (typeof userSettings.setting('bbi.recordsNotice') === 'undefined' || !userSettings.setting('bbi.recordsNotice')) {
						$scope.bbiRecordsNotice = false;
						userSettings.setting('bbi.recordsNotice', false);
						return ngDialog.open({
							template: bbiRecordsDialog,
							className: 'ngdialog-theme-default',
							closeByDocument: false,
							plain: true,
							scope: $scope
						}).closePromise;
					}
				}

				//============================================================
				//
				//
				//============================================================
				function firstRequest() {
					if (typeof userSettings.setting('bbi.firstRequestNotice') === 'undefined' || !userSettings.setting('bbi.firstRequestNotice')) {
						$scope.bbiFirstRequest = false;
						userSettings.setting('bbi.firstRequestNotice', false);
						return ngDialog.open({
							template: bbiFirstRequestDialog,
							className: 'ngdialog-theme-default',
							closeByDocument: false,
							plain: true,
							scope: $scope
						}).closePromise;
					}
				}

				//============================================================
				//
				//
				//============================================================
				function settingsChange(key, value) {
					userSettings.setting(key, value);
				} //bbiRecordsNoticeChange
				$scope.settingsChange = settingsChange;

				//==================================
				//
				//==================================
				$scope.loadRecords = function(identifier) {

					if (identifier) { //lookup single record
						var deferred = $q.defer();

						storage.documents.get(identifier)
							.then(function(r) {
								deferred.resolve(r.data);
							}, function(e) {
								if (e.status == 404) {
									storage.drafts.get(identifier)
										.then(function(r) {
												deferred.resolve(r.data);
											},
											function(e) {
												deferred.reject(e);
											});
								} else {
									deferred.reject(e);
								}
							});
						return deferred.promise;
					}

				};

				var killContactWatch = $scope.$watch("document.contact", function() {

					if ($scope.document && $scope.document.contact) {
						$scope.loading.contact = true;
						$scope.loadRecords($scope.document.contact.identifier)
							.then(function(data) {
								$scope.loading.contact = false;

								if (data.contactOrganization && data.contactOrganization.identifier) {
									$scope.loading.org = true;
									$scope.loadRecords(data.contactOrganization.identifier)
										.then(function(d) {
											$scope.document.organization = {
												identifier: d.header.identifier
											};
											$scope.loading.org = false;
											killContactWatch();
										});
								} else killContactWatch();
							});
					}
				});

				//====================
				//
				//====================
				var killOrgWatch = $scope.$watch("document.organization", function() {

					if ($scope.document && $scope.document.organization)
						$scope.loadRecords($scope.document.organization.identifier)
						.then(function(data) {
							if (data.country)
								$scope.document.country = data.country;
							killOrgWatch();
						});
				});
				//==================================
				//
				//==================================
				$scope.init = function() {

					if ($scope.document)
						return;
					$scope.status = "loading";

					var id = $route.current.params.id;
					if (id === 'new') {
						$q.when(authentication.getUser()).then(function(u) {
							$scope.user = u;
						}).then(loadDraftOrNew);
					} else
						mongoStorage.loadDoc($scope.schema, id).then(loadDoc);
				};

				//==================================
				//
				//==================================
				$scope.maxTypes = function() {

					return 3;
				};

				//============================================================
				//
				//============================================================
				$scope.nextTab = function() {
					var next = 'review';

					if ($scope.tab == 'org') {
						next = 'general';
					}
					if ($scope.tab == 'general') {
						next = 'details';
					}
					if ($scope.tab == 'details') {
						next = 'linkages';
					}
					if ($scope.tab == 'linkages') {
						next = 'review';
						$scope.validate();
					}

					$scope.tab = next;
				};

				//============================================================
				//
				//============================================================
				$scope.prevTab = function() {
					var prev;

					if ($scope.tab == 'review') {
						prev = 'linkages';
					}
					if ($scope.tab == 'linkages') {
						prev = 'details';
					}
					if ($scope.tab == 'details') {
						prev = 'general';
					}
					if ($scope.tab == 'general') {
						prev = 'org';
					}

					$scope.tab = prev;
				};
				//=======================================================================
				//
				//=======================================================================
				function loadDraftOrNew() {

					var q = {
						'meta.createdBy': $scope.user.userID,
						'meta.status': 'draft',
					};
					var fields = {
						history: 0
					};

					var sort = {
						'meta.modifiedOn': -1
					};

					return mongoStorage.loadDocs('bbi-requests', q, 0, 100, sort, fields).then(
						function(res) {
							if (res.data.length > 0) {
								$scope.document = res.data[0];
								if ($scope.document.meta && !$scope.document.meta.languages) $scope.document.meta.languages = [locale];
								if ($scope.document && $scope.document.meta && !$scope.document.meta.baseUrl)
									$scope.document.meta.baseUrl = $location.host();
								if ($scope.document.meta.baseUrl === 'localhost')
									$scope.document.meta.baseUrl = 'bbi.staging.cbd.int';
								$scope.status = false;
							} else
								return $scope.saveDoc('draft').then(function(r) {

									$scope.document._id = r.data.id;
									$route.current.params.id == r.data.id;
									$scope.status = false;
								});
						});
				} //loadDraftOrNew

				//=======================================================================
				//
				//=======================================================================
				$scope.saveDoc = function(status) {

					if (!$scope.document)
						$scope.document = {};
					if (!$scope.document.meta)
						$scope.document.meta = {};
					if ($scope.document && $scope.document.meta && status)
						$scope.document.meta.status = status;
					if ($scope.document && $scope.document.meta && !$scope.document.meta.languages)
						$scope.document.meta.languages = [locale];
					if (!$scope.document.typesDetails)
						$scope.document.typesDetails = {};

					if ($scope.document && $scope.document.meta && !$scope.document.meta.baseUrl)
						$scope.document.meta.baseUrl = $location.host();
					if ($scope.document.meta.baseUrl === 'localhost')
						$scope.document.meta.baseUrl = 'bbi.staging.cbd.int';
					if (!$scope.document.id && !$scope.document._id)
						return mongoStorage.save($scope.schema, cleanDoc($scope.document)).catch($scope.onError).then(function(res) {

							$scope.$emit('showSuccess', 'Request for Assistance Created');
							return res;
						}).catch($scope.onError);
					else
						return mongoStorage.save($scope.schema, cleanDoc($scope.document), $scope._id).then(function() {
							var msg = 'intitled';
							if ($scope.document.title)
								msg = $scope.document.title[locale];

							$scope.$emit('showSuccess', 'Requests for Assistance ' + msg + ' Saved as ' + status);

							if ($scope.document.meta.status !== 'draft')
								$timeout(function() {
									$location.path('platform/submit/' + $scope.schema.slice(0, -1));
									$location.search('index-update', $scope.document._id);
									$location.search('index-view', status);
								}, 1500);
						}).catch($scope.onError);
				};
				//=======================================================================
				//
				//=======================================================================
				function loadDoc(doc) {

					$scope.document = doc;
					if ($scope.document.meta && !$scope.document.meta.languages) $scope.document.meta.languages = [locale];
					if ($scope.document && $scope.document.meta && !$scope.document.meta.baseUrl)
						$scope.document.meta.baseUrl = $location.host();
					if ($scope.document && $scope.document.meta && !$scope.document.meta.baseUrl)
						$scope.document.meta.baseUrl = $location.host();
					if ($scope.document.meta.baseUrl === 'localhost')
						$scope.document.meta.baseUrl = 'bbi.staging.cbd.int';
					if (!$scope.document.typesDetails) $scope.document.typesDetails = {};
					$scope.status = false;
				}

				//=======================================================================
				//
				//=======================================================================
				$scope.saveDraft = function() {

					// validateRequestedBy($scope.editForm);
					// validateGeneral($scope.editForm);
					// $scope.generateValidationReport();
					return $scope.saveDoc('draft');
				};

				//=======================================================================
				//
				//=======================================================================
				$scope.generateValidationReport = function() {
					$scope.editForm.$submitted = true;
					if ($scope.editForm.$error && $scope.editForm.$error.required && $scope.editForm.$error.required.length) {
						$scope.validationReport = [];
						$scope.validationReport.errors = [];
						for (var i = 0; i < $scope.editForm.$error.required.length; i++)
							if ($scope.editForm.$error.required[i].$name !== 'linkForm' && $scope.editForm.$error.required[i].$name)
								$scope.validationReport.errors.push({
									code: 'Error.Mandatory',
									property: $scope.editForm.$error.required[i].$name
								});

					}

					//	return $scope.saveDoc('draft');
				};
				$scope.validate = $scope.generateValidationReport;
				//=======================================================================
				//
				//=======================================================================
				function validateRequestedBy(formData) {
					formData.$submitted = true;

					if (formData.organization.$error.required && formData.$submitted) {
						changeTab('org');
						findScrollFocus('editForm.organization');
					}
					if (formData.contact.$error.required && formData.$submitted) {
						changeTab('org');
						findScrollFocus('editForm.contact');
					}
					if (formData.country.$error.required && formData.$submitted) {
						changeTab('org');
						findScrollFocus('editForm.country');
					}
				} //validateRequestedBy

				//=======================================================================
				//
				//=======================================================================
				function validateGeneral(formData) {
					formData.$submitted = true;

					if (formData.title.$error.required && formData.$submitted) {
						changeTab('org');
						findScrollFocus('editForm.title');
					}
					if (formData.contact.$error.required && formData.$submitted) {
						changeTab('org');
						findScrollFocus('editForm.contact');
					}
					if (formData.country.$error.required && formData.$submitted) {
						changeTab('org');
						findScrollFocus('editForm.country');
					}
				} //validateRequestedBy

				//=======================================================================
				//
				//=======================================================================
				function changeTab(tab) {
					$timeout(function() {
						$scope.tab = tab;
						$('#' + tab).tab('show');
					});
				}

				//=======================================================================
				//
				//=======================================================================
				function findScrollFocus(id) {

					var el = document.getElementById(id);

					if (!$scope.focused) {

						smoothScroll(el);
						if ($(el).is("input") || $(el).is("select"))
							el.focus();
						else {
							if ($(el).find('input').length === 0)
								$(el).find('textarea').focus();
							else
								$(el).find('input').focus();

						}
						$scope.focused = true;
					}
				}

				//=======================================================================
				//
				//=======================================================================
				$scope.saveRequest = function() {
					validateRequestedBy($scope.editForm);
					validateGeneral($scope.editForm);
					$scope.generateValidationReport();

					if ($scope.validationReport && !$scope.validationReport.errors.length)
						return $scope.saveDoc('workflow');
				};

				//=======================================================================
				//
				//=======================================================================
				$scope.saveCompleted = function() {
					validateRequestedBy($scope.editForm);
					validateGeneral($scope.editForm);
					$scope.generateValidationReport();

					if ($scope.validationReport && !$scope.validationReport.errors.length)
						return $scope.saveDoc('public');
				};

				//=======================================================================
				//
				//=======================================================================
				function cleanDoc(doc) {
					var cDoc = _.cloneDeep(doc);
					delete(cDoc.history);
					_.each(cDoc, function(property, name) {
						if (_.isEmpty(document[name])) delete(document[name]);
					});
					return cDoc;
				} //toggleListView

				//============================================================
				//
				//============================================================
				$scope.wordCount = function(s) {
					if (!s || !_.isString(s)) return;
					s = s.replace(/(^\s*)|(\s*$)/gi, ""); //exclude  start and end white-space
					s = s.replace(/[ ]{2,}/gi, " "); //2 or more space to 1
					s = s.replace(/\n /, "\n"); // exclude newline with a start spacing
					return s.split(' ').length;
				};

				//============================================================
				//
				//============================================================
				$scope.updateWebsites = function(name, value) {
					if (!$scope.document.websites) $scope.document.websites = [];
					var site = _.find($scope.document.websites, {
						'name': name
					});
					if (site)
						if (value)
							site.value = value;
						else
							delete($scope.document.websites[_.findIndex($scope.document.websites, {
								'name': name
							})]);

					else
						$scope.document.websites.push({
							name: name,
							url: value,
							type: 'link'
						});
					$scope.document.websites = _.compact($scope.document.websites);
				};

				//==================================
				//
				//==================================
				$scope.isLoading = function() {

					return $scope.status === "loading";
				};

				//==================================
				//
				//==================================
				$scope.hasError = function() {
					return !!$scope.error;
				};

				//==================================
				//
				//==================================
				$scope.isFieldValid = function(field) {
					if (field && $scope.validationReport && $scope.validationReport.errors)
						return !Enumerable.From($scope.validationReport.errors).Any(function(x) {
							return x.property == field;
						});

					return true;
				};

				//==================================
				//
				//==================================
				$scope.onError = function(error, status) {
					$scope.status = "error";

					if (status == "notAuthorized") {
						$scope.status = "hidden";
						$scope.error = "You are not authorized to modify this record";
					} else if (status == 404) {
						$scope.status = "hidden";
						$scope.error = "Record not found.";
					} else if (status == "badSchema") {
						$scope.status = "hidden";
						$scope.error = "Record type is invalid.";
					} else if (error.Message)
						$scope.error = error.Message;
					else
						$scope.error = error;
				};

				$scope.init();
			}
		};
	}]);

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * @package    apostrophePlugin
 * @subpackage    action
 * @author     P'unk Avenue <apostrophe@punkave.com>
 */
class BaseaMediaComponents extends sfComponents
{

  /**
   * DOCUMENT ME
   * @param mixed $request
   */
  public function executeBrowser($request)
  {
    // We don't use a single integrated form for this anymore. What we wanted was
    // individual-link behavior, and yet we overlaid a form on that,
    // which had some interesting aspects but was ultimately confusing
    // and a problem for search engine indexing etc

    // ... But we do now use a simple form for the search form

    $this->current = "aMedia/index";
    $params = array();
    $type = aMediaTools::getSearchParameter('type');
    if (strlen($type))
    {
      $this->type = $type;
      $params['type'] = $type;
    }
    $tag = aMediaTools::getSearchParameter('tag');
    if (strlen($tag))
    {
      $this->selectedTag = $tag;
      $params['tag'] = $tag;
    }
    $categorySlug = aMediaTools::getSearchParameter('category');
    if (strlen($categorySlug))
    {
      $this->selectedCategory = Doctrine::getTable('aCategory')->findOneBySlug($categorySlug);
      $params['category'] = $categorySlug;
    }
    $search = aMediaTools::getSearchParameter('search');
    if (strlen($search))
    {
      $this->search = $search;
      $params['search'] = $search;
    }
    $this->searchForm = new aMediaSearchForm();
    $this->searchForm->bind(array('search' => $request->getParameter('search')));
    $this->current .= "?" . http_build_query($params);
    $this->allTags = aMediaItemTable::getAllTagNameForUserWithCount();
    $tagsByPopularity = $this->allTags;
    arsort($tagsByPopularity);
    $this->popularTags = array();
    $n = 0;
    $max = aMediaTools::getOption('popular_tags');
    foreach ($tagsByPopularity as $tag => $count)
    {
      if ($n == $max)
      {
        break;
      }
      $this->popularTags[$tag] = $count;
      $n++;
    }
  }

  /**
   * DOCUMENT ME
   * @param mixed $request
   */
  public function executeBreadcrumb($request)
  {
    $this->type = aMediaTools::getSearchParameter('type');
    $this->tag = aMediaTools::getSearchParameter('tag');
    $this->search = aMediaTools::getSearchParameter('search');
    $this->categorySlug = aMediaTools::getSearchParameter('category');
    $this->crumbs = array();
    // I tried calling I18N here but that requires enabling
    // I18N for every project which the I18N helper does not...
    // I'm not internationalizing this site, so I give up.
    // If you're reading this, tell me how to localize these labels
    // without punishing noninternationalized sites. I really don't
    // want to push this much logic into a template. tom@punkave.com
    $this->crumbs[] = array(
      "label" => "Home",
      "link" => "@homepage",
      "first" => true);
    $this->crumbs[] = array(
      "label" => "Media",
      "link" => "aMedia/index");
    if ($this->type)
    {
      $this->crumbs[] = array(
        "label" => $this->type,
        "link" => aUrl::addParams("aMedia/index", array("type" => $this->type)));
    }
    if ($this->categorySlug)
    {
      $this->crumbs[] = array(
        "label" => $this->category,
        "link" => aUrl::addParams("aMedia/index", array('type' => $this->type, "category" => $this->categorySlug)));
    }
    if ($this->tag)
    {
      $this->crumbs[] = array(
        "label" => htmlspecialchars($this->tag),
        "link" => aUrl::addParams("aMedia/index", array("type" => $this->type, 'category' => $this->categorySlug, "tag" => $this->tag)));
    }
    if ($this->search)
    {
      $this->crumbs[] = array(
        "label" => htmlspecialchars($this->search),
        "link" => aUrl::addParams("aMedia/index", array("type" => $this->type, 'category' => $this->categorySlug, "tag" => $this->tag, "search" => $this->search)));
    }
    if (isset($this->item))
    {
      $this->crumbs[] = array(
        "label" => $this->item->getTitle(),
        "link" => aUrl::addParams("aMedia/show", array("slug" => $this->item->getSlug())));
    }
    $this->crumbs[count($this->crumbs) - 1]['last'] = true;
  }

  /**
   * DOCUMENT ME
   * @param mixed $request
   */
  public function executeSelectMultiple($request)
  {
    $this->items = aMediaTools::getSelectedItems();
  }

  /**
   * DOCUMENT ME
   * @param mixed $request
   */
  public function executeSelectSingle($request)
  {
    $this->items = aMediaTools::getSelectedItems();
  }

  /**
   * DOCUMENT ME
   * @param mixed $request
   */
  public function executeMultipleList($request)
  {
    $this->items = aMediaTools::getSelectedItems();
  }

  /**
   * DOCUMENT ME
   */
  public function executeMultiplePreview()
  {
    $this->items = aMediaTools::getSelectedItems();
  }
}


text:
/*! @file
    @brief Ring buffer implementation, operating on the internal RAM dataspace objects.

    A simple MCRingBuffer implementation which operates on the internal RAM dataspaces. This
    is designed for communication with the clients who share to us our own dataspace. Since reading
    from a page entry is computationally expensive as it requires mapping the frame, copying the
    data out and then unmapping the frame, the MCRingBuffer algorithm is used here to minimise the
    frequency of read / writes to the shared control variables.

    Reference:

    > P.P.C. Lee, T. Bu,  and G.P. Chandranmenon,  A lock-free, cache-efficient shared ring buffer
    > for multi-core architectures.  ;In Proceedings of ANCS. 2009, 78-79.

    > http://www.cse.cuhk.edu.hk/~pclee/www/pubs/ancs09poster.pdf
*/

#ifndef _REFOS_PROCESS_SERVER_SYSTEM_MEMSERV_RING_BUFFER_H_
#define _REFOS_PROCESS_SERVER_SYSTEM_MEMSERV_RING_BUFFER_H_

#include "../../common.h"
#include "dataspace.h"

#define RINGBUFFER_MAGIC 0x660149F7
#define RINGBUFFER_METADATA_SIZE (sizeof(uint32_t) * 2)

/*! @brief Ring buffer modes - read only or write only. */
enum rb_mode {
    RB_READONLY,
    RB_WRITEONLY
};

/*! @brief Ring buffer structure.

    A structure containing information regarding to a single ring buffer. Does NOT take ownership of
    the associated dataspace; merely provides a wrapping to use ringbuffers on top of a struct
    ram_dataspace. Ringbuffers are uni-directional; either read-only or write-only, as described in
    rb_modes_t.

    The structure also shares ownership of the underlying dataspace object, using a shared
    reference. This ensures that the ram_dspace structure pointed here is always valid, but also
    means this rb_buffer must be deleted for the linked ram_dspace to be truly deleted, as this
    object "hangs onto" its dataspace.
 */
struct rb_buffer {
    enum rb_mode mode;
    uint32_t magic;

    uint32_t localStart;
    uint32_t localEnd;
    uint32_t size;

    struct ram_dspace *dataspace; /* Shared ownership. */
};

/*! @brief Creates a ring buffer structure operating on the given dataspace.

    Creates a ring buffer structure operating on the given dataspace. This assumes a shared
    ownership of the given dataspace, and keeps a strong reference to it.

    @param dataspace The dataspace to wrap a ring buffer interface on. (Shared ownership)
    @param mode Either RB_READONLY or RB_WRITEONLY.
    @return An empty ring buffer on success (Passes ownership), NULL otherwise.
 */
struct rb_buffer *rb_create(struct ram_dspace *dataspace, enum rb_mode mode);

/*! @brief Deletes given ring buffer structure.
    @param rb The ring buffer to delete. (Takes ownership)
 */
void rb_delete(struct rb_buffer *rb);

/*! @brief Writes data to ring buffer. (See code comments for more info).
    @param buf Destination ring buffer to write to. (No ownership)
    @param str Source buffer to read from in bytes. (No ownership)
    @param len Size of source buffer containing data.
    @return ESUCCESS if success, ENOMEM if ring buffer is full, refos_error otherwise.
 */
int rb_write(struct rb_buffer *buf, char *str, size_t len);

/*! @brief Reads data from ring buffer. (See code comments for more info).
    @param buf Source ring buffer to read from. (No ownership)
    @param dest Destination buffer to read to. (No ownership)
    @param len Maximum length of data to read in bytes.
    @param bytesRead How many bytes were read into the destination buffer. (No ownership)
    @return ESUCCESS if success, refos_error otherwise.
 */
int rb_read(struct rb_buffer *buf, char *dest, size_t len, size_t *bytesRead);

#endif /* _REFOS_PROCESS_SERVER_SYSTEM_MEMSERV_RING_BUFFER_H_ */


text:
package smoketest;

import com.haulmont.yarg.formatters.ReportFormatter;
import com.haulmont.yarg.formatters.factory.DefaultFormatterFactory;
import com.haulmont.yarg.formatters.factory.FormatterFactoryInput;
import com.haulmont.yarg.structure.BandData;
import com.haulmont.yarg.structure.BandOrientation;
import com.haulmont.yarg.structure.ReportOutputType;
import com.haulmont.yarg.structure.impl.ReportFieldFormatImpl;
import com.haulmont.yarg.structure.impl.ReportTemplateImpl;
import org.apache.commons.io.IOUtils;
import org.junit.Test;

import java.io.FileOutputStream;
import java.util.HashMap;

/**
 * @author degtyarjov
 * @version $Id$
 */
public class DocxSpecificTest extends AbstractFormatSpecificTest {
    @Test
    public void testDocxTableWithSplittedBandAlias() throws Exception {
        BandData root = new BandData("Root", null, BandOrientation.HORIZONTAL);
        HashMap<String, Object> rootData = new HashMap<>();
        root.setData(rootData);
        BandData ride = new BandData("ride", root, BandOrientation.HORIZONTAL);
        ride.setData(new RandomMap());
        root.addChild(ride);

        FileOutputStream outputStream = new FileOutputStream("./result/smoke/splitted-aliases-in-table.docx");
        ReportFormatter formatter = new DefaultFormatterFactory().createFormatter(new FormatterFactoryInput("docx", root,
                new ReportTemplateImpl("", "./modules/core/test/smoketest/splitted-aliases-in-table.docx", "./modules/core/test/smoketest/splitted-aliases-in-table.docx", ReportOutputType.docx), outputStream));
        formatter.renderDocument();

        IOUtils.closeQuietly(outputStream);
    }

    @Test
    public void testDocxWithSplittedAlias() throws Exception {
        BandData root = new BandData("Root", null, BandOrientation.HORIZONTAL);
        HashMap<String, Object> rootData = new HashMap<>();
        rootData.put("param1", "AAAAAA");
        root.setData(rootData);
        BandData cover = new BandData("Cover", root, BandOrientation.HORIZONTAL);
        cover.setData(new HashMap<String, Object>());
        cover.addData("index", "123");
        cover.addData("volume", "321");
        cover.addData("name", "AAA");
        BandData documents = new BandData("Documents", root, BandOrientation.HORIZONTAL);
        documents.setData(new HashMap<String, Object>());
        root.addChild(cover);
        root.addChild(documents);

        FileOutputStream outputStream = new FileOutputStream("./result/smoke/splitted-aliases.docx");
        ReportFormatter formatter = new DefaultFormatterFactory().createFormatter(new FormatterFactoryInput("docx", root,
                new ReportTemplateImpl("", "./modules/core/test/smoketest/splitted-aliases.docx", "./modules/core/test/smoketest/splitted-aliases.docx", ReportOutputType.docx), outputStream));
        formatter.renderDocument();

        IOUtils.closeQuietly(outputStream);
    }

    @Test
    public void testDocxWithColontitulesAndHtmlPageBreak() throws Exception {
        BandData root = new BandData("Root", null, BandOrientation.HORIZONTAL);
        HashMap<String, Object> rootData = new HashMap<>();
        rootData.put("param1", "AAAAAA");
        root.setData(rootData);
        BandData letterTable = new BandData("letterTable", root, BandOrientation.HORIZONTAL);
        BandData creatorInfo = new BandData("creatorInfo", root, BandOrientation.HORIZONTAL);
        HashMap<String, Object> letterTableData = new HashMap<>();
        String html = "";
        html += "
";
        for (int i = 0; i < 5; i++) {
            html += "
123456712345671234567123456712345671234567123456712345" +
                    "67123456712345671234567123456712345671234567123456712345671234" +
                    "5671234567123456712345671234567123456712345671234567
";
        }
        html += "
";
        html += "
";
        html += "
Second table
";
        html += "
";
        for (int i = 0; i < 5; i++) {
            html += "
1234567
";
        }
        html += "
";

        html += "";
        letterTableData.put("html", html);
        letterTable.setData(letterTableData);
        HashMap<String, Object> creatorInfoData = new HashMap<>();
        creatorInfoData.put("name", "12345");
        creatorInfoData.put("phone", "54321");
        creatorInfo.setData(creatorInfoData);
        root.addChild(letterTable);
        root.addChild(creatorInfo);
        root.getReportFieldFormats().put("letterTable.html", new ReportFieldFormatImpl("letterTable.html", "${html}"));

        FileOutputStream outputStream = new FileOutputStream("./result/smoke/colontitules.docx");
        DefaultFormatterFactory defaultFormatterFactory = new DefaultFormatterFactory();
        ReportFormatter formatter = defaultFormatterFactory.createFormatter(new FormatterFactoryInput("docx", root,
                new ReportTemplateImpl("", "./modules/core/test/smoketest/colontitules.docx", "./modules/core/test/smoketest/colontitules.docx", ReportOutputType.docx), outputStream));
        formatter.renderDocument();

        IOUtils.closeQuietly(outputStream);
    }
}


text:
RSpec.describe Hanami::Action::Rack do
  let(:action) { MethodInspectionAction.new }

  %w(GET POST PATCH PUT DELETE TRACE OPTIONS).each do |verb|
    it "returns current request method (#{verb})" do
      env = Rack::MockRequest.env_for('/', method: verb)
      _, _, body = action.call(env)

      expect(body).to eq([verb])
    end
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>H-Index</title>
<meta name="date" content="2016-01-21">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I J L M N P R S T U V W

H

handle(Message<JsonObject>) - Method in class de.orolle.bigsense.server.ssh.SSHVerticle

Receives messages from eventbus.

handle(String) - Method in class de.orolle.bigsense.server.update.BigSenseUpdater.Command

handle(String) - Method in class de.orolle.bigsense.server.update.BigSenseUpdater.Put

handler(String, Handler<E>) - Method in class de.orolle.bigsense.server.util.Parallel

Generates a named result handler for a single execution.

handler() - Method in class de.orolle.bigsense.server.util.Parallel

Generates a named result handler for a single execution.

handler(String) - Method in class de.orolle.bigsense.server.util.Parallel

Generates a named result handler for a single execution.

HTTP_EXTERNAL_PORT - Static variable in class de.orolle.bigsense.server.Config

The Constant HTTP_EXTERNAL_PORT.

HTTP_INTERNAL_PORT - Static variable in class de.orolle.bigsense.server.Config

The Constant HTTP_INTERNAL_PORT.

A B C D E F G H I J L M N P R S T U V W

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
<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>com.azure</groupId>
  <artifactId>azure-sdk-bom</artifactId>
  <version>1.0.2-beta.1</version>
  <packaging>pom</packaging>
  <name>Azure Java SDK BOM (Bill of Materials)</name>
  <description>Azure Java SDK BOM (Bill of Materials)</description>
  <url>https://github.com/azure/azure-sdk-for-java</url>

  <licenses>
    <license>
      <name>The MIT License (MIT)</name>
      <url>http://opensource.org/licenses/MIT</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <developers>
    <developer>
      <id>microsoft</id>
      <name>Microsoft Corporation</name>
    </developer>
  </developers>

  <scm>
    <connection>scm:git:git://github.com/azure/azure-sdk-for-java</connection>
    <developerConnection>scm:git:git://github.com/azure/azure-sdk-for-java</developerConnection>
    <url>https://github.com/azure/azure-sdk-for-java</url>
  </scm>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <packageOutputDirectory>${project.build.directory}</packageOutputDirectory>
  </properties>

  <issueManagement>
    <system>GitHub</system>
    <url>https://github.com/azure/azure-sdk-for-java/issues</url>
  </issueManagement>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-core</artifactId>
        <version>1.5.1</version>
      </dependency>

      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-core-amqp</artifactId>
        <version>1.2.0</version>
      </dependency>
      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-core-http-netty</artifactId>
        <version>1.5.2</version>
      </dependency>
      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-core-http-okhttp</artifactId>
        <version>1.2.3</version>
      </dependency>

      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-data-appconfiguration</artifactId>
        <version>1.1.2</version>
      </dependency>

      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-cosmos</artifactId>
        <version>4.0.1</version>
      </dependency>

      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-messaging-eventhubs</artifactId>
        <version>5.1.1</version>
      </dependency>
      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-messaging-eventhubs-checkpointstore-blob</artifactId>
        <version>1.1.1</version>
      </dependency>

      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-ai-formrecognizer</artifactId>
        <version>1.0.0-beta.3</version>
      </dependency>

      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-identity</artifactId>
        <version>1.0.7</version>
      </dependency>

      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-security-keyvault-certificates</artifactId>
        <version>4.0.4</version>
      </dependency>
      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-security-keyvault-keys</artifactId>
        <version>4.1.4</version>
      </dependency>
      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-security-keyvault-secrets</artifactId>
        <version>4.1.4</version>
      </dependency>

      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-search-documents</artifactId>
        <version>1.0.0-beta.4</version>
      </dependency>

      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-messaging-servicebus</artifactId>
        <version>7.0.0-beta.3</version>
      </dependency>

      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-storage-blob</artifactId>
        <version>12.7.0</version>
      </dependency>
      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-storage-blob-batch</artifactId>
        <version>12.5.2</version>
      </dependency>
      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-storage-blob-cryptography</artifactId>
        <version>12.7.0</version>
      </dependency>
      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-storage-common</artifactId>
        <version>12.7.0</version>
      </dependency>
      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-storage-file-datalake</artifactId>
        <version>12.1.2</version>
      </dependency>
      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-storage-file-share</artifactId>
        <version>12.5.0</version>
      </dependency>
      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-storage-queue</artifactId>
        <version>12.5.2</version>
      </dependency>

      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-ai-textanalytics</artifactId>
        <version>1.0.0</version>
      </dependency>

      <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-core-tracing-opentelemetry</artifactId>
        <version>1.0.0-beta.5</version>
      </dependency>

      <!-- Dependencies used by the Azure SDKs -->
      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.10.1</version>
      </dependency>

      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.10.1</version>
      </dependency>

      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.10.1</version>
      </dependency>

      <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
        <version>2.10.1</version>
      </dependency>

      <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jsr310</artifactId>
        <version>2.10.1</version>
      </dependency>

      <dependency>
        <groupId>com.fasterxml.jackson.module</groupId>
        <artifactId>jackson-module-afterburner</artifactId>
        <version>2.10.1</version>
      </dependency>

      <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.5</version>
      </dependency>

      <dependency>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>msal4j</artifactId>
        <version>0.5.0-preview</version>
      </dependency>

      <dependency>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>qpid-proton-j-extensions</artifactId>
        <version>1.2.3</version>
      </dependency>

      <dependency>
        <groupId>com.nimbusds</groupId>
        <artifactId>oauth2-oidc-sdk</artifactId>
        <version>6.14</version>
      </dependency>

      <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.2.2</version>
      </dependency>

      <dependency>
        <groupId>io.dropwizard.metrics</groupId>
        <artifactId>metrics-core</artifactId>
        <version>4.1.0</version>
      </dependency>

      <dependency>
        <groupId>io.micrometer</groupId>
        <artifactId>micrometer-core</artifactId>
        <version>1.2.0</version>
      </dependency>

      <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-buffer</artifactId>
        <version>4.1.49.Final</version>
      </dependency>

      <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-codec-http2</artifactId>
        <version>4.1.49.Final</version>
      </dependency>

      <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-codec-http</artifactId>
        <version>4.1.49.Final</version>
      </dependency>

      <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-handler-proxy</artifactId>
        <version>4.1.49.Final</version>
      </dependency>

      <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-handler</artifactId>
        <version>4.1.49.Final</version>
      </dependency>

      <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-tcnative-boringssl-static</artifactId>
        <version>2.0.29.Final</version>
      </dependency>

      <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-transport-native-epoll</artifactId>
        <version>4.1.49.Final</version>
      </dependency>

      <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-transport-native-unix-common</artifactId>
        <version>4.1.49.Final</version>
      </dependency>

      <dependency>
        <groupId>io.opentelemetry</groupId>
        <artifactId>opentelemetry-api</artifactId>
        <version>0.2.4</version>
      </dependency>

      <dependency>
        <groupId>io.projectreactor.netty</groupId>
        <artifactId>reactor-netty</artifactId>
        <version>0.9.7.RELEASE</version>
      </dependency>

      <dependency>
        <groupId>io.projectreactor</groupId>
        <artifactId>reactor-core</artifactId>
        <version>3.3.5.RELEASE</version>
      </dependency>

      <dependency>
        <groupId>net.java.dev.jna</groupId>
        <artifactId>jna-platform</artifactId>
        <version>5.4.0</version>
      </dependency>

      <dependency>
        <groupId>org.apache.qpid</groupId>
        <artifactId>proton-j</artifactId>
        <version>0.33.4</version>
      </dependency>

      <dependency>
        <groupId>org.linguafranca.pwdb</groupId>
        <artifactId>KeePassJava2</artifactId>
        <version>2.1.4</version>
        <exclusions>

        </exclusions>
      </dependency>

      <dependency>
        <groupId>org.nanohttpd</groupId>
        <artifactId>nanohttpd</artifactId>
        <version>2.3.1</version>
      </dependency>

      <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.28</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <profiles>
    <profile>
      <id>dependency-checker</id>
      <activation>
        <property>
          <name>dependency-checker</name>
        </property>
      </activation>
      <build>
        <plugins>
          <!-- This plugin validates that the artifacts in this BOM use a common dependency set. -->
          <plugin>
            <groupId>net.jonathangiles.tools</groupId>
            <artifactId>dependencyChecker-maven-plugin</artifactId>
            <version>1.0.4</version> <!-- {x-version-update;net.jonathangiles.tools:dependencyChecker-maven-plugin;external_dependency} -->
            <executions>
              <execution>
                <phase>package</phase>
                <goals>
                  <goal>check</goal>
                </goals>
                <configuration>
                  <reporters>html</reporters>
                  <showAll>true</showAll>
                  <analyseBom>true</analyseBom>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

  <build>
    <plugins>
      <!-- Copy the pom file to output -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-antrun-plugin</artifactId>
        <version>1.8
        </version> <!-- {x-version-update;org.apache.maven.plugins:maven-antrun-plugin;external_dependency} -->
        <executions>
          <execution>
            <id>copy</id>
            <phase>package</phase>
            <configuration>
              <target>
                <copy file="${project.pomFile}" tofile="${packageOutputDirectory}/${project.build.finalName}.pom"/>
              </target>
            </configuration>
            <goals>
              <goal>run</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
package com.kevinjennison.boop;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;

import com.facebook.react.LifecycleState;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.magus.fblogin.FacebookLoginPackage;

public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {

    private ReactInstanceManager mReactInstanceManager;
    private ReactRootView mReactRootView;

    private FacebookLoginPackage mFacebookLoginPackage;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mReactRootView = new ReactRootView(this);

        mFacebookLoginPackage = new FacebookLoginPackage(this);

        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setBundleAssetName("index.android.bundle")
                .setJSMainModuleName("index.android")
                .addPackage(new MainReactPackage())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .addPackage(mFacebookLoginPackage)
                .build();

        mReactRootView.startReactApplication(mReactInstanceManager, "boop", null);

        setContentView(mReactRootView);
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
            mReactInstanceManager.showDevOptionsDialog();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (mReactInstanceManager != null) {
            mReactInstanceManager.onBackPressed();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void invokeDefaultOnBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mReactInstanceManager != null) {
            mReactInstanceManager.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mReactInstanceManager != null) {
            mReactInstanceManager.onResume(this, this);
        }
    }

    @Override
    public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        mFacebookLoginPackage.handleActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.kevinjennison.boop/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.kevinjennison.boop/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.atanarro.contentprovidersample" android:versionCode="1"
	android:versionName="1.0">
	<uses-sdk android:minSdkVersion="8" />

	<application android:icon="@drawable/icon" android:label="@string/app_name">
		<activity android:name=".ContentProviderSampleActivity"
			android:label="@string/app_name">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
		<provider android:name="SongsProvider" android:authorities="net.atanarro.provider.Songs" />
	</application>
</manifest>