<commit_before>define("backburner",
  ["backburner/deferred_action_queues","exports"],
  function(__dependency1__, __exports__) {
    "use strict";
    var DeferredActionQueues = __dependency1__.DeferredActionQueues;

    var slice = [].slice,
        pop = [].pop,
        debouncees = [],
        timers = [],
        autorun, laterTimer, laterTimerExpiresAt;

    function Backburner(queueNames, options) {
      this.queueNames = queueNames;
      this.options = options || {};
      if (!this.options.defaultQueue) {
        this.options.defaultQueue = queueNames[0];
      }
      this.instanceStack = [];
    }

    Backburner.prototype = {
      queueNames: null,
      options: null,
      currentInstance: null,
      instanceStack: null,

      begin: function() {
        if (this.currentInstance) {
          this.instanceStack.push(this.currentInstance);
        }

        this.currentInstance = new DeferredActionQueues(this.queueNames, this.options);
      },

      end: function() {
        try {
          this.currentInstance.flush();
        } finally {
          this.currentInstance = null;

          if (this.instanceStack.length) {
            this.currentInstance = this.instanceStack.pop();
          }
        }
      },

      run: function(target, method /*, args */) {
        var ret;
        this.begin();

        if (!method) {
          method = target;
          target = null;
        }

        if (typeof method === 'string') {
          method = target[method];
        }

        // Prevent Safari double-finally.
        var finallyAlreadyCalled = false;
        try {
          if (arguments.length > 2) {
            ret = method.apply(target, slice.call(arguments, 2));
          } else {
            ret = method.call(target);
          }
        } finally {
          if (!finallyAlreadyCalled) {
            finallyAlreadyCalled = true;
            this.end();
          }
        }
        return ret;
      },

      defer: function(queueName, target, method /* , args */) {
        if (!method) {
          method = target;
          target = null;
        }

        if (typeof method === 'string') {
          method = target[method];
        }

        var stack = new Error().stack,
            args = arguments.length > 3 ? slice.call(arguments, 3) : undefined;
        if (!this.currentInstance) { createAutorun(this); }
        return this.currentInstance.schedule(queueName, target, method, args, false, stack);
      },

      deferOnce: function(queueName, target, method /* , args */) {
        if (!method) {
          method = target;
          target = null;
        }

        if (typeof method === 'string') {
          method = target[method];
        }

        var stack = new Error().stack,
            args = arguments.length > 3 ? slice.call(arguments, 3) : undefined;
        if (!this.currentInstance) { createAutorun(this); }
        return this.currentInstance.schedule(queueName, target, method, args, true, stack);
      },

      setTimeout: function() {
        var self = this,
            wait = pop.call(arguments),
            target = arguments[0],
            method = arguments[1],
            executeAt = (+new Date()) + wait;

        if (!method) {
          method = target;
          target = null;
        }

        if (typeof method === 'string') {
          method = target[method];
        }

        var fn, args;
        if (arguments.length > 2) {
          args = slice.call(arguments, 2);

          fn = function() {
            method.apply(target, args);
          };
        } else {
          fn = function() {
            method.call(target);
          };
        }

        // find position to insert - TODO: binary search
        var i, l;
        for (i = 0, l = timers.length; i < l; i += 2) {
          if (executeAt < timers[i]) { break; }
        }

        timers.splice(i, 0, executeAt, fn);

        if (laterTimer && laterTimerExpiresAt < executeAt) { return fn; }

        if (laterTimer) {
          clearTimeout(laterTimer);
          laterTimer = null;
        }
        laterTimer = setTimeout(function() {
          executeTimers(self);
          laterTimer = null;
          laterTimerExpiresAt = null;
        }, wait);
        laterTimerExpiresAt = executeAt;

        return fn;
      },

      debounce: function(target, method /* , args, wait */) {
        var self = this,
            args = arguments,
            wait = pop.call(args),
            debouncee;

        for (var i = 0, l = debouncees.length; i < l; i++) {
          debouncee = debouncees[i];
          if (debouncee[0] === target && debouncee[1] === method) { return; } // do nothing
        }

        var timer = setTimeout(function() {
          self.run.apply(self, args);

          // remove debouncee
          var index = -1;
          for (var i = 0, l = debouncees.length; i < l; i++) {
            debouncee = debouncees[i];
            if (debouncee[0] === target && debouncee[1] === method) {
              index = i;
              break;
            }
          }

          if (index > -1) { debouncees.splice(index, 1); }
        }, wait);

        debouncees.push([target, method, timer]);
      },

      cancelTimers: function() {
        for (var i = 0, l = debouncees.length; i < l; i++) {
          clearTimeout(debouncees[i][2]);
        }
        debouncees = [];

        if (laterTimer) {
          clearTimeout(laterTimer);
          laterTimer = null;
        }
        timers = [];

        if (autorun) {
          clearTimeout(autorun);
          autorun = null;
        }
      },

      hasTimers: function() {
        return !!timers.length || autorun;
      },

      cancel: function(timer) {
        if (typeof timer === 'object' && timer.queue && timer.method) { // we're cancelling a deferOnce
          return timer.queue.cancel(timer);
        } else if (typeof timer === 'function') { // we're cancelling a setTimeout
          for (var i = 0, l = timers.length; i < l; i += 2) {
            if (timers[i + 1] === timer) {
              timers.splice(i, 2); // remove the two elements
              return true;
            }
          }
        }
      }
    };

    Backburner.prototype.schedule = Backburner.prototype.defer;
    Backburner.prototype.scheduleOnce = Backburner.prototype.deferOnce;
    Backburner.prototype.later = Backburner.prototype.setTimeout;

    function createAutorun(backburner) {
      backburner.begin();
      autorun = setTimeout(function() {
        backburner.end();
      });
    }

    function executeTimers(self) {
      var now = +new Date(),
          time, fns, i, l;

      self.run(function() {
        // TODO: binary search
        for (i = 0, l = timers.length; i < l; i += 2) {
          time = timers[i];
          if (time > now) { break; }
        }

        fns = timers.splice(0, i);

        for (i = 1, l = fns.length; i < l; i += 2) {
          self.schedule(self.options.defaultQueue, null, fns[i]);
        }
      });

      if (timers.length) {
        laterTimer = setTimeout(function() {
          executeTimers(self);
          laterTimer = null;
          laterTimerExpiresAt = null;
        }, timers[0] - now);
        laterTimerExpiresAt = timers[0];
      }
    }

    __exports__.Backburner = Backburner;
  });

define("backburner/deferred_action_queues",
  ["backburner/queue","exports"],
  function(__dependency1__, __exports__) {
    "use strict";
    var Queue = __dependency1__.Queue;

    function DeferredActionQueues(queueNames, options) {
      var queues = this.queues = {};
      this.queueNames = queueNames = queueNames || [];

      var queueName;
      for (var i = 0, l = queueNames.length; i < l; i++) {
        queueName = queueNames[i];
        queues[queueName] = new Queue(this, queueName, options[queueName]);
      }
    }

    DeferredActionQueues.prototype = {
      queueNames: null,
      queues: null,

      schedule: function(queueName, target, method, args, onceFlag, stack) {
        var queues = this.queues,
            queue = queues[queueName];

        if (!queue) { throw new Error("You attempted to schedule an action in a queue (" + queueName + ") that doesn't exist"); }

        if (onceFlag) {
          return queue.pushUnique(target, method, args, stack);
        } else {
          return queue.push(target, method, args, stack);
        }
      },

      flush: function() {
        var queues = this.queues,
            queueNames = this.queueNames,
            queueName, queue, queueItems, priorQueueNameIndex,
            queueNameIndex = 0, numberOfQueues = queueNames.length;

        outerloop:
        while (queueNameIndex < numberOfQueues) {
          queueName = queueNames[queueNameIndex];
          queue = queues[queueName];
          queueItems = queue._queue.slice();
          queue._queue = [];

          var options = queue.options,
              before = options && options.before,
              after = options && options.after,
              target, method, args,
              queueIndex = 0, numberOfQueueItems = queueItems.length;

          if (numberOfQueueItems && before) { before(); }
          while (queueIndex < numberOfQueueItems) {
            target = queueItems[queueIndex];
            method = queueItems[queueIndex+1];
            args   = queueItems[queueIndex+2];

            if (typeof method === 'string') { method = target[method]; }

            // TODO: error handling
            if (args && args.length > 0) {
              method.apply(target, args);
            } else {
              method.call(target);
            }

            queueIndex += 4;
          }
          if (numberOfQueueItems && after) { after(); }

          if ((priorQueueNameIndex = indexOfPriorQueueWithActions(this, queueNameIndex)) !== -1) {
            queueNameIndex = priorQueueNameIndex;
            continue outerloop;
          }

          queueNameIndex++;
        }
      }
    };

    function indexOfPriorQueueWithActions(daq, currentQueueIndex) {
      var queueName, queue;

      for (var i = 0, l = currentQueueIndex; i <= l; i++) {
        queueName = daq.queueNames[i];
        queue = daq.queues[queueName];
        if (queue._queue.length) { return i; }
      }

      return -1;
    }

    __exports__.DeferredActionQueues = DeferredActionQueues;
  });

define("backburner/queue",
  ["exports"],
  function(__exports__) {
    "use strict";
    function Queue(daq, name, options) {
      this.daq = daq;
      this.name = name;
      this.options = options;
      this._queue = [];
    }

    Queue.prototype = {
      daq: null,
      name: null,
      options: null,
      _queue: null,

      push: function(target, method, args, stack) {
        var queue = this._queue;
        queue.push(target, method, args, stack);
        return {queue: this, target: target, method: method};
      },

      pushUnique: function(target, method, args, stack) {
        var queue = this._queue, currentTarget, currentMethod, i, l;

        for (i = 0, l = queue.length; i < l; i += 4) {
          currentTarget = queue[i];
          currentMethod = queue[i+1];

          if (currentTarget === target && currentMethod === method) {
            queue[i+2] = args; // replace args
            queue[i+3] = stack; // replace stack
            return {queue: this, target: target, method: method}; // TODO: test this code path
          }
        }

        this._queue.push(target, method, args, stack);
        return {queue: this, target: target, method: method};
      },

      // TODO: remove me, only being used for Ember.run.sync
      flush: function() {
        var queue = this._queue,
            options = this.options,
            before = options && options.before,
            after = options && options.after,
            action, target, method, args, i, l = queue.length;

        if (l && before) { before(); }
        for (i = 0; i < l; i += 4) {
          target = queue[i];
          method = queue[i+1];
          args   = queue[i+2];

          method.apply(target, args); // TODO: error handling
        }
        if (l && after) { after(); }

        // check if new items have been added
        if (queue.length > l) {
          this._queue = queue.slice(l);
          this.flush();
        } else {
          this._queue.length = 0;
        }
      },

      cancel: function(actionToCancel) {
        var queue = this._queue, currentTarget, currentMethod, i, l;

        for (i = 0, l = queue.length; i < l; i += 4) {
          currentTarget = queue[i];
          currentMethod = queue[i+1];

          if (currentTarget === actionToCancel.target && currentMethod === actionToCancel.method) {
            queue.splice(i, 4);
            return true;
          }
        }
      }
    };

    __exports__.Queue = Queue;
  });<commit_msg>Update Backburner.js<commit_after>define("backburner",
  ["backburner/deferred_action_queues","exports"],
  function(__dependency1__, __exports__) {
    "use strict";
    var DeferredActionQueues = __dependency1__.DeferredActionQueues;

    var slice = [].slice,
        pop = [].pop,
        debouncees = [],
        timers = [],
        autorun, laterTimer, laterTimerExpiresAt;

    function Backburner(queueNames, options) {
      this.queueNames = queueNames;
      this.options = options || {};
      if (!this.options.defaultQueue) {
        this.options.defaultQueue = queueNames[0];
      }
      this.instanceStack = [];
    }

    Backburner.prototype = {
      queueNames: null,
      options: null,
      currentInstance: null,
      instanceStack: null,

      begin: function() {
        var onBegin = this.options && this.options.onBegin,
            previousInstance = this.currentInstance;

        if (previousInstance) {
          this.instanceStack.push(previousInstance);
        }

        this.currentInstance = new DeferredActionQueues(this.queueNames, this.options);
        if (onBegin) {
          onBegin(this.currentInstance, previousInstance);
        }
      },

      end: function() {
        var onEnd = this.options && this.options.onEnd,
            currentInstance = this.currentInstance,
            nextInstance = null;

        try {
          currentInstance.flush();
        } finally {
          this.currentInstance = null;

          if (this.instanceStack.length) {
            nextInstance = this.instanceStack.pop();
            this.currentInstance = nextInstance;
          }

          if (onEnd) {
            onEnd(currentInstance, nextInstance);
          }
        }
      },

      run: function(target, method /*, args */) {
        var ret;
        this.begin();

        if (!method) {
          method = target;
          target = null;
        }

        if (typeof method === 'string') {
          method = target[method];
        }

        // Prevent Safari double-finally.
        var finallyAlreadyCalled = false;
        try {
          if (arguments.length > 2) {
            ret = method.apply(target, slice.call(arguments, 2));
          } else {
            ret = method.call(target);
          }
        } finally {
          if (!finallyAlreadyCalled) {
            finallyAlreadyCalled = true;
            this.end();
          }
        }
        return ret;
      },

      defer: function(queueName, target, method /* , args */) {
        if (!method) {
          method = target;
          target = null;
        }

        if (typeof method === 'string') {
          method = target[method];
        }

        var stack = new Error().stack,
            args = arguments.length > 3 ? slice.call(arguments, 3) : undefined;
        if (!this.currentInstance) { createAutorun(this); }
        return this.currentInstance.schedule(queueName, target, method, args, false, stack);
      },

      deferOnce: function(queueName, target, method /* , args */) {
        if (!method) {
          method = target;
          target = null;
        }

        if (typeof method === 'string') {
          method = target[method];
        }

        var stack = new Error().stack,
            args = arguments.length > 3 ? slice.call(arguments, 3) : undefined;
        if (!this.currentInstance) { createAutorun(this); }
        return this.currentInstance.schedule(queueName, target, method, args, true, stack);
      },

      setTimeout: function() {
        var self = this,
            wait = pop.call(arguments),
            target = arguments[0],
            method = arguments[1],
            executeAt = (+new Date()) + wait;

        if (!method) {
          method = target;
          target = null;
        }

        if (typeof method === 'string') {
          method = target[method];
        }

        var fn, args;
        if (arguments.length > 2) {
          args = slice.call(arguments, 2);

          fn = function() {
            method.apply(target, args);
          };
        } else {
          fn = function() {
            method.call(target);
          };
        }

        // find position to insert - TODO: binary search
        var i, l;
        for (i = 0, l = timers.length; i < l; i += 2) {
          if (executeAt < timers[i]) { break; }
        }

        timers.splice(i, 0, executeAt, fn);

        if (laterTimer && laterTimerExpiresAt < executeAt) { return fn; }

        if (laterTimer) {
          clearTimeout(laterTimer);
          laterTimer = null;
        }
        laterTimer = setTimeout(function() {
          executeTimers(self);
          laterTimer = null;
          laterTimerExpiresAt = null;
        }, wait);
        laterTimerExpiresAt = executeAt;

        return fn;
      },

      debounce: function(target, method /* , args, wait */) {
        var self = this,
            args = arguments,
            wait = pop.call(args),
            debouncee;

        for (var i = 0, l = debouncees.length; i < l; i++) {
          debouncee = debouncees[i];
          if (debouncee[0] === target && debouncee[1] === method) { return; } // do nothing
        }

        var timer = setTimeout(function() {
          self.run.apply(self, args);

          // remove debouncee
          var index = -1;
          for (var i = 0, l = debouncees.length; i < l; i++) {
            debouncee = debouncees[i];
            if (debouncee[0] === target && debouncee[1] === method) {
              index = i;
              break;
            }
          }

          if (index > -1) { debouncees.splice(index, 1); }
        }, wait);

        debouncees.push([target, method, timer]);
      },

      cancelTimers: function() {
        for (var i = 0, l = debouncees.length; i < l; i++) {
          clearTimeout(debouncees[i][2]);
        }
        debouncees = [];

        if (laterTimer) {
          clearTimeout(laterTimer);
          laterTimer = null;
        }
        timers = [];

        if (autorun) {
          clearTimeout(autorun);
          autorun = null;
        }
      },

      hasTimers: function() {
        return !!timers.length || autorun;
      },

      cancel: function(timer) {
        if (typeof timer === 'object' && timer.queue && timer.method) { // we're cancelling a deferOnce
          return timer.queue.cancel(timer);
        } else if (typeof timer === 'function') { // we're cancelling a setTimeout
          for (var i = 0, l = timers.length; i < l; i += 2) {
            if (timers[i + 1] === timer) {
              timers.splice(i, 2); // remove the two elements
              return true;
            }
          }
        }
      }
    };

    Backburner.prototype.schedule = Backburner.prototype.defer;
    Backburner.prototype.scheduleOnce = Backburner.prototype.deferOnce;
    Backburner.prototype.later = Backburner.prototype.setTimeout;

    function createAutorun(backburner) {
      backburner.begin();
      autorun = setTimeout(function() {
        backburner.end();
      });
    }

    function executeTimers(self) {
      var now = +new Date(),
          time, fns, i, l;

      self.run(function() {
        // TODO: binary search
        for (i = 0, l = timers.length; i < l; i += 2) {
          time = timers[i];
          if (time > now) { break; }
        }

        fns = timers.splice(0, i);

        for (i = 1, l = fns.length; i < l; i += 2) {
          self.schedule(self.options.defaultQueue, null, fns[i]);
        }
      });

      if (timers.length) {
        laterTimer = setTimeout(function() {
          executeTimers(self);
          laterTimer = null;
          laterTimerExpiresAt = null;
        }, timers[0] - now);
        laterTimerExpiresAt = timers[0];
      }
    }

    __exports__.Backburner = Backburner;
  });

define("backburner/deferred_action_queues",
  ["backburner/queue","exports"],
  function(__dependency1__, __exports__) {
    "use strict";
    var Queue = __dependency1__.Queue;

    function DeferredActionQueues(queueNames, options) {
      var queues = this.queues = {};
      this.queueNames = queueNames = queueNames || [];

      var queueName;
      for (var i = 0, l = queueNames.length; i < l; i++) {
        queueName = queueNames[i];
        queues[queueName] = new Queue(this, queueName, options[queueName]);
      }
    }

    DeferredActionQueues.prototype = {
      queueNames: null,
      queues: null,

      schedule: function(queueName, target, method, args, onceFlag, stack) {
        var queues = this.queues,
            queue = queues[queueName];

        if (!queue) { throw new Error("You attempted to schedule an action in a queue (" + queueName + ") that doesn't exist"); }

        if (onceFlag) {
          return queue.pushUnique(target, method, args, stack);
        } else {
          return queue.push(target, method, args, stack);
        }
      },

      flush: function() {
        var queues = this.queues,
            queueNames = this.queueNames,
            queueName, queue, queueItems, priorQueueNameIndex,
            queueNameIndex = 0, numberOfQueues = queueNames.length;

        outerloop:
        while (queueNameIndex < numberOfQueues) {
          queueName = queueNames[queueNameIndex];
          queue = queues[queueName];
          queueItems = queue._queue.slice();
          queue._queue = [];

          var options = queue.options,
              before = options && options.before,
              after = options && options.after,
              target, method, args, stack,
              queueIndex = 0, numberOfQueueItems = queueItems.length;

          if (numberOfQueueItems && before) { before(); }
          while (queueIndex < numberOfQueueItems) {
            target = queueItems[queueIndex];
            method = queueItems[queueIndex+1];
            args   = queueItems[queueIndex+2];
            stack  = queueItems[queueIndex+3]; // Debugging assistance

            if (typeof method === 'string') { method = target[method]; }

            // TODO: error handling
            if (args && args.length > 0) {
              method.apply(target, args);
            } else {
              method.call(target);
            }

            queueIndex += 4;
          }
          if (numberOfQueueItems && after) { after(); }

          if ((priorQueueNameIndex = indexOfPriorQueueWithActions(this, queueNameIndex)) !== -1) {
            queueNameIndex = priorQueueNameIndex;
            continue outerloop;
          }

          queueNameIndex++;
        }
      }
    };

    function indexOfPriorQueueWithActions(daq, currentQueueIndex) {
      var queueName, queue;

      for (var i = 0, l = currentQueueIndex; i <= l; i++) {
        queueName = daq.queueNames[i];
        queue = daq.queues[queueName];
        if (queue._queue.length) { return i; }
      }

      return -1;
    }

    __exports__.DeferredActionQueues = DeferredActionQueues;
  });

define("backburner/queue",
  ["exports"],
  function(__exports__) {
    "use strict";
    function Queue(daq, name, options) {
      this.daq = daq;
      this.name = name;
      this.options = options;
      this._queue = [];
    }

    Queue.prototype = {
      daq: null,
      name: null,
      options: null,
      _queue: null,

      push: function(target, method, args, stack) {
        var queue = this._queue;
        queue.push(target, method, args, stack);
        return {queue: this, target: target, method: method};
      },

      pushUnique: function(target, method, args, stack) {
        var queue = this._queue, currentTarget, currentMethod, i, l;

        for (i = 0, l = queue.length; i < l; i += 4) {
          currentTarget = queue[i];
          currentMethod = queue[i+1];

          if (currentTarget === target && currentMethod === method) {
            queue[i+2] = args; // replace args
            queue[i+3] = stack; // replace stack
            return {queue: this, target: target, method: method}; // TODO: test this code path
          }
        }

        this._queue.push(target, method, args, stack);
        return {queue: this, target: target, method: method};
      },

      // TODO: remove me, only being used for Ember.run.sync
      flush: function() {
        var queue = this._queue,
            options = this.options,
            before = options && options.before,
            after = options && options.after,
            target, method, args, stack, i, l = queue.length;

        if (l && before) { before(); }
        for (i = 0; i < l; i += 4) {
          target = queue[i];
          method = queue[i+1];
          args   = queue[i+2];
          stack  = queue[i+3]; // Debugging assistance

          // TODO: error handling
          if (args && args.length > 0) {
            method.apply(target, args);
          } else {
            method.call(target);
          }
        }
        if (l && after) { after(); }

        // check if new items have been added
        if (queue.length > l) {
          this._queue = queue.slice(l);
          this.flush();
        } else {
          this._queue.length = 0;
        }
      },

      cancel: function(actionToCancel) {
        var queue = this._queue, currentTarget, currentMethod, i, l;

        for (i = 0, l = queue.length; i < l; i += 4) {
          currentTarget = queue[i];
          currentMethod = queue[i+1];

          if (currentTarget === actionToCancel.target && currentMethod === actionToCancel.method) {
            queue.splice(i, 4);
            return true;
          }
        }
      }
    };

    __exports__.Queue = Queue;
  });<|endoftext|>


<commit_before>// Node modules.
import { useEffect, useState } from 'react';
import { orderBy } from 'lodash';
// Relative imports.
import environment from 'platform/utilities/environment';
import recordEvent from 'platform/monitoring/record-event';
import { SEARCH_IGNORE_LIST } from '../constants';

const countInstancesFound = (searchableString = '', keyword = '') =>
  searchableString.toLowerCase()?.split(keyword.toLowerCase())?.length - 1;

export default function useGetSearchResults(articles, query, page) {
  const [results, setResults] = useState([]);

  // Refresh the results list when the query is submitted or the page is changed.
  useEffect(
    () => {
      if (!articles || !query) {
        return;
      }

      // Begin filtering logic.
      // =====
      const keywords = query
        .split(' ')
        .filter(word => !!word)
        .map(keyword => keyword.toLowerCase())
        .filter(word => !SEARCH_IGNORE_LIST.includes(word))
        .map(keyword => {
          if (keyword.length > 6 && keyword.endsWith('ies')) {
            // Unpluralize the word, so that a search for "disabilities"
            // will still yield articles titled "disability"
            return keyword.slice(0, keyword.length - 3);
          } else if (keyword.length > 3 && keyword.endsWith('s')) {
            // Unpluralize the word, so that a search for "claims"
            // will still yield articles titled "claim or appeal status"
            return keyword.slice(0, keyword.length - 1);
          }
          return keyword;
        });

      let filteredArticles = articles.filter(article => {
        const articleTitleKeywords = article.title.toLowerCase().split(' ');

        return keywords.some(keyword => {
          return articleTitleKeywords.some(titleWord =>
            titleWord.startsWith(keyword),
          );
        });
      });
      // =====
      // End of filtering logic.

      // Begin ordering logic.
      // =====
      let orderedResults = [];

      filteredArticles = filteredArticles?.map(article => {
        // Derive keywords counts.
        const keywordsCountsTitle = keywords?.reduce(
          (keywordInstances, keyword) =>
            keywordInstances + countInstancesFound(article.title, keyword),
          0,
        );
        const keywordsCountsIntroText = keywords?.reduce(
          (keywordInstances, keyword) =>
            keywordInstances + countInstancesFound(article.introText, keyword),
          0,
        );
        const keywordsCountsContent = keywords?.reduce(
          (keywordInstances, keyword) =>
            keywordInstances +
            countInstancesFound(article.searchableContent, keyword),
          0,
        );

        // Derive whole phrase match counts.
        const wholePhraseMatchCountsTitle = countInstancesFound(
          article.title,
          query,
        );
        const wholePhraseMatchCountsIntroText = countInstancesFound(
          article.introText,
          query,
        );
        const wholePhraseMatchCountsContent = countInstancesFound(
          article.searchableContent,
          query,
        );

        return {
          ...article,

          // Number of times a keyword is found in the article's title.
          keywordsCountsTitle,

          // Number of times a keyword is found in the article's introText.
          keywordsCountsIntroText,

          // Number of times a keyword is found in the article's searchableContent.
          keywordsCountsContent,

          // Number of times the full query is found in the article's title.
          wholePhraseMatchCountsTitle,

          // Number of times the full query is found in the article's introText.
          wholePhraseMatchCountsIntroText,

          // Number of times the full query is found in the article's searchableContent.
          wholePhraseMatchCountsContent,

          // Number of times the full query is found in the article's title, introText, searchableContent combined.
          wholePhraseMatchCountsTotal:
            wholePhraseMatchCountsTitle +
            wholePhraseMatchCountsIntroText +
            wholePhraseMatchCountsContent,
        };
      });

      if (environment.isProduction()) {
        // Sort first by query word instances found in title descending
        // Sort ties then by query word instances found in introText descending
        // Sort ties then by alphabetical descending
        orderedResults = orderBy(
          filteredArticles,
          ['keywordsCountsTitle', 'keywordsCountsIntroText', 'title'],
          ['desc', 'desc', 'asc'],
        );
      } else {
        // Sort first by the number of exact query matches (ignoring casing) in the title and introText
        // Sort ties by query word instances found in title descending
        // Sort ties then by query word instances found in searchableContent descending
        // Sort ties then by alphabetical descending
        orderedResults = orderBy(
          filteredArticles,
          [
            'wholePhraseMatchCountsTotal',
            'keywordsCountsTitle',
            'keywordsCountsContent',
            'title',
          ],
          ['desc', 'desc', 'desc', 'asc'],
        );
      }
      // =====
      // End of ordering logic.

      // Track R&S search results.
      recordEvent({
        event: 'view_search_results',
        'search-page-path': document.location.pathname,
        'search-query': query,
        'search-results-total-count': orderedResults.length,
        'search-results-total-pages': Math.ceil(orderedResults.length / 10),
        'search-selection': 'Resources and support',
        'search-typeahead-enabled': false,
        'sitewide-search-app-used': false, // this is not the sitewide search app
        'type-ahead-option-keyword-selected': undefined,
        'type-ahead-option-position': undefined,
        'type-ahead-options-list': undefined,
        'type-ahead-options-count': undefined,
      });

      setResults(orderedResults);
    },
    [articles, setResults, query, page],
  );

  return [results];
}
<commit_msg>Kelsonic 22196 part 1 merge exp sorting to prod (#16990)<commit_after>// Node modules.
import { useEffect, useState } from 'react';
import { orderBy } from 'lodash';
// Relative imports.
import recordEvent from 'platform/monitoring/record-event';
import { SEARCH_IGNORE_LIST } from '../constants';

const countInstancesFound = (searchableString = '', keyword = '') =>
  searchableString.toLowerCase()?.split(keyword.toLowerCase())?.length - 1;

export default function useGetSearchResults(articles, query, page) {
  const [results, setResults] = useState([]);

  // Refresh the results list when the query is submitted or the page is changed.
  useEffect(
    () => {
      if (!articles || !query) {
        return;
      }

      // Begin filtering logic.
      // =====
      const keywords = query
        .split(' ')
        .filter(word => !!word)
        .map(keyword => keyword.toLowerCase())
        .filter(word => !SEARCH_IGNORE_LIST.includes(word))
        .map(keyword => {
          if (keyword.length > 6 && keyword.endsWith('ies')) {
            // Unpluralize the word, so that a search for "disabilities"
            // will still yield articles titled "disability"
            return keyword.slice(0, keyword.length - 3);
          } else if (keyword.length > 3 && keyword.endsWith('s')) {
            // Unpluralize the word, so that a search for "claims"
            // will still yield articles titled "claim or appeal status"
            return keyword.slice(0, keyword.length - 1);
          }
          return keyword;
        });

      let filteredArticles = articles.filter(article => {
        const articleTitleWords = article.title.toLowerCase().split(' ');

        return keywords.some(keyword => {
          return articleTitleWords.some(titleWord =>
            titleWord.startsWith(keyword),
          );
        });
      });
      // =====
      // End of filtering logic.

      // Begin ordering logic.
      // =====
      let orderedResults = [];

      filteredArticles = filteredArticles?.map(article => {
        // Derive keywords counts.
        const keywordsCountsTitle = keywords?.reduce(
          (keywordInstances, keyword) =>
            keywordInstances + countInstancesFound(article.title, keyword),
          0,
        );
        const keywordsCountsIntroText = keywords?.reduce(
          (keywordInstances, keyword) =>
            keywordInstances + countInstancesFound(article.introText, keyword),
          0,
        );
        const keywordsCountsContent = keywords?.reduce(
          (keywordInstances, keyword) =>
            keywordInstances +
            countInstancesFound(article.searchableContent, keyword),
          0,
        );

        // Derive whole phrase match counts.
        const wholePhraseMatchCountsTitle = countInstancesFound(
          article.title,
          query,
        );
        const wholePhraseMatchCountsIntroText = countInstancesFound(
          article.introText,
          query,
        );
        const wholePhraseMatchCountsContent = countInstancesFound(
          article.searchableContent,
          query,
        );

        return {
          ...article,

          // Number of times a keyword is found in the article's title.
          keywordsCountsTitle,

          // Number of times a keyword is found in the article's introText.
          keywordsCountsIntroText,

          // Number of times a keyword is found in the article's searchableContent.
          keywordsCountsContent,

          // Number of times the full query is found in the article's title.
          wholePhraseMatchCountsTitle,

          // Number of times the full query is found in the article's introText.
          wholePhraseMatchCountsIntroText,

          // Number of times the full query is found in the article's searchableContent.
          wholePhraseMatchCountsContent,

          // Number of times the full query is found in the article's title, introText, searchableContent combined.
          wholePhraseMatchCountsTotal:
            wholePhraseMatchCountsTitle +
            wholePhraseMatchCountsIntroText +
            wholePhraseMatchCountsContent,
        };
      });

      // Sort first by the number of exact query matches (ignoring casing) in the title, introText, and searchableContent descending
      // Sort ties by query word instances found in title descending
      // Sort ties then by query word instances found in searchableContent descending
      // Sort ties then by alphabetical descending
      orderedResults = orderBy(
        filteredArticles,
        [
          'wholePhraseMatchCountsTotal',
          'keywordsCountsTitle',
          'keywordsCountsContent',
          'title',
        ],
        ['desc', 'desc', 'desc', 'asc'],
      );
      // =====
      // End of ordering logic.

      // Track R&S search results.
      recordEvent({
        event: 'view_search_results',
        'search-page-path': document.location.pathname,
        'search-query': query,
        'search-results-total-count': orderedResults.length,
        'search-results-total-pages': Math.ceil(orderedResults.length / 10),
        'search-selection': 'Resources and support',
        'search-typeahead-enabled': false,
        'sitewide-search-app-used': false, // this is not the sitewide search app
        'type-ahead-option-keyword-selected': undefined,
        'type-ahead-option-position': undefined,
        'type-ahead-options-list': undefined,
        'type-ahead-options-count': undefined,
      });

      setResults(orderedResults);
    },
    [articles, setResults, query, page],
  );

  return [results];
}
<|endoftext|>


<commit_before>var acequia = require('./lib/acequia');

var START = function () {
    var acequiaServer = acequia.createServer();
    acequiaServer.start();
};

var start = function () {
    var timeout = 0;
    // If you want to debug via node-inspector, uncomment the following line:
    // timeout = 20000;

    setTimeout(START, timeout);
}

start();
<commit_msg>added a flag to set a delay at the start of the run for debugging purposes<commit_after>var acequia = require('./lib/acequia');

var START = function () {
    var acequiaServer = acequia.createServer();
    acequiaServer.start();
};

var start = function () {
    var i, timeout = 0;

    process.argv.forEach(function (val, index, array) {
        if (val === "--debug") {
            timeout = 20000;
        }
    });

    setTimeout(START, timeout);
}

start();
<|endoftext|>


<commit_before>//
// Server side activity detection for the session timeout
//
// Meteor settings:
// - staleSessionInactivityTimeout: the amount of time (in ms) after which, if no activity is noticed, a session will be considered stale
// - staleSessionPurgeInterval: interval (in ms) at which stale sessions are purged i.e. found and forcibly logged out
//
var staleSessionPurgeInterval = Meteor.settings && Meteor.settings.public && Meteor.settings.public.staleSessionPurgeInterval || (1*60*1000); // 1min
var inactivityTimeout = Meteor.settings && Meteor.settings.public && Meteor.settings.public.staleSessionInactivityTimeout || (30*60*1000); // 30mins

//
// provide a user activity heartbeat method which stamps the user record with a timestamp of the last
// received activity heartbeat.
//
Meteor.methods({
    heartbeat: function(options) {
        if (!this.userId) { return; }
        var user = Meteor.users.findOne(this.userId);
        if (user) {
            Meteor.users.update(user._id, {$set: {heartbeat: new Date()}});
        }
    }
});

//
// periodically purge any stale sessions, removing their login tokens and clearing out the stale heartbeat.
//
Meteor.setInterval(function() {
    var now = new Date(), overdueTimestamp = new Date(now-inactivityTimeout);
    Meteor.users.update({heartbeat: {$lt: overdueTimestamp}},
                        {$set: {'services.resume.loginTokens': []},
                         $unset: {heartbeat:1}},
                        {multi: true});
}, staleSessionPurgeInterval);
<commit_msg>Feature/UsersRoles - You can now specify which users you do not want the sessions to expire for.<commit_after>//
// Server side activity detection for the session timeout
//
// Meteor settings:
// - staleSessionInactivityTimeout: the amount of time (in ms) after which, if no activity is noticed, a session will be considered stale
// - staleSessionPurgeInterval: interval (in ms) at which stale sessions are purged i.e. found and forcibly logged out
//
var staleSessionPurgeInterval = Meteor.settings && Meteor.settings.public && Meteor.settings.public.staleSessionPurgeInterval || (1*60*1000); // 1min
var inactivityTimeout = Meteor.settings && Meteor.settings.public && Meteor.settings.public.staleSessionInactivityTimeout || (30*60*1000); // 30mins
var usersRoles = Meteor.settings && Meteor.settings.public && Meteor.settings.public.staleSessionUserRoles || []; // null
//
// provide a user activity heartbeat method which stamps the user record with a timestamp of the last
// received activity heartbeat.
//
Meteor.methods({
    heartbeat: function(options) {
        if (!this.userId) { return; }
        var user = Meteor.users.findOne(this.userId);
        if (user) {
            if(usersRoles) {
                for (var x = 0, count = user.roles.length; x < count; x++) {
                    for (var y = 0, count1 = usersRoles.length; y < count1; y++) {
                        if (user.roles[x] === usersRoles[y]) {
                            return
                        }
                    }
                }
            }
            Meteor.users.update(user._id, {$set: {heartbeat: new Date()}});
        }
    }
});

//
// periodically purge any stale sessions, removing their login tokens and clearing out the stale heartbeat.
//
var self = this;
Meteor.setInterval(function() {
    //var user = Meteor.users.findOne(userID);
    console.log("test");
    //var roles = user.roles;
    //for (var x = 0, count = roles.length; x < count; x++){
    //    for(var y = 0, count1 = usersRoles.length; y < count1; y++) {
    //        if (roles[x] === usersRoles[y]) {
    //            return
    //        }
    //    }
    //}
    var now = new Date(), overdueTimestamp = new Date(now-inactivityTimeout);
    Meteor.users.update({heartbeat: {$lt: overdueTimestamp}},
                        {$set: {'services.resume.loginTokens': []},
                         $unset: {heartbeat:1}},
                        {multi: true});
}, staleSessionPurgeInterval);
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import { arrayMove } from 'react-sortable-hoc';

export class ListWrapper extends React.Component {
  constructor({items}) {
    super();
    this.state = {
      items, isSorting: false
    };
  }

  componentWillReceiveProps(nextProps) {
    this.setState ({
      items: nextProps.items
    })
  }

  onSortStart({node, index, collection}, e) {
    e.stopImmediatePropagation();
    let {onSortStart} = this.props;
    this.setState({isSorting: true});

    if (onSortStart) {
      onSortStart(this.ref);
    }

    this.sortingIndex = index;

    this.sortStartTop = e.offsetTop;
    this.sortStartLeft = e.offsetLeft;
  }

  onSortMove() {}

  onSortEnd({oldIndex, newIndex}) {
    let {onSortEnd} = this.props;
    let {items} = this.state;

    this.setState({
      items: arrayMove(items, oldIndex, newIndex),
      isSorting: false
    });

    if (onSortEnd) {
      onSortEnd(this.state.items);
    }

    this.sortingIndex = null;
  }

  render() {
    const Component = this.props.component;
    const {items, isSorting} = this.state;
    const props = {
      isSorting, items,
      onSortEnd: this.onSortEnd.bind(this),
      onSortStart: this.onSortStart.bind(this),
      onSortMove: this.onSortMove.bind(this)
    }

    return (
      <Component
        {...this.props}
        {...props}
        ref={element => this.ref = element}
      />
    );
  }
}

ListWrapper.propTypes = {
  className: PropTypes.string,
  component: PropTypes.func,
  height: PropTypes.number,
  itemClass: PropTypes.string,
  items: PropTypes.array,
  onSortEnd: PropTypes.func,
  onSortStart: PropTypes.func,
  width: PropTypes.number
}

ListWrapper.defaultProps = {
  className: 'list stylizedList',
  itemClass: 'item stylizedItem',
  width: 400,
  height: 600
};

export default ListWrapper;
<commit_msg>Add missing prop types<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import { arrayMove } from 'react-sortable-hoc';

export class ListWrapper extends React.Component {
  constructor({items}) {
    super();
    this.state = {
      items, isSorting: false
    };
  }

  componentWillReceiveProps(nextProps) {
    this.setState ({
      items: nextProps.items
    })
  }

  onSortStart({node, index, collection}, e) {
    e.stopImmediatePropagation();
    let {onSortStart} = this.props;
    this.setState({isSorting: true});

    if (onSortStart) {
      onSortStart(this.ref);
    }

    this.sortingIndex = index;

    this.sortStartTop = e.offsetTop;
    this.sortStartLeft = e.offsetLeft;
  }

  onSortMove() {}

  onSortEnd({oldIndex, newIndex}) {
    let {onSortEnd} = this.props;
    let {items} = this.state;

    this.setState({
      items: arrayMove(items, oldIndex, newIndex),
      isSorting: false
    });

    if (onSortEnd) {
      onSortEnd(this.state.items);
    }

    this.sortingIndex = null;
  }

  render() {
    const Component = this.props.component;
    const {items, isSorting} = this.state;
    const props = {
      isSorting, items,
      onSortEnd: this.onSortEnd.bind(this),
      onSortStart: this.onSortStart.bind(this),
      onSortMove: this.onSortMove.bind(this)
    }

    return (
      <Component
        {...this.props}
        {...props}
        ref={element => this.ref = element}
      />
    );
  }
}

ListWrapper.propTypes = {
  axis: PropTypes.string,
  className: PropTypes.string,
  component: PropTypes.func,
  editable: PropTypes.bool,
  handleConfigTrack: PropTypes.func,
  handleResizeTrack: PropTypes.func,
  height: PropTypes.number,
  helperClass: PropTypes.string,
  itemClass: PropTypes.string,
  itemReactClass: PropTypes.func,
  items: PropTypes.array,
  onAddSeries: PropTypes.func,
  onCloseTrack: PropTypes.func,
  onCloseTrackMenuOpened: PropTypes.func,
  onConfigTrackMenuOpened: PropTypes.func,
  onSortEnd: PropTypes.func,
  onSortStart: PropTypes.func,
  referenceAncestor: PropTypes.string,
  resizeHandles: PropTypes.object,
  useDragHandle: PropTypes.bool,
  width: PropTypes.number
}

ListWrapper.defaultProps = {
  className: 'list stylizedList',
  itemClass: 'item stylizedItem',
  width: 400,
  height: 600
};

export default ListWrapper;
<|endoftext|>


<commit_before>var events = require('events');
var wormhole = function (socket) {
	events.EventEmitter.call(this);
	this.isWormhole = null;
	this.setupListeners();
	this.setSocket(socket);

	this._availablerpc = {};
	this.rpc = {};

	this.__hash__ = "";
};
wormhole.prototype.__proto__ = events.EventEmitter.prototype;
wormhole.prototype.setSocket = function(socket) {
	this.socket && this.socket.removeAllListeners();
	this.socket = socket;
	this.setupSocketListeners();
};
wormhole.prototype.isWormhole = function(cb) {
	if (this.isWormhole === null) {
		this.socket.emit("isWormhole", function (err, isWormhole) {
			if (!err) {
				this.isWormhole = isWormhole;
			} else {
				this.isWormhole = !!isWormhole;
			}
		});
	} else {
		cb(null, isWormhole);
	}
};
wormhole.prototype.setupListeners = function() {
	var self = this;
	this.on("newListener", function (event, func) {
		if (event != "removeListener" && event != "newListener") {
			// Oh, this is an RPC, Add the fucker!
			self.addFunction(event, func);
		}
	});
};
wormhole.prototype.setupSocketListeners = function() {
	var self = this;
	//Original func
	this.socket.on("isWormhole", function (cb) {
		cb(null, true);
		self.syncFunctions();
	});

	this.socket.on("rpc", function (data) {
		if (data.__hash__ != self.__hash__) {
			self.emit("outofsync", self);
		}
	});
};
wormhole.prototype.addFunction = function(func, cb) {
	this._availablerpc[func] = cb;
	var str = Object.keys(this._availablerpc).join("");
	this.__hash__ = new Buffer(str).toString('base64');
};
wormhole.prototype.syncFunctions = function() {
	this.socket.emit("functions", Object.keys(this._availablerpc));
};
wormhole.prototype.addClientFunction = function(func) {
	var self = this;
	this.rpc[func] = function () {
		var args = ["rpc", func].concat([].slice.call(arguments));
		self.socket.emit.apply(self, args);
	};
};
module.exports = wormhole;<commit_msg>Keeping track of changes for rpc versioning<commit_after>var events = require('events');
var wormhole = function (socket) {
	events.EventEmitter.call(this);
	this.isWormhole = null;
	this.setupListeners();
	this.setSocket(socket);

	this._availablerpc = {};
	this.rpc = {};

	this.__hashes__ = [];

	this.__hash__ = "";
};
wormhole.prototype.__proto__ = events.EventEmitter.prototype;
wormhole.prototype.setSocket = function(socket) {
	this.socket && this.socket.removeAllListeners();
	this.socket = socket;
	this.setupSocketListeners();
};
wormhole.prototype.isWormhole = function(cb) {
	if (this.isWormhole === null) {
		this.socket.emit("isWormhole", function (err, isWormhole) {
			if (!err) {
				this.isWormhole = isWormhole;
			} else {
				this.isWormhole = !!isWormhole;
			}
		});
	} else {
		cb(null, isWormhole);
	}
};
wormhole.prototype.setupListeners = function() {
	var self = this;
	this.on("newListener", function (event, func) {
		if (event != "removeListener" && event != "newListener") {
			// Oh, this is an RPC, Add the fucker!
			self.addFunction(event, func);
		}
	});
};
wormhole.prototype.setupSocketListeners = function() {
	var self = this;
	//Original func
	this.socket.on("isWormhole", function (cb) {
		cb(null, true);
		self.syncFunctions();
	});

	this.socket.on("rpc", function (data) {
		if (data.__hash__ != self.__hash__) {
			self.emit("outofsync", self);
		}
	});
};
wormhole.prototype.addFunction = function(func, cb) {
	this._availablerpc[func] = cb;
	var str = Object.keys(this._availablerpc).join("");
	// Simple RPC versioning.
	this.__hash__ = new Buffer(str).toString('base64');
	this.__hashes__.push({hash: this.__hash__, name: func});
};
wormhole.prototype.syncFunctions = function(__oldHash__) {
	if (__oldHash__) {
		var changes = this.__changes__(__oldHash__);
		this.socket.emit("functions", changes);
	} else {
		this.socket.emit("functions", Object.keys(this._availablerpc));
	}
};
wormhole.prototype.addClientFunction = function(func) {
	var self = this;
	this.rpc[func] = function () {
		var args = ["rpc", func].concat([].slice.call(arguments));
		self.socket.emit.apply(self, args);
	};
};
wormhole.prototype.__changes__ = function(hash) {
	var out = [];
	var keys = Object.keys(this.__hashes__);
	for (var i = keys.length; i >= 0; i--) {
		// Reverse traverse, most likely they'll have a more-or-less up to date stash.
		if (keys[i].hash === hash) {
			out.push(keys[i].name)
			break;
		}
	}
	return out;
};
module.exports = wormhole;<|endoftext|>


<commit_before>// Karma E2E configuration

// base path, that will be used to resolve files and exclude
basePath = '';

// list of files / patterns to load in the browser
files = [
  ANGULAR_SCENARIO,
  ANGULAR_SCENARIO_ADAPTER,
  'test/e2e/**/*.js'
];

// list of files to exclude
exclude = [];

// test results reporter to use
// possible values: dots || progress || growl
reporters = ['progress'];

// web server port
port = 8080;

// cli runner port
runnerPort = 9100;

// enable / disable colors in the output (reporters and logs)
colors = true;

// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;

// enable / disable watching file and executing tests whenever any file changes
autoWatch = false;

// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['Chrome'];

// If browser does not capture in given timeout [ms], kill it
captureTimeout = 5000;

// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;
<commit_msg>Get rid of confusingly unusued config file<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 Expression organization is undefined on line 4, column 61 in Templates/Licenses/license-gpl30.txt.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * LayerSelector
 * A generic component to retrieve the layers
 * @author Meine Toonen
 */
Ext.define ("viewer.components.LayerSelector",{
    popupWin:null,
    layerList : null,
    combobox : null,
    div: null,
    config: {
        viewerController: new Object(),
        restriction : null
    },
    constructor: function (conf,div){
        this.initConfig(conf);
        this.div = div;
        var layerList = this.viewerController.app.appLayers;
        var layerArray = new Array();
        for (var layer in layerList){
            var l = layerList[layer];
            l.layer = l;
            layerArray.push(l);
        }
        var layers = Ext.create('Ext.data.Store', {
            fields: ['id', 'layerName','layer'],
            data : layerArray
        });

        this.combobox = Ext.create('Ext.form.ComboBox', {
            fieldLabel: 'Kies kaartlaag',
            store: layers,
            queryMode: 'local',
            displayField: 'layerName',
            valueField: 'layer',
            renderTo: this.div
        });
        return this;
    },
    getValue : function (){
        return this.combobox.getValue();
    }
});<commit_msg>Events added to layerselector<commit_after>/*
 * Copyright (C) 2012 Expression organization is undefined on line 4, column 61 in Templates/Licenses/license-gpl30.txt.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * LayerSelector
 * A generic component to retrieve the layers
 * @author Meine Toonen
 */
Ext.define ("viewer.components.LayerSelector",{
    extend: "viewer.components.Component",
    popupWin:null,
    layerList : null,
    combobox : null,
    div: null,
    config: {
        viewerController: new Object(),
        restriction : null
    },
    constructor: function (conf,div){
        this.initConfig(conf);
        this.addEvents(viewer.viewercontroller.controller.Event.ON_LAYERSELECTOR_CHANGE);
        this.div = div;
        var layerList = this.viewerController.app.appLayers;
        var layerArray = new Array();
        for (var layer in layerList){
            var l = layerList[layer];
            l.layer = l;
            layerArray.push(l);
        }
        var layers = Ext.create('Ext.data.Store', {
            fields: ['id', 'layerName','layer'],
            data : layerArray
        });

        this.combobox = Ext.create('Ext.form.ComboBox', {
            fieldLabel: 'Kies kaartlaag',
            store: layers,
            queryMode: 'local',
            displayField: 'layerName',
            valueField: 'layer',
            listeners :{
                change:{
                    fn: this.changed,
                    scope: this
                }
            },
            renderTo: this.div
        });
        return this;
    },
    changed :function (combobox,item,previousSelected){
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_LAYERSELECTOR_CHANGE,item,this);
    },
    getValue : function (){
        return this.combobox.getValue();
    }
});<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const bodyParser = require('body-parser');

const restService = express();
restService.use(bodyParser.json());

restService.post('/hook', function (req, res) {

    console.log('hook request');

    try {
        var speech = 'empty speech';

        if (req.body) {
            console.log('Request Body: ', req.body);
            var requestBody = req.body;

            if (requestBody.result) {
                speech = '';

                if (requestBody.result.fulfillment) {
                    speech += requestBody.result.fulfillment.speech;
                    speech += ' ';
                }

                if (requestBody.result.action) {
                    speech += 'action: ' + requestBody.result.action;
                }
            }
        }

        console.log('result: ', speech);

        return res.json({
            speech: speech,
            displayText: speech,
            source: 'apiai-webhook-sample'
        });
    } catch (err) {
        console.error("Can't process request", err);

        return res.status(400).json({
            status: {
                code: 400,
                errorType: err.message
            }
        });
    }
});

restService.listen((process.env.PORT || 5000), function () {
    console.log("Server listening");
});
<commit_msg>1st commit<commit_after>'use strict';

const express = require('express');
const bodyParser = require('body-parser');

const restService = express();
restService.use(bodyParser.json());

restService.post('/hook', function (req, res) {

    console.log('hook request');

    try {
        var speech = 'empty speech';

        if (req.body) {
            console.log('Request Body: ', req.body);
            var requestBody = req.body;

            if (requestBody.result) {
                speech = '';

                if (requestBody.result.fulfillment) {
                    speech += requestBody.result.fulfillment.speech;
                    speech += ' ';
                }

                if (requestBody.result.action) {
                    speech += 'EBS action: ' + requestBody.result.action;
                }
            }
        }

        console.log('result: ', speech);

        return res.json({
            speech: speech,
            displayText: speech,
            source: 'apiai-webhook-sample'
        });
    } catch (err) {
        console.error("Can't process request", err);

        return res.status(400).json({
            status: {
                code: 400,
                errorType: err.message
            }
        });
    }
});

restService.listen((process.env.PORT || 5000), function () {
    console.log("Server listening");
});
<|endoftext|>


<commit_before>'use strict';

angular.module('impactApp')
  .factory('ProfileService', function ProfileService(estAdulte, estMineur) {
    var estMineurProfile = function(profile) {
      if (profile.identites && profile.identites.beneficiaire) {
        return estMineur(profile.identites.beneficiaire.dateNaissance);
      } else {
        return false;
      }
    };

    var estAdulteProfile = function(profile) {
      if (profile.identites && profile.identites.beneficiaire) {
        return estAdulte(profile.identites.beneficiaire.dateNaissance);
      } else {
        return true;
      }
    };

    var getMissingSection = function(profile) {
      var missingSections = [];

      if (!profile.identites || !profile.identites.beneficiaire) {
        missingSections.push('beneficiaire');
      }

      if (estMineurProfile(profile) && (!profile.identites || !profile.identites.autorite)) {
        missingSections.push('autorite');
      }

      if (!profile.vie_quotidienne || !profile.vie_quotidienne.__completion) {
        missingSections.push('vieQuotidienne');
      }

      return missingSections;
    };

    var getCompletion = function(profile) {
      if (!profile.identites || !profile.identites.beneficiaire) {
        return false;
      }

      if (estMineur() && !profile.identites.autorite) {
        return false;
      }

      if (!profile.vie_quotidienne || !profile.vie_quotidienne.__completion) {
        return false;
      }

      return true;
    };

    return {
      estMasculin: function(profile) {
        if (profile.identites && profile.identites.beneficiaire) {
          return profile.identites.beneficiaire.sexe === 'masculin';
        } else {
          return false;
        }
      },

      getPrenom: function(profile) {
        if (profile.identites && profile.identites.beneficiaire) {
          return profile.identites.beneficiaire.prenom;
        } else {
          return 'le bénéficiaire de la demande';
        }
      },

      estAdulte: estAdulteProfile,
      estMineur: estMineurProfile,
      getCompletion: getCompletion,
      getMissingSection: getMissingSection
    };
  });
<commit_msg>Fix age tests bis<commit_after>'use strict';

angular.module('impactApp')
  .factory('ProfileService', function ProfileService(estAdulte, estMineur) {
    var estMineurProfile = function(profile) {
      if (profile.identites && profile.identites.beneficiaire) {
        return estMineur(profile.identites.beneficiaire.dateNaissance);
      } else {
        return false;
      }
    };

    var estAdulteProfile = function(profile) {
      if (profile.identites && profile.identites.beneficiaire) {
        return estAdulte(profile.identites.beneficiaire.dateNaissance);
      } else {
        return true;
      }
    };

    var getMissingSection = function(profile) {
      var missingSections = [];

      if (!profile.identites || !profile.identites.beneficiaire) {
        missingSections.push('beneficiaire');
      }

      if (estMineurProfile(profile) && (!profile.identites || !profile.identites.autorite)) {
        missingSections.push('autorite');
      }

      if (!profile.vie_quotidienne || !profile.vie_quotidienne.__completion) {
        missingSections.push('vieQuotidienne');
      }

      return missingSections;
    };

    var getCompletion = function(profile) {
      if (!profile.identites || !profile.identites.beneficiaire) {
        return false;
      }

      if (estMineurProfile() && !profile.identites.autorite) {
        return false;
      }

      if (!profile.vie_quotidienne || !profile.vie_quotidienne.__completion) {
        return false;
      }

      return true;
    };

    return {
      estMasculin: function(profile) {
        if (profile.identites && profile.identites.beneficiaire) {
          return profile.identites.beneficiaire.sexe === 'masculin';
        } else {
          return false;
        }
      },

      getPrenom: function(profile) {
        if (profile.identites && profile.identites.beneficiaire) {
          return profile.identites.beneficiaire.prenom;
        } else {
          return 'le bénéficiaire de la demande';
        }
      },

      estAdulte: estAdulteProfile,
      estMineur: estMineurProfile,
      getCompletion: getCompletion,
      getMissingSection: getMissingSection
    };
  });
<|endoftext|>


<commit_before>var applicationMock;
var ApplicationMock = Ember.Object.extend();

var containerMock;
var ContainerMock = Ember.Object.extend({
  init: function() {
    this.registrations = {};
    this.injections = [];
  },
  register: function(name, factory, options) {
    this.registrations[name] = {
      factory: factory,
      options: options
    };
  },
  inject: function(target, property, name) {
    var registration = this.registrations[name];
    if (registration) {
      this.injections.push({
        target:   target,
        property: property,
        object:   registration.factory
      });
    }
  }
});

var authorizerMock;
var AuthorizerMock = Ember.Object.extend({
  authorize: function() {
    this.authorized = true;
  }
});
AuthorizerMock.reopenClass({
  create: function(options) {
    return (authorizerMock = this._super(options));
  }
});

var ajaxPrefilterMock;
var AjaxPrefilterMock = Ember.Object.extend({
  ajaxPrefilterCapture: function(prefilter) {
    this.registeredAjaxPrefilter = prefilter;
  }
});

module('Ember.SimpleAuth', {
  originalAjaxPrefilter: Ember.$.ajaxPrefilter,
  setup: function() {
    applicationMock       = ApplicationMock.create();
    containerMock         = ContainerMock.create();
    ajaxPrefilterMock     = AjaxPrefilterMock.create();
    Ember.$.ajaxPrefilter = Ember.$.proxy(ajaxPrefilterMock.ajaxPrefilterCapture, ajaxPrefilterMock);
  },
  teardown: function() {
    Ember.$.ajaxPrefilter = this.originalAjaxPrefilter;
    Ember.run.cancel(Ember.SimpleAuth.Session._syncPropertiesTimeout);
  }
});

test('assigns the authentication route', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { authenticationRoute: 'somewhere' });

  equal(Ember.SimpleAuth.authenticationRoute, 'somewhere', 'Ember.SimpleAuth assigns authenticationRoute when specified for setup.');
});

test('assigns the route after authentication', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { routeAfterAuthentication: 'somewhere' });

  equal(Ember.SimpleAuth.routeAfterAuthentication, 'somewhere', 'Ember.SimpleAuth assigns routeAfterAuthentication when specified for setup.');
});

test('assigns the route after session invalidation', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { routeAfterInvalidation: 'somewhere' });

  equal(Ember.SimpleAuth.routeAfterInvalidation, 'somewhere', 'Ember.SimpleAuth assigns routeAfterInvalidation when specified for setup.');
});

test('injects the session in models, views, controllers and routes', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock);

  Ember.$.each(['model', 'view', 'controller', 'view'], function(i, component) {
    var injection = Ember.$.grep(containerMock.injections, function(injection) {
      return injection.target === component;
    })[0];

    equal(injection.object.constructor, Ember.SimpleAuth.Session, 'Ember.SimpleAuth injects the session into ' + component + '.');
    equal(injection.property, 'session', 'Ember.SimpleAuth makes the session available as "session" in ' + component + '.');
  });
});

test('registers an AJAX prefilter that authorizes requests', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { authorizer: AuthorizerMock });

  ajaxPrefilterMock.registeredAjaxPrefilter({}, {}, {});
  ok(authorizerMock.authorized, "Ember.SimpleAuth registers an AJAX prefilter that authorizes requests that fo the the application's origin.");

  authorizerMock.authorized = false;
  ajaxPrefilterMock.registeredAjaxPrefilter({ url: 'https://a.different.domain:1234' }, {}, {});
  ok(!authorizerMock.authorized, 'Ember.SimpleAuth registers an AJAX prefilter that does not authorize cross-origin requests.');

  Ember.SimpleAuth.setup(containerMock, applicationMock, { crossOriginWhitelist: ['https://a.different.domain:1234'], authorizer: AuthorizerMock, store: Ember.SimpleAuth.Stores.Ephemeral });
  ajaxPrefilterMock.registeredAjaxPrefilter({ url: 'https://a.different.domain:1234' }, {}, {});
  ok(authorizerMock.authorized, 'Ember.SimpleAuth registers an AJAX prefilter that authorizes cross-origin requests when the origin is in the crossOriginWhitelist.');
});
<commit_msg>added missing test<commit_after>var applicationMock;
var ApplicationMock = Ember.Object.extend();

var containerMock;
var ContainerMock = Ember.Object.extend({
  init: function() {
    this.registrations = {};
    this.injections = [];
  },
  register: function(name, factory, options) {
    this.registrations[name] = {
      factory: factory,
      options: options
    };
  },
  inject: function(target, property, name) {
    var registration = this.registrations[name];
    if (registration) {
      this.injections.push({
        target:   target,
        property: property,
        object:   registration.factory
      });
    }
  }
});

var authorizerMock;
var AuthorizerMock = Ember.Object.extend({
  authorize: function() {
    this.authorized = true;
  }
});
AuthorizerMock.reopenClass({
  create: function(options) {
    return (authorizerMock = this._super(options));
  }
});

var ajaxPrefilterMock;
var AjaxPrefilterMock = Ember.Object.extend({
  ajaxPrefilterCapture: function(prefilter) {
    this.registeredAjaxPrefilter = prefilter;
  }
});

module('Ember.SimpleAuth', {
  originalAjaxPrefilter: Ember.$.ajaxPrefilter,
  setup: function() {
    applicationMock       = ApplicationMock.create();
    containerMock         = ContainerMock.create();
    ajaxPrefilterMock     = AjaxPrefilterMock.create();
    Ember.$.ajaxPrefilter = Ember.$.proxy(ajaxPrefilterMock.ajaxPrefilterCapture, ajaxPrefilterMock);
  },
  teardown: function() {
    Ember.$.ajaxPrefilter = this.originalAjaxPrefilter;
    Ember.run.cancel(Ember.SimpleAuth.Session._syncPropertiesTimeout);
  }
});

test('assigns the authentication route', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { authenticationRoute: 'somewhere' });

  equal(Ember.SimpleAuth.authenticationRoute, 'somewhere', 'Ember.SimpleAuth assigns authenticationRoute when specified for setup.');
});

test('assigns the route after authentication', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { routeAfterAuthentication: 'somewhere' });

  equal(Ember.SimpleAuth.routeAfterAuthentication, 'somewhere', 'Ember.SimpleAuth assigns routeAfterAuthentication when specified for setup.');
});

test('assigns the route after session invalidation', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { routeAfterInvalidation: 'somewhere' });

  equal(Ember.SimpleAuth.routeAfterInvalidation, 'somewhere', 'Ember.SimpleAuth assigns routeAfterInvalidation when specified for setup.');
});

test('injects the session in models, views, controllers and routes', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock);

  Ember.$.each(['model', 'view', 'controller', 'view'], function(i, component) {
    var injection = Ember.$.grep(containerMock.injections, function(injection) {
      return injection.target === component;
    })[0];

    equal(injection.object.constructor, Ember.SimpleAuth.Session, 'Ember.SimpleAuth injects the session into ' + component + '.');
    equal(injection.property, 'session', 'Ember.SimpleAuth makes the session available as "session" in ' + component + '.');
  });
});

test('assigns the store and container to the session', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { store: Ember.SimpleAuth.Stores.Ephemeral });

  var session = containerMock.injections[0].object;

  equal(session.container, containerMock, 'Ember.SimpleAuth assigns the container to the session.');
  equal(session.store.constructor, Ember.SimpleAuth.Stores.Ephemeral, 'Ember.SimpleAuth assigns the correct store to the session.');
});

test('registers an AJAX prefilter that authorizes requests', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { authorizer: AuthorizerMock });

  ajaxPrefilterMock.registeredAjaxPrefilter({}, {}, {});
  ok(authorizerMock.authorized, "Ember.SimpleAuth registers an AJAX prefilter that authorizes requests that fo the the application's origin.");

  authorizerMock.authorized = false;
  ajaxPrefilterMock.registeredAjaxPrefilter({ url: 'https://a.different.domain:1234' }, {}, {});
  ok(!authorizerMock.authorized, 'Ember.SimpleAuth registers an AJAX prefilter that does not authorize cross-origin requests.');

  Ember.SimpleAuth.setup(containerMock, applicationMock, { crossOriginWhitelist: ['https://a.different.domain:1234'], authorizer: AuthorizerMock, store: Ember.SimpleAuth.Stores.Ephemeral });
  ajaxPrefilterMock.registeredAjaxPrefilter({ url: 'https://a.different.domain:1234' }, {}, {});
  ok(authorizerMock.authorized, 'Ember.SimpleAuth registers an AJAX prefilter that authorizes cross-origin requests when the origin is in the crossOriginWhitelist.');
});
<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */
sap.ui.define([],
	function() {
	"use strict";

	/**
	 * DraftIndicator renderer.
	 * @namespace
	 */
	var DraftIndicatorRenderer = {};

	/**
	 * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
	 */
	DraftIndicatorRenderer.render = function(oRm, oControl) {

		oRm.write("<div");
		oRm.writeControlData(oControl);
		oRm.addClass("sapMDraftIndicator");
		oRm.writeClasses();
		oRm.write(">");

		var oLabel = oControl._getLabel();

		oRm.renderControl(oLabel);

		oRm.write("</div>");
	};

	return DraftIndicatorRenderer;

}, /* bExport= */ true);
<commit_msg>[INTERNAL] sap.m.DraftIndicator: convert to new renderer syntax<commit_after>/*!
 * ${copyright}
 */
sap.ui.define([],
	function() {
	"use strict";

	/**
	 * DraftIndicator renderer.
	 * @namespace
	 */
	var DraftIndicatorRenderer = {
		apiVersion: 2
	};

	/**
	 * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
	 */
	DraftIndicatorRenderer.render = function(oRm, oControl) {

		oRm.openStart("div", oControl);
		oRm.class("sapMDraftIndicator");
		oRm.openEnd();

		var oLabel = oControl._getLabel();

		oRm.renderControl(oLabel);

		oRm.close("div");
	};

	return DraftIndicatorRenderer;

}, /* bExport= */ true);
<|endoftext|>