<commit_before>var __bind = function (fn, me) {
    return function () {
      return fn.apply(me, arguments);
    };
  },
  __hasProp = {}.hasOwnProperty,
  __extends = function (child, parent) {
    for (var key in parent) {
      if (__hasProp.call(parent, key)) child[key] = parent[key];
    }
    function ctor() {
      this.constructor = child;
    }

    ctor.prototype = parent.prototype;
    child.prototype = new ctor();
    child.__super__ = parent.prototype;
    return child;
  };

module.exports = function (env) {
  var M, OnkyneerRemotePlugin, OnkyneerRemoteActionProvider, OnkyneerRemoteActionHandler, OnkyneerRemotePlugin, onkyo, pluginConfig, connected;
  M = env.matcher;

  var Promise = env.require('bluebird');
  var net = env.require('net');
  var util = env.require('util');
  var assert = env.require('cassert');

  /**
   * Default connection parameters
   **/
  var defaultHost = '192.168.0.15';
  var defaultMaxVolume = 98;

  var retryCount = 0;
  var lastRetry = new Date();
  var currentVolume = 0;
  var currentDisplay = '';
  var currentStatus = 0;
  var currentInput = '';
  var updateInterval = 2000;

  var Onkyo = require("onkyo.js");

  /**
   * THE PLUGIN ITSELF
   **/
  OnkyneerRemotePlugin = (function (_super) {
    __extends(OnkyneerRemotePlugin, _super);

    function OnkyneerRemotePlugin() {
      this.init = __bind(this.init, this);
      return OnkyneerRemotePlugin.__super__.constructor.apply(this, arguments);
    }

    OnkyneerRemotePlugin.prototype.init = function (app, framework, config) {
      var deviceConfigDef;
      this.framework = framework;
      this.config = config;
      pluginConfig = config;
      this.framework.ruleManager.addActionProvider(new OnkyneerRemoteActionProvider(this.framework));

      deviceConfigDef = require("./device-config-schema");

      this.framework.deviceManager.registerDeviceClass("OnkyneerSensor", {
        configDef: deviceConfigDef.OnkyneerSensor,
        createCallback: (function (_this) {
          return function (config) {
            return new OnkyneerSensor(config, framework);
          };
        })(this)
      });
    };

    return OnkyneerRemotePlugin;

  })(env.plugins.Plugin);

  OnkyneerRemotePlugin = new OnkyneerRemotePlugin;
  /**
   * THE ACTION PROVIDER
   **/
  OnkyneerRemoteActionProvider = (function (_super) {
    __extends(OnkyneerRemoteActionProvider, _super);

    function OnkyneerRemoteActionProvider(framework, config) {
      this.framework = framework;
      this.config = config;
      this.connectAction = __bind(this.connectAction, this);
    }

    /**
     *This function handles action in the form of `sendOnkyneer "some string"`
     **/

    OnkyneerRemoteActionProvider.prototype.parseAction = function (input, context) {
      var commandTokens, fullMatch, m, match, onEnd, retVal, setCommand;
      retVal = null;
      commandTokens = null;
      fullMatch = false;
      setCommand = (function (_this) {
        return function (m, tokens) {
          return commandTokens = tokens;
        };
      })(this);

      onEnd = (function (_this) {
        return function () {
          return fullMatch = true;
        };
      })(this);

      m = M(input, context).match("sendOnkyneer ").matchStringWithVars(setCommand);
      if (m.hadMatch()) {
        match = m.getFullMatch();
        return {
          token: match,
          nextInput: input.substring(match.length),
          actionHandler: new OnkyneerRemoteActionHandler(this.framework, commandTokens)
        };
      } else {
        return null;
      }
    };

    return OnkyneerRemoteActionProvider;

  })(env.actions.ActionProvider);

  /**
   * THE ACTION HANDLER
   **/

  OnkyneerRemoteActionHandler = (function (_super) {
    __extends(OnkyneerRemoteActionHandler, _super);

    function OnkyneerRemoteActionHandler(framework, commandTokens) {
      this.framework = framework;
      this.commandTokens = commandTokens;
      this.executeAction = __bind(this.executeAction, this);
      this.connect = __bind(this.connect, this);
      this.disconnect = __bind(this.disconnect, this);
      this.sendCommand = __bind(this.sendCommand, this);
    }

    /**
     * Method for establishing connection to the receiver
     **/
    OnkyneerRemoteActionHandler.prototype.connect = function (command) {
      if (!connected) {
        env.logger.info('Client isn\'t connected yet, establish new connection...');

        if(!onkyo) {
          var host = pluginConfig.host ? pluginConfig.host : defaultHost;
          onkyo = Onkyo.init({
            "log": true,
            "ip": host
          });
        }

        onkyo.on("error", function(err){
          console.log(err);
        });

        onkyo.on("detected", function(device){
          console.log(device);
        });

        onkyo.on("connected", function(host){
          console.log("connected to: "+JSON.stringify(host));
          connected = true;
        });

        onkyo.Connect(function(error, ok){
          if(!error) {
            env.logger.info('Connection successful.');
          }
        });

      }

      return 'done';
    };

    /**
     * Method to call when connection isn't needed any longer
     **/
    OnkyneerRemoteActionHandler.prototype.disconnect = function () {
      if (onkyo && connected) {
	    onkyo.Close(function(error, ok){
          if(!error) {
			env.logger.info('Disconnected');
			connected = false;
		  }
		});

        return 'disconnected';
      } else {
	    if(logLevel === "info") {
          env.logger.info('Nothing to disconnect from.');
		}
      }

      return 'disconnected';
    };

    /**
     * Method for sending a command
     **/
    OnkyneerRemoteActionHandler.prototype.sendCommand = function (command) {

	  var splittedCommand = command.split('\.');
      var category = splittedCommand[0];
      var func = splittedCommand[1];

	  var maxVolume = pluginConfig.maxVolume || defaultMaxVolume;

      var volLevel = (currentVolume + 80.5) * 2;
      var value = '';

      /**
       * Handle max volume to avoid damage on user and equipment
      **/

	  onkyo.SendCommand(category, func, function(error, ok){
		if(!error) {
			return 'Sent command: ' + command;
		} else {
			return 'Error while sending command: ' + command;
		}
      });

    };

    /**
     * Handle the incoming data
     **/
    OnkyneerRemoteActionHandler.prototype.handleData = function (stringyfiedData) {

    };

    /**
     * This function handles action in the form of `sendOnkyneer "command"`
     **/
    OnkyneerRemoteActionHandler.prototype.executeAction = function () {
      return this.framework.variableManager.evaluateStringExpression(this.commandTokens).then((function (_this) {
        return function (command) {
          switch (command) {
            case 'connect':
              return OnkyneerRemoteActionHandler.connect();
              break;
            case 'disconnect':
              return OnkyneerRemoteActionHandler.disconnect();
              break;
            default:
              /**
               * If no connection to the AVR exists, connect first and send the command afterwards
               **/
              if (!onkyo || !connected) {
                return OnkyneerRemoteActionHandler.connect(command);
              } else {
                return OnkyneerRemoteActionHandler.sendCommand(command);
              }
          }
        };
      })(this));
    };

    return OnkyneerRemoteActionHandler;

  })(env.actions.ActionHandler);

  /**
   * THE AVR SENSOR
   **/
  OnkyneerSensor = (function (_super) {
    __extends(OnkyneerSensor, _super);

    function OnkyneerSensor(config, framework) {
      var attr;
      this.config = config;
      this.id = config.id;
      this.name = config.name;
      this.attributes = {};
	  this.intervalTimeoutObject = null;

      var func = (function (_this) {
        return function (attr) {
          var name = attr.name;

          assert(name === 'vol' || name === 'display' || name === 'status');

          switch (name) {
            case 'vol':
              _this.attributes[name] = {
                description: name,
                type: "number"
              };

              var getter = (function () {
                if (retryCount < 3 || (new Date - lastRetry) > 60000) {
                  if (!onkyo) {
                    OnkyneerRemoteActionHandler.connect();
                  } else {
                    //OnkyneerRemoteActionHandler.sendCommand('volume.status');
                  }
                }
                return Promise.resolve(currentVolume);
              });
              _this.attributes[name].unit = 'dB';
              _this.attributes[name].acronym = 'VOL';
              break;
            case 'display':
              _this.attributes[name] = {
                description: name,
                type: "string"
              };

              var getter = (function () {
                if (retryCount < 3 || (new Date - lastRetry) > 60000) {
                  if (!onkyo) {
                    OnkyneerRemoteActionHandler.connect();
                  }
                }
                return Promise.resolve(currentDisplay);
              });
              break;
			case 'status':
              _this.attributes[name] = {
                description: name,
                type: "number"
              };

              var getter = (function () {
                if (retryCount < 3 || (new Date - lastRetry) > 60000) {
                  if (!onkyo) {
                    OnkyneerRemoteActionHandler.connect();
                  }
                }
				return Promise.resolve(currentStatus);
              });
              break;
            default:
              throw new Error("Illegal attribute name: " + name + " in OnkyneerSensor.");
          }

          _this._createGetter(name, getter);

          _this.intervalTimeoutObject = setInterval((function () {
            return getter().then(function (value) {
              return _this.emit(name, value);
            })["catch"](function (error) {
              return env.logger.debug(error.stack);
            });
          }), updateInterval);
		  return _this.intervalTimeoutObject;

        };
      })(this);

      for (var i = 0; i < this.config.attributes.length; i++) {
        attr = this.config.attributes[i];
        func(attr);
      }

      OnkyneerSensor.__super__.constructor.call(this);
    }

    return OnkyneerSensor;

  })(env.devices.Sensor);

  OnkyneerSensor.prototype.destroy = function() {
	if (this.intervalTimeoutObject != null) {
	  clearInterval(this.intervalTimeoutObject);
    }
    return OnkyneerSensor.__super__.destroy.call(this);
  };

  module.exports.OnkyneerRemoteActionProvider = OnkyneerRemoteActionProvider;

  return OnkyneerRemotePlugin;
};
<commit_msg>fix for following error "not a function"<commit_after>var __bind = function (fn, me) {
    return function () {
      return fn.apply(me, arguments);
    };
  },
  __hasProp = {}.hasOwnProperty,
  __extends = function (child, parent) {
    for (var key in parent) {
      if (__hasProp.call(parent, key)) child[key] = parent[key];
    }
    function ctor() {
      this.constructor = child;
    }

    ctor.prototype = parent.prototype;
    child.prototype = new ctor();
    child.__super__ = parent.prototype;
    return child;
  };

module.exports = function (env) {
  var M, OnkyneerRemotePlugin, OnkyneerRemoteActionProvider, OnkyneerRemoteActionHandler, OnkyneerRemotePlugin, onkyo, pluginConfig, connected;
  M = env.matcher;

  var Promise = env.require('bluebird');
  var net = env.require('net');
  var util = env.require('util');
  var assert = env.require('cassert');

  /**
   * Default connection parameters
   **/
  var defaultHost = '192.168.0.15';
  var defaultMaxVolume = 98;

  var retryCount = 0;
  var lastRetry = new Date();
  var currentVolume = 0;
  var currentDisplay = '';
  var currentStatus = 0;
  var currentInput = '';
  var updateInterval = 2000;

  var Onkyo = require("onkyo.js");

  /**
   * THE PLUGIN ITSELF
   **/
  OnkyneerRemotePlugin = (function (_super) {
    __extends(OnkyneerRemotePlugin, _super);

    function OnkyneerRemotePlugin() {
      this.init = __bind(this.init, this);
      return OnkyneerRemotePlugin.__super__.constructor.apply(this, arguments);
    }

    OnkyneerRemotePlugin.prototype.init = function (app, framework, config) {
      var deviceConfigDef;
      this.framework = framework;
      this.config = config;
      pluginConfig = config;
      this.framework.ruleManager.addActionProvider(new OnkyneerRemoteActionProvider(this.framework));

      deviceConfigDef = require("./device-config-schema");

      this.framework.deviceManager.registerDeviceClass("OnkyneerSensor", {
        configDef: deviceConfigDef.OnkyneerSensor,
        createCallback: (function (_this) {
          return function (config) {
            return new OnkyneerSensor(config, framework);
          };
        })(this)
      });
    };

    return OnkyneerRemotePlugin;

  })(env.plugins.Plugin);

  OnkyneerRemotePlugin = new OnkyneerRemotePlugin;
  /**
   * THE ACTION PROVIDER
   **/
  OnkyneerRemoteActionProvider = (function (_super) {
    __extends(OnkyneerRemoteActionProvider, _super);

    function OnkyneerRemoteActionProvider(framework, config) {
      this.framework = framework;
      this.config = config;
      this.connectAction = __bind(this.connectAction, this);
    }

    /**
     *This function handles action in the form of `sendOnkyneer "some string"`
     **/

    OnkyneerRemoteActionProvider.prototype.parseAction = function (input, context) {
      var commandTokens, fullMatch, m, match, onEnd, retVal, setCommand;
      retVal = null;
      commandTokens = null;
      fullMatch = false;
      setCommand = (function (_this) {
        return function (m, tokens) {
          return commandTokens = tokens;
        };
      })(this);

      onEnd = (function (_this) {
        return function () {
          return fullMatch = true;
        };
      })(this);

      m = M(input, context).match("sendOnkyneer ").matchStringWithVars(setCommand);
      if (m.hadMatch()) {
        match = m.getFullMatch();
        return {
          token: match,
          nextInput: input.substring(match.length),
          actionHandler: new OnkyneerRemoteActionHandler(this.framework, commandTokens)
        };
      } else {
        return null;
      }
    };

    return OnkyneerRemoteActionProvider;

  })(env.actions.ActionProvider);

  /**
   * THE ACTION HANDLER
   **/

  OnkyneerRemoteActionHandler = (function (_super) {
    __extends(OnkyneerRemoteActionHandler, _super);

    function OnkyneerRemoteActionHandler(framework, commandTokens) {
      this.framework = framework;
      this.commandTokens = commandTokens;
      this.executeAction = __bind(this.executeAction, this);
      this.connect = __bind(this.connect, this);
      this.disconnect = __bind(this.disconnect, this);
      this.sendCommand = __bind(this.sendCommand, this);
    }

    /**
     * Method for establishing connection to the receiver
     **/
    OnkyneerRemoteActionHandler.prototype.connect = function (command) {
      if (!connected) {
        env.logger.info('Client isn\'t connected yet, establish new connection...');

        if(!onkyo) {
          var host = pluginConfig.host ? pluginConfig.host : defaultHost;
          onkyo = Onkyo.init({
            "log": true,
            "ip": host
          });
        }

        onkyo.on("error", function(err){
          console.log(err);
        });

        onkyo.on("detected", function(device){
          console.log(device);
        });

        onkyo.on("connected", function(host){
          console.log("connected to: "+JSON.stringify(host));
          connected = true;
        });

        onkyo.Connect(function(error, ok){
          if(!error) {
            env.logger.info('Connection successful.');
          }
        });

      }

      return 'done';
    };

    /**
     * Method to call when connection isn't needed any longer
     **/
    OnkyneerRemoteActionHandler.prototype.disconnect = function () {
      if (onkyo && connected) {
	    onkyo.Close(function(error, ok){
          if(!error) {
			env.logger.info('Disconnected');
			connected = false;
		  }
		});

        return 'disconnected';
      } else {
	    if(logLevel === "info") {
          env.logger.info('Nothing to disconnect from.');
		}
      }

      return 'disconnected';
    };

    /**
     * Method for sending a command
     **/
    OnkyneerRemoteActionHandler.prototype.sendCommand = function (command) {

	  var splittedCommand = command.split('\.');
      var category = splittedCommand[0];
      var func = splittedCommand[1];

	  var maxVolume = pluginConfig.maxVolume || defaultMaxVolume;

      var volLevel = (currentVolume + 80.5) * 2;
      var value = '';

      /**
       * Handle max volume to avoid damage on user and equipment
      **/

	  onkyo.SendCommand(category, func, function(error, ok){
		if(!error) {
			return 'Sent command: ' + command;
		} else {
			return 'Error while sending command: ' + command;
		}
      });

    };

    /**
     * Handle the incoming data
     **/
    OnkyneerRemoteActionHandler.prototype.handleData = function (stringyfiedData) {

    };

    /**
     * This function handles action in the form of `sendOnkyneer "command"`
     **/
    OnkyneerRemoteActionHandler.prototype.executeAction = function () {
      return this.framework.variableManager.evaluateStringExpression(this.commandTokens).then((function (_this) {
        return function (command) {
          switch (command) {
            case 'connect':
              return _this.connect();
              break;
            case 'disconnect':
              return _this.disconnect();
              break;
            default:
              /**
               * If no connection to the AVR exists, connect first and send the command afterwards
               **/
              if (!onkyo || !connected) {
                return _this.connect(command);
              } else {
                return _this.sendCommand(command);
              }
          }
        };
      })(this));
    };

    return OnkyneerRemoteActionHandler;

  })(env.actions.ActionHandler);

  /**
   * THE AVR SENSOR
   **/
  OnkyneerSensor = (function (_super) {
    __extends(OnkyneerSensor, _super);

    function OnkyneerSensor(config, framework) {
      var attr;
      this.config = config;
      this.id = config.id;
      this.name = config.name;
      this.attributes = {};
	  this.intervalTimeoutObject = null;

      var func = (function (_this) {
        return function (attr) {
          var name = attr.name;

          assert(name === 'vol' || name === 'display' || name === 'status');

          switch (name) {
            case 'vol':
              _this.attributes[name] = {
                description: name,
                type: "number"
              };

              var getter = (function () {
                if (retryCount < 3 || (new Date - lastRetry) > 60000) {
                  if (!onkyo) {
                    OnkyneerRemoteActionHandler.connect();
                  } else {
                    //OnkyneerRemoteActionHandler.sendCommand('volume.status');
                  }
                }
                return Promise.resolve(currentVolume);
              });
              _this.attributes[name].unit = 'dB';
              _this.attributes[name].acronym = 'VOL';
              break;
            case 'display':
              _this.attributes[name] = {
                description: name,
                type: "string"
              };

              var getter = (function () {
                if (retryCount < 3 || (new Date - lastRetry) > 60000) {
                  if (!onkyo) {
                    OnkyneerRemoteActionHandler.connect();
                  }
                }
                return Promise.resolve(currentDisplay);
              });
              break;
			case 'status':
              _this.attributes[name] = {
                description: name,
                type: "number"
              };

              var getter = (function () {
                if (retryCount < 3 || (new Date - lastRetry) > 60000) {
                  if (!onkyo) {
                    OnkyneerRemoteActionHandler.connect();
                  }
                }
				return Promise.resolve(currentStatus);
              });
              break;
            default:
              throw new Error("Illegal attribute name: " + name + " in OnkyneerSensor.");
          }

          _this._createGetter(name, getter);

          _this.intervalTimeoutObject = setInterval((function () {
            return getter().then(function (value) {
              return _this.emit(name, value);
            })["catch"](function (error) {
              return env.logger.debug(error.stack);
            });
          }), updateInterval);
		  return _this.intervalTimeoutObject;

        };
      })(this);

      for (var i = 0; i < this.config.attributes.length; i++) {
        attr = this.config.attributes[i];
        func(attr);
      }

      OnkyneerSensor.__super__.constructor.call(this);
    }

    return OnkyneerSensor;

  })(env.devices.Sensor);

  OnkyneerSensor.prototype.destroy = function() {
	if (this.intervalTimeoutObject != null) {
	  clearInterval(this.intervalTimeoutObject);
    }
    return OnkyneerSensor.__super__.destroy.call(this);
  };

  module.exports.OnkyneerRemoteActionProvider = OnkyneerRemoteActionProvider;

  return OnkyneerRemotePlugin;
};
<|endoftext|>


<commit_before>import { startApp, destroyApp } from '../helpers/app-lifecycle';
import { injectTransitionSpies } from '../helpers/integration';

let app;

module('Acceptance: Demos', {
  setup: function() {
    app = startApp();

    // Conceptually, integration tests shouldn't be digging around in
    // the container. But animations are slippery, and it's easier to
    // just spy on them to make sure they're being run than to try to
    // observe their behavior more directly.
    injectTransitionSpies(app);
  },

  teardown: function() {
    destroyApp(app);
  }
});

test('components are not destroyed until animation has finished', function() {
  visit('/scenarios/component-in-tether');

  andThen(() => {
    find('button:contains(Toggle)').click();
    equal(find('.velocity-animating').text().trim(), 'testing', 'component markup still exists');
  });
});

test('nested tethers work properly', function() {
  visit('/scenarios/nested-tethers');

  click('button');

  andThen(() => {
    const redbox = find('.red-box');
    const greenbox = find('.green-box');
    const bluebox = find('.blue-box');

    const redboxOffset = redbox.offset();
    const greenboxOffset = greenbox.offset();
    const blueboxOffset = bluebox.offset();

    const greenboxHeight = greenbox.outerHeight();
    const redboxHeight = redbox.outerHeight();
    const redboxWidth = redbox.outerWidth();

    ok(withinTolerance(greenboxOffset.top + greenboxHeight, redboxOffset.top), 'redbox vertical pos within tolerance');
    ok(withinTolerance(greenboxOffset.left, redboxOffset.left), 'redbox horizontal pos within tolerance');

    ok(withinTolerance(redboxOffset.top + redboxHeight, blueboxOffset.top), 'bluebox vertical pos within tolerance');
    ok(withinTolerance(redboxOffset.left + redboxWidth, blueboxOffset.left), 'bluebox horizontal pos within tolerance');
  });
});

test('target only shows one tether at a time', function() {
  visit('/scenarios/multiple-tethers');

  andThen(() => {
    equal(find('.liquid-target-container').text().trim(), '456');
  });
});

function withinTolerance(offset1, offset2) {
  return Math.abs(offset1 - offset2) <= 3;
}
<commit_msg>descriptive module name, scenarios<commit_after>import { startApp, destroyApp } from '../helpers/app-lifecycle';
import { injectTransitionSpies } from '../helpers/integration';

let app;

module('Acceptance: Scenarios', {
  setup: function() {
    app = startApp();

    // Conceptually, integration tests shouldn't be digging around in
    // the container. But animations are slippery, and it's easier to
    // just spy on them to make sure they're being run than to try to
    // observe their behavior more directly.
    injectTransitionSpies(app);
  },

  teardown: function() {
    destroyApp(app);
  }
});

test('components are not destroyed until animation has finished', function() {
  visit('/scenarios/component-in-tether');

  andThen(() => {
    find('button:contains(Toggle)').click();
    equal(find('.velocity-animating').text().trim(), 'testing', 'component markup still exists');
  });
});

test('nested tethers work properly', function() {
  visit('/scenarios/nested-tethers');

  click('button');

  andThen(() => {
    const redbox = find('.red-box');
    const greenbox = find('.green-box');
    const bluebox = find('.blue-box');

    const redboxOffset = redbox.offset();
    const greenboxOffset = greenbox.offset();
    const blueboxOffset = bluebox.offset();

    const greenboxHeight = greenbox.outerHeight();
    const redboxHeight = redbox.outerHeight();
    const redboxWidth = redbox.outerWidth();

    ok(withinTolerance(greenboxOffset.top + greenboxHeight, redboxOffset.top), 'redbox vertical pos within tolerance');
    ok(withinTolerance(greenboxOffset.left, redboxOffset.left), 'redbox horizontal pos within tolerance');

    ok(withinTolerance(redboxOffset.top + redboxHeight, blueboxOffset.top), 'bluebox vertical pos within tolerance');
    ok(withinTolerance(redboxOffset.left + redboxWidth, blueboxOffset.left), 'bluebox horizontal pos within tolerance');
  });
});

test('target only shows one tether at a time', function() {
  visit('/scenarios/multiple-tethers');

  andThen(() => {
    equal(find('.liquid-target-container').text().trim(), '456');
  });
});

function withinTolerance(offset1, offset2) {
  return Math.abs(offset1 - offset2) <= 3;
}
<|endoftext|>


<commit_before>var badges_info_list = require(process.cwd() + '/document/badges_info_list.json');
module.exports = {
    get_arch_list: function(Models) {
        return function(req, res, next) {
            Models['arch'].find({
                uid: req.user.uid,
                provider: 'arch'
            }, function(err, result) {
                var temp_result = result;
                return res.send(temp_result);
            });
        };
    },
    create_arch: function(Models) {
        return function(req, res, next) {
            var _item = req.body;
            Models['arch'].find({
                uid: req.user.uid,
                provider: 'arch'
            }, function(err, result) {
                var temp_result = result;
                for (var i = 0; i < temp_result.length - 1; i++) {
                    if (temp_result[i].arch_name === _item.arch_name) {
                        return res.send({
                            error: true,
                            data: temp_result[i]
                        });
                    }
                    if ((i + 1) === temp_result.length) {
                        Models('arch').create({
                            aid: req.user.uid + (temp_result.length + 1),
                            uid: req.user.uid,
                            provider: 'arch',
                            arch_name: _item.arch_name,
                            information: _item.information,
                            content: _item.content,
                            frequency: 1,
                            finish: false,
                            create_time: new Date()
                        }, function(err, result) {
                            return res.send({
                                error: null,
                                data: result[i]
                            });
                        });
                    }
                }
            });
        };
    },
    create_badge: function(Models) {
        return function(req, res, next) {
            var _item = req.body;
            Models['arch'].find({
                uid: req.user.uid,
                provider: 'badge'
            }, function(err, result) {
                var temp_result = result;
                for (var i = 0; i < temp_result.length - 1; i++) {
                    if (temp_result[i].arch_name === _item.arch_name) {
                        return res.send({
                            error: true,
                            data: temp_result[i]
                        });
                    }
                    if ((i + 1) === temp_result.length) {
                        Models('arch').create({
                            aid: req.user.uid + (temp_result.length + 1),
                            uid: req.user.uid,
                            provider: 'arch',
                            arch_name: _item.arch_name,
                            information: _item.information,
                            content: _item.content,
                            frequency: 1,
                            finish: false,
                            create_time: new Date()
                        }, function(err, result) {
                            return res.send({
                                error: null,
                                data: result[i]
                            });
                        });
                    }
                }
            });
        };
    },
    get_badge: function(Models) {
        return function(req, res, next) {
            Models['arch'].findOne({
                uid: req.user.uid,
                provider: 'badge',
                content: req.params.aid
            }, function(err, result) {
                var temp_result = result;
                return res.send(temp_result);
            });
        };
    },
    get_badge_list: function(Models) {
        return function(req, res, next) {
            Models['arch'].find({
                uid: req.user.uid,
                provider: 'badge'
            }, function(err, result) {
                var temp_result = result;
                return res.send(temp_result);
            });
        };
    },
    update_badge: function(Modals) {
        return function(req, res, next) {
            if (!!req.user.uid && !!req.body.badge_name) {
                Modals['arch'].findOne({
                    uid: req.user.uid,
                    provider: 'badge',
                    content: req.body.badge_name
                }, function(err, badge_info) {
                    if (badge_info.finish) {
                        return res.send(badge_info);
                    } else {
                        Modals['arch'].update({
                            uid: req.user.uid,
                            provider: 'badge',
                            content: req.body.badge_name
                        }, {
                            finish: true
                        }, function(err, update_date) {
                            if (/step_/.test(req.body.badge_name)) {
                                Modals['user'].findOne({
                                    uid: req.user.uid
                                }, function(err, user_result) {
                                    var step_level = req.body.badge_name.replace('step_', '');
                                    console.log(step_level);
                                    if (user_result.step_level < step_level) {
                                        Modals['user'].update({
                                            uid: req.user.uid
                                        }, {
                                            step_level: step_level
                                        }, function(err, update_user) {});
                                    }
                                });
                            }
                            return res.send(badge_info);
                        });
                    }
                });
            } else {
                return next();
            }
        };
    }
}
<commit_msg>Fix Path in /api/arch.js<commit_after>var path = require('path');
var badges_info_list = require(path.join(process.cwd(), '/document/badges_info_list.json'));
module.exports = {
    get_arch_list: function(Models) {
        return function(req, res, next) {
            Models['arch'].find({
                uid: req.user.uid,
                provider: 'arch'
            }, function(err, result) {
                var temp_result = result;
                return res.send(temp_result);
            });
        };
    },
    create_arch: function(Models) {
        return function(req, res, next) {
            var _item = req.body;
            Models['arch'].find({
                uid: req.user.uid,
                provider: 'arch'
            }, function(err, result) {
                var temp_result = result;
                for (var i = 0; i < temp_result.length - 1; i++) {
                    if (temp_result[i].arch_name === _item.arch_name) {
                        return res.send({
                            error: true,
                            data: temp_result[i]
                        });
                    }
                    if ((i + 1) === temp_result.length) {
                        Models('arch').create({
                            aid: req.user.uid + (temp_result.length + 1),
                            uid: req.user.uid,
                            provider: 'arch',
                            arch_name: _item.arch_name,
                            information: _item.information,
                            content: _item.content,
                            frequency: 1,
                            finish: false,
                            create_time: new Date()
                        }, function(err, result) {
                            return res.send({
                                error: null,
                                data: result[i]
                            });
                        });
                    }
                }
            });
        };
    },
    create_badge: function(Models) {
        return function(req, res, next) {
            var _item = req.body;
            Models['arch'].find({
                uid: req.user.uid,
                provider: 'badge'
            }, function(err, result) {
                var temp_result = result;
                for (var i = 0; i < temp_result.length - 1; i++) {
                    if (temp_result[i].arch_name === _item.arch_name) {
                        return res.send({
                            error: true,
                            data: temp_result[i]
                        });
                    }
                    if ((i + 1) === temp_result.length) {
                        Models('arch').create({
                            aid: req.user.uid + (temp_result.length + 1),
                            uid: req.user.uid,
                            provider: 'arch',
                            arch_name: _item.arch_name,
                            information: _item.information,
                            content: _item.content,
                            frequency: 1,
                            finish: false,
                            create_time: new Date()
                        }, function(err, result) {
                            return res.send({
                                error: null,
                                data: result[i]
                            });
                        });
                    }
                }
            });
        };
    },
    get_badge: function(Models) {
        return function(req, res, next) {
            Models['arch'].findOne({
                uid: req.user.uid,
                provider: 'badge',
                content: req.params.aid
            }, function(err, result) {
                var temp_result = result;
                return res.send(temp_result);
            });
        };
    },
    get_badge_list: function(Models) {
        return function(req, res, next) {
            Models['arch'].find({
                uid: req.user.uid,
                provider: 'badge'
            }, function(err, result) {
                var temp_result = result;
                return res.send(temp_result);
            });
        };
    },
    update_badge: function(Modals) {
        return function(req, res, next) {
            if (!!req.user.uid && !!req.body.badge_name) {
                Modals['arch'].findOne({
                    uid: req.user.uid,
                    provider: 'badge',
                    content: req.body.badge_name
                }, function(err, badge_info) {
                    if (badge_info.finish) {
                        return res.send(badge_info);
                    } else {
                        Modals['arch'].update({
                            uid: req.user.uid,
                            provider: 'badge',
                            content: req.body.badge_name
                        }, {
                            finish: true
                        }, function(err, update_date) {
                            if (/step_/.test(req.body.badge_name)) {
                                Modals['user'].findOne({
                                    uid: req.user.uid
                                }, function(err, user_result) {
                                    var step_level = req.body.badge_name.replace('step_', '');
                                    console.log(step_level);
                                    if (user_result.step_level < step_level) {
                                        Modals['user'].update({
                                            uid: req.user.uid
                                        }, {
                                            step_level: step_level
                                        }, function(err, update_user) {});
                                    }
                                });
                            }
                            return res.send(badge_info);
                        });
                    }
                });
            } else {
                return next();
            }
        };
    }
}
<|endoftext|>


<commit_before>/* global QUnit sinon */

jQuery.sap.require("sap.ui.qunit.qunit-coverage");

jQuery.sap.require("sap.ui.thirdparty.sinon");
jQuery.sap.require("sap.ui.thirdparty.sinon-ie");
jQuery.sap.require("sap.ui.thirdparty.sinon-qunit");

jQuery.sap.require("sap.m.Button");
jQuery.sap.require("sap.m.Input");
jQuery.sap.require("sap.m.Label");
jQuery.sap.require("sap.m.ObjectHeader");
jQuery.sap.require("sap.m.ObjectAttribute");
jQuery.sap.require("sap.ui.core.Title");
jQuery.sap.require("sap.ui.layout.form.SimpleForm");
jQuery.sap.require("sap.ui.layout.VerticalLayout");
jQuery.sap.require("sap.ui.dt.command.BaseCommand");
jQuery.sap.require("sap.ui.dt.command.CommandFactory");

(function() {
	"use strict";

	var CommandFactory = sap.ui.dt.command.CommandFactory;

	var sandbox = sinon.sandbox.create();

	QUnit.module("Given a command factory", {
		beforeEach : function(assert) {

			this.oTitle0 = new sap.ui.core.Title({
				text : "Title 0"
			});
			this.oTitle1 = new sap.ui.core.Title({
				text : "Title 1"
			});
			this.oLabel0 = new sap.m.Label({
				text : "Label 0"
			});
			this.oLabel1 = new sap.m.Label({
				text : "Label 1"
			});
			this.oLabel2 = new sap.m.Label({
				text : "Label 2"
			});
			this.oLabel3 = new sap.m.Label({
				text : "Label 3"
			});
			this.oInput0 = new sap.m.Input();
			this.oInput1 = new sap.m.Input();
			this.oInput2 = new sap.m.Input();
			this.oInput3 = new sap.m.Input();

			this.oSimpleForm = new sap.ui.layout.form.SimpleForm({
				layout : "ResponsiveGridLayout",
				title : "Simple Form",
				content : [this.oTitle0, this.oLabel0, this.oInput0, this.oLabel1, this.oInput1, this.oTitle1, this.oLabel2,
						this.oInput2, this.oLabel3, this.oInput3]
			});

			this.oVisibleControl = new sap.m.Button();

			// Test Setup:
			// VerticalLayout
			// content
			// ObjectHeader
			// attributes
			// ObjectAttribute
			// Button

			this.oButton = new sap.m.Button();
			this.oObjectAttribute = new sap.m.ObjectAttribute({
				text : "Some attribute"
			});
			this.oObjectHeader = new sap.m.ObjectHeader({
				// title : "header",
				attributes : [this.oObjectAttribute]
			});
			this.oLayout = new sap.ui.layout.VerticalLayout({
				content : [this.oObjectHeader, this.oButton]
			});

		},
		afterEach : function(assert) {
			this.oSimpleForm.destroy();
			this.oVisibleControl.destroy();
			this.oLayout.destroy();
		}
	});

	QUnit.test("when getting a base command,", function(assert) {
		var oCmd = new sap.ui.dt.command.BaseCommand();
		assert.ok(oCmd, "then command can be instantiated");
	});

	QUnit.test("when getting a move command,", function(assert) {
		var oCmd = CommandFactory.getCommandFor(this.oVisibleControl, "Move");
		assert.ok(oCmd, "then command can be instantiated");
		assert.strictEqual(oCmd.getName(), "Move");
		assert.strictEqual(oCmd.getElement(), this.oVisibleControl);
	});

	QUnit.test("when getting a SimpleFormMove command,", function(assert) {

		var oCmd = CommandFactory.getCommandFor(this.oSimpleForm, "Move", {
			elementId : 'id_of_SimpleForm',
			movedElements : ['id_of_FormContainer_or_FormElement'],
			source : {
				//parent : this.oLayout,
				aggregation : 'formContainer_or_formElements',
				index : 0
			},
			target : {
				//parent : this.oLayout,
				aggregation : 'formContainer_or_formElements',
				index : 1
			}
		});
		assert.ok(oCmd, "then command can be instantiated");

	});

	QUnit.test("when getting a regular Move command,", function(assert) {

		var oCmd = CommandFactory.getCommandFor(this.oLayout, "Move", {
			movedElements : [{
				element : this.oButton,
				sourceIndex : 1,
				targetIndex : 0
			}],
			source : {
				parent : this.oLayout,
				aggregation : 'content',
				index : 1
			},
			target : {
				parent : this.oLayout,
				aggregation : 'content',
				index : 0
			}
		});

		oCmd.execute();

		var aContent = this.oLayout.getContent();
		assert.equal(aContent[0].getId(), this.oButton.getId(), "then the button is at position 0");
		assert.equal(aContent[1].getId(), this.oObjectHeader.getId(), "then the object header is at position 1");
		assert.equal(aContent.length, 2, "then the content aggregation has still the expected size");
		assert.ok(oCmd, "then command can be instantiated");
	});

})();
<commit_msg>[FIX] preparation for change 1793710(support sequences of add field for simple form), the deleted failing test is without value<commit_after>/* global QUnit sinon */

jQuery.sap.require("sap.ui.qunit.qunit-coverage");

jQuery.sap.require("sap.ui.thirdparty.sinon");
jQuery.sap.require("sap.ui.thirdparty.sinon-ie");
jQuery.sap.require("sap.ui.thirdparty.sinon-qunit");

jQuery.sap.require("sap.m.Button");
jQuery.sap.require("sap.m.Input");
jQuery.sap.require("sap.m.Label");
jQuery.sap.require("sap.m.ObjectHeader");
jQuery.sap.require("sap.m.ObjectAttribute");
jQuery.sap.require("sap.ui.core.Title");
jQuery.sap.require("sap.ui.layout.form.SimpleForm");
jQuery.sap.require("sap.ui.layout.VerticalLayout");
jQuery.sap.require("sap.ui.dt.command.BaseCommand");
jQuery.sap.require("sap.ui.dt.command.CommandFactory");

(function() {
	"use strict";

	var CommandFactory = sap.ui.dt.command.CommandFactory;

	var sandbox = sinon.sandbox.create();

	QUnit.module("Given a command factory", {
		beforeEach : function(assert) {

			this.oTitle0 = new sap.ui.core.Title({
				text : "Title 0"
			});
			this.oTitle1 = new sap.ui.core.Title({
				text : "Title 1"
			});
			this.oLabel0 = new sap.m.Label({
				text : "Label 0"
			});
			this.oLabel1 = new sap.m.Label({
				text : "Label 1"
			});
			this.oLabel2 = new sap.m.Label({
				text : "Label 2"
			});
			this.oLabel3 = new sap.m.Label({
				text : "Label 3"
			});
			this.oInput0 = new sap.m.Input();
			this.oInput1 = new sap.m.Input();
			this.oInput2 = new sap.m.Input();
			this.oInput3 = new sap.m.Input();

			this.oSimpleForm = new sap.ui.layout.form.SimpleForm({
				layout : "ResponsiveGridLayout",
				title : "Simple Form",
				content : [this.oTitle0, this.oLabel0, this.oInput0, this.oLabel1, this.oInput1, this.oTitle1, this.oLabel2,
						this.oInput2, this.oLabel3, this.oInput3]
			});

			this.oVisibleControl = new sap.m.Button();

			// Test Setup:
			// VerticalLayout
			// content
			// ObjectHeader
			// attributes
			// ObjectAttribute
			// Button

			this.oButton = new sap.m.Button();
			this.oObjectAttribute = new sap.m.ObjectAttribute({
				text : "Some attribute"
			});
			this.oObjectHeader = new sap.m.ObjectHeader({
				// title : "header",
				attributes : [this.oObjectAttribute]
			});
			this.oLayout = new sap.ui.layout.VerticalLayout({
				content : [this.oObjectHeader, this.oButton]
			});

		},
		afterEach : function(assert) {
			this.oSimpleForm.destroy();
			this.oVisibleControl.destroy();
			this.oLayout.destroy();
		}
	});

	QUnit.test("when getting a base command,", function(assert) {
		var oCmd = new sap.ui.dt.command.BaseCommand();
		assert.ok(oCmd, "then command can be instantiated");
	});

	QUnit.test("when getting a move command,", function(assert) {
		var oCmd = CommandFactory.getCommandFor(this.oVisibleControl, "Move");
		assert.ok(oCmd, "then command can be instantiated");
		assert.strictEqual(oCmd.getName(), "Move");
		assert.strictEqual(oCmd.getElement(), this.oVisibleControl);
	});

	QUnit.test("when getting a regular Move command,", function(assert) {

		var oCmd = CommandFactory.getCommandFor(this.oLayout, "Move", {
			movedElements : [{
				element : this.oButton,
				sourceIndex : 1,
				targetIndex : 0
			}],
			source : {
				parent : this.oLayout,
				aggregation : 'content',
				index : 1
			},
			target : {
				parent : this.oLayout,
				aggregation : 'content',
				index : 0
			}
		});

		oCmd.execute();

		var aContent = this.oLayout.getContent();
		assert.equal(aContent[0].getId(), this.oButton.getId(), "then the button is at position 0");
		assert.equal(aContent[1].getId(), this.oObjectHeader.getId(), "then the object header is at position 1");
		assert.equal(aContent.length, 2, "then the content aggregation has still the expected size");
		assert.ok(oCmd, "then command can be instantiated");
	});

})();
<|endoftext|>


<commit_before>import platform from '../utils/platform';
import keyMirror from 'keymirror';
import dialog from 'dialog';
import shell from 'shell';

import AutoUpdater from '../components/auto-updater';
import EventEmitter from 'events';

const STATES = keyMirror({
  IDLE: null,
  UPDATE_CHECKING: null,
  UPDATE_AVAILABLE: null,
  UPDATE_DOWNLOADED: null
});

class AutoUpdateManager extends EventEmitter {

  constructor(manifest, options, mainWindowManager) {
    super();

    this.manifest = manifest;
    this.options = options;
    this.mainWindowManager = mainWindowManager;

    this.enabled = !process.mas;
    this.state = STATES.IDLE;
    this.states = STATES;

    this.latestVersion = null;
    this.latestDownloadUrl = null;
  }

  init() {
    log('starting auto updater');
    this.initFeedUrl();
    this.initErrorListener();
    this.initStateListeners();
    this.initVersionListener();
  }

  initFeedUrl() {
    let feedUrl = this.manifest.updater.urls[process.platform]
      .replace(/%CURRENT_VERSION%/g, this.manifest.version);

    if (this.options.portable) {
      feedUrl += '/portable';
    }

    log('updater feed url:', feedUrl);
    AutoUpdater.setFeedURL(feedUrl);
  }

  initErrorListener() {
    AutoUpdater.on('error', (ex) => {
      logError('auto updater error', ex);
    });
  }

  initStateListeners() {
    const eventToStateMap = {
      'error': STATES.IDLE,
      'checking-for-update': STATES.UPDATE_CHECKING,
      'update-available': STATES.UPDATE_AVAILABLE,
      'update-not-available': STATES.IDLE,
      'update-downloaded': STATES.UPDATE_DOWNLOADED
    };

    for (let [eventName, state] of Object.entries(eventToStateMap)) {
      AutoUpdater.on(eventName, () => this.state = state);
    }
  }

  initVersionListener() {
    AutoUpdater.on('update-available', (newVersion, downloadUrl) => {
      this.latestVersion = newVersion;
      this.latestDownloadUrl = downloadUrl;
    });
  }

  handleMenuCheckForUpdate() {
    this.checkForUpdate(false);
  }

  handleMenuUpdateAvailable() {
    this.onCheckUpdateAvailable(this.latestVersion, this.latestDownloadUrl);
  }

  handleMenuUpdateDownloaded() {
    this.quitAndInstall();
  }

  onCheckUpdateAvailable(newVersion, downloadUrl) {
    log('onCheckUpdateAvailable', 'newVersion:', newVersion, 'downloadUrl:', downloadUrl);
    if (platform.isLinux) {
      dialog.showMessageBox({
        type: 'info',
        message: 'A new version is available: ' + newVersion,
        detail: 'Use your package manager to update, or click Download to get the new package.',
        buttons: ['OK', 'Download']
      }, function(response) {
        if (response === 1) {
          log('user clicked Download, opening url', downloadUrl);
          shell.openExternal(downloadUrl);
        }
      });
    } else if (platform.isWin && this.options.portable) {
      dialog.showMessageBox({
        type: 'info',
        message: 'A new version is available: ' + newVersion,
        detail: 'Click Download to get a portable zip with the new version.',
        buttons: ['OK', 'Download']
      }, function(response) {
        if (response === 1) {
          log('user clicked Download, opening url', downloadUrl);
          shell.openExternal(downloadUrl);
        }
      });
    } else {
      dialog.showMessageBox({
        type: 'info',
        message: 'A new version is available.',
        detail: 'It will start downloading in the background.',
        buttons: ['OK']
      }, function() {});
    }
  }

  onCheckUpdateNotAvailable() {
    log('onCheckUpdateNotAvailable');
    dialog.showMessageBox({
      type: 'info',
      message: 'No update available.',
      detail: 'You are using the latest version: ' + this.manifest.version,
      buttons: ['OK']
    }, function() {});
  }

  onCheckError(err) {
    log('onCheckError:', err);
    dialog.showMessageBox({
      type: 'warning',
      message: 'Error while checking for update.',
      detail: err.message,
      buttons: ['OK']
    }, function() {});
  }

  scheduleUpdateChecks() {
    setInterval(::this.checkForUpdate, 1000 * 60 * 60 * 4); // 4 hours
    this.checkForUpdate();
  }

  checkForUpdate(silent = true) {
    log('checking for update...');
    AutoUpdater.checkForUpdates();
    if (!silent) {
      const onCheck = {};

      const removeListeners = () => {
        AutoUpdater.removeListener('update-available', onCheck.updateAvailable);
        AutoUpdater.removeListener('update-not-available', onCheck.updateNotAvailable);
        AutoUpdater.removeListener('error', onCheck.error);
      };

      onCheck.updateAvailable = () => {
        this.onCheckUpdateAvailable.apply(this, arguments);
        removeListeners();
      };

      onCheck.updateNotAvailable = () => {
        this.onCheckUpdateNotAvailable.apply(this, arguments);
        removeListeners();
      };

      onCheck.error = () => {
        this.onCheckError.apply(this, arguments);
        removeListeners();
      };

      AutoUpdater.once('update-available', onCheck.updateAvailable);
      AutoUpdater.once('update-not-available', onCheck.updateNotAvailable);
      AutoUpdater.once('error', onCheck.error);
    }
  }

  quitAndInstall() {
    if (this.mainWindowManager) {
      this.mainWindowManager.updateInProgress = true;
      AutoUpdater.quitAndInstall();
    } else {
      logError(new Error('cannot quit to install update'));
    }
  }

}

export default AutoUpdateManager;
<commit_msg>Changes dialog type for updater errors<commit_after>import platform from '../utils/platform';
import keyMirror from 'keymirror';
import dialog from 'dialog';
import shell from 'shell';

import AutoUpdater from '../components/auto-updater';
import EventEmitter from 'events';

const STATES = keyMirror({
  IDLE: null,
  UPDATE_CHECKING: null,
  UPDATE_AVAILABLE: null,
  UPDATE_DOWNLOADED: null
});

class AutoUpdateManager extends EventEmitter {

  constructor(manifest, options, mainWindowManager) {
    super();

    this.manifest = manifest;
    this.options = options;
    this.mainWindowManager = mainWindowManager;

    this.enabled = !process.mas;
    this.state = STATES.IDLE;
    this.states = STATES;

    this.latestVersion = null;
    this.latestDownloadUrl = null;
  }

  init() {
    log('starting auto updater');
    this.initFeedUrl();
    this.initErrorListener();
    this.initStateListeners();
    this.initVersionListener();
  }

  initFeedUrl() {
    let feedUrl = this.manifest.updater.urls[process.platform]
      .replace(/%CURRENT_VERSION%/g, this.manifest.version);

    if (this.options.portable) {
      feedUrl += '/portable';
    }

    log('updater feed url:', feedUrl);
    AutoUpdater.setFeedURL(feedUrl);
  }

  initErrorListener() {
    AutoUpdater.on('error', (ex) => {
      logError('auto updater error', ex);
    });
  }

  initStateListeners() {
    const eventToStateMap = {
      'error': STATES.IDLE,
      'checking-for-update': STATES.UPDATE_CHECKING,
      'update-available': STATES.UPDATE_AVAILABLE,
      'update-not-available': STATES.IDLE,
      'update-downloaded': STATES.UPDATE_DOWNLOADED
    };

    for (let [eventName, state] of Object.entries(eventToStateMap)) {
      AutoUpdater.on(eventName, () => this.state = state);
    }
  }

  initVersionListener() {
    AutoUpdater.on('update-available', (newVersion, downloadUrl) => {
      this.latestVersion = newVersion;
      this.latestDownloadUrl = downloadUrl;
    });
  }

  handleMenuCheckForUpdate() {
    this.checkForUpdate(false);
  }

  handleMenuUpdateAvailable() {
    this.onCheckUpdateAvailable(this.latestVersion, this.latestDownloadUrl);
  }

  handleMenuUpdateDownloaded() {
    this.quitAndInstall();
  }

  onCheckUpdateAvailable(newVersion, downloadUrl) {
    log('onCheckUpdateAvailable', 'newVersion:', newVersion, 'downloadUrl:', downloadUrl);
    if (platform.isLinux) {
      dialog.showMessageBox({
        type: 'info',
        message: 'A new version is available: ' + newVersion,
        detail: 'Use your package manager to update, or click Download to get the new package.',
        buttons: ['OK', 'Download']
      }, function(response) {
        if (response === 1) {
          log('user clicked Download, opening url', downloadUrl);
          shell.openExternal(downloadUrl);
        }
      });
    } else if (platform.isWin && this.options.portable) {
      dialog.showMessageBox({
        type: 'info',
        message: 'A new version is available: ' + newVersion,
        detail: 'Click Download to get a portable zip with the new version.',
        buttons: ['OK', 'Download']
      }, function(response) {
        if (response === 1) {
          log('user clicked Download, opening url', downloadUrl);
          shell.openExternal(downloadUrl);
        }
      });
    } else {
      dialog.showMessageBox({
        type: 'info',
        message: 'A new version is available.',
        detail: 'It will start downloading in the background.',
        buttons: ['OK']
      }, function() {});
    }
  }

  onCheckUpdateNotAvailable() {
    log('onCheckUpdateNotAvailable');
    dialog.showMessageBox({
      type: 'info',
      message: 'No update available.',
      detail: 'You are using the latest version: ' + this.manifest.version,
      buttons: ['OK']
    }, function() {});
  }

  onCheckError(err) {
    log('onCheckError:', err);
    dialog.showMessageBox({
      type: 'error',
      message: 'Error while checking for update.',
      detail: err.message,
      buttons: ['OK']
    }, function() {});
  }

  scheduleUpdateChecks() {
    setInterval(::this.checkForUpdate, 1000 * 60 * 60 * 4); // 4 hours
    this.checkForUpdate();
  }

  checkForUpdate(silent = true) {
    log('checking for update...');
    AutoUpdater.checkForUpdates();
    if (!silent) {
      const onCheck = {};

      const removeListeners = () => {
        AutoUpdater.removeListener('update-available', onCheck.updateAvailable);
        AutoUpdater.removeListener('update-not-available', onCheck.updateNotAvailable);
        AutoUpdater.removeListener('error', onCheck.error);
      };

      onCheck.updateAvailable = () => {
        this.onCheckUpdateAvailable.apply(this, arguments);
        removeListeners();
      };

      onCheck.updateNotAvailable = () => {
        this.onCheckUpdateNotAvailable.apply(this, arguments);
        removeListeners();
      };

      onCheck.error = () => {
        this.onCheckError.apply(this, arguments);
        removeListeners();
      };

      AutoUpdater.once('update-available', onCheck.updateAvailable);
      AutoUpdater.once('update-not-available', onCheck.updateNotAvailable);
      AutoUpdater.once('error', onCheck.error);
    }
  }

  quitAndInstall() {
    if (this.mainWindowManager) {
      this.mainWindowManager.updateInProgress = true;
      AutoUpdater.quitAndInstall();
    } else {
      logError(new Error('cannot quit to install update'));
    }
  }

}

export default AutoUpdateManager;
<|endoftext|>


<commit_before>var SUPPORTED_IMAGE_TYPES = ['jpg','jpeg','png','gif'];

var Semver = function(ver) {
  var segs = ver.split('.');
  return { major: (segs[0] || 0), minor: (segs[1] || 0), patch: (segs[2] || 0), version: ver };
};

var isValidFileType = function(extension) {
  return SUPPORTED_IMAGE_TYPES.indexOf(extension) >= 0;
};

var getOrInsertFileInput = function() {
  if (document.getElementById('asset-input')) {
    return document.getElementById('asset-input');
  }

  var assetInput = document.createElement('input');

  assetInput.type = 'file';
  assetInput.style.display = 'none';
  assetInput.id = 'asset-input';

  // Stop event propagation to make sure we don't set editable state to false
  //  - when we click on the input[type="file"]
  assetInput.onclick = function(event) {
    event.stopPropagation();
  };

  return assetInput;
};

var postAsset = function(url, sessionId, assetData, callback) {
  var request = new XMLHttpRequest();

  var formData = new FormData();
  Object.keys(assetData).forEach(function(key) {
    if (key === 'tags') {
      formData.append(key, JSON.stringify(assetData[key]));
    } else {
      formData.append(key, assetData[key]);
    }
  });

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      if (request.status == 201) {
        return callback(null, JSON.parse(request.responseText));
      } else {
        return callback(new Error('Something went wrong when uploading an asset. please try again'));
      }
    }
  };

  request.open('POST', url + '/assets', true);
  request.setRequestHeader('SID', sessionId);
  request.send(formData);
};

var serializeFile = function(file, type) {
  var fileNameSplit = file.name.split('.'),
      extension     = fileNameSplit[fileNameSplit.length - 1],
      contentType   = file.type || type + '/x-' + extension;

  if (!isValidFileType(extension)) {
    return console.warn('invalid file type:', extension);
  }

  var attributes = {
    title:        'New File',
    type:         type,
    tags:         [type],
    content:      file,
    contentType:  contentType
  };

  return attributes;
};

var patch = function(to, from) {
  if(from) {
    Object.keys(from).forEach(function(key){
      to[key] = from[key];
      if (to[key] === null) {
        delete to[key];
      }
    });
  }
  return to;
};

var isNullish = function(obj) {
  return obj == null; // jshint ignore:line
};

var JSONDeepEquals = function(o1, o2) {
  if (typeof o1 !== "object" || typeof o1 !== typeof o2 || isNullish(o1) || isNullish(o2)) {
    return o1 === o2;
  }

  var k1 = Object.keys(o1).sort();
  var k2 = Object.keys(o2).sort();
  if (k1.length != k2.length) return false;

  for (var i=0; i<k1.length; i++) {
    if (!JSONDeepEquals(o1[k1[i]], o2[k2[i]])) return false;
  }
  return true;
};

var prototype = Object.create(HTMLElement.prototype, {
  src: {
    get: function(){ return this.getAttribute('src') || 'about:blank'; }
  },

  editable: {
    get: function(){ return this.getAttribute('editable') == 'true'; }
  },

  env: {
    get: function(){ return this.readAttributeAsJson('data-environment'); }
  },

  config: {
    get: function(){ return this.readAttributeAsJson('data-config'); }
  },

  userstate: {
    get: function(){ return this.readAttributeAsJson('data-userstate'); }
  },

  debug: {
    get: function(){ return this.hasAttribute('debug'); }
  },

  apiVersion: {
    get: function(){
      if(!this._apiVersion) {
        this._apiVersion = new Semver(this.getAttribute('data-api-version') || '0.0.0');
      }
      return this._apiVersion;
    }
  }
});

prototype.readAttributeAsJson = function(name) {
  if(!this.hasAttribute(name)) { return {}; }
  return JSON.parse(this.getAttribute(name));
};

prototype.log = function(dir, event, data) {
  if(this.debug) { console.log(dir, event, data); }
};

prototype.createdCallback = function() {
  this._previousMessages = {};
};

prototype.attachedCallback = function(){
  this.iframe = document.createElement('iframe');
  this.iframe.src = this.src;
  this.iframe.addEventListener('message', this.handleMessage.bind(this));
  this.iframe.setAttribute('allowfullscreen', 'allowfullscreen');

  this.appendChild(this.iframe);
};

prototype.detachedCallback = function(){
  this.removeChild(this.iframe);
  this._reset();
};

prototype._reset = function(){
  this._previousMessages = {};
  window.clearTimeout(this._attributesChangedTimeout);
  window.clearTimeout(this._learnerStateChangedTimeout);
};

prototype.attributeChangedCallback = function(name, oldAttribute, newAttribute){
  switch(name) {
    case 'editable':
      this.sendMessage('editableChanged', { editable: this.editable });
      if(this.apiVersion.minor < 1) {
        this.sendMessage('setEditable', { editable: this.editable });
      }
      break;

    case 'data-config':
      window.clearTimeout(this._attributesChangedTimeout);
      this._attributesChangedTimeout = window.setTimeout((function() {
        this.sendMessage('attributesChanged', this.config);
      }).bind(this));
      break;

    case 'data-userstate':
      window.clearTimeout(this._learnerStateChangedTimeout);
      this._learnerStateChangedTimeout = window.setTimeout((function() {
        this.sendMessage('learnerStateChanged', this.userstate);
      }).bind(this));
      break;
  }
};

prototype.handleMessage = function(event) {
  if(event.detail.event) {
    var eventName = event.detail.event;
    var data = event.detail.data;

    this.log('↖', eventName, data);

    var handler = this.messageHandlers[eventName];
    if(handler) {
      handler.call(this, data);
    } else {
      console.error('Unknown event received: ' + eventName);
      this.error({message: 'Unknown event received: ' + eventName});
    }
  }
};

prototype.sendMessage = function(eventName, data) {
  if (!this._listening) return;
  if (JSONDeepEquals(this._previousMessages[eventName], data)) return;

  var message = { event: eventName };
  if(data) { message.data = data; }
  if(this.iframe && this.iframe.contentWindow) {
    this.iframe.contentWindow.postMessage(message, '*');
    this.log('↘', message.event, message.data);
    this._previousMessages[eventName] = data;
  }
};

prototype.fireCustomEvent = function(eventName, data, options) {
  options = options || {};
  var evt = new CustomEvent(eventName, { detail: data, bubbles: options.bubbles || false });
  this.dispatchEvent(evt);
};

prototype.messageHandlers = {
  startListening: function(){
    this._reset();
    this._listening = true;
    this.sendMessage('environmentChanged', this.env);
    this.sendMessage('attributesChanged', this.config);
    this.sendMessage('learnerStateChanged', this.userstate);
    this.sendMessage('editableChanged', { editable: this.editable });
  },

  setHeight: function(data){
    this.iframe.style.height = data.pixels + 'px';
    if (!this._firedRendered) {
      this._firedRendered = true;
      this.fireCustomEvent('rendered');
    }
  },

  setAttributes: function(data){
    if(!this.editable && !this.uploadingAsset) {
      console.warn('Unable to setAttributes in the read-only state');
      return;
    }
    var config = this.readAttributeAsJson('data-config');
    patch(config, data);
    this.setAttribute('data-config', JSON.stringify(config));

    // Player needs those events, until we have mutation observers in place
    this.fireCustomEvent('setAttributes', config);
  },

  setLearnerState: function(data) {
    var userstate = this.readAttributeAsJson('data-userstate');
    patch(userstate, data);
    this.setAttribute('data-userstate', JSON.stringify(userstate));

    // Player needs those events, until we have mutation observers in place
    this.fireCustomEvent('setLearnerState', userstate);
  },

  getPath: function(data) {
    console.warn('getPath/setPath are obsolete');
    var assetUrlTemplate = this.env && this.env.assetUrlTemplate;
    if(assetUrlTemplate) {
      var url = assetUrlTemplate.replace('<%= id %>', data.assetId );
      this.sendMessage('setPath', { url: url});
    }
  },

  setPropertySheetAttributes: function(data) { this.fireCustomEvent('setPropertySheetAttributes', data); },
  track: function(data) { this.fireCustomEvent('track', data, {bubbles: true}); },
  error: function(data) { this.fireCustomEvent('error', data, {bubbles: true}); },
  requestAsset: function(data) {
    // TODO support other updload types
    if (data.type == 'video') {
      this.fireCustomEvent('requestAsset', data);
      return;
    }
    var apiUrl      = this.env.apiUrl,
        sessionId   = this.env.sessionId,
        assetInput  = getOrInsertFileInput();

    assetInput = this.appendChild(assetInput);
    assetInput.click();

    var that = this;
    assetInput.onchange = function(e) {
      if (e && e.target && e.target.files && e.target.files[0]) {
        var serializedFile = serializeFile(e.target.files[0], 'image');

        if (!serializeFile) {
          return;
        }
        // To patch attributesChanged if author toggles out of gadget editing
        that.uploadingAsset = true;

        var loadingOverlay;
        if (document.querySelector('.asset-loading-overlay')) {
          loadingOverlay = document.querySelector('.asset-loading-overlay');
        }

        var loadingOverlay = document.createElement('div');
        loadingOverlay.className = 'asset-loading-overlay';
        loadingOverlay.innerHTML = '
Loading...
';

        that.appendChild(loadingOverlay);

        loadingOverlay.className = 'asset-loading-overlay';
        postAsset(apiUrl, sessionId, serializedFile, function(error, assetJson) {
          loadingOverlay.className = 'asset-loading-overlay hidden';
          if (error) {
            return alert(error.message);
          }

          var assetAttributes = {};
          assetAttributes[data.attribute] = assetJson;
          that.sendMessage('attributesChanged', assetAttributes);

          // After a period of time allotted to communicate the change to 'attributesChanged'
          // set uploadingAsset to false
          setTimeout(function() { that.uploadingAsset = false; }, 1000)
        });
      }
    };
  },

  // Soon to be deprecated in favour of in-iframe APIs
  // E.g. https://github.com/Versal/challenges-js-api/
  setEmpty: function(data) { this.fireCustomEvent('setEmpty', data); },
  changeBlocking: function(data) { this.fireCustomEvent('changeBlocking', data); }
};

window.addEventListener('message', function(event){
  var iframes = document.querySelectorAll('versal-iframe-launcher > iframe');
  Array.prototype.forEach.call(iframes, function(iframe){
    if(iframe.contentWindow == event.source) {
      iframe.dispatchEvent(new CustomEvent('message', { detail: event.data }));
    }
  });
});

document.registerElement('versal-iframe-launcher', { prototype: prototype });
<commit_msg>onselect listener for asset input / render on created<commit_after>var SUPPORTED_IMAGE_TYPES = ['jpg','jpeg','png','gif'];

var Semver = function(ver) {
  var segs = ver.split('.');
  return { major: (segs[0] || 0), minor: (segs[1] || 0), patch: (segs[2] || 0), version: ver };
};

var isValidFileType = function(extension) {
  return SUPPORTED_IMAGE_TYPES.indexOf(extension) >= 0;
};

var getOrCreateAssetInput = function() {
  if (document.getElementById('asset-input')) {
    return document.getElementById('asset-input');
  }

  var assetInput = document.createElement('input');

  assetInput.type = 'file';
  assetInput.style.display = 'none';
  assetInput.id = 'asset-input';

  // Stop event propagation to make sure we don't set editable state to false
  //  - when we click on the input[type="file"]
  assetInput.onclick = function(event) {
    event.stopPropagation();
  };

  return assetInput;
};

var getOrCreateLoadingOverlay = function() {
  var loadingOverlay;
  if (document.querySelector('.asset-loading-overlay')) {
    loadingOverlay = document.querySelector('.asset-loading-overlay');
  } else {
    var loadingOverlay = document.createElement('div');
    loadingOverlay.className = 'asset-loading-overlay';
    loadingOverlay.innerHTML = '
Loading...
';

    loadingOverlay.className = 'asset-loading-overlay hidden';
  }
  return loadingOverlay;
};

var postAsset = function(url, sessionId, assetData, callback) {
  var request = new XMLHttpRequest();

  var formData = new FormData();
  Object.keys(assetData).forEach(function(key) {
    if (key === 'tags') {
      formData.append(key, JSON.stringify(assetData[key]));
    } else {
      formData.append(key, assetData[key]);
    }
  });

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      if (request.status == 201) {
        return callback(null, JSON.parse(request.responseText));
      } else {
        return callback(new Error('Something went wrong when uploading an asset. please try again'));
      }
    }
  };

  request.open('POST', url + '/assets', true);
  request.setRequestHeader('SID', sessionId);
  request.send(formData);
};

var serializeFile = function(file, type) {
  var fileNameSplit = file.name.split('.'),
      extension     = fileNameSplit[fileNameSplit.length - 1],
      contentType   = file.type || type + '/x-' + extension;

  if (!isValidFileType(extension)) {
    return console.warn('invalid file type:', extension);
  }

  var attributes = {
    title:        'New File',
    type:         type,
    tags:         [type],
    content:      file,
    contentType:  contentType
  };

  return attributes;
};

var patch = function(to, from) {
  if(from) {
    Object.keys(from).forEach(function(key){
      to[key] = from[key];
      if (to[key] === null) {
        delete to[key];
      }
    });
  }
  return to;
};

var isNullish = function(obj) {
  return obj == null; // jshint ignore:line
};

var JSONDeepEquals = function(o1, o2) {
  if (typeof o1 !== "object" || typeof o1 !== typeof o2 || isNullish(o1) || isNullish(o2)) {
    return o1 === o2;
  }

  var k1 = Object.keys(o1).sort();
  var k2 = Object.keys(o2).sort();
  if (k1.length != k2.length) return false;

  for (var i=0; i<k1.length; i++) {
    if (!JSONDeepEquals(o1[k1[i]], o2[k2[i]])) return false;
  }
  return true;
};

var prototype = Object.create(HTMLElement.prototype, {
  src: {
    get: function(){ return this.getAttribute('src') || 'about:blank'; }
  },

  editable: {
    get: function(){ return this.getAttribute('editable') == 'true'; }
  },

  env: {
    get: function(){ return this.readAttributeAsJson('data-environment'); }
  },

  config: {
    get: function(){ return this.readAttributeAsJson('data-config'); }
  },

  userstate: {
    get: function(){ return this.readAttributeAsJson('data-userstate'); }
  },

  debug: {
    get: function(){ return this.hasAttribute('debug'); }
  },

  apiVersion: {
    get: function(){
      if(!this._apiVersion) {
        this._apiVersion = new Semver(this.getAttribute('data-api-version') || '0.0.0');
      }
      return this._apiVersion;
    }
  }
});

prototype.readAttributeAsJson = function(name) {
  if(!this.hasAttribute(name)) { return {}; }
  return JSON.parse(this.getAttribute(name));
};

prototype.log = function(dir, event, data) {
  if(this.debug) { console.log(dir, event, data); }
};

prototype.createdCallback = function() {
  this._previousMessages = {};
};

prototype.attachedCallback = function(){
  this.iframe = document.createElement('iframe');
  this.iframe.src = this.src;
  this.iframe.addEventListener('message', this.handleMessage.bind(this));
  this.iframe.setAttribute('allowfullscreen', 'allowfullscreen');

  this.appendChild(this.iframe);

  this.assetInput      = getOrCreateAssetInput();
  this.loadingOverlay  = getOrCreateLoadingOverlay();

  this.appendChild(this.assetInput);
  this.appendChild(this.loadingOverlay);
};

prototype.detachedCallback = function(){
  this.removeChild(this.iframe);
  this._reset();
};

prototype._reset = function(){
  this._previousMessages = {};
  window.clearTimeout(this._attributesChangedTimeout);
  window.clearTimeout(this._learnerStateChangedTimeout);
};

prototype.attributeChangedCallback = function(name, oldAttribute, newAttribute){
  switch(name) {
    case 'editable':
      this.sendMessage('editableChanged', { editable: this.editable });
      if(this.apiVersion.minor < 1) {
        this.sendMessage('setEditable', { editable: this.editable });
      }
      break;

    case 'data-config':
      window.clearTimeout(this._attributesChangedTimeout);
      this._attributesChangedTimeout = window.setTimeout((function() {
        this.sendMessage('attributesChanged', this.config);
      }).bind(this));
      break;

    case 'data-userstate':
      window.clearTimeout(this._learnerStateChangedTimeout);
      this._learnerStateChangedTimeout = window.setTimeout((function() {
        this.sendMessage('learnerStateChanged', this.userstate);
      }).bind(this));
      break;
  }
};

prototype.handleMessage = function(event) {
  if(event.detail.event) {
    var eventName = event.detail.event;
    var data = event.detail.data;

    this.log('↖', eventName, data);

    var handler = this.messageHandlers[eventName];
    if(handler) {
      handler.call(this, data);
    } else {
      console.error('Unknown event received: ' + eventName);
      this.error({message: 'Unknown event received: ' + eventName});
    }
  }
};

prototype.sendMessage = function(eventName, data) {
  if (!this._listening) return;
  if (JSONDeepEquals(this._previousMessages[eventName], data)) return;

  var message = { event: eventName };
  if(data) { message.data = data; }
  if(this.iframe && this.iframe.contentWindow) {
    this.iframe.contentWindow.postMessage(message, '*');
    this.log('↘', message.event, message.data);
    this._previousMessages[eventName] = data;
  }
};

prototype.fireCustomEvent = function(eventName, data, options) {
  options = options || {};
  var evt = new CustomEvent(eventName, { detail: data, bubbles: options.bubbles || false });
  this.dispatchEvent(evt);
};

prototype.uploadAssetAndSetAttributes = function(data, file) {
  var apiUrl      = this.env.apiUrl,
      sessionId   = this.env.sessionId,
      serializedFile = serializeFile(file, 'image');

  if (!serializedFile) { return; }

  // To patch attributesChanged if author toggles out of gadget editing
  this.uploadingAsset = true;
  this.loadingOverlay.className = 'asset-loading-overlay';

  postAsset(apiUrl, sessionId, serializedFile, function(error, assetJson) {
    this.loadingOverlay.className = 'asset-loading-overlay hidden';
    if (error) {
      return alert(error.message);
    }

    var assetAttributes = {};
    assetAttributes[data.attribute] = assetJson;
    this.sendMessage('attributesChanged', assetAttributes);

    // After a period of time allotted to communicate the change to 'attributesChanged'
    // set uploadingAsset to false
    setTimeout(function() { this.uploadingAsset = false; }.bind(this), 1000)
  }.bind(this));
};

prototype.messageHandlers = {
  startListening: function(){
    this._reset();
    this._listening = true;
    this.sendMessage('environmentChanged', this.env);
    this.sendMessage('attributesChanged', this.config);
    this.sendMessage('learnerStateChanged', this.userstate);
    this.sendMessage('editableChanged', { editable: this.editable });
  },

  setHeight: function(data){
    this.iframe.style.height = data.pixels + 'px';
    if (!this._firedRendered) {
      this._firedRendered = true;
      this.fireCustomEvent('rendered');
    }
  },

  setAttributes: function(data){
    if(!this.editable && !this.uploadingAsset) {
      console.warn('Unable to setAttributes in the read-only state');
      return;
    }
    var config = this.readAttributeAsJson('data-config');
    patch(config, data);
    this.setAttribute('data-config', JSON.stringify(config));

    // Player needs those events, until we have mutation observers in place
    this.fireCustomEvent('setAttributes', config);
  },

  setLearnerState: function(data) {
    var userstate = this.readAttributeAsJson('data-userstate');
    patch(userstate, data);
    this.setAttribute('data-userstate', JSON.stringify(userstate));

    // Player needs those events, until we have mutation observers in place
    this.fireCustomEvent('setLearnerState', userstate);
  },

  getPath: function(data) {
    console.warn('getPath/setPath are obsolete');
    var assetUrlTemplate = this.env && this.env.assetUrlTemplate;
    if(assetUrlTemplate) {
      var url = assetUrlTemplate.replace('<%= id %>', data.assetId );
      this.sendMessage('setPath', { url: url});
    }
  },

  setPropertySheetAttributes: function(data) { this.fireCustomEvent('setPropertySheetAttributes', data); },
  track: function(data) { this.fireCustomEvent('track', data, {bubbles: true}); },
  error: function(data) { this.fireCustomEvent('error', data, {bubbles: true}); },
  requestAsset: function(data) {
    // TODO support other updload types
    if (data.type == 'video') {
      return this.fireCustomEvent('requestAsset', data);
    }

    this.assetInput.click();
    this.assetInput.onchange = function(e) {
      if (e && e.target && e.target.files && e.target.files[0]) {
        this.uploadAssetAndSetAttributes(data, e.target.files[0]);
      }
    }.bind(this);
  },

  // Soon to be deprecated in favour of in-iframe APIs
  // E.g. https://github.com/Versal/challenges-js-api/
  setEmpty: function(data) { this.fireCustomEvent('setEmpty', data); },
  changeBlocking: function(data) { this.fireCustomEvent('changeBlocking', data); }
};

window.addEventListener('message', function(event){
  var iframes = document.querySelectorAll('versal-iframe-launcher > iframe');
  Array.prototype.forEach.call(iframes, function(iframe){
    if(iframe.contentWindow == event.source) {
      iframe.dispatchEvent(new CustomEvent('message', { detail: event.data }));
    }
  });
});

document.registerElement('versal-iframe-launcher', { prototype: prototype });
<|endoftext|>


<commit_before>/*!
 * -------------
 * NobelDB®-Data
 * -------------
 * Data of NobelDB — A manually curated dedicated database of Nobel Laureates.
 * ___________________________________________________________________________
 *
 * Grunt, http://gruntjs.com/ — The JavaScript Task Runner.
 * ___________________________________________________________________________
 *
 * Architecture and Code Handcrafted by Prabhat Kumar.
 * Architectuur en Code handgemaakt door Prabhat Kumar.
 * @author    : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Sequømics Research [http://research.sequomics.com/].
 * @copyright : Sequømics Corporation [http://sequomics.com/].
 * ___________________________________________________________________________
 *
 * @date      : 28-Nov-2016
 * @license   : Apache, version 2.0
 * @require   : Node.js®
 * @require   : NPM
 * @require   : Request
 * @build     : SEED™ — Umeå
 *              └────── A Sequømics Product — http://sequomics.com/.
 * ___________________________________________________________________________
 *
 * --/The Heart of Build System/-- of "NobelDB®-Data".
 * ___________________________________________________________________________
 */

module.exports = function(grunt) {

  // To load required NPM modules.
  // -----------------------------
  var chalk    = require('chalk');
  var request  = require('request');

  // Default color defined.
  // ----------------------
  var noop     = chalk.red;
  var yeep     = chalk.green;
  var okay     = chalk.blue;

  /*!
   * Getting Started with Nobel Prize API
   * ------------------------------------
   * [Nobelprize.org/] offers open data to developers in two ways: An API and as Linked Data.
   * The data is free to use and contains information about who has been awarded the Nobel Prize,
   * when, in what prize category and the motivation, as well as basic information about the Nobel Laureates
   * such as birth data and the affiliation at the time of the award. The data is regularly updated
   * as the information on Nobelprize.org is updated, including at the time of announcements of new Laureates.
   * ---------------------------------------------------------------------------------------------------------
   * The REST based API provides different ways to list and search the data.
   * The result is returned as JSON or CSV.
   */

  // https://nobelprize.readme.io/.
  grunt.registerTask("get", "Connecting to the API of [Nobelprize.org/].", function() {

    var path        = require('path');
    var seedFile    = path.resolve(__dirname, 'seed.json');
<commit_msg>Initial commit<commit_after>/*!
 * -------------
 * NobelDB®-Data
 * -------------
 * Data of NobelDB — A manually curated dedicated database of Nobel Laureates.
 * ___________________________________________________________________________
 *
 * Grunt, http://gruntjs.com/ — The JavaScript Task Runner.
 * ___________________________________________________________________________
 *
 * Architecture and Code Handcrafted by Prabhat Kumar.
 * Architectuur en Code handgemaakt door Prabhat Kumar.
 * @author    : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Sequømics Research [http://research.sequomics.com/].
 * @copyright : Sequømics Corporation [http://sequomics.com/].
 * ___________________________________________________________________________
 *
 * @date      : 28-Nov-2016
 * @license   : Apache, version 2.0
 * @require   : Node.js®
 * @require   : NPM
 * @require   : Request
 * @build     : SEED™ — Umeå
 *              └────── A Sequømics Product — http://sequomics.com/.
 * ___________________________________________________________________________
 *
 * --/The Heart of Build System/-- of "NobelDB®-Data".
 * ___________________________________________________________________________
 */

module.exports = function(grunt) {

  // To load required NPM modules.
  // -----------------------------
  var chalk    = require('chalk');
  var request  = require('request');

  // Default color defined.
  // ----------------------
  var noop     = chalk.red;
  var yeep     = chalk.green;
  var okay     = chalk.blue;

  /*!
   * Getting Started with Nobel Prize API
   * ------------------------------------
   * [Nobelprize.org/] offers open data to developers in two ways: An API and as Linked Data.
   * The data is free to use and contains information about who has been awarded the Nobel Prize,
   * when, in what prize category and the motivation, as well as basic information about the Nobel Laureates
   * such as birth data and the affiliation at the time of the award. The data is regularly updated
   * as the information on Nobelprize.org is updated, including at the time of announcements of new Laureates.
   * ---------------------------------------------------------------------------------------------------------
   * The REST based API provides different ways to list and search the data.
   * The result is returned as JSON or CSV.
   */

  // https://nobelprize.readme.io/.
  grunt.registerTask("get", "Connecting to the API of [Nobelprize.org/].", function() {

    var path        = require('path');
    var seedFile    = path.resolve(__dirname, 'seed.json');
    // ---------------[API URL of nobelprize.org]----------
    var apiURL      = "http://api.nobelprize.org/v1/";
<|endoftext|>


<commit_before>/*
 * grunt-gta
 * https://github.com/ZuBB/grunt-gta
 *
 * Copyright (c) 2014 Vasyl Zuzyak
 * Licensed under the MIT license.
 */

'use strict';
var exec = require('child_process').exec;

module.exports = function(grunt) {
    grunt.registerMultiTask('gta', 'All Git commands for grunt', function() {
        var cb = this.async();
        var cmd = this.data.command;
        var options = this.options({
            failOnError: true,

            stdout: false,
            stderr: false,

            storeOutputTo: '',
            postProcessOutput: null,

            cwd: null
        });

        if (typeof cmd !== 'string') {
            throw new Error('`command` required');
        }

        cmd = 'git ' + cmd;
        grunt.verbose.writeln('Command:', cmd);

        var childProcess = exec(cmd, {cwd: options.cwd}, function (error) {
            if (error && options.failOnError) {
                grunt.warn(error);
            }

            cb();
        });

        var output = '';
        var func = options.postProcessOutput;
        var variable = options.storeOutputTo;

        if (typeof variable === 'string' && variable !== '') {
            childProcess.stdout.on('data', function(buf) {
                output += buf.toString();
            });
            childProcess.stdout.on('end', function() {
                var value = typeof func === 'function' ? func(output) : output;
                grunt.config(variable, value);
            });
        }

        if (options.stdout || grunt.option('verbose')) {
            childProcess.stdout.pipe(process.stdout);
        }

        if (options.stderr || grunt.option('verbose')) {
            childProcess.stderr.pipe(process.stderr);
        }
    });
};
<commit_msg>gta: be less strick as for specifying 'git' word<commit_after>/*
 * grunt-gta
 * https://github.com/ZuBB/grunt-gta
 *
 * Copyright (c) 2014 Vasyl Zuzyak
 * Licensed under the MIT license.
 */

'use strict';
var exec = require('child_process').exec;

module.exports = function(grunt) {
    grunt.registerMultiTask('gta', 'All Git commands for grunt', function() {
        var cb = this.async();
        var cmd = this.data.command.trim();
        var options = this.options({
            failOnError: true,

            stdout: false,
            stderr: false,

            storeOutputTo: '',
            postProcessOutput: null,

            cwd: null
        });

        if (typeof cmd !== 'string') {
            throw new Error('`command` required');
        }

        if (cmd.indexOf('git ') !== 0) {
            cmd = 'git ' + cmd;
        }

        grunt.verbose.writeln('Command:', cmd);

        var childProcess = exec(cmd, {cwd: options.cwd}, function (error) {
            if (error && options.failOnError) {
                grunt.warn(error);
            }

            cb();
        });

        var output = '';
        var func = options.postProcessOutput;
        var variable = options.storeOutputTo;

        if (typeof variable === 'string' && variable !== '') {
            childProcess.stdout.on('data', function(buf) {
                output += buf.toString();
            });
            childProcess.stdout.on('end', function() {
                var value = typeof func === 'function' ? func(output) : output;
                grunt.config(variable, value);
            });
        }

        if (options.stdout || grunt.option('verbose')) {
            childProcess.stdout.pipe(process.stdout);
        }

        if (options.stderr || grunt.option('verbose')) {
            childProcess.stderr.pipe(process.stderr);
        }
    });
};
<|endoftext|>


<commit_before>exports.getByAgencyLocationId = function(reg, res, next) {
    res.send(200, [{
        "agencyLocationPropertyId": 501,
        "propertyName": "AMSType",
        "propertyValue": "HawkSoft",
        "propertyDescription": "",
        "dateCreated": "2014-02-24T19:27:30.86",
        "dateModified": "2014-02-24T19:27:30.86",
        "portalId": 42
    }, {
        "agencyLocationPropertyId": 502,
        "propertyName": "AMSType",
        "propertyValue": "HawkSoftDesktop",
        "propertyDescription": "",
        "dateCreated": "2014-02-24T19:27:30.86",
        "dateModified": "2014-02-24T19:27:30.86",
        "portalId": 42
    }, {
        "agencyLocationPropertyId": 503,
        "propertyName": "AMSType",
        "propertyValue": "AMS360",
        "propertyDescription": "",
        "dateCreated": "2014-02-24T19:27:30.86",
        "dateModified": "2014-02-24T19:27:30.86",
        "portalId": 42
    }, {
        "agencyLocationPropertyId": 504,
        "propertyName": "AMSType",
        "propertyValue": "TAM",
        "propertyDescription": "",
        "dateCreated": "2014-02-24T19:27:30.86",
        "dateModified": "2014-02-24T19:27:30.86",
        "portalId": 42
    }, {
        "agencyLocationPropertyId": 505,
        "propertyName": "AMSType",
        "propertyValue": "Vision",
        "propertyDescription": "",
        "dateCreated": "2014-02-24T19:27:30.86",
        "dateModified": "2014-02-24T19:27:30.86",
        "portalId": 42
    }, {
        "agencyLocationPropertyId": 506,
        "propertyName": "AMSType",
        "propertyValue": "PowerBroker",
        "propertyDescription": "",
        "dateCreated": "2014-02-24T19:27:30.86",
        "dateModified": "2014-02-24T19:27:30.86",
        "portalId": 42
    }, {
        "agencyLocationPropertyId": 507,
        "propertyName": "AMSType",
        "propertyValue": "InStar",
        "propertyDescription": "",
        "dateCreated": "2014-02-24T19:27:30.86",
        "dateModified": "2014-02-24T19:27:30.86",
        "portalId": 42
    }, {
        "agencyLocationPropertyId": 508,
        "propertyName": "AMSType",
        "propertyValue": "Xanatek",
        "propertyDescription": "",
        "dateCreated": "2014-02-24T19:27:30.86",
        "dateModified": "2014-02-24T19:27:30.86",
        "portalId": 42
    }, {
        "agencyLocationPropertyId": 509,
        "propertyName": "AMSType",
        "propertyValue": "Eclipse",
        "propertyDescription": "",
        "dateCreated": "2014-02-24T19:27:30.86",
        "dateModified": "2014-02-24T19:27:30.86",
        "portalId": 42
    }, {
        "agencyLocationPropertyId": 510,
        "propertyName": "AMSType",
        "propertyValue": "DORIS",
        "propertyDescription": "",
        "dateCreated": "2014-02-24T19:27:30.86",
        "dateModified": "2014-02-24T19:27:30.86",
        "portalId": 42
    }, {
        "agencyLocationPropertyId": 511,
        "propertyName": "AMSType",
        "propertyValue": "FSC",
        "propertyDescription": "",
        "dateCreated": "2014-02-24T19:27:30.86",
        "dateModified": "2014-02-24T19:27:30.86",
        "portalId": 42
    }, {
        "agencyLocationPropertyId": 512,
        "propertyName": "AMSType",
        "propertyValue": "PartnerXE",
        "propertyDescription": "",
        "dateCreated": "2014-02-24T19:27:30.86",
        "dateModified": "2014-02-24T19:27:30.86",
        "portalId": 42
    }, {
        "agencyLocationPropertyId": 513,
        "propertyName": "AMSType",
        "propertyValue": "QQCatalyst",
        "propertyDescription": "",
        "dateCreated": "2014-02-24T19:27:30.86",
        "dateModified": "2014-02-24T19:27:30.86",
        "portalId": 42
    }, {
        "agencyLocationPropertyId": 514,
        "propertyName": "AMSType",
        "propertyValue": "EbixASP",
        "propertyDescription": "",
        "dateCreated": "2014-02-24T19:27:30.86",
        "dateModified": "2014-02-24T19:27:30.86",
        "portalId": 42
    }, {
        "agencyLocationPropertyId": 515,
        "propertyName": "AMSType",
        "propertyValue": "Epic",
        "propertyDescription": "",
        "dateCreated": "2014-02-24T19:27:30.86",
        "dateModified": "2014-02-24T19:27:30.86",
        "portalId": 42
    }]);
};<commit_msg>Delete routes<commit_after><|endoftext|>


<commit_before>var superagent = require('superagent');
var expect = require('expect.js');
var mongodb = require('mongodb').MongoClient;

var BASE_URL = 'http://localhost:8000/';
var LOAD_URL = BASE_URL + 'api/load';
var SAVE_URL = BASE_URL + 'api/save';

describe('activities rest api', function() {

  function cleanDatabase() {
    mongodb.connect('mongodb://localhost/journal', function(err, db) {
      var collection = db.collection('activities');
      collection.remove({});
    });
  }

  before(function() {
    cleanDatabase();
  });

  afterEach(function() {
    cleanDatabase();
  })

  it('can access the endpoint for loading activities', function(done) {
    superagent.get(LOAD_URL)
      .end(function(error, response) {
        expect(error).to.equal(null);
        expect(response.status).to.equal(200);
        done();
      });
  });

  it('can access the endpoint for saving activities', function(done) {
    var expectedDate = 'January 15, 2015';
    var expectedActivities = [{
      name: 'Hyung',
      time: 15
    }];

    superagent.post(SAVE_URL)
      .send({
        _id: expectedDate,
        activities: expectedActivities
      })
      .end(function(error, response) {
        expect(error).to.equal(null);
        expect(response.body._id).to.equal(expectedDate);
        expect(response.body.activities).to.eql(expectedActivities);
        done();
      });
  });

  it('can retrieve data from the database', function(done) {
    var expectedDate = 'January 15, 2015';
    var expectedActivities = [{
      name: 'Hyung',
      time: 15
    }];

    superagent.post(SAVE_URL)
      .send({
        _id: expectedDate,
        activities: expectedActivities
      })
      .end(function(error, response) {
        expect(response.body._id).to.equal(expectedDate);
        expect(response.body.activities).to.eql(expectedActivities);
        done();
      });

    superagent.get(LOAD_URL)
      .end(function(error, response) {
        expect(response.body.length).to.equal(1);
        expect(response.body[0]._id).to.equal(expectedDate);
        expect(response.body[0].activities).to.equal(expectedActivities);
        done();
      });
  });

  it('will update an existing record if the data was already posted on the same day', function(done) {
    var expectedDate = 'January 15, 2015';
    var originalActivities = [{
      name: 'Hyung',
      time: 15
    }];
    var updatedActivities = [{
      name: 'Hyung',
      time: 60
    }];

    superagent.post(SAVE_URL)
      .send({
        _id: expectedDate,
        activities: originalActivities
      });

    superagent.post(SAVE_URL)
      .send({
        _id: expectedDate,
        activities: updatedActivities
      })
      .end(function(error, response) {
        done();
      });

    superagent.get(LOAD_URL)
      .end(function(error, response) {
        expect(response.body.length).to.equal(1);
        expect(response.body[0]._id).to.equal(expectedDate);
        expect(response.body[0].activities).to.equal(updatedActivities);
        done();
      });
  });

});
<commit_msg>Async stuff<commit_after>var superagent = require('superagent');
var expect = require('expect.js');
var mongodb = require('mongodb').MongoClient;

var BASE_URL = 'http://localhost:8000/';
var LOAD_URL = BASE_URL + 'api/load';
var SAVE_URL = BASE_URL + 'api/save';

describe('activities rest api', function() {

  function cleanDatabase(done) {
    mongodb.connect('mongodb://localhost/journal', function(err, db) {
      var collection = db.collection('activities');
      collection.remove({}, function() {
        done();
      });
    });
  }

  beforeEach(function(done) {
    cleanDatabase(done);
  });

  after(function(done) {
    cleanDatabase(done);
  });

  it('can access the endpoint for loading activities', function(done) {
    superagent.get(LOAD_URL)
      .end(function(error, response) {
        expect(error).to.equal(null);
        expect(response.status).to.equal(200);
        done();
      });
  });

  it('can access the endpoint for saving activities', function(done) {
    var expectedDate = 'January 1, 2015';
    var expectedActivities = [{
      name: 'Hyung',
      time: 15
    }];

    superagent.post(SAVE_URL)
      .send({
        date: expectedDate,
        activities: expectedActivities
      })
      .end(function(error, response) {
        expect(error).to.equal(null);
        expect(response.body.date).to.equal(expectedDate);
        expect(response.body.activities).to.eql(expectedActivities);
        done();
      });
  });

  it('can retrieve data from the database', function(done) {
    var expectedDate = 'January 1, 2015';
    var expectedActivities = [{
      name: 'Hyung',
      time: 15
    }];

    superagent.post(SAVE_URL)
      .send({
        date: expectedDate,
        activities: expectedActivities
      })
      .end(function() {
        superagent.get(LOAD_URL)
          .end(function(error, response) {
            expect(response.body.length).to.equal(1);
            expect(response.body[0]._id).to.equal(expectedDate);
            expect(response.body[0].activities).to.eql(expectedActivities);
            done();
          });
      });
  });

  it('will update an existing record if the data was already posted on the same day', function(done) {
    var expectedDate = 'January 1, 2015';
    var originalActivities = [{
      name: 'Hyung',
      time: 15
    }];
    var updatedActivities = [{
      name: 'Hyung',
      time: 60
    }];

    superagent.post(SAVE_URL)
      .send({
        date: expectedDate,
        activities: originalActivities
      })
      .end(function() {
        superagent.post(SAVE_URL)
          .send({
            date: expectedDate,
            activities: updatedActivities
          })
          .end(function() {
            superagent.get(LOAD_URL)
              .end(function(error, response) {
                expect(response.body.length).to.equal(1);
                expect(response.body[0]._id).to.equal(expectedDate);
                expect(response.body[0].activities).to.eql(updatedActivities);
                done();
              });
          });
      });
  });

  it('will store a separate record for each day in the database', function(done) {
    var firstDate = 'January 1, 2015';
    var secondDate = 'January 2, 2015';
    var activities = [{
      name: 'Hyung',
      time: 15
    }];

    superagent.post(SAVE_URL)
      .send({
        date: firstDate,
        activities: activities
      })
      .end(function() {
        superagent.post(SAVE_URL)
          .send({
            date: secondDate,
            activities: activities
          })
          .end(function(error, response) {
            superagent.get(LOAD_URL)
              .end(function(error, response) {
                expect(response.body.length).to.equal(2);
                done();
              });
          });
      });
  });

});
<|endoftext|>