<commit_before>var models = require("../../../models");
var log = require('../../utils/logger');
var toJson = require('../../utils/to_json');
var async = require('async');
var queue = require('../../workers/queue');

var filterNotificationForDelivery = function (notification, user, notification_settings_type, template, subject, callback) {
  var method = user.notifications_settings[notification_settings_type].method;
  var frequency = user.notifications_settings[notification_settings_type].frequency;

  //TODO: Switch from FREQUENCY_AS_IT_HAPPENS if user has had a lot of emails > 25 in the hour or something

  console.log("Notification Email Processing", {user: user, method: method, frequency: frequency});

  if (method !== models.AcNotification.METHOD_MUTED) {
    if (frequency === models.AcNotification.FREQUENCY_AS_IT_HAPPENS) {
      queue.create('send-one-email', {
        subject: subject,
        template: template,
        user: user,
        domain: notification.AcActivities[0].Domain,
        community: notification.AcActivities[0].Community,
        activity: notification.AcActivities[0],
        post: notification.AcActivities[0].Post,
        point: notification.AcActivities[0].Point
      }).priority('critical').removeOnComplete(true).save();
      callback();
    } else if (user.notifications_settings.my_posts.method != models.AcNotification.METHOD_MUTED) {
      AcDelayedNotification.findOrCreate({
        where: {
          user_id: user.id,
          method: method,
          frequency: frequency,
          type: notification.type
        },
        defaults: {
          user_id: user.id,
          method: method,
          frequency: frequency,
          type: notification.type
        }
      }).spread(function(delayedNotification, created) {
        if (created) {
          log.info('AcDelayedNotification Created', { delayedNotification: toJson(delayedNotification), context: 'create' });
        } else {
          log.info('AcDelayedNotification Loaded', { delayedNotification: toJson(delayedNotification), context: 'loaded' });
        }
        delayedNotification.addDelayedNotification(notification).then(function (results) {
          if (delayedNotification.delivered) {
            delayedNotification.delivered = false;
            delayedNotification.save().then(function (results) {
              callback();
            });
          } else {
            callback();
          }
        });
      }).catch(function (error) {
        callback(error);
      });
    }
  } else {
    callback();
  }
};

module.exports = {
  filterNotificationForDelivery: filterNotificationForDelivery
};<commit_msg>Debug notifications<commit_after>var models = require("../../../models");
var log = require('../../utils/logger');
var toJson = require('../../utils/to_json');
var async = require('async');
var queue = require('../../workers/queue');

var filterNotificationForDelivery = function (notification, user, notification_settings_type, template, subject, callback) {
  var method = user.notifications_settings[notification_settings_type].method;
  var frequency = user.notifications_settings[notification_settings_type].frequency;

  //TODO: Switch from FREQUENCY_AS_IT_HAPPENS if user has had a lot of emails > 25 in the hour or something

  console.log("Notification Email Processing", {email: user.email, notification_settings_type: notification_settings_type,
                                                method: method, frequency: frequency});

  if (method !== models.AcNotification.METHOD_MUTED) {
    if (frequency === models.AcNotification.FREQUENCY_AS_IT_HAPPENS) {
      console.log("Notification Email Processing Sending eMail", {email: user.email, method: method, frequency: frequency});
      queue.create('send-one-email', {
        subject: subject,
        template: template,
        user: user,
        domain: notification.AcActivities[0].Domain,
        community: notification.AcActivities[0].Community,
        activity: notification.AcActivities[0],
        post: notification.AcActivities[0].Post,
        point: notification.AcActivities[0].Point
      }).priority('critical').removeOnComplete(true).save();
      callback();
    } else if (user.notifications_settings.my_posts.method != models.AcNotification.METHOD_MUTED) {
      AcDelayedNotification.findOrCreate({
        where: {
          user_id: user.id,
          method: method,
          frequency: frequency,
          type: notification.type
        },
        defaults: {
          user_id: user.id,
          method: method,
          frequency: frequency,
          type: notification.type
        }
      }).spread(function(delayedNotification, created) {
        if (created) {
          log.info('AcDelayedNotification Created', { delayedNotification: toJson(delayedNotification), context: 'create' });
        } else {
          log.info('AcDelayedNotification Loaded', { delayedNotification: toJson(delayedNotification), context: 'loaded' });
        }
        delayedNotification.addDelayedNotification(notification).then(function (results) {
          if (delayedNotification.delivered) {
            delayedNotification.delivered = false;
            delayedNotification.save().then(function (results) {
              callback();
            });
          } else {
            callback();
          }
        });
      }).catch(function (error) {
        callback(error);
      });
    }
  } else {
    callback();
  }
};

module.exports = {
  filterNotificationForDelivery: filterNotificationForDelivery
};<|endoftext|>


<commit_before><commit_msg>use less complicated and faster algorithm for finding expressions<commit_after><|endoftext|>


<commit_before>// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview The module loader for loading modules across the network.
 *
 * Webkit and IE do not guarantee that scripts appended to the document
 * are executed in the order they are added. For production mode, we use
 * XHRs to load scripts, because they do not have this problem and they
 * have superior mechanisms for handling failure. However, XHR-evaled
 * scripts are harder to debug.
 *
 * In debugging mode, we use normal script tags. In order to make this work
 * in WebKit and IE, we load the scripts in serial: we do not execute
 * script B to the document until we are certain that script A is
 * finished loading.
 *
 */

goog.provide('goog.module.ModuleLoader');

goog.require('goog.Disposable');
goog.require('goog.array');
goog.require('goog.debug.Logger');
goog.require('goog.dom');
goog.require('goog.events.Event');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
goog.require('goog.module.AbstractModuleLoader');
goog.require('goog.net.BulkLoader');
goog.require('goog.net.EventType');
goog.require('goog.net.jsloader');

/**
 * A class that loads Javascript modules.
 * @constructor
 * @extends {goog.events.EventTarget}
 * @implements {goog.module.AbstractModuleLoader}
 */
goog.module.ModuleLoader = function() {
  goog.base(this);

  /**
   * Event handler for managing handling events.
   * @type {goog.events.EventHandler}
   * @private
   */
  this.eventHandler_ = new goog.events.EventHandler(this);
};
goog.inherits(goog.module.ModuleLoader, goog.events.EventTarget);

/**
 * A logger.
 * @type {goog.debug.Logger}
 * @protected
 */
goog.module.ModuleLoader.prototype.logger = goog.debug.Logger.getLogger(
    'goog.module.ModuleLoader');

/**
 * Whether debug mode is enabled.
 * @type {boolean}
 * @private
 */
goog.module.ModuleLoader.prototype.debugMode_ = false;

/**
 * Whether source url injection is enabled.
 * @type {boolean}
 * @private
 */
goog.module.ModuleLoader.prototype.sourceUrlInjection_ = false;

/**
 * Gets the debug mode for the loader.
 * @return {boolean} debugMode Whether the debug mode is enabled.
 */
goog.module.ModuleLoader.prototype.getDebugMode = function() {
  return this.debugMode_;
};

/**
 * Sets the debug mode for the loader.
 * @param {boolean} debugMode Whether the debug mode is enabled.
 */
goog.module.ModuleLoader.prototype.setDebugMode = function(debugMode) {
  this.debugMode_ = debugMode;
};

/**
 * When enabled, we will add a sourceURL comment to the end of all scripts
 * to mark their origin.
 *
 * Notice that in most cases, this is far superior to debug mode, because
 * the scripts will load faster on most browsers. (Debug mode is very slow,
 * unless you're using Gecko < 1.9. See the comment at the top of this file.)
 *
 * On WebKit, stack traces will refect the sourceURL comment, so this is also
 * useful for debugging webkit stack traces in production.
 *
 * There is some performance overhead to doing this.
 *
 * TODO(nicksantos): Measure the performance cost, and figure out a decision
 * tree for when users should turn this on. I'm not sure if most users are
 * sophisticated enough to know whether they want this or not, because
 * there are a couple different trade-offs involved. We might want to make
 * debug mode do this on browsers that support sourceURL.
 *
 * @param {boolean} enabled
 * @see http://bugzilla.mozilla.org/show_bug.cgi?id=583083
 */
goog.module.ModuleLoader.prototype.setSourceUrlInjection = function(enabled) {
  this.sourceUrlInjection_ = enabled;
};

/** @return {boolean} Whether we're using source url injection. */
goog.module.ModuleLoader.prototype.usingSourceUrlInjection = function() {
  return this.sourceUrlInjection_;
};

/** @override */
goog.module.ModuleLoader.prototype.loadModules = function(
    ids, moduleInfoMap, opt_successFn, opt_errorFn, opt_timeoutFn,
    opt_forceReload) {
  var uris = [];
  for (var i = 0; i < ids.length; i++) {
    goog.array.extend(uris, moduleInfoMap[ids[i]].getUris());
  }
  this.logger.info('loadModules ids:' + ids + ' uris:' + uris);

  if (this.getDebugMode()) {
    // In debug mode use <script> tags rather than XHRs to load the files.
    // This makes it possible to debug and inspect stack traces more easily.
    // It's also possible to use it to load JavaScript files that are hosted on
    // another domain.
    goog.net.jsloader.loadMany(uris);
  } else {
    var bulkLoader = new goog.net.BulkLoader(uris);
    var eventHandler = this.eventHandler_;
    eventHandler.listen(
        bulkLoader,
        goog.net.EventType.SUCCESS,
        goog.bind(this.handleSuccess_, this, bulkLoader, ids,
            opt_successFn, opt_errorFn),
        false,
        null);
    eventHandler.listen(
        bulkLoader,
        goog.net.EventType.ERROR,
        goog.bind(this.handleError_, this, bulkLoader, ids, opt_errorFn),
        false,
        null);
    // TODO(user): Need to handle timeouts in the module loading code.

    bulkLoader.load();
  }
};

/**
 * Evaluate the JS code.
 * @param {Array.<string>} moduleIds The module ids.
 * @param {string} jsCode The JS code.
 * @return {boolean} Whether the JS code was evaluated successfully.
 */
goog.module.ModuleLoader.prototype.evaluateCode = function(
    moduleIds, jsCode) {
  var success = true;
  try {
    goog.globalEval(jsCode);
  } catch (e) {
    success = false;
    // TODO(user): Consider throwing an exception here.
    this.logger.warning('Loaded incomplete code for module(s): ' +
        moduleIds, e);
  }

  this.dispatchEvent(
      new goog.module.ModuleLoader.Event(
          goog.module.ModuleLoader.EventType.EVALUATE_CODE, moduleIds));

  return success;
};

/**
 * Handles a successful response to a request for one or more modules.
 * @param {string} jsCode the JS code.
 * @param {Array.<string>} moduleIds The ids of the modules requested.
 * @param {function()} successFn The callback for success.
 * @param {function(?number)} errorFn The callback for error.
 * @protected
 */
goog.module.ModuleLoader.prototype.handleRequestSuccess = function(
    jsCode, moduleIds, successFn, errorFn) {
  var success = this.evaluateCode(moduleIds, jsCode);
  if (!success) {
    this.handleRequestError(moduleIds, errorFn, null);
  } else if (success && successFn) {
    successFn();
  }
};

/**
 * Handles an error during a request for one or more modules.
 * @param {Array.<string>} moduleIds The ids of the modules requested.
 * @param {function(?number)} errorFn The function to call on failure.
 * @param {?number} status The response status.
 * @protected
 */
goog.module.ModuleLoader.prototype.handleRequestError = function(
    moduleIds, errorFn, status) {
  this.dispatchEvent(
      new goog.module.ModuleLoader.Event(
          goog.module.ModuleLoader.EventType.REQUEST_ERROR, moduleIds));

  this.logger.warning('Request failed for module(s): ' + moduleIds);

  if (errorFn) {
    errorFn(status);
  }
};

/**
 * Handles a timeout during a request for one or more modules.
 * @param {Array.<string>} moduleIds The ids of the modules requested.
 * @param {function()} timeoutFn The function to call on timeout.
 * @protected
 */
goog.module.ModuleLoader.prototype.handleRequestTimeout = function(
    moduleIds, timeoutFn) {
  this.logger.warning('Request timed out for module(s): ' + moduleIds);

  if (timeoutFn) {
    timeoutFn();
  }
};

/**
 * Handles a successful response to a request for one or more modules.
 *
 * @param {goog.net.BulkLoader} bulkLoader The bulk loader.
 * @param {Array.<string>} moduleIds The ids of the modules requested.
 * @param {function()} successFn The callback for success.
 * @param {function(?number)} errorFn The callback for error.
 * @private
 */
goog.module.ModuleLoader.prototype.handleSuccess_ = function(
    bulkLoader, moduleIds, successFn, errorFn) {
  this.logger.info('Code loaded for module(s): ' + moduleIds);
  this.dispatchEvent(
      new goog.module.ModuleLoader.Event(
          goog.module.ModuleLoader.EventType.REQUEST_SUCCESS, moduleIds));

  var contents = bulkLoader.getResponseTexts();
  if (this.usingSourceUrlInjection()) {
    // TODO(nicksantos): It's not really clear how to reconcile this with
    // people who override handleRequestSuccess. Let's just punt for now.
    var uris = bulkLoader.getRequestUris();
    for (var i = 0; i < uris.length; i++) {
      var uri = uris[i];
      var success = this.evaluateCode(
          moduleIds, contents[i] + ' //@ sourceURL=' + uri);
      if (!success) {
        this.handleRequestError(moduleIds, errorFn, null);
        break;
      }
    }

    if (success && successFn) {
      successFn();
    }
  } else {
    this.handleRequestSuccess(
        contents.join('\n'), moduleIds, successFn, errorFn);
  }

  // NOTE: A bulk loader instance is used for loading a set of module ids. Once
  // these modules have been loaded succesfully or in error the bulk loader
  // should be disposed as it is not needed anymore. A new bulk loader is
  // instantiated for any new modules to be loaded. The dispose is called
  // on a timer so that the bulkloader has a chance to release its
  // objects.
  goog.Timer.callOnce(bulkLoader.dispose, 5, bulkLoader);
};

/**
 * Handles an error during a request for one or more modules.
 * @param {goog.net.BulkLoader} bulkLoader The bulk loader.
 * @param {Array.<string>} moduleIds The ids of the modules requested.
 * @param {function(?number)} errorFn The function to call on failure.
 * @param {number} status The response status.
 * @private
 */
goog.module.ModuleLoader.prototype.handleError_ = function(
    bulkLoader, moduleIds, errorFn, status) {
  this.handleRequestError(moduleIds, errorFn, status);

  // NOTE: A bulk loader instance is used for loading a set of module ids. Once
  // these modules have been loaded succesfully or in error the bulk loader
  // should be disposed as it is not needed anymore. A new bulk loader is
  // instantiated for any new modules to be loaded. The dispose is called
  // on another thread so that the bulkloader has a chance to release its
  // objects.
  goog.Timer.callOnce(bulkLoader.dispose, 5, bulkLoader);
};

/** @override */
goog.module.ModuleLoader.prototype.disposeInternal = function() {
  goog.module.ModuleLoader.superClass_.disposeInternal.call(this);

  this.eventHandler_.dispose();
  this.eventHandler_ = null;
};

/**
 * @enum {string}
 */
goog.module.ModuleLoader.EventType = {
  /** Called after the code for a module is evaluated. */
  EVALUATE_CODE: goog.events.getUniqueId('evaluateCode'),

  /** Called when the BulkLoader finishes successfully. */
  REQUEST_SUCCESS: goog.events.getUniqueId('requestSuccess'),

  /** Called when the BulkLoader fails, or code loading fails. */
  REQUEST_ERROR: goog.events.getUniqueId('requestError')
};

/**
 * @param {goog.module.ModuleLoader.EventType} type The type.
 * @param {Array.<string>} moduleIds The ids of the modules being evaluated.
 * @constructor
 * @extends {goog.events.Event}
 */
goog.module.ModuleLoader.Event = function(type, moduleIds) {
  goog.base(this, type);

  /**
   * @type {Array.<string>}
   */
  this.moduleIds = moduleIds;
};
goog.inherits(goog.module.ModuleLoader.Event, goog.events.Event);
<commit_msg><commit_after>// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview The module loader for loading modules across the network.
 *
 * Webkit and IE do not guarantee that scripts appended to the document
 * are executed in the order they are added. For production mode, we use
 * XHRs to load scripts, because they do not have this problem and they
 * have superior mechanisms for handling failure. However, XHR-evaled
 * scripts are harder to debug.
 *
 * In debugging mode, we use normal script tags. In order to make this work
 * in WebKit and IE, we load the scripts in serial: we do not execute
 * script B to the document until we are certain that script A is
 * finished loading.
 *
 */

goog.provide('goog.module.ModuleLoader');

goog.require('goog.Disposable');
goog.require('goog.array');
goog.require('goog.debug.Logger');
goog.require('goog.dom');
goog.require('goog.events.Event');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
goog.require('goog.module.AbstractModuleLoader');
goog.require('goog.net.BulkLoader');
goog.require('goog.net.EventType');
goog.require('goog.net.jsloader');

/**
 * A class that loads Javascript modules.
 * @constructor
 * @extends {goog.events.EventTarget}
 * @implements {goog.module.AbstractModuleLoader}
 */
goog.module.ModuleLoader = function() {
  goog.base(this);

  /**
   * Event handler for managing handling events.
   * @type {goog.events.EventHandler}
   * @private
   */
  this.eventHandler_ = new goog.events.EventHandler(this);
};
goog.inherits(goog.module.ModuleLoader, goog.events.EventTarget);

/**
 * A logger.
 * @type {goog.debug.Logger}
 * @protected
 */
goog.module.ModuleLoader.prototype.logger = goog.debug.Logger.getLogger(
    'goog.module.ModuleLoader');

/**
 * Whether debug mode is enabled.
 * @type {boolean}
 * @private
 */
goog.module.ModuleLoader.prototype.debugMode_ = false;

/**
 * Whether source url injection is enabled.
 * @type {boolean}
 * @private
 */
goog.module.ModuleLoader.prototype.sourceUrlInjection_ = false;

/**
 * Gets the debug mode for the loader.
 * @return {boolean} debugMode Whether the debug mode is enabled.
 */
goog.module.ModuleLoader.prototype.getDebugMode = function() {
  return this.debugMode_;
};

/**
 * Sets the debug mode for the loader.
 * @param {boolean} debugMode Whether the debug mode is enabled.
 */
goog.module.ModuleLoader.prototype.setDebugMode = function(debugMode) {
  this.debugMode_ = debugMode;
};

/**
 * When enabled, we will add a sourceURL comment to the end of all scripts
 * to mark their origin.
 *
 * Notice that in most cases, this is far superior to debug mode, because
 * the scripts will load faster on most browsers. (Debug mode is very slow,
 * unless you're using Gecko < 1.9. See the comment at the top of this file.)
 *
 * On WebKit, stack traces will refect the sourceURL comment, so this is also
 * useful for debugging webkit stack traces in production.
 *
 * There is some performance overhead to doing this.
 *
 * TODO(nicksantos): Measure the performance cost, and figure out a decision
 * tree for when users should turn this on. I'm not sure if most users are
 * sophisticated enough to know whether they want this or not, because
 * there are a couple different trade-offs involved. We might want to make
 * debug mode do this on browsers that support sourceURL.
 *
 * @param {boolean} enabled
 * @see http://bugzilla.mozilla.org/show_bug.cgi?id=583083
 */
goog.module.ModuleLoader.prototype.setSourceUrlInjection = function(enabled) {
  this.sourceUrlInjection_ = enabled;
};

/** @return {boolean} Whether we're using source url injection. */
goog.module.ModuleLoader.prototype.usingSourceUrlInjection = function() {
  return this.sourceUrlInjection_;
};

/** @override */
goog.module.ModuleLoader.prototype.loadModules = function(
    ids, moduleInfoMap, opt_successFn, opt_errorFn, opt_timeoutFn,
    opt_forceReload) {
  var uris = [];
  for (var i = 0; i < ids.length; i++) {
    goog.array.extend(uris, moduleInfoMap[ids[i]].getUris());
  }
  this.logger.info('loadModules ids:' + ids + ' uris:' + uris);

  if (this.getDebugMode()) {
    // In debug mode use <script> tags rather than XHRs to load the files.
    // This makes it possible to debug and inspect stack traces more easily.
    // It's also possible to use it to load JavaScript files that are hosted on
    // another domain.
    goog.net.jsloader.loadMany(uris);
  } else {
    var bulkLoader = new goog.net.BulkLoader(uris);
    var eventHandler = this.eventHandler_;
    eventHandler.listen(
        bulkLoader,
        goog.net.EventType.SUCCESS,
        goog.bind(this.handleSuccess_, this, bulkLoader, ids,
            opt_successFn, opt_errorFn),
        false,
        null);
    eventHandler.listen(
        bulkLoader,
        goog.net.EventType.ERROR,
        goog.bind(this.handleError_, this, bulkLoader, ids, opt_errorFn),
        false,
        null);
    // TODO(user): Need to handle timeouts in the module loading code.

    bulkLoader.load();
  }
};

/**
 * Evaluate the JS code.
 * @param {Array.<string>} moduleIds The module ids.
 * @param {Array.<string>} uris The uris of the resources.
 * @param {Array.<string>} texts The response texts of the resources..
 * @return {boolean} Whether the JS code was evaluated successfully.
 * @private
 */
goog.module.ModuleLoader.prototype.evaluateCode_ = function(
    moduleIds, uris, texts) {
  var success = true;
  try {
    if (this.usingSourceUrlInjection()) {
      for (var i = 0; i < uris.length; i++) {
        var uri = uris[i];
        goog.globalEval(texts[i] + ' //@ sourceURL=' + uri);
      }
    } else {
      goog.globalEval(texts.join('\n'));
    }
  } catch (e) {
    success = false;
    // TODO(user): Consider throwing an exception here.
    this.logger.warning('Loaded incomplete code for module(s): ' +
        moduleIds, e);
  }

  this.dispatchEvent(
      new goog.module.ModuleLoader.Event(
          goog.module.ModuleLoader.EventType.EVALUATE_CODE, moduleIds));

  return success;
};

/**
 * Handles a successful response to a request for one or more modules.
 *
 * @param {goog.net.BulkLoader} bulkLoader The bulk loader.
 * @param {Array.<string>} moduleIds The ids of the modules requested.
 * @param {function()} successFn The callback for success.
 * @param {function(?number)} errorFn The callback for error.
 * @private
 */
goog.module.ModuleLoader.prototype.handleSuccess_ = function(
    bulkLoader, moduleIds, successFn, errorFn) {
  this.logger.info('Code loaded for module(s): ' + moduleIds);
  this.dispatchEvent(
      new goog.module.ModuleLoader.Event(
          goog.module.ModuleLoader.EventType.REQUEST_SUCCESS, moduleIds));

  var success = this.evaluateCode_(
      moduleIds, bulkLoader.getRequestUris(), bulkLoader.getResponseTexts());
  if (!success) {
    this.handleErrorHelper_(moduleIds, errorFn, null);
  } else if (success && successFn) {
    successFn();
  }

  // NOTE: A bulk loader instance is used for loading a set of module ids. Once
  // these modules have been loaded succesfully or in error the bulk loader
  // should be disposed as it is not needed anymore. A new bulk loader is
  // instantiated for any new modules to be loaded. The dispose is called
  // on a timer so that the bulkloader has a chance to release its
  // objects.
  goog.Timer.callOnce(bulkLoader.dispose, 5, bulkLoader);
};

/**
 * Handles an error during a request for one or more modules.
 * @param {goog.net.BulkLoader} bulkLoader The bulk loader.
 * @param {Array.<string>} moduleIds The ids of the modules requested.
 * @param {function(?number)} errorFn The function to call on failure.
 * @param {number} status The response status.
 * @private
 */
goog.module.ModuleLoader.prototype.handleError_ = function(
    bulkLoader, moduleIds, errorFn, status) {
  this.handleErrorHelper_(moduleIds, errorFn, status);

  // NOTE: A bulk loader instance is used for loading a set of module ids. Once
  // these modules have been loaded succesfully or in error the bulk loader
  // should be disposed as it is not needed anymore. A new bulk loader is
  // instantiated for any new modules to be loaded. The dispose is called
  // on another thread so that the bulkloader has a chance to release its
  // objects.
  goog.Timer.callOnce(bulkLoader.dispose, 5, bulkLoader);
};

/**
 * Handles an error during a request for one or more modules.
 * @param {Array.<string>} moduleIds The ids of the modules requested.
 * @param {function(?number)} errorFn The function to call on failure.
 * @param {?number} status The response status.
 * @private
 */
goog.module.ModuleLoader.prototype.handleErrorHelper_ = function(
    moduleIds, errorFn, status) {
  this.dispatchEvent(
      new goog.module.ModuleLoader.Event(
          goog.module.ModuleLoader.EventType.REQUEST_ERROR, moduleIds));

  this.logger.warning('Request failed for module(s): ' + moduleIds);

  if (errorFn) {
    errorFn(status);
  }
};

/** @override */
goog.module.ModuleLoader.prototype.disposeInternal = function() {
  goog.module.ModuleLoader.superClass_.disposeInternal.call(this);

  this.eventHandler_.dispose();
  this.eventHandler_ = null;
};

/**
 * @enum {string}
 */
goog.module.ModuleLoader.EventType = {
  /** Called after the code for a module is evaluated. */
  EVALUATE_CODE: goog.events.getUniqueId('evaluateCode'),

  /** Called when the BulkLoader finishes successfully. */
  REQUEST_SUCCESS: goog.events.getUniqueId('requestSuccess'),

  /** Called when the BulkLoader fails, or code loading fails. */
  REQUEST_ERROR: goog.events.getUniqueId('requestError')
};

/**
 * @param {goog.module.ModuleLoader.EventType} type The type.
 * @param {Array.<string>} moduleIds The ids of the modules being evaluated.
 * @constructor
 * @extends {goog.events.Event}
 */
goog.module.ModuleLoader.Event = function(type, moduleIds) {
  goog.base(this, type);

  /**
   * @type {Array.<string>}
   */
  this.moduleIds = moduleIds;
};
goog.inherits(goog.module.ModuleLoader.Event, goog.events.Event);
<|endoftext|>


<commit_before>$(function(){

	var config = {
		api_path : window.location.origin+'/api/',
		ctrl_path : window.location.origin+'/controllers/',
		view_path : 'templates/',
		element : $('div.view'),
	};

	$.jqMVC.config(config);

	$.jqMVC.before();

	$.jqMVC.addSvc('nav',function(user){
		console.log('nav service');
		twig({
			href: config.view_path+'nav.twig',
			load: function(template) {
				$('nav').html(template.render(user));
			}
		});
	});

	$.jqMVC.addSvc('csrf',function(){
		return $('meta[name="csrf"]').attr('content');
	});

	$.getJSON(config.api_path+'init.json',function(data){
		$('head').append('<meta name="csrf" content="'+data.result.csrf+'" />');
		$.jqMVC.svc('nav',data.result);
	});

	$.jqMVC
	.path('/',function(data){
		$.jqMVC.render('index.twig',{},function(){
			console.log('index callback');
			$.jqMVC.controller('index.js?version='+ (new Date().getTime() / 1000 ) );
			$.jqMVC.done();
		});

	})
	.path('/404',function(data){
		var args = {
			code: 404,
			error: '404 Not Found'
		};
		$.jqMVC.render('error.twig',args,function(){
			$('title').html('404 Not Found');
			$.jqMVC.done();
		});
	});

	$.jqMVC.run();
});<commit_msg>added some comments to the demo<commit_after>$(function(){

	var config = {
		api_path : window.location.origin+'/api/',
		ctrl_path : window.location.origin+'/controllers/',
		view_path : 'templates/',
		element : $('div.view'),
	};

	$.jqMVC.config(config);

	$.jqMVC.before(); // before() starts the progress bar. done() stops and removes it.

	//like services in angular, invokable at your leisure.
	$.jqMVC.addSvc('nav',function(user){
		console.log('nav service');
		twig({
			href: config.view_path+'nav.twig',
			load: function(template) {
				$('nav').html(template.render(user));
			}
		});
	});
	//this simple service returns our csrf token for usage with our api.
	$.jqMVC.addSvc('csrf',function(){
		return $('meta[name="csrf"]').attr('content');
	});

	//before we can initialize our application, we need to get our csrf token and find out
	//if the user is logged in. init.json provides us that data. lets get it and invoke our nav service with the result.
	$.getJSON(config.api_path+'init.json',function(data){
		//first we append the csrf token to our meta tag that stores the token.
		$('head').append('<meta name="csrf" content="'+data.result.csrf+'" />');
		//now we invoke our nav service.
		$.jqMVC.svc('nav',data.result);
	});

	//lets set up some routes.
	//do not use normal href's in your sites links. instead use `data-href` attribute.
	$.jqMVC
	.path('/',function(data){
		//to render a template, call jqMVC's render method signature: template,template args, callback (optional)
		$.jqMVC.render('index.twig',{},function(){
			//here i want to use the callback to instantiate my index controller.
			//ill append the current timestamp to the request to always load  fresh copy of the controller.
			$.jqMVC.controller('index.js?version='+ (new Date().getTime() / 1000 ) );
			//from the standpoint of our application, we have fullfilled the request. we need to stop the app now.
			$.jqMVC.done();
		});

	})
	.path('/404',function(data){
		//this example route passes some arguments to our template.
		var args = {
			code: 404,
			error: '404 Not Found'
		};
		$.jqMVC.render('error.twig',args,function(){
			$('title').html('404 Not Found');
			$.jqMVC.done();
		});
	});

	//now that we have fully defined our application, we can run it for the first time.
	//think of run as a server, as it handles the initial request on page load, and nothing else.
	$.jqMVC.run();
});<|endoftext|>


<commit_before>/* Is this needed? */
angular.module("loadmaster",[])
  .config(function($httpProvider){
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
});

/* User controller with angularjs */
function userCtrl($scope) {

	$scope.IS_MOBILE=true
	window.myscope = $scope;
	window.db = $scope.isDatabaseEmpty;

	$scope.shortName = 'WebSqlDB';
	$scope.version = '1.0';
	$scope.displayName = 'WebSqlDB';
	$scope.maxSize = 65535;
	$scope.host = 'http://195.231.85.191:5000';

	$scope.init = function(){
/* 		debugging function */

/* 		$scope.dropTables(); */

/* 		End of debugging functions */
		$scope.initializeDB()
		$scope.isAccessTokenInDatabase()

	    $.mobile.buttonMarkup.hoverDelay = 0;
		$.mobile.defaultPageTransition   = 'none';
	    $.mobile.defaultDialogTransition = 'none';

		if($scope.access_token != ""){
			$scope.checkInterval();
		}
	}

	$scope.checkInterval = function(){
		$scope.intervalID = setInterval(function(){
				$scope.$apply(function(scope){
					document.addEventListener("deviceready", function(){
					}, false);
				scope.checkConnection();
			  	})
				console.log("firing checkConnection")
			}, 5000);
	}

	$scope.isAccessTokenInDatabase = function(){
			// initial variables
		if(!$scope.db){
			$scope.db = openDatabase($scope.shortName, $scope.version, $scope.displayName, $scope.maxSize);
		}
		if (!window.openDatabase) {
			alert('Databases are not supported in this browser.');
			return;
		}

		console.log("is access token in database?")

		$scope.db.transaction(function (tx){
			tx.executeSql('SELECT * FROM Auth', [], function (tx, result){  // Fetch records from SQLite
				var dataset = result.rows;
				if (dataset.length == 0 ){
					$.mobile.changePage("#tokencontainer");
				}
				else if(!!dataset.length){
					console.log("dataset item 1 " + dataset.item(0).imei)
					$scope.access_token = dataset.item(0).access_token;
					$scope.imei = dataset.item(0).imei;

					$.mobile.changePage("#home");
					console.log("access token " + $scope.access_token + "og imei er " + $scope.imei);
				}
			});
		});
	}

	/* check Connection */
	$scope.checkConnection = function(){
		console.log("Checking connection");
		if(navigator.connection.type == Connection.UNKNOWN || navigator.connection.type == Connection.UNKNOWN){
			console.log('Unknown connection');
		} else if(navigator.connection.type == Connection.CELL_3G || navigator.connection.type == Connection.CELL_4G || navigator.connection.type == Connection.WIFI){
			console.log("Found connection. Checking if database is empty ")
			$scope.isDatabaseEmpty();

		}
	}

	/* Is database empty */
	$scope.isDatabaseEmpty = function() {
		if(!$scope.db){
			$scope.db = openDatabase($scope.shortName, $scope.version, $scope.displayName, $scope.maxSize);
		}

		var numberOfRows;

		if (!window.openDatabase) {
			alert('Databases are not supported in this browser.');
			return;
		}

		query = "SELECT * FROM Trip;";
		$scope.db.transaction(function(transaction){
	         transaction.executeSql(query, [], function(tx, results){
		         var dataset = results.rows;
		         if (dataset.length == 0){
			        numberOfRows = results.rows.length;
					console.log("table has "+results.rows.length+" rows. returning "+ numberOfRows);
		         }else if (dataset.length > 0){
			        console.log("Dataset is bigger than 0")
			        var item = dataset.item(0)
					if (item['_is_finished'] == undefined) {
						console.log("first trip is not done")
			        } else if(item['_is_finished'] == 1) {
			        	console.log("first trip is finished. Syncing to database")
				        $scope.syncToDatabase();
			        }
		         }
	         },function error(err){alert('error selecting from database ' + err)}, function success(){});
		});
		return numberOfRows;
	}

	/* Sync to server */
	$scope.syncToDatabase = function () {

		if(!$scope.db){
			$scope.db = openDatabase($scope.shortName, $scope.version, $scope.displayName, $scope.maxSize);
		}

			$scope.db.transaction(function (tx)
				{
					tx.executeSql('SELECT * FROM Trip', [], function (tx, result)  // Fetch records from SQLite
					{
						var dataset = result.rows;
						var trips = new Array();
						for (var i = 0, item = null; i < dataset.length; i++) {
							item = dataset.item(i);
							var trip = {
								trip_id			: item['Id'],
								cargo			: item['_cargo'],
								license_plate 	: item['_license_plate'],
								start_location 	: item['_start_location'],
								start_address 	: item['_start_address'],
								end_location 	: item['_end_location'],
								end_address	 	: item['_end_address'],
								start_timestamp : item['_start_timestamp'],
								end_timestamp 	: item['_end_timestamp'],
								start_comments 	: item['_start_comments'],
								end_comments 	: item['_end_comments']
							};

							if(!!item['_is_finished']){
								console.log(trip)
								trips.push(trip);
							}
						}
						$scope.InsertRecordOnServerFunction(trips);      // Call Function for insert Record into SQl Server
					});
				});
			}

	/* Syncs with server */
	$scope.InsertRecordOnServerFunction = function(trips){  // Function for insert Record into SQl Server
		$.ajax({
			type: "POST",
			url: $scope.host + "/api/v1/trips",
			data :  {
			     access_token	: $scope.access_token, // Skal kun sættes en gang ind i databasen
			     trips			: trips,
			     device_id		: $scope.imei
			 },

			processdata: true,
			success: function (msg)
			{
				console.log('succes!!!!')
				console.log()
				//On Successfull service call
				$scope.dropAllRows(); //Uncomment this when success message is received. Make this function receive synced rows from server
			},
			error: function (msg) {
				window.msg = msg;
				console.log(msg);
				console.log(msg.status);
				if(!!msg.responseText && !!msg.responseText.err_ids){
					if(JSON.parse(msg.responseText).err_ids != 0){
						$scope.dropRowsSynced(JSON.parse(msg.responseText).err_ids)
					}
				}

				else if(msg.status == 401){
					$scope.resetAccessToken()
				}

				else if(msg.status == 404){
					console.log("404 error ")
					}
			}
		});
	};

/* 	Reset access token if incorrect */
	$scope.resetAccessToken = function(){
	 	if(!$scope.db){
			$scope.db = openDatabase($scope.shortName, $scope.version, $scope.displayName, $scope.maxSize);
		}

		console.log("Deleting access token and device id from table")

		if (!window.openDatabase) {
			alert('Databases are not supported in this browser.');
			return;
		}

		/* 	Deletes synced rows from trips table */
		$scope.db.transaction(function(transaction) {
			transaction.executeSql('DELETE FROM Auth', [/* Insert array of IDs of synced rows. See below */]);
			},function error(err){alert('error resetting accesstoken ' + err)}, function success(){}
		);
		console.log("access token er " + $scope.access_token)
		alert("Access token er forkert")
		clearInterval($scope.intervalID);
		$.mobile.changePage("#tokencontainer");
	}

	/* Drops synced rows */
	$scope.dropAllRows = function(){

		 if(!$scope.db){
			$scope.db = openDatabase($scope.shortName, $scope.version, $scope.displayName, $scope.maxSize);
		}
		if (!window.openDatabase) {
			alert('Databases are not supported in this browser.');
			return;
		}

		/* 	Deletes synced rows from trips table */
			$scope.db.transaction(function(transaction) {
				transaction.executeSql('DELETE FROM Trip WHERE _is_finished = 1', [/* Insert array of IDs of synced rows. See below */]);
				},function error(err){alert('error deleting from database ' + err)}, function success(){}
			);
			return false;

		}

		/* Drops synced rows */
	$scope.dropRowsSynced = function(err_ids){

		 if(!$scope.db){
			$scope.db = openDatabase($scope.shortName, $scope.version, $scope.displayName, $scope.maxSize);
		}

		if (!window.openDatabase) {
			alert('Databases are not supported in this browser.');
			return;
		}

		/* 	Deletes synced rows from trips table */
			$scope.db.transaction(function(transaction) {
				transaction.executeSql('DELETE FROM Trip WHERE id <> *', [err_ids]);
				},function error(err){alert('error deleting from database ' + err)}, function success(){}
			);
			return false;
		}

		/* 	Starting new trip*/
	$scope.submitStartNewTrip = function($event){

		$event.preventDefault();
		$.mobile.changePage("#home");
	}

	$scope.submitToken = function($event){

		console.log($scope.access_token)

		// this is the section that actually inserts the values into the User table
		$scope.db.transaction(function(transaction) {
			transaction.executeSql('INSERT INTO AUTH (access_token, imei) VALUES ("'+$scope.access_token+'", "'+$scope.imei+'")',[]);
			},function error(err){alert('error on save to local db ' + err)}, function success(){}
		);

		$scope.checkInterval()
		$event.preventDefault();
		$.mobile.changePage("#home");

		return false;
	}

	/* --------------  Database ---------------- */
	// called when the application loads
	$scope.initializeDB = function(){

			// initial variables

		// This alert is used to make sure the application is loaded correctly
		// you can comment this out once you have the application working
		console.log("DEBUGGING: we are in the InitializeDB function");

		if (!window.openDatabase) {
			// not all mobile devices support databases  if it does not, the following alert will display
			// indicating the device will not be albe to run this application
			alert('Databases are not supported in this browser.');
			return;
		}

		// this line tries to open the database base locally on the device
		// if it does not exist, it will create it and return a database object stored in variable db
		if(!$scope.db){
			$scope.db = openDatabase($scope.shortName, $scope.version, $scope.displayName, $scope.maxSize);
		}
		// this line will try to create the table User in the database justcreated/openned
		$scope.db.transaction(function(tx){

			tx.executeSql( 'CREATE TABLE IF NOT EXISTS Auth(access_token varchar, imei varchar)', []);

			// this line actually creates the table User if it does not exist and sets up the three columns and their types
			// note the UserId column is an auto incrementing column which is useful if you want to pull back distinct rows
			// easily from the table.
			tx.executeSql( 'CREATE TABLE IF NOT EXISTS Trip(Id INTEGER PRIMARY KEY AUTOINCREMENT, _license_plate varchar, _cargo varchar, _start_timestamp int, _start_location int, _start_address varchar,  _start_comments varchar, _end_timestamp int, _end_location int, _end_address varchar, _end_comments varchar, _is_finished int)', [])},
			function error(err){alert('error on init local db ' + err)}, function success(){console.log("database created")}
		)
	}

	// this is the function that puts values into the database from page #home
	$scope.AddStartValuesToDB = function(trip) {
		$scope.startlocation=trip.start_location
		console.log("cargo er " + trip.cargo);

		if (!window.openDatabase) {
			alert('Databases are not supported in this browser.');
			return;
		}

		// this is the section that actually inserts the values into the User table
		$scope.db.transaction(function(transaction) {
			console.log("Cargo er i submit og vi kører nu addstartvalues to db" + $scope.cargo);
			transaction.executeSql('INSERT INTO Trip(_license_plate, _cargo, _start_timestamp, _start_location, _start_address, _start_comments) VALUES ("'+trip.license_plate+'", "'+trip.cargo+'", "'+trip.start_timestamp+'", "'+trip.start_location+'", "'+trip.start_address+'", "'+trip.start_comments+'")');
		},function error(err){alert('error on save to local db ' + err)}, function success(){});
		return false;
	}

	// this is the function that puts values into the database from page #home
	$scope.AddEndValuesToDB = function(trip) {
	 	$scope.endlocation=trip.end_location
		if (!window.openDatabase) {
			alert('Databases are not supported in this browser.');
			return;
		}

		// this is the section that actually inserts the values into the User table
		$scope.db.transaction(function(transaction) {
			transaction.executeSql('UPDATE Trip SET _end_timestamp ="'+trip.end_timestamp+'", _end_location ="'+trip.end_location+'", _end_address ="'+trip.end_address+'", _end_comments ="'+trip.end_comments+'", _is_finished = 1 WHERE Id= last_insert_rowid()',[]);
			},function error(err){alert('error on save to local db ' + err)}, function success(){}
		);
		return false;
	}

/* DEBUGGING functions */

$scope.dropTables = function(){

	shortName = 'WebSqlDB';
	version = '1.0';
	displayName = 'WebSqlDB';
	maxSize = 65535;

	db = openDatabase(shortName, version, displayName, maxSize);

	db.transaction(function(tx){

		// IMPORTANT FOR DEBUGGING!!!!
		// you can uncomment these next twp lines if you want the table Trip and the table Auth to be empty each time the application runs
		tx.executeSql( 'DROP TABLE Trip');
		tx.executeSql( 'DROP TABLE Auth');

	})
}

}

<commit_msg>connection type working<commit_after>/* Is this needed? */
angular.module("loadmaster",[])
  .config(function($httpProvider){
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
});

/* User controller with angularjs */
function userCtrl($scope) {

	$scope.IS_MOBILE=true
	window.myscope = $scope;
	window.db = $scope.isDatabaseEmpty;

	$scope.shortName = 'WebSqlDB';
	$scope.version = '1.0';
	$scope.displayName = 'WebSqlDB';
	$scope.maxSize = 65535;
	$scope.host = 'http://195.231.85.191:5000';

	$scope.init = function(){
/* 		debugging function */

/* 		$scope.dropTables(); */

/* 		End of debugging functions */
		$scope.initializeDB()
		$scope.isAccessTokenInDatabase()

	    $.mobile.buttonMarkup.hoverDelay = 0;
		$.mobile.defaultPageTransition   = 'none';
	    $.mobile.defaultDialogTransition = 'none';

		if($scope.access_token != ""){
			$scope.checkInterval();
		}
	}

	$scope.checkInterval = function(){
		$scope.intervalID = setInterval(function(){
				$scope.$apply(function(scope){
					document.addEventListener("deviceready", function(){
					}, false);
				scope.checkConnection();
			  	})
				console.log("firing checkConnection")
			}, 5000);
	}

	$scope.isAccessTokenInDatabase = function(){
			// initial variables
		if(!$scope.db){
			$scope.db = openDatabase($scope.shortName, $scope.version, $scope.displayName, $scope.maxSize);
		}
		if (!window.openDatabase) {
			alert('Databases are not supported in this browser.');
			return;
		}

		console.log("is access token in database?")

		$scope.db.transaction(function (tx){
			tx.executeSql('SELECT * FROM Auth', [], function (tx, result){  // Fetch records from SQLite
				var dataset = result.rows;
				if (dataset.length == 0 ){
					$.mobile.changePage("#tokencontainer");
				}
				else if(!!dataset.length){
					console.log("dataset item 1 " + dataset.item(0).imei)
					$scope.access_token = dataset.item(0).access_token;
					$scope.imei = dataset.item(0).imei;

					$.mobile.changePage("#home");
					console.log("access token " + $scope.access_token + "og imei er " + $scope.imei);
				}
			});
		});
	}

	/* check Connection */
	$scope.checkConnection = function(){
		console.log("Checking connection");
		if(navigator.connection.type == Connection.UNKNOWN || navigator.connection.type == Connection.NONE || navigator.connection.type == Connection.CELL || navigator.connection.type == Connection.CELL_2G){
			console.log('Unknown connection');
		} else if(navigator.connection.type == Connection.CELL_3G || navigator.connection.type == Connection.CELL_4G || navigator.connection.type == Connection.WIFI ||navigator.connection.type == Connection.ETHERNET){
			console.log("Found connection. Checking if database is empty ")
			$scope.isDatabaseEmpty();

		}
	}

	/* Is database empty */
	$scope.isDatabaseEmpty = function() {
		if(!$scope.db){
			$scope.db = openDatabase($scope.shortName, $scope.version, $scope.displayName, $scope.maxSize);
		}

		var numberOfRows;

		if (!window.openDatabase) {
			alert('Databases are not supported in this browser.');
			return;
		}

		query = "SELECT * FROM Trip;";
		$scope.db.transaction(function(transaction){
	         transaction.executeSql(query, [], function(tx, results){
		         var dataset = results.rows;
		         if (dataset.length == 0){
			        numberOfRows = results.rows.length;
					console.log("table has "+results.rows.length+" rows. returning "+ numberOfRows);
		         }else if (dataset.length > 0){
			        console.log("Dataset is bigger than 0")
			        var item = dataset.item(0)
					if (item['_is_finished'] == undefined) {
						console.log("first trip is not done")
			        } else if(item['_is_finished'] == 1) {
			        	console.log("first trip is finished. Syncing to database")
				        $scope.syncToDatabase();
			        }
		         }
	         },function error(err){alert('error selecting from database ' + err)}, function success(){});
		});
		return numberOfRows;
	}

	/* Sync to server */
	$scope.syncToDatabase = function () {

		if(!$scope.db){
			$scope.db = openDatabase($scope.shortName, $scope.version, $scope.displayName, $scope.maxSize);
		}

			$scope.db.transaction(function (tx)
				{
					tx.executeSql('SELECT * FROM Trip', [], function (tx, result)  // Fetch records from SQLite
					{
						var dataset = result.rows;
						var trips = new Array();
						for (var i = 0, item = null; i < dataset.length; i++) {
							item = dataset.item(i);
							var trip = {
								trip_id			: item['Id'],
								cargo			: item['_cargo'],
								license_plate 	: item['_license_plate'],
								start_location 	: item['_start_location'],
								start_address 	: item['_start_address'],
								end_location 	: item['_end_location'],
								end_address	 	: item['_end_address'],
								start_timestamp : item['_start_timestamp'],
								end_timestamp 	: item['_end_timestamp'],
								start_comments 	: item['_start_comments'],
								end_comments 	: item['_end_comments']
							};

							if(!!item['_is_finished']){
								console.log(trip)
								trips.push(trip);
							}
						}
						$scope.InsertRecordOnServerFunction(trips);      // Call Function for insert Record into SQl Server
					});
				});
			}

	/* Syncs with server */
	$scope.InsertRecordOnServerFunction = function(trips){  // Function for insert Record into SQl Server
		$.ajax({
			type: "POST",
			url: $scope.host + "/api/v1/trips",
			data :  {
			     access_token	: $scope.access_token, // Skal kun sættes en gang ind i databasen
			     trips			: trips,
			     device_id		: $scope.imei
			 },

			processdata: true,
			success: function (msg)
			{
				console.log('succes!!!!')
				console.log()
				//On Successfull service call
				$scope.dropAllRows(); //Uncomment this when success message is received. Make this function receive synced rows from server
			},
			error: function (msg) {
				window.msg = msg;
				console.log(msg);
				console.log(msg.status);
				if(!!msg.responseText && !!msg.responseText.err_ids){
					if(JSON.parse(msg.responseText).err_ids != 0){
						$scope.dropRowsSynced(JSON.parse(msg.responseText).err_ids)
					}
				}

				else if(msg.status == 401){
					$scope.resetAccessToken()
				}

				else if(msg.status == 404){
					console.log("404 error ")
					}
			}
		});
	};

/* 	Reset access token if incorrect */
	$scope.resetAccessToken = function(){
	 	if(!$scope.db){
			$scope.db = openDatabase($scope.shortName, $scope.version, $scope.displayName, $scope.maxSize);
		}

		console.log("Deleting access token and device id from table")

		if (!window.openDatabase) {
			alert('Databases are not supported in this browser.');
			return;
		}

		/* 	Deletes synced rows from trips table */
		$scope.db.transaction(function(transaction) {
			transaction.executeSql('DELETE FROM Auth', [/* Insert array of IDs of synced rows. See below */]);
			},function error(err){alert('error resetting accesstoken ' + err)}, function success(){}
		);
		console.log("access token er " + $scope.access_token)
		alert("Access token er forkert")
		clearInterval($scope.intervalID);
		$.mobile.changePage("#tokencontainer");
	}

	/* Drops synced rows */
	$scope.dropAllRows = function(){

		 if(!$scope.db){
			$scope.db = openDatabase($scope.shortName, $scope.version, $scope.displayName, $scope.maxSize);
		}
		if (!window.openDatabase) {
			alert('Databases are not supported in this browser.');
			return;
		}

		/* 	Deletes synced rows from trips table */
			$scope.db.transaction(function(transaction) {
				transaction.executeSql('DELETE FROM Trip WHERE _is_finished = 1', [/* Insert array of IDs of synced rows. See below */]);
				},function error(err){alert('error deleting from database ' + err)}, function success(){}
			);
			return false;

		}

		/* Drops synced rows */
	$scope.dropRowsSynced = function(err_ids){

		 if(!$scope.db){
			$scope.db = openDatabase($scope.shortName, $scope.version, $scope.displayName, $scope.maxSize);
		}

		if (!window.openDatabase) {
			alert('Databases are not supported in this browser.');
			return;
		}

		/* 	Deletes synced rows from trips table */
			$scope.db.transaction(function(transaction) {
				transaction.executeSql('DELETE FROM Trip WHERE id <> *', [err_ids]);
				},function error(err){alert('error deleting from database ' + err)}, function success(){}
			);
			return false;
		}

		/* 	Starting new trip*/
	$scope.submitStartNewTrip = function($event){

		$event.preventDefault();
		$.mobile.changePage("#home");
	}

	$scope.submitToken = function($event){

		console.log($scope.access_token)

		// this is the section that actually inserts the values into the User table
		$scope.db.transaction(function(transaction) {
			transaction.executeSql('INSERT INTO AUTH (access_token, imei) VALUES ("'+$scope.access_token+'", "'+$scope.imei+'")',[]);
			},function error(err){alert('error on save to local db ' + err)}, function success(){}
		);

		$scope.checkInterval()
		$event.preventDefault();
		$.mobile.changePage("#home");

		return false;
	}

	/* --------------  Database ---------------- */
	// called when the application loads
	$scope.initializeDB = function(){

			// initial variables

		// This alert is used to make sure the application is loaded correctly
		// you can comment this out once you have the application working
		console.log("DEBUGGING: we are in the InitializeDB function");

		if (!window.openDatabase) {
			// not all mobile devices support databases  if it does not, the following alert will display
			// indicating the device will not be albe to run this application
			alert('Databases are not supported in this browser.');
			return;
		}

		// this line tries to open the database base locally on the device
		// if it does not exist, it will create it and return a database object stored in variable db
		if(!$scope.db){
			$scope.db = openDatabase($scope.shortName, $scope.version, $scope.displayName, $scope.maxSize);
		}
		// this line will try to create the table User in the database justcreated/openned
		$scope.db.transaction(function(tx){

			tx.executeSql( 'CREATE TABLE IF NOT EXISTS Auth(access_token varchar, imei varchar)', []);

			// this line actually creates the table User if it does not exist and sets up the three columns and their types
			// note the UserId column is an auto incrementing column which is useful if you want to pull back distinct rows
			// easily from the table.
			tx.executeSql( 'CREATE TABLE IF NOT EXISTS Trip(Id INTEGER PRIMARY KEY AUTOINCREMENT, _license_plate varchar, _cargo varchar, _start_timestamp int, _start_location int, _start_address varchar,  _start_comments varchar, _end_timestamp int, _end_location int, _end_address varchar, _end_comments varchar, _is_finished int)', [])},
			function error(err){alert('error on init local db ' + err)}, function success(){console.log("database created")}
		)
	}

	// this is the function that puts values into the database from page #home
	$scope.AddStartValuesToDB = function(trip) {
		$scope.startlocation=trip.start_location
		console.log("cargo er " + trip.cargo);

		if (!window.openDatabase) {
			alert('Databases are not supported in this browser.');
			return;
		}

		// this is the section that actually inserts the values into the User table
		$scope.db.transaction(function(transaction) {
			console.log("Cargo er i submit og vi kører nu addstartvalues to db" + $scope.cargo);
			transaction.executeSql('INSERT INTO Trip(_license_plate, _cargo, _start_timestamp, _start_location, _start_address, _start_comments) VALUES ("'+trip.license_plate+'", "'+trip.cargo+'", "'+trip.start_timestamp+'", "'+trip.start_location+'", "'+trip.start_address+'", "'+trip.start_comments+'")');
		},function error(err){alert('error on save to local db ' + err)}, function success(){});
		return false;
	}

	// this is the function that puts values into the database from page #home
	$scope.AddEndValuesToDB = function(trip) {
	 	$scope.endlocation=trip.end_location
		if (!window.openDatabase) {
			alert('Databases are not supported in this browser.');
			return;
		}

		// this is the section that actually inserts the values into the User table
		$scope.db.transaction(function(transaction) {
			transaction.executeSql('UPDATE Trip SET _end_timestamp ="'+trip.end_timestamp+'", _end_location ="'+trip.end_location+'", _end_address ="'+trip.end_address+'", _end_comments ="'+trip.end_comments+'", _is_finished = 1 WHERE Id= last_insert_rowid()',[]);
			},function error(err){alert('error on save to local db ' + err)}, function success(){}
		);
		return false;
	}

/* DEBUGGING functions */

$scope.dropTables = function(){

	shortName = 'WebSqlDB';
	version = '1.0';
	displayName = 'WebSqlDB';
	maxSize = 65535;

	db = openDatabase(shortName, version, displayName, maxSize);

	db.transaction(function(tx){

		// IMPORTANT FOR DEBUGGING!!!!
		// you can uncomment these next twp lines if you want the table Trip and the table Auth to be empty each time the application runs
		tx.executeSql( 'DROP TABLE Trip');
		tx.executeSql( 'DROP TABLE Auth');

	})
}

}

<|endoftext|>


<commit_before>var SIPU = (function(SIPU, $, undefined) {
	"use strict";
	//master function
	var Selector = function (){
		this.node = "";
		this.active = false;
	};

	function getSelector(val, tag) {
		var temp = [];
		var node = document.getElementsByTagName("*");
		for (var i = 0; i < node.length ; i++ ) {
			if (node[i].getAttribute("SIPU-INTERACTIVE") === val && node[i].tagName === tag) {
				var a = new Selector();
				a.node = node[i];
				temp.push(a);
			}
		}
		return temp;
	}

	function loadImage(imgsrc) {
		var images = [];
		var count = 0;
		$.each (imgsrc,function (index) {
			var imageObj = new Image();
			imageObj.onload = function () {
				images.push(imageObj);
			};
			imageObj.src = imgsrc[index];
		});
		return images;
	}

	function getimagelist(imgList) {
		var imgs = [];
		$.each(imgList,function (index){
			$(imgList[index].node).hide();
			var chimg = $(imgList[index].node).children("img");
			var chimglist = [];
			$.each(chimg,function() {
				chimglist.push($(this).attr("src"));
			});
			imgs.push(loadImage(chimglist));
		});
		return imgs;
	}

	function do_input_event (ran, can, iamgelist) {
		$.each(ran,function (index) {
			$(ran[index].node).on("change mousemove input", function () {
				$(this).attr("min","1");
				$(this).attr("max","255");
				do_canvas_event(can[index].node, iamgelist[index], $(this).val());
			});
		});
	}

	function do_canvas_event (can, img, val) {
		var ctx = can.getContext("2d");
		var sq = Math.ceil( val / (255 / (img.length - 1)));
		var sqfl = Math.ceil(val / (255 / (img.length - 1))) - (val / (255 / (img.length - 1)));

		ctx.drawImage(img[sq-1],0,0);
		ctx.globalAlpha = 1-sqfl;
		ctx.drawImage(img[sq],0,0);
		ctx.globalAlpha = sqfl;
	}

	function do_play_button(ran, can, img) {
		$.each(ran,function (index) {
			var i = $(ran[index].node).val();
			var max = $(ran[index].node).attr("max");
			var timerId = setInterval(function () {
				ran[index].node.value = i;
				do_canvas_event(can[index].node, img[index], i);
				if (i === max) { clearInterval(timerId); }
				i++;
			} ,30);
		});
	}

	SIPU.run = function () {
		var image_list = getimagelist(getSelector("timelapse","DL"));
		var input_range_list = getSelector("timelapse","INPUT");
		var canvas_list = getSelector("timelapse","CANVAS");

		do_input_event(input_range_list, canvas_list, image_list);
	};
	return SIPU;
})(window.SIPU || {}, jQuery);
SIPU.run();
<commit_msg>add play button<commit_after>var SIPU = (function(SIPU, $, undefined) {
	"use strict";
	//master function
	var Selector = function (){
		this.node = "";
		this.active = false;
	};

	function getSelector(val, tag) {
		var temp = [];
		var node = document.getElementsByTagName("*");
		for (var i = 0; i < node.length ; i++ ) {
			if (node[i].getAttribute("SIPU-INTERACTIVE") === val && node[i].tagName === tag) {
				var a = new Selector();
				a.node = node[i];
				temp.push(a);
			}
		}
		return temp;
	}

	function loadImage(imgsrc) {
		var images = [];
		var count = 0;
		$.each(imgsrc,function (index) {
			var imageObj = new Image();
			imageObj.onload = function () {
				images.push(imageObj);
			};
			imageObj.src = imgsrc[index];
		});
		return images;
	}

	function getimagelist(imgList) {
		var imgs = [];
		$.each(imgList,function (index){
			$(imgList[index].node).hide();
			var chimg = $(imgList[index].node).children("img");
			var chimglist = [];
			$.each(chimg,function() {
				chimglist.push(this.getAttribute("src"));
			});
			imgs.push(loadImage(chimglist));
		});
		return imgs;
	}

	function do_input_event (ran, can, iamgelist) {
		$.each(ran,function (index) {
			ran[index].node.value = 1;
			ran[index].node.setAttribute("min","1");
			ran[index].node.setAttribute("max","255");
			$(ran[index].node).on("change mousemove input", function () {
				do_canvas_event(can[index].node, iamgelist[index], this.value);
			});
		});
	}

	function do_canvas_event (can, img, val) {
		var ctx = can.getContext("2d");
		var sq = Math.ceil( val / (255 / (img.length - 1)));
		var sqfl = Math.ceil(val / (255 / (img.length - 1))) - (val / (255 / (img.length - 1)));

		ctx.drawImage(img[sq-1],0,0);
		ctx.globalAlpha = 1-sqfl;
		ctx.drawImage(img[sq],0,0);
		ctx.globalAlpha = sqfl;
	}

	function do_play_button(ran, can, img, but) {
		$.each(but,function (index) {
			$(but[index].node).click(function (){
				var i = $(ran[index].node).val();
				var max = $(ran[index].node).attr("max");
				var timerId = setInterval(function () {
					ran[index].node.value = i;
					do_canvas_event(can[index].node, img[index], i);
					if (i === max) { clearInterval(timerId); }
					i++;
				} ,100);
			});
		});
	}

	SIPU.run = function () {
		var image_list = getimagelist(getSelector("timelapse","DL"));
		var input_range_list = getSelector("timelapse","INPUT");
		var canvas_list = getSelector("timelapse","CANVAS");
		var button_list = getSelector("timelapse","BUTTON");

		do_input_event(input_range_list, canvas_list, image_list);
		do_play_button(input_range_list, canvas_list, image_list, button_list);
	};
	return SIPU;
})(window.SIPU || {}, jQuery);
SIPU.run();
<|endoftext|>


<commit_before>var app = app || {};
//var Codemirror = require('../../node_modules/react-codemirror/dist/react-codemirror.min.js')

(function() {
    app.APP_TEST = 1;
    app.STANDARD_TEST = 0;
    app.SERVER_TEST = 2;
    var TestButton  = app.TestButton;
    var CodeEditor = app.CodeEditor;
    var UrlEditor = app.UrlEditor;
    var ResultDisplay = app.ResultDisplay;
    var TokenEditor = app.TokenEditor;
    var UserBtnArea = app.UserBtnArea;
    var Modal = app.Modal;
    var HistoryViewer = app.HistoryViewer;
    var ServerList = app.ServerList
    var TaskSearchView = app.TaskSearchView;
    var FullyDetail = app.FullyDetail;
    app.type2str = function(test_type){
        var typeStr = '';
        switch (test_type)
        {
            case app.APP_TEST:
            typeStr = 'App Test';
            break;
            case app.STANDARD_TEST:
            typeStr = 'Standard Test';
            break;
            case app.SERVER_TEST:
            typeStr = 'Server Test';
            break;
        }
        return typeStr;
    }
    function onChange(newCode) {
        console.log(newCode)
    }
    function updateCode(newCode){
        console.log(newCode);
    }
    var options = {
            lineNumbers: true,
            mode:'java'
        };
    var TesterApp = React.createClass({
        getInitialState: function() {
            return {code:"",url:"", test_type:'', isResultReady:true, isLoading:false, isTestPass:true, isTestFail:false,chosen_server:-1, access_token:null, is_history_show:false, isEditting:false, isCustomedURL:false, isSearchShow:false, isDetailShow:false};
        },
        updateCode:function(newCode){
            this.setState({code:newCode});

        },
        showHistoryView:function(){
            this.setState({is_history_show:!this.state.is_history_show});
        },
        showSearchView:function(){
            this.setState({isSearchShow:!this.state.isSearchShow});
        },
        updateUrl:function(newUrl){
            this.setState({url:newUrl});
        },
        updateAccessToken:function(newToken){
            this.setState({access_token:newToken});
        },
        handleTaskSubmit:function(submitType){
            //this.state.isLoading = !this.state.isLoading;
            //this.setState({isLoading:!this.state.isLoading});

            this.refs.res_area.emptyCurrentDisplay();
            var token = $.cookie('fhir_token');
            if( this.state.isCustomedURL ){
                var post_data = {curr_detail:null,code:this.state.code,language:'python',type:submitType,url:this.state.url,access_token :this.state.access_token, token:token};
            }else{
                if( this.state.chosen_server == -1 ){
                    app.showMsg("Please Choose a Server or Input one");
                    return
                }else{
                    var post_data = {code:this.state.code,language:'python',type:submitType,chosen_server:this.state.chosen_server, token:token};
                }
            }
            console.log(post_data);
            var self = this;
            this.setState({isLoading:true});
            $.ajax({
                url:app.host+ '/home/submit',
                type:'POST',
                data:JSON.stringify(post_data),
                dataType:'json',
                cache:false,
                success:function(data){
                    console.log(data);
                    if( data.isSuccessful ){
                        app.setup_websocket(data.task_id, 1)
                    }else{
                        self.setState({isLoading:false});
                        app.showMsg(data.error);
                    }

                    // var task_id = data.task_id;
                    // var ws_scheme = window.location.protocol == "https" ? "wss" : "ws";
                    // var tasksocket = new WebSocket(ws_scheme + '://localhost:8000/task/' + task_id);
                    // tasksocket.onmessage = function(message){
                    //     var data = JSON.parse(message.data);
                    //     //console.log(data);
                    //     window.comp.setState({isLoading:false});
                    //     window.comp.updateTestResult(data);
                    // };
                    // tasksocket.onopen = function(e){
                    //     tasksocket.send(task_id, 1);
                    // }
                }
            });
            //connect with websocket
        },
        componentDidMount:function(){
            window.comp = this;
        },
        updateTestResult:function(res){
            this.setState({isResultReady:true, isLoading:false});
            this.refs.res_area.displayResult(res);
        },
        handleHideModal(){
            this.setState({is_history_show:false});
        },
        handleSearchHideModal(){
            this.setState({isSearchShow:false});
        },
        showFullyDetail:function(detail){
            if( this.state.curr_detail === detail ){
                this.setState({isDetailShow:!this.state.isDetailShow})
            }else{
                this.setState({isDetailShow:true, curr_detail:detail})
            }
        },
        toggleCustomedURL:function(){
            this.setState({isCustomedURL:!this.state.isCustomedURL});
        },
        toggleEditting:function(){
            this.setState({isEditting:!this.state.isEditting});
        },
        updateChosenServer:function(server_id){
            this.setState({chosen_server:server_id});
        },
        render:function(){
            return (

                    <UserBtnArea history_action={this.showHistoryView} search_action={this.showSearchView}/>

                        <ServerList updateServer={this.updateChosenServer}/>

                            <TestButton btn_name="App Test" submitTestTask={this.handleTaskSubmit} btnType={app.APP_TEST}/>
                            <TestButton btn_name="Server Test" submitTestTask={this.handleTaskSubmit} btnType={app.SERVER_TEST}/>
                            <TestButton btn_name="Standard Test" submitTestTask={this.handleTaskSubmit} btnType={app.STANDARD_TEST}/>

                                <input type="checkbox" checked={this.state.isEditting} onChange={this.toggleEditting}/> Code Editor

                                <input type="checkbox" checked={this.state.isCustomedURL} onChange={this.toggleCustomedURL}/> Custome URL

                        {this.state.isCustomedURL ?
<UrlEditor updateUrl={this.updateUrl}/><TokenEditor updateToken={this.updateAccessToken} />
 : null}
                        {this.state.isLoading ?

  : null}
                        {!this.state.isLoading && this.state.isResultReady ? <ResultDisplay showFullyDetail={this.showFullyDetail} ref="res_area"/> : null }
                        {this.state.isEditting ? <CodeEditor updateCode={this.updateCode} language="python"/> : null}

                        { this.state.isDetailShow ? <FullyDetail detail={this.state.curr_detail}/> : null }

                    {this.state.is_history_show ? <Modal handleHideModal={this.handleHideModal} title="History" content={<HistoryViewer />} /> : null}
                    {this.state.isSearchShow ? <Modal handleHideModal={this.handleSearchHideModal} title="History" content={<TaskSearchView />} /> : null}

            );
        }
    });
    function render() {
        ReactDOM.render(
            <TesterApp />,
            document.getElementById('main')
        );
    }
    render();
})();<commit_msg>Fix typos in pages<commit_after>var app = app || {};
//var Codemirror = require('../../node_modules/react-codemirror/dist/react-codemirror.min.js')

(function() {
    app.APP_TEST = 1;
    app.STANDARD_TEST = 0;
    app.SERVER_TEST = 2;
    var TestButton  = app.TestButton;
    var CodeEditor = app.CodeEditor;
    var UrlEditor = app.UrlEditor;
    var ResultDisplay = app.ResultDisplay;
    var TokenEditor = app.TokenEditor;
    var UserBtnArea = app.UserBtnArea;
    var Modal = app.Modal;
    var HistoryViewer = app.HistoryViewer;
    var ServerList = app.ServerList
    var TaskSearchView = app.TaskSearchView;
    var FullyDetail = app.FullyDetail;
    app.type2str = function(test_type){
        var typeStr = '';
        switch (test_type)
        {
            case app.APP_TEST:
            typeStr = 'App Test';
            break;
            case app.STANDARD_TEST:
            typeStr = 'Standard Test';
            break;
            case app.SERVER_TEST:
            typeStr = 'Server Test';
            break;
        }
        return typeStr;
    }
    function onChange(newCode) {
        console.log(newCode)
    }
    function updateCode(newCode){
        console.log(newCode);
    }
    var options = {
            lineNumbers: true,
            mode:'java'
        };
    var TesterApp = React.createClass({
        getInitialState: function() {
            return {code:"",url:"", test_type:'', isResultReady:true, isLoading:false, isTestPass:true, isTestFail:false,chosen_server:-1, access_token:null, is_history_show:false, isEditting:false, isCustomedURL:false, isSearchShow:false, isDetailShow:false};
        },
        updateCode:function(newCode){
            this.setState({code:newCode});

        },
        showHistoryView:function(){
            this.setState({is_history_show:!this.state.is_history_show});
        },
        showSearchView:function(){
            this.setState({isSearchShow:!this.state.isSearchShow});
        },
        updateUrl:function(newUrl){
            this.setState({url:newUrl});
        },
        updateAccessToken:function(newToken){
            this.setState({access_token:newToken});
        },
        handleTaskSubmit:function(submitType){
            //this.state.isLoading = !this.state.isLoading;
            //this.setState({isLoading:!this.state.isLoading});

            this.refs.res_area.emptyCurrentDisplay();
            var token = $.cookie('fhir_token');
            if( this.state.isCustomedURL ){
                var post_data = {curr_detail:null,code:this.state.code,language:'python',type:submitType,url:this.state.url,access_token :this.state.access_token, token:token};
            }else{
                if( this.state.chosen_server == -1 ){
                    app.showMsg("Please Choose a Server or Input one");
                    return
                }else{
                    var post_data = {code:this.state.code,language:'python',type:submitType,chosen_server:this.state.chosen_server, token:token};
                }
            }
            console.log(post_data);
            var self = this;
            this.setState({isLoading:true});
            $.ajax({
                url:app.host+ '/home/submit',
                type:'POST',
                data:JSON.stringify(post_data),
                dataType:'json',
                cache:false,
                success:function(data){
                    console.log(data);
                    if( data.isSuccessful ){
                        app.setup_websocket(data.task_id, 1)
                    }else{
                        self.setState({isLoading:false});
                        app.showMsg(data.error);
                    }

                    // var task_id = data.task_id;
                    // var ws_scheme = window.location.protocol == "https" ? "wss" : "ws";
                    // var tasksocket = new WebSocket(ws_scheme + '://localhost:8000/task/' + task_id);
                    // tasksocket.onmessage = function(message){
                    //     var data = JSON.parse(message.data);
                    //     //console.log(data);
                    //     window.comp.setState({isLoading:false});
                    //     window.comp.updateTestResult(data);
                    // };
                    // tasksocket.onopen = function(e){
                    //     tasksocket.send(task_id, 1);
                    // }
                }
            });
            //connect with websocket
        },
        componentDidMount:function(){
            window.comp = this;
        },
        updateTestResult:function(res){
            this.setState({isResultReady:true, isLoading:false});
            this.refs.res_area.displayResult(res);
        },
        handleHideModal(){
            this.setState({is_history_show:false});
        },
        handleSearchHideModal(){
            this.setState({isSearchShow:false});
        },
        showFullyDetail:function(detail){
            if( this.state.curr_detail === detail ){
                this.setState({isDetailShow:!this.state.isDetailShow})
            }else{
                this.setState({isDetailShow:true, curr_detail:detail})
            }
        },
        toggleCustomedURL:function(){
            this.setState({isCustomedURL:!this.state.isCustomedURL});
        },
        toggleEditting:function(){
            this.setState({isEditting:!this.state.isEditting});
        },
        updateChosenServer:function(server_id){
            this.setState({chosen_server:server_id});
        },
        render:function(){
            return (

                    <UserBtnArea history_action={this.showHistoryView} search_action={this.showSearchView}/>

                        <ServerList updateServer={this.updateChosenServer}/>

                            <TestButton btn_name="App Test" submitTestTask={this.handleTaskSubmit} btnType={app.APP_TEST}/>
                            <TestButton btn_name="Server Test" submitTestTask={this.handleTaskSubmit} btnType={app.SERVER_TEST}/>
                            <TestButton btn_name="Level Test" submitTestTask={this.handleTaskSubmit} btnType={app.STANDARD_TEST}/>

                                <input type="checkbox" checked={this.state.isEditting} onChange={this.toggleEditting}/> Code Editor

                                <input type="checkbox" checked={this.state.isCustomedURL} onChange={this.toggleCustomedURL}/> Custom URL

                        {this.state.isCustomedURL ?
<UrlEditor updateUrl={this.updateUrl}/><TokenEditor updateToken={this.updateAccessToken} />
 : null}
                        {this.state.isLoading ?

  : null}
                        {!this.state.isLoading && this.state.isResultReady ? <ResultDisplay showFullyDetail={this.showFullyDetail} ref="res_area"/> : null }
                        {this.state.isEditting ? <CodeEditor updateCode={this.updateCode} language="python"/> : null}

                        { this.state.isDetailShow ? <FullyDetail detail={this.state.curr_detail}/> : null }

                    {this.state.is_history_show ? <Modal handleHideModal={this.handleHideModal} title="History" content={<HistoryViewer />} /> : null}
                    {this.state.isSearchShow ? <Modal handleHideModal={this.handleSearchHideModal} title="History" content={<TaskSearchView />} /> : null}

            );
        }
    });
    function render() {
        ReactDOM.render(
            <TesterApp />,
            document.getElementById('main')
        );
    }
    render();
})();<|endoftext|>


<commit_before>const assert = require('assert');
const langsData = require('../langs.json');

const languages = {
	0: null,
	1: null,
	2: null,
	3: null,
	4: null,
	5: null,
	6: null,
	7: null,
	8: 'recurse',
	9: 'hbcht',
	10: 'cmm',
	11: 'cubically',
	12: 'cardinal',
	13: null,
	14: null,
	15: null,
	16: null,
	17: null,
	18: null,
	19: null,
	20: null,
	21: null,
	22: null,
	23: null,
	24: null,
	25: null,
	26: null,
	27: null,
	28: null,
	29: null,
	30: null,
	31: null,
	32: 'whitespace',
	33: 'apl',
	34: null,
	35: null,
	36: 'picfunge',
	37: null,
	38: null,
	39: null,
	40: null,
	41: null,
	42: null,
	43: null,
	44: null,
	45: null,
	46: null,
	47: null,
	48: null,
	49: null,
	50: null,
	51: null,
	52: 'fernando',
	53: 'labyrinth',
	54: 'aubergine',
	55: 'multi-reader',
	56: 'convex',
	57: 'befunge98',
	58: 'golfish',
	59: 'ezhil',
	60: 'cy',
	61: 'snobol',
	62: '2sable',
	63: 'awk',
	64: 'powershell',
	65: 'floater',
	66: 'irc',
	67: 'braille',
	68: 'typhon',
	69: null,
	70: null,
	71: null,
	72: null,
	73: null,
	74: null,
	75: null,
	76: 'wake',
	77: 'simula',
	78: null,
	79: null,
	80: 'coq',
	81: 'function2d',
	82: null,
	83: null,
	84: 'fish',
	85: 'nuts',
	86: null,
	87: null,
	88: 'unicue',
	89: 'tetris',
	90: null,
	91: null,
	92: 'exchangeif',
	93: null,
	94: null,
	95: null,
	96: 'maybelater',
	97: 'logicode',
	98: 'element',
	99: 'make',
	100: 'emojicode',
	101: 'cubix',
	102: 'reversed-c',
	103: 'octave',
	104: 'golfscript',
	105: 'calc',
	106: 'rust',
	107: 'ring',
	108: 'canvas',
	109: 'perl6',
	110: 'sed',
	111: 'starry',
	112: 'bash-pure',
	113: 'htms',
	114: 'x86asm-nasm',
	115: 'wierd',
	116: 'i4004asm',
	117: null,
	118: null,
	119: null,
	120: 'stuck',
	121: 'lazyk',
	122: null,
	123: null,
	124: 'qlb',
	125: 'riscv',
	126: null,
	127: null,
	128: 'haskell',
	129: null,
	130: null,
	131: null,
	132: 'ocaml',
	133: 'wysiscript',
	134: null,
	135: null,
	136: 'vim',
	137: 'floating',
	138: null,
	139: null,
	140: 'stackcats',
	141: null,
	142: null,
	143: null,
	144: null,
	145: null,
	146: 'axo',
	147: 'streem',
	148: 'nadesiko',
	149: 'beam',
	150: 'matl',
	151: 'hack',
	152: 'jelly',
	153: 'swift',
	154: 'd-gdc',
	155: 'python3',
	156: 'c-gcc',
	157: 'ruby',
	158: 'node',
	159: 'elixir',
	160: 'gs2',
	161: 'lua',
	162: 'goruby',
	163: 'z80',
	164: '05ab1e',
	165: 'm4',
	166: 'ppap',
	167: null,
	168: null,
	169: null,
	170: null,
	171: null,
	172: 'aheui',
	173: 'grass',
	174: null,
	175: null,
	176: 'clisp-sbcl',
	177: null,
	178: null,
	179: null,
	180: 'perl',
	181: null,
	182: null,
	183: null,
	184: 'crystal',
	185: 'minimal2d',
	186: null,
	187: null,
	188: 'stop',
	189: null,
	190: null,
	191: null,
	192: 'doubleplusungood',
	193: 'asciidots',
	194: 'csharp-dotnet',
	195: 'autovim',
	196: 'arcyou',
	197: 'jellyfish',
	198: 'java',
	199: 'produire',
	200: 'cjam',
	201: 'erlang',
	202: 'bash-busybox',
	203: 'kotlin',
	204: 'gaia',
	205: 'fortran',
	206: 'php',
	207: 'rail',
	208: 'jelly',
	209: 'cmd',
	210: 'sqlite3',
	211: 'suzy',
	212: 'unreadable',
	213: null,
	214: null,
	215: null,
	216: 'path',
	217: 'bots',
	218: null,
	219: null,
	220: 'cpp-compile-time-clang',
	221: 'hexagony',
	222: null,
	223: null,
	224: 'fsharp-dotnet',
	225: 'piet',
	226: null,
	227: null,
	228: 'jq',
	229: 'unlambda',
	230: null,
	231: null,
	232: 'ubergenes',
	233: 'hypertorus',
	234: null,
	235: null,
	236: 'sceql',
	237: null,
	238: null,
	239: null,
	240: null,
	241: null,
	242: 'pure-folders',
	243: 'adjust',
	244: 'zucchini',
	245: 'hanoi_stack',
	246: 'ruby0.49',
	247: 'japt',
	248: 'fish-shell-pure',
	249: 'standback',
	250: 'copos-rb',
	251: 'cobol',
	252: 'moo',
	253: 'snusp',
	254: 'pxem',
	255: 'width',
	256: 'evil',
	257: 'snowman',
	258: 'verilog',
	259: 'iwashi',
	260: 'glass',
	261: '3var',
	262: 'lolcode',
	263: null,
	264: null,
	265: null,
	266: null,
	267: null,
	268: null,
	269: null,
	270: null,
	271: null,
	272: 'abc',
	273: 'arithmetic',
	274: null,
	275: null,
	276: 'rprogn',
	277: 'brainfuck-esotope',
	278: null,
	279: null,
	280: 'emoji',
	281: null,
	282: null,
	283: null,
	284: null,
	285: null,
	286: null,
	287: null,
	288: null,
	289: null,
	290: null,
	291: null,
	292: null,
	293: null,
	294: 'whenever',
	295: 'alice',
	296: 'wordcpu',
	297: 'beatnik',
	298: 'codemania',
	299: 'minus',
	300: 'spl',
	301: 'taxi',
	302: 'unicat',
	303: null,
	304: null,
	305: null,
	306: null,
	307: null,
	308: null,
	309: null,
	310: null,
	311: null,
	312: null,
	313: null,
	314: null,
	315: null,
	316: null,
	317: null,
	318: null,
	319: null,
	320: null,
	321: null,
	322: null,
	323: null,
	324: null,
	325: null,
	326: null,
	327: null,
	328: null,
	329: null,
	330: null,
	331: null,
	332: null,
	333: null,
	334: null,
	335: null,
};

module.exports = Array(24 * 14)
	.fill()
	.map((_, index) => {
		if (index === 129) {
			return {
				type: 'base',
				team: 0,
			};
		}

		if (index === 177) {
			return {
				type: 'base',
				team: 1,
			};
		}

		if (index === 181) {
			return {
				type: 'base',
				team: 2,
			};
		}

		if (languages[index] === null) {
			return null;
		}

		const langDatum = langsData.find((lang) => lang.slug === languages[index]);
		assert(langDatum, languages[index]);

		return {
			type: 'language',
			slug: languages[index],
			name: langDatum.name,
			link: langDatum.link,
		};
	});
<commit_msg>Update languages<commit_after>const assert = require('assert');
const langsData = require('../langs.json');

const languages = {
	0: null,
	1: null,
	2: null,
	3: null,
	4: null,
	5: null,
	6: null,
	7: null,
	8: 'recurse',
	9: 'hbcht',
	10: 'cmm',
	11: 'cubically',
	12: 'cardinal',
	13: null,
	14: null,
	15: null,
	16: null,
	17: null,
	18: null,
	19: null,
	20: null,
	21: null,
	22: null,
	23: null,
	24: null,
	25: null,
	26: null,
	27: null,
	28: null,
	29: null,
	30: null,
	31: null,
	32: 'whitespace',
	33: 'apl',
	34: null,
	35: null,
	36: 'picfunge',
	37: null,
	38: null,
	39: null,
	40: null,
	41: null,
	42: null,
	43: null,
	44: null,
	45: null,
	46: null,
	47: null,
	48: null,
	49: null,
	50: null,
	51: null,
	52: 'fernando',
	53: 'labyrinth',
	54: 'aubergine',
	55: 'multi-reader',
	56: 'convex',
	57: 'befunge98',
	58: 'golfish',
	59: 'ezhil',
	60: 'cy',
	61: 'snobol',
	62: '2sable',
	63: 'awk',
	64: 'powershell',
	65: 'floater',
	66: 'irc',
	67: 'braille',
	68: 'typhon',
	69: null,
	70: null,
	71: null,
	72: null,
	73: null,
	74: null,
	75: null,
	76: 'wake',
	77: 'simula',
	78: null,
	79: null,
	80: 'coq',
	81: 'function2d',
	82: null,
	83: null,
	84: 'fish',
	85: 'nuts',
	86: null,
	87: null,
	88: 'unicue',
	89: 'tetris',
	90: null,
	91: null,
	92: 'exchangeif',
	93: null,
	94: null,
	95: null,
	96: 'maybelater',
	97: 'logicode',
	98: 'element',
	99: 'make',
	100: 'emojicode',
	101: 'cubix',
	102: 'reversed-c',
	103: 'octave',
	104: 'golfscript',
	105: 'calc',
	106: 'rust',
	107: 'ring',
	108: 'canvas',
	109: 'perl6',
	110: 'sed',
	111: 'starry',
	112: 'bash-pure',
	113: 'htms',
	114: 'x86asm-nasm',
	115: 'wierd',
	116: 'i4004asm',
	117: null,
	118: null,
	119: null,
	120: 'stuck',
	121: 'lazyk',
	122: null,
	123: null,
	124: 'qlb',
	125: 'riscv',
	126: null,
	127: null,
	128: 'haskell',
	129: null,
	130: null,
	131: null,
	132: 'ocaml',
	133: 'wysiscript',
	134: null,
	135: null,
	136: 'vim',
	137: 'floating',
	138: null,
	139: null,
	140: 'stackcats',
	141: null,
	142: null,
	143: null,
	144: null,
	145: null,
	146: 'axo',
	147: 'streem',
	148: 'nadesiko',
	149: 'beam',
	150: 'matl',
	151: 'hack',
	152: 'jelly',
	153: 'swift',
	154: 'd-gdc',
	155: 'python3',
	156: 'c-gcc',
	157: 'ruby',
	158: 'node',
	159: 'elixir',
	160: 'gs2',
	161: 'lua',
	162: 'goruby',
	163: 'z80',
	164: '05ab1e',
	165: 'm4',
	166: 'ppap',
	167: null,
	168: null,
	169: null,
	170: null,
	171: null,
	172: 'aheui',
	173: 'grass',
	174: null,
	175: null,
	176: 'clisp-sbcl',
	177: null,
	178: null,
	179: null,
	180: 'perl',
	181: null,
	182: null,
	183: null,
	184: 'crystal',
	185: 'minimal2d',
	186: null,
	187: null,
	188: 'stop',
	189: null,
	190: null,
	191: null,
	192: 'doubleplusungood',
	193: 'asciidots',
	194: 'csharp-dotnet',
	195: 'autovim',
	196: 'arcyou',
	197: 'jellyfish',
	198: 'java',
	199: 'produire',
	200: 'cjam',
	201: 'erlang',
	202: 'bash-busybox',
	203: 'kotlin',
	204: 'gaia',
	205: 'fortran',
	206: 'php',
	207: 'rail',
	208: 'codemania',
	209: 'cmd',
	210: 'sqlite3',
	211: 'suzy',
	212: 'unreadable',
	213: null,
	214: null,
	215: null,
	216: 'path',
	217: 'bots',
	218: null,
	219: null,
	220: 'cpp-compile-time-clang',
	221: 'hexagony',
	222: null,
	223: null,
	224: 'fsharp-dotnet',
	225: 'piet',
	226: null,
	227: null,
	228: 'jq',
	229: 'unlambda',
	230: null,
	231: null,
	232: 'ubergenes',
	233: 'hypertorus',
	234: null,
	235: null,
	236: 'sceql',
	237: null,
	238: null,
	239: null,
	240: null,
	241: null,
	242: 'pure-folders',
	243: 'adjust',
	244: 'zucchini',
	245: 'hanoi_stack',
	246: 'ruby0.49',
	247: 'japt',
	248: 'fish-shell-pure',
	249: 'standback',
	250: 'copos-rb',
	251: 'cobol',
	252: 'moo',
	253: 'snusp',
	254: 'pxem',
	255: 'width',
	256: 'evil',
	257: 'snowman',
	258: 'verilog',
	259: 'iwashi',
	260: 'glass',
	261: '3var',
	262: 'lolcode',
	263: null,
	264: null,
	265: null,
	266: null,
	267: null,
	268: null,
	269: null,
	270: null,
	271: null,
	272: 'abc',
	273: 'arithmetic',
	274: null,
	275: null,
	276: 'rprogn',
	277: 'brainfuck-esotope',
	278: null,
	279: null,
	280: 'emoji',
	281: null,
	282: null,
	283: null,
	284: null,
	285: null,
	286: null,
	287: null,
	288: null,
	289: null,
	290: null,
	291: null,
	292: null,
	293: null,
	294: 'whenever',
	295: 'alice',
	296: 'wordcpu',
	297: 'beatnik',
	298: 'fugue',
	299: 'minus',
	300: 'spl',
	301: 'taxi',
	302: 'unicat',
	303: null,
	304: null,
	305: null,
	306: null,
	307: null,
	308: null,
	309: null,
	310: null,
	311: null,
	312: null,
	313: null,
	314: null,
	315: null,
	316: null,
	317: null,
	318: null,
	319: null,
	320: null,
	321: null,
	322: null,
	323: null,
	324: null,
	325: null,
	326: null,
	327: null,
	328: null,
	329: null,
	330: null,
	331: null,
	332: null,
	333: null,
	334: null,
	335: null,
};

module.exports = Array(24 * 14)
	.fill()
	.map((_, index) => {
		if (index === 129) {
			return {
				type: 'base',
				team: 0,
			};
		}

		if (index === 177) {
			return {
				type: 'base',
				team: 1,
			};
		}

		if (index === 181) {
			return {
				type: 'base',
				team: 2,
			};
		}

		if (languages[index] === null) {
			return null;
		}

		const langDatum = langsData.find((lang) => lang.slug === languages[index]);
		assert(langDatum, languages[index]);

		return {
			type: 'language',
			slug: languages[index],
			name: langDatum.name,
			link: langDatum.link,
		};
	});
<|endoftext|>


<commit_before>
  var BuildStep = React.createClass({
    render: function () {
      if (this.props.data.stepType === 'in-parallel') {
        return
<ParallelBuildStep data={this.props.data}/>
;
      } else if (this.props.data.stepType === 'trigger') {
        return
<TriggerStep data={this.props.data}/>
;
      } else {
        return
<RegularBuildStep data={this.props.data}/>
;
      }
    }
  });

  var ParallelBuildStep = React.createClass({

    render: function () {
      var rows = this.props.data.steps.map(function (step) {
        return (
<RegularBuildStep data={step}/>
)

      });

      return (

        {rows}

)
    }
  });

  var RegularBuildStep = React.createClass({

    render: function () {

      var panelType = PanelType[this.props.data.stepState];

      var currentSteps;
      var steps = [];
      if (this.props.data.runningBuildSteps().length > 0) {
        steps.push(<CurrentBuildSteps key="current" title="Current Buildsteps"
                                      data={this.props.data.runningBuildSteps()}/>);
      }
      if (this.props.data.failedBuildSteps().length > 0) {
        steps.push(<CurrentBuildSteps key="failed" title="Failed Buildsteps" data={this.props.data.failedBuildSteps()}/>);
      }
      if (steps.length > 0) {
        currentSteps =

          {steps}

;
      }

      var props = this.props;

      var zoomIntoSubSteps = function () {
        window.visiblePipeline = props.data;
      };

      return (

              {this.props.data.stepName}

                  {this.props.data.duration}

          {currentSteps}

      );

    }

  })

  var TriggerStep = React.createClass({
    render: function () {

      return (

      );
    }
  });

  var Pipeline = React.createClass({

    getInitialState: function(){
      return window.testPipeline;
    },

    updateState: function() {
      this.setState(window.visiblePipeline);
    },

    componentDidMount: function(){
      setInterval(this.updateState, 1000);
    }
    ,

    render: function () {
      var buildsteps = this.state.steps.map(function (buildstep) {
        return <BuildStep key={buildstep.stepId} data={buildstep}/>
      });
      return (

          {buildsteps}

      );

    }

  });

<commit_msg>inject small separators between pipeline steps<commit_after>
  var BuildStep = React.createClass({
    render: function () {
      if (this.props.data.stepType === 'in-parallel') {
        return
<ParallelBuildStep data={this.props.data}/>
;
      } else if (this.props.data.stepType === 'trigger') {
        return
<TriggerStep data={this.props.data}/>
;
      } else {
        return
<RegularBuildStep data={this.props.data}/>
;
      }
    }
  });

  var ParallelBuildStep = React.createClass({

    render: function () {
      var rows = this.props.data.steps.map(function (step) {
        return (
<RegularBuildStep data={step}/>
)

      });

      return (

        {rows}

)
    }
  });

  var RegularBuildStep = React.createClass({

    render: function () {

      var panelType = PanelType[this.props.data.stepState];

      var currentSteps;
      var steps = [];
      if (this.props.data.runningBuildSteps().length > 0) {
        steps.push(<CurrentBuildSteps key="current" title="Current Buildsteps"
                                      data={this.props.data.runningBuildSteps()}/>);
      }
      if (this.props.data.failedBuildSteps().length > 0) {
        steps.push(<CurrentBuildSteps key="failed" title="Failed Buildsteps" data={this.props.data.failedBuildSteps()}/>);
      }
      if (steps.length > 0) {
        currentSteps =

          {steps}

;
      }

      var props = this.props;

      var zoomIntoSubSteps = function () {
        window.visiblePipeline = props.data;
      };

      return (

              {this.props.data.stepName}

                  {this.props.data.duration}

          {currentSteps}

      );

    }

  });

  var PipeIcon = React.createClass({
    render: function() {
      return (

);
    }
  });

  var TriggerStep = React.createClass({
    render: function () {

      return (

      );
    }
  });

  var Pipeline = React.createClass({

    getInitialState: function(){
      return window.testPipeline;
    },

    updateState: function() {
      this.setState(window.visiblePipeline);
    },

    componentDidMount: function(){
      setInterval(this.updateState, 1000);
    },
    injectSeparatorElements: function (p, n) {
      if (p.length > 0 && p[p.length-1].props.data.stepType != "trigger") {
        var key = "after-"+p[p.length-1].props.data.stepId;
        return p.concat([(<PipeIcon key={key}/>), n]);
      } else {
        return p.concat([n]);
      }
    },
    render: function () {
      var buildsteps = this.state.steps.map(function (buildstep) {
        return <BuildStep key={buildstep.stepId} data={buildstep}/>
      }).reduce(this.injectSeparatorElements, []);

      return (

          {buildsteps}

      );

    }

  });

<|endoftext|>


<commit_before>'use strict';

var identity       = require('es5-ext/function/identity')
  , d              = require('d')
  , memoize        = require('memoizee/plain')
  , memoizeMethods = require('memoizee/methods-plain')
  , getNormalizer  = require('memoizee/normalizers/get-fixed')
  , setGetFirst    = require('es6-set/ext/get-first')
  , setGetLast     = require('es6-set/ext/get-last')
  , setCopy        = require('es6-set/ext/copy')
  , setEvery       = require('es6-set/ext/every')
  , setSome        = require('es6-set/ext/some')
  , map            = require('observable-value/map')
  , DbjsError      = require('../error')
  , serialize      = require('../serialize/key')

  , defineProperties = Object.defineProperties
  , filterValue = function (value) { return value == null; }
  , filterNull = function (value) { return value != null; }
  , byObjId = function (args) { return args[0].__id__; }
  , resolveFilter, baseProto;

resolveFilter = memoize(function (filter) {
	if (filter === undefined) return filterNull;
	if (filter === null) return filterValue;
	if (typeof filter === 'function') return filter;
	return function (value) { return value === filter; };
}, { normalizer: require('memoizee/normalizers/get-1')() });

module.exports = function (setProto) {
	return defineProperties(setProto, memoizeMethods({
		filterByKey: d(function (key, filter) {
			var sKey = serialize(key), set, observe;
			if (sKey == null) throw new DbjsError(key + " is invalid key", 'INVALID_KEY');
			observe = memoize(function (obj) {
				if (!obj || (typeof obj._getObservable_ !== 'function')) return false;
				if (obj.isKeyStatic(key)) return filter(obj[key], obj);
				return map(obj._getObservable_(sKey), function (value) {
					return map(filter(value, obj), Boolean);
				}).on('change', function (event) { set.refresh(obj); });
			}, { normalizer: byObjId });
			set = this.filter(function (obj) {
				var observable = observe(obj);
				if (typeof observable === 'boolean') return observable;
				return observable.value;
			});
			return set;
		}, {
			normalizer: getNormalizer(2),
			resolvers: [identity, resolveFilter],
			cacheName: '__filterByKey__',
			desc: ''
		})
	}));
};

// Temporary hack
// (until we solve mixed configuration of observable and read only sets)
baseProto = require('observable-set/create-read-only')(require('observable-set')).prototype;
module.exports(baseProto);
defineProperties(baseProto, {
	first: d.gs(setGetFirst),
	last: d.gs(setGetLast),
	copy: d(setCopy),
	every: d(setEvery),
	some: d(setSome)
});
<commit_msg>Optimize filterByKey<commit_after>'use strict';

var identity       = require('es5-ext/function/identity')
  , d              = require('d')
  , memoize        = require('memoizee/plain')
  , memoizeMethods = require('memoizee/methods-plain')
  , getNormalizer  = require('memoizee/normalizers/get-fixed')
  , setGetFirst    = require('es6-set/ext/get-first')
  , setGetLast     = require('es6-set/ext/get-last')
  , setCopy        = require('es6-set/ext/copy')
  , setEvery       = require('es6-set/ext/every')
  , setSome        = require('es6-set/ext/some')
  , map            = require('observable-value/map')
  , isObservableValue = require('observable-value/is-observable-value')
  , DbjsError      = require('../error')
  , serialize      = require('../serialize/key')

  , create = Object.create, defineProperties = Object.defineProperties
  , filterValue = function (value) { return value == null; }
  , filterNull = function (value) { return value != null; }
  , resolveFilter, baseProto;

resolveFilter = memoize(function (filter) {
	if (filter === undefined) return filterNull;
	if (filter === null) return filterValue;
	if (typeof filter === 'function') return filter;
	return function (value) { return value === filter; };
}, { normalizer: require('memoizee/normalizers/get-1')() });

module.exports = function (setProto) {
	return defineProperties(setProto, memoizeMethods({
		filterByKey: d(function (key, filter) {
			var sKey = serialize(key), set, observed = create(null);
			if (sKey == null) throw new DbjsError(key + " is invalid key", 'INVALID_KEY');
			set = this.filter(function (obj) {
				var observable, result, cached;
				cached = observed[obj.__id__];
				if (!cached) {
					if (!obj || (typeof obj._getObservable_ !== 'function')) return false;
					if (obj.isKeyStatic(key)) return filter(obj[key], obj);
					observable = obj._getObservable_(sKey);
					result = filter(observable.value, obj);
					if (isObservableValue(result)) {
						observable = map(observable, function (value) {
							return map(filter(value, obj), Boolean);
						});
						result = result.value;
					}
					observable.on('change', function () { set.refresh(obj); });
					observed[obj.__id__] = true;
					return result;
				}
				if (cached !== true) return cached.value;
				observable = obj._getObservable_(sKey);
				result = filter(observable.value, obj);
				if (!isObservableValue(result)) return result;
				return result.value;
			});
			return set;
		}, {
			normalizer: getNormalizer(2),
			resolvers: [identity, resolveFilter],
			cacheName: '__filterByKey__',
			desc: ''
		})
	}));
};

// Temporary hack
// (until we solve mixed configuration of observable and read only sets)
baseProto = require('observable-set/create-read-only')(require('observable-set')).prototype;
module.exports(baseProto);
defineProperties(baseProto, {
	first: d.gs(setGetFirst),
	last: d.gs(setGetLast),
	copy: d(setCopy),
	every: d(setEvery),
	some: d(setSome)
});
<|endoftext|>


<commit_before><commit_msg>Add counter to the static page<commit_after><|endoftext|>