<commit_before>var Package = require('auto-package')

Package.name = 'combokeys'
Package.versionFile()
Package.description = 'Handles keyboard shortcuts in the browser'
Package.main = 'Combokeys/index.js'
Package.implements = ['CommonJS/Modules/1.0']
Package.scripts = {
  lint: 'standard',
  unit: './node_modules/zuul/bin/zuul --phantom -- test/test.combokeys.js test/plugins/test.*.js',
  build: 'mkdir -p dist && browserify index.js -o dist/combokeys.js --standalone Combokeys',
  test: 'npm run lint && npm run unit && npm run build'

}
Package.githubRepo('PolicyStat/combokeys')
Package.keywords = [
  'keyboard',
  'shortcuts',
  'events',
  'browser'
]
Package.contributors = [
  {
    'name': 'Shahar Or',
    'email': 'mightyiampresence@gmail.com',
    'web': 'https://github.com/mightyiam'
  },
  {
    'name': 'Craig Campbell',
    'web': 'http://craig.is'
  }
]
Package.bugs = 'https://github.com/mightyiam/combokeys/issues'
Package.license = {
  'type': 'Apache 2.0',
  'url': 'https://www.apache.org/licenses/LICENSE-2.0.txt'
}
Package.devDependencies = {
  standard: '*',
  'auto-package': '^1.0.0',
  'browserify': '^9.0.3',
  'chai': '^1.10.0',
  'es5-shim': '^4.0.3',
  'grunt': '~0.4.1',
  'grunt-complexity': '~0.1.2',
  'grunt-eslint': '^2.0.0',
  'load-grunt-tasks': '^1.0.0',
  'mocha': '^2.0.1',
  'phantomjs': '^1.9.12',
  'sinon': '^1.12.1',
  'zuul': '^2.1.1'
}
Package.dependencies = {
  'add-event-handler': '^1.0.0'
}
Package.standard = {
  ignore: [
    'dist/**'
  ]
}
<commit_msg>npm run build: fix it<commit_after>var Package = require('auto-package')

Package.name = 'combokeys'
Package.versionFile()
Package.description = 'Handles keyboard shortcuts in the browser'
Package.main = 'Combokeys/index.js'
Package.implements = ['CommonJS/Modules/1.0']
Package.scripts = {
  lint: 'standard',
  unit: './node_modules/zuul/bin/zuul --phantom -- test/test.combokeys.js test/plugins/test.*.js',
  build: 'mkdir -p dist && browserify . -o dist/combokeys.js --standalone Combokeys',
  test: 'npm run lint && npm run unit && npm run build'

}
Package.githubRepo('PolicyStat/combokeys')
Package.keywords = [
  'keyboard',
  'shortcuts',
  'events',
  'browser'
]
Package.contributors = [
  {
    'name': 'Shahar Or',
    'email': 'mightyiampresence@gmail.com',
    'web': 'https://github.com/mightyiam'
  },
  {
    'name': 'Craig Campbell',
    'web': 'http://craig.is'
  }
]
Package.bugs = 'https://github.com/mightyiam/combokeys/issues'
Package.license = {
  'type': 'Apache 2.0',
  'url': 'https://www.apache.org/licenses/LICENSE-2.0.txt'
}
Package.devDependencies = {
  standard: '*',
  'auto-package': '^1.0.0',
  'browserify': '^9.0.3',
  'chai': '^1.10.0',
  'es5-shim': '^4.0.3',
  'grunt': '~0.4.1',
  'grunt-complexity': '~0.1.2',
  'grunt-eslint': '^2.0.0',
  'load-grunt-tasks': '^1.0.0',
  'mocha': '^2.0.1',
  'phantomjs': '^1.9.12',
  'sinon': '^1.12.1',
  'zuul': '^2.1.1'
}
Package.dependencies = {
  'add-event-handler': '^1.0.0'
}
Package.standard = {
  ignore: [
    'dist/**'
  ]
}
<|endoftext|>


<commit_before>const version = '2.67.0';

Package.describe({
  name: 'akasha:request',
  version: version,
  // Brief, one-line summary of the package.
  summary: '',
  // URL to the Git repository containing the source code for this package.
  git: '',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Npm.depends({
  'request':  version
});

Package.onUse(function(api) {
  api.versionsFrom('1.2.1');
  api.use('ecmascript');
  api.addFiles('request.js');
  api.export('Request', 'server');
});

Package.onTest(function(api) {
  api.use('ecmascript');
  api.use('tinytest');
  api.use('akasha:request');
  api.addFiles('request-tests.js');
});
<commit_msg>added github link<commit_after>const version = '2.67.0';

Package.describe({
  name: 'akasha:request',
  version: version,
  // Brief, one-line summary of the package.
  summary: 'request package wrapped for meteor',
  // URL to the Git repository containing the source code for this package.
  git: 'https://github.com/AkashaProject/meteor-request',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Npm.depends({
  'request':  version
});

Package.onUse(function(api) {
  api.versionsFrom('1.2.1');
  api.use('ecmascript');
  api.addFiles('request.js');
  api.export('Request', 'server');
});

Package.onTest(function(api) {
  api.use('ecmascript');
  api.use('tinytest');
  api.use('akasha:request');
  api.addFiles('request-tests.js');
});
<|endoftext|>


<commit_before>Package.describe({
    name: "socialize:messaging",
    summary: "A social messaging package",
    version: "0.5.0",
    git:"https://github.com/copleykj/socialize-messaging.git"
});

Package.onUse(function(api) {
    api.versionsFrom("1.0.2.1");

    api.use([
        "socialize:user-model@0.1.7", "socialize:user-presence@0.3.4", "socialize:server-time@0.1.2"
    ]);

    //Add the conversation-model files
    api.addFiles("conversation-model/common/conversation-model.js");
    api.addFiles("conversation-model/common/user-extensions.js");
    api.addFiles("conversation-model/server/publications.js", "server");
    api.addFiles("conversation-model/server/server.js", "server");

    //Add the message-model files
    api.addFiles("message-model/common/message-model.js");
    api.addFiles("message-model/server/server.js", "server");

    //Add the participant-model files
    api.addFiles("participant-model/common/participant-model.js");
    api.addFiles("participant-model/server/server.js", "server");

    api.export(["Conversation", "Message", "Participant"]);
});

<commit_msg>:ballot_box_with_check: Add check package<commit_after>Package.describe({
    name: "socialize:messaging",
    summary: "A social messaging package",
    version: "0.5.1",
    git:"https://github.com/copleykj/socialize-messaging.git"
});

Package.onUse(function(api) {
    api.versionsFrom("1.0.2.1");

    api.use([
        "check", "socialize:user-model@0.1.7", "socialize:user-presence@0.3.4", "socialize:server-time@0.1.2"
    ]);

    //Add the conversation-model files
    api.addFiles("conversation-model/common/conversation-model.js");
    api.addFiles("conversation-model/common/user-extensions.js");
    api.addFiles("conversation-model/server/publications.js", "server");
    api.addFiles("conversation-model/server/server.js", "server");

    //Add the message-model files
    api.addFiles("message-model/common/message-model.js");
    api.addFiles("message-model/server/server.js", "server");

    //Add the participant-model files
    api.addFiles("participant-model/common/participant-model.js");
    api.addFiles("participant-model/server/server.js", "server");

    api.export(["Conversation", "Message", "Participant"]);
});

<|endoftext|>


<commit_before>
Package.describe({
  summary:  "Gagarin bindings for Meteor",
  name:     "anti:gagarin",
  version:  "0.1.0",
  git:      "https://github.com/anticoders/gagarin.git",
});
});

Package.on_use(function (api) {

  api.use('apendua:altimeter@0.0.2', 'server');

  api.add_files([
    'meteor_hooks.js'
  ], 'server');

  api.export('Gagarin');

});
<commit_msg>Hotfix<commit_after>
Package.describe({
  summary:  "Gagarin bindings for Meteor",
  name:     "anti:gagarin",
  version:  "0.1.1",
  git:      "https://github.com/anticoders/gagarin.git",
});

Package.on_use(function (api) {

  api.use('apendua:altimeter@0.0.2', 'server');

  api.add_files([
    'meteor_hooks.js'
  ], 'server');

  api.export('Gagarin');

});
<|endoftext|>


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

var CombineBlocks    = require('../Manipulation/CombineBlocks');
var CombineBlockPrev = require('../Manipulation/CombineBlockPrev');
var DeleteFigure     = require('../Manipulation/DeleteFigure');

var KEY_CODES = { 'bspace': 8 };

class BspaceKey extends BaseKey {
  constructor(content, selection) {
    this.content   = content;
    this.selection = selection;
  }

  static getName() {
    return 'bspace-key';
  }

  // return or ctrl+m
  matches(event) {
    return event.keyCode === KEY_CODES.bspace;
  }

  down(callback) {
    var guids = this.selection.guids();
    var offsets = this.selection.offsets();
    var results;

    if (this.selection.isFigure() && !this.selection.isCaption()) {
      results = this._deleteFigure().execute(guids);

    } else if (this.selection.crossBlock()) {
      results = this._combineBlocks().execute(guids, offsets);

    } else if (this.selection.begOfBlock() && !this.selection.isRange()) {
      results = this._combineWithPrev().execute(guids);
    }

    this._complete(results, callback);
  }

  _complete(results, callback) {
    this.focusResults(results);

    var content = results ? results.content : this.content;
    this.saveHistory(content);

    callback({
      content: content,
      selection: this.selection,
      stopPropagation: !!results,
      preventDefault: results && results.block,
      emit: true
    });
  }

  _deleteFigure() {
    return new DeleteFigure(this.content);
  }

  _combineBlocks() {
    return new CombineBlocks(this.content);
  }

  _combineWithPrev() {
    return new CombineBlockPrev(this.content);
  }
}

module.exports = BspaceKey;
<commit_msg>fix issues deleting list items<commit_after>var BaseKey = require('./BaseKey');

var CombineBlocks    = require('../Manipulation/CombineBlocks');
var CombineBlockPrev = require('../Manipulation/CombineBlockPrev');
var ToggleBlockType  = require('../Manipulation/ToggleBlockType');
var DeleteFigure     = require('../Manipulation/DeleteFigure');

var KEY_CODES = { 'bspace': 8 };

class BspaceKey extends BaseKey {
  constructor(content, selection) {
    this.content   = content;
    this.selection = selection;
  }

  static getName() {
    return 'bspace-key';
  }

  // return or ctrl+m
  matches(event) {
    return event.keyCode === KEY_CODES.bspace;
  }

  down(callback) {
    var guids = this.selection.guids();
    var offsets = this.selection.offsets();
    var results;

    // is this a list item
    var node = document.getElementsByName(guids.anchor)[0];
    var type = node.tagName.toLowerCase();

    if (this.selection.isFigure() && !this.selection.isCaption()) {
      results = this._deleteFigure().execute(guids);

    // combine the blocks selected
    } else if (this.selection.crossBlock()) {
      results = this._combineBlocks().execute(guids, offsets);

    // beginning of a list item converts to a paragraph
    } else if (this.selection.begOfBlock() && type === 'li') {
      results = this._toggleBlockType().execute(guids, offsets, { type: 'li' });

    // at beginning of block - combine with previous
    } else if (this.selection.begOfBlock() && !this.selection.isRange()) {
      results = this._combineWithPrev().execute(guids);
    }

    this._complete(results, callback);
  }

  _complete(results, callback) {
    this.focusResults(results);

    var content = results ? results.content : this.content;
    this.saveHistory(content);

    callback({
      content: content,
      selection: this.selection,
      stopPropagation: !!results,
      preventDefault: !!results,
      emit: true
    });
  }

  _deleteFigure() {
    return new DeleteFigure(this.content);
  }

  _toggleBlockType() {
    return new ToggleBlockType(this.content);
  }

  _combineBlocks() {
    return new CombineBlocks(this.content);
  }

  _combineWithPrev() {
    return new CombineBlockPrev(this.content);
  }
}

module.exports = BspaceKey;
<|endoftext|>


<commit_before>/*
* ---
* EDITOR SETTINGS MODULE
* ---
*
* Creates an additional tab in the Pen Settings modal in the editor.
*
* Allows for control of things like editor theme/fonts/etc
* without leaving the editor at all.
*
*
*/

var ces__editorSettings = (function(){
  "use strict";

  // In order to not trample on CodePen's POST requests,
  // we track whether or not there is an ouststanding
  // request to '/pen/save'
  var pendingSave = false;

  // Grabs the inital settings for the editor so we can change 'em as necessary.
  var editorSettings = initData.__pen.editor_settings;

  // Markup is reconstructed from what CodePen was already using so that
  // I can just re-use their tab functionality.
  var $editorTab = $("Editor");
  var $editorSettingsContainer = $("

");
  $("#settings-tabs").append($editorTab);

  // I wanted to hook into something with an ID rather than a class to append to,
  // so this just looks to the html settings container since that shouldn't change at all.
  $("#settings-html").parent().append($editorSettingsContainer);

  // For whatever reason, while the custom tab taggles *on* just fine,
  // it gets stuck in the active state. This fixes that.
  //
  // It would be nice to not need to deal with any of this, so if someone has a fix
  // let me know and I'll gladly use it.
  $editorTab.siblings().click(function(){
    $editorTab.removeClass("active");
    $editorSettingsContainer.removeClass("active");
  })

  // This grabs the actual content for the editor settings,
  // and then places it into the container we created.
  //
  // Once it's fully loaded, it sets the active theme
  // based on the init data.
  u_requestExtensionUrl("lib/html/editor-settings.html", function(response){
    $editorSettingsContainer.load(response, function(){
      $( "#" + editorSettings.theme).prop("checked", true);
      $( "#" + editorSettings.font_type).prop("selected", true);
      $( "#" + editorSettings.font_size).prop("selected", true);

      // Because of the redirect caused by saving a new Pen, the callback gets screwed up
      // when saving editor settings. The easiest way to fix this is to force people to save
      // first. Sorta sucks, but it works.
      if (initData.__pen.slug_hash === "") {
        $editorSettingsContainer.prepend("
Editor settings are only available once you've saved your Pen at least once. I know it's weird, I'm working on it :(
");
        $editorSettingsContainer.find("input, select, label").addClass("disabled");
        return;
      }

      // This module won't work over an insecure connection because it needs to hit
      // a secure endpoint. If the user is browsing over HTTP it'll throw a cross-origin
      // error and won't save.
      if (!u_isHttps()) {
        $editorSettingsContainer.find("input, select, label").addClass("disabled");
        var httpsMessage = "Hi! Looks like you're not currently using HTTPS. Editor settings will only work over a secure connection.";
        var httpsUrl = location.href.replace("http://", "https://");
        var httpsLink = "Reload over HTTPS?";
        $editorSettingsContainer.prepend("
"+httpsMessage+" "+httpsLink+"
");
      }
    });
  })

  // We need some way to hook into the save requests.
  // Unfortunately waiting for a "pen-saved" event to fire
  // doesn't quite work out, since our responses end up
  // firing *after* CodePen's.
  //
  // This modifies all outgoing requests to the '/pen/save' end point
  // and has them toggle the pendingSave variable.
  $.ajaxSetup({
    beforeSend: function(request, settings) {
      if (settings.url === "/pen/save") {

        // Since we're making use of the 'complete' callback
        // on ajax requests, we can't just overwrite everything.
        //
        // Instead, we'll only modify the request if it doesn't already
        // have a 'complete' callback queued up. If CodePen starts using
        // complete callbacks I'm gonna have a bad time.
        if (!settings.complete) {
          pendingSave = true;
          settings.complete = function(response) {
            pendingSave = false;
          }
        }
      }
    }
  });

  // Kicks off our custom save function every time a
  // 'pen-saved' event gets fired.
  u_onPenSave(cesSaveInit);
  function cesSaveInit() {

    // If there's an outstanding save request,
    // wait until it's done to avoid any interference.
    if (pendingSave) {
      $(document).ajaxComplete(function(event, request, settings){
        if (settings.url === "/pen/save") {
          $(document).unbind("ajaxComplete");
          saveEditorSettings();
        }
      })
    }

    // Otherwise we can just go ahead and do whatevs.
    else {
      saveEditorSettings();
    }
  }

  // Returns a JSON object with the new editor settings.
  // If the new settings are the same as the old ones, returns false.
  function getNewEditorSettings() {

      var oldEditorSettings = editorSettings;
      var newEditorSettings = $.extend(true, {}, oldEditorSettings);

      newEditorSettings.theme = $("#editor-theme :checked").val();
      newEditorSettings.font_size = $("#font_size :checked").val();
      newEditorSettings.font_type = $("#font_type :checked").val();

      // If the selected theme is the same as the one we initialized with,
      // we don't need to do anything here so we can bail early.
      if ( JSON.stringify(newEditorSettings) == JSON.stringify(oldEditorSettings) ) {
        return false;
      }
      return newEditorSettings;
  }

  // Checks to see if the editor settings are valid.
  // For the most part, the only reason saving settings
  // is gonna fail is if the user isn't using HTTPS.
  //
  // This is because CodePen forwards insecure settings requests to
  // a secure domain, which then leads to cross-origin errors.
  //
  // To combat that, we throw an error client-side and ask the user to reload
  // the page over HTTPS (and even give 'em a link, how nice are we?)
  function editorSettingsValid() {
    if (!u_isHttps()) {
      var httpsUrl = location.href.replace("http://", "https://");
      var httpsLink = "Reload this page over HTTPS.";
      u_throwErrorModal("Whoops! You need to be browsing over HTTPS for editor settings to work.

"+httpsLink);
      return false;
    }
    return true;
  }

  // Nothing fancy here. Makes the literal POST request to save editor settings,
  // then makes sure that the page is refreshed so the changes are actually visible.
  function saveEditorSettings() {

    // Bails early if there's nothing to save or something is invalid
    var newEditorSettings = getNewEditorSettings();
    if (!newEditorSettings || !editorSettingsValid()) {
      return;
    }

    u_CP("/" + initData.__user.username + "/settings/save/editor", "editor_settings", newEditorSettings, function(response){
      if (response.status === 200 ) {
        location.reload();
      }
      else {
        u_throwErrorModal("Uh oh. Those editor settings failed to save. CodePen doesn't know why, I don't know why, you don't know why (well, maybe you do?). It's a bad time.");
        return false;
      }
    });
  }
})();
<commit_msg>Code review, ditch $.ajaxSetup()<commit_after>/*
* ---
* EDITOR SETTINGS MODULE
* ---
*
* Creates an additional tab in the Pen Settings modal in the editor.
*
* Allows for control of things like editor theme/fonts/etc
* without leaving the editor at all.
*
*
*/

var ces__editorSettings = (function(){
  "use strict";
  var $document = $(document);
  // In order to not trample on CodePen's POST requests,
  // we track whether or not there is an ouststanding
  // request to '/pen/save'
  var pendingSave = false;
  // Grabs the inital settings for the editor so we can change 'em as necessary.
  var editorSettings = initData.__pen.editor_settings;

  // Markup is reconstructed from what CodePen was already using so that
  // I can just re-use their tab functionality.
  var $editorTab = $("Editor");
  var $editorSettingsContainer = $("

");
  $("#settings-tabs").append($editorTab);

  // I wanted to hook into something with an ID rather than a class to append to,
  // so this just looks to the html settings container since that shouldn't change at all.
  $("#settings-html").parent().append($editorSettingsContainer);

  // For whatever reason, while the custom tab taggles *on* just fine,
  // it gets stuck in the active state. This fixes that.
  //
  // It would be nice to not need to deal with any of this, so if someone has a fix
  // let me know and I'll gladly use it.
  $editorTab.siblings().click(function(){
    $editorTab.removeClass("active");
    $editorSettingsContainer.removeClass("active");
  });

  // This grabs the actual content for the editor settings,
  // and then places it into the container we created.
  //
  // Once it's fully loaded, it sets the active theme
  // based on the init data.
  u_requestExtensionUrl("lib/html/editor-settings.html", function(response){
    $editorSettingsContainer.load(response, function(){
      $( "#" + editorSettings.theme).prop("checked", true);
      $( "#" + editorSettings.font_type).prop("selected", true);
      $( "#" + editorSettings.font_size).prop("selected", true);

      // Because of the redirect caused by saving a new Pen, the callback gets screwed up
      // when saving editor settings. The easiest way to fix this is to force people to save
      // first. Sorta sucks, but it works.
      if (initData.__pen.slug_hash === "") {
        $editorSettingsContainer.prepend("
Editor settings are only available once you've saved your Pen at least once. I know it's weird, I'm working on it :(
");
        $editorSettingsContainer.find("input, select, label").addClass("disabled");
        return;
      }

      // This module won't work over an insecure connection because it needs to hit
      // a secure endpoint. If the user is browsing over HTTP it'll throw a cross-origin
      // error and won't save.
      if (!u_isHttps()) {
        $editorSettingsContainer.find("input, select, label").addClass("disabled");
        var httpsMessage = "Hi! Looks like you're not currently using HTTPS. Editor settings will only work over a secure connection.";
        var httpsUrl = location.href.replace("http://", "https://");
        var httpsLink = "Reload over HTTPS?";
        $editorSettingsContainer.prepend("
"+httpsMessage+" "+httpsLink+"
");
      }
    });
  })

  // Keeps track of whether or not CodePen is trying to save stuff already
  $document.ajaxSend(function( event, xhr, settings ){
    if (settings.url === "/pen/save") {
      pendingSave = true;
      settings.complete = function(response) {
        pendingSave = false;
      }
    }
  });

  // Kicks off our custom save function every time a
  // 'pen-saved' event gets fired.
  u_onPenSave(cesSaveInit);
  function cesSaveInit() {

    // If there's an outstanding save request,
    // wait until it's done to avoid any interference.
    if (pendingSave) {
      $document.ajaxComplete(function(event, request, settings){
        if (settings.url === "/pen/save") {
          $document.unbind("ajaxComplete");
          saveEditorSettings();
        }
      })
    }

    // Otherwise we can just go ahead and do whatevs.
    else {
      saveEditorSettings();
    }
  }

  // Returns a JSON object with the new editor settings.
  // If the new settings are the same as the old ones, returns false.
  function getNewEditorSettings() {

      var oldEditorSettings = editorSettings;
      var newEditorSettings = $.extend(true, {}, oldEditorSettings);

      newEditorSettings.theme = $("#editor-theme :checked").val();
      newEditorSettings.font_size = $("#font_size :checked").val();
      newEditorSettings.font_type = $("#font_type :checked").val();

      // If the selected theme is the same as the one we initialized with,
      // we don't need to do anything here so we can bail early.
      if ( JSON.stringify(newEditorSettings) == JSON.stringify(oldEditorSettings) ) {
        return false;
      }
      return newEditorSettings;
  }

  // Checks to see if the editor settings are valid.
  // For the most part, the only reason saving settings
  // is gonna fail is if the user isn't using HTTPS.
  //
  // This is because CodePen forwards insecure settings requests to
  // a secure domain, which then leads to cross-origin errors.
  //
  // To combat that, we throw an error client-side and ask the user to reload
  // the page over HTTPS (and even give 'em a link, how nice are we?)
  function editorSettingsValid() {
    if (!u_isHttps()) {
      var httpsUrl = location.href.replace("http://", "https://");
      var httpsLink = "Reload this page over HTTPS.";
      u_throwErrorModal("Whoops! You need to be browsing over HTTPS for editor settings to work.

"+httpsLink);
      return false;
    }
    return true;
  }

  // Nothing fancy here. Makes the literal POST request to save editor settings,
  // then makes sure that the page is refreshed so the changes are actually visible.
  function saveEditorSettings() {

    // Bails early if there's nothing to save or something is invalid
    var newEditorSettings = getNewEditorSettings();
    if (!newEditorSettings || !editorSettingsValid()) {
      return;
    }

    u_CP("/" + initData.__user.username + "/settings/save/editor", "editor_settings", newEditorSettings, function(response){
      if (response.status === 200 ) {
        location.reload();
      }
      else {
        u_throwErrorModal("Uh oh. Those editor settings failed to save. CodePen doesn't know why, I don't know why, you don't know why (well, maybe you do?). It's a bad time.");
        return false;
      }
    });
  }
})();
<|endoftext|>


<commit_before>methods = {};

methods.save = function(callback) {
  // Get collection for given class.
  var Collection = this.constructor.schema.getCollection();
  if (!Collection) {
    throw new Error('There is no collection to save to');
  }

  // Flag indicating whether we should update or insert document.
  var update = !!this._values._id;

  // Trigger "beforeSave", "beforeInsert" and "beforeUpdate" event handlers on
  // current and parent schemas.
  _.each(this.constructor.schemas, function(schema) {
    schema.triggerEvent('beforeSave', this, true);
    if (update) {
      schema.triggerEvent('beforeUpdate', this, true);
    } else {
      schema.triggerEvent('beforeInsert', this, true);
    }
  }, this);

  // Get values to update or insert.
  var values = update ? this.getModified() : this.get();
  // Remove "_id" field, if its value is null (object is new and have not been
  // saved yet) or it's not null but "update" flag is set what means that we are
  // updating document.
  if (!values['_id'] || update) {
    values = _.omit(values, '_id');
  }

  // Check if there are any values to update or insert. If there are no modified
  // fields, we shouldn't do anything.
  if (_.size(values) === 0) {
    return false;
  }

  // Add callback to arguments list if provided.
  var args = [];
  if (callback) {
    args.push(callback);
  }

  var result;
  if (update) {
    // Add selector and modifier at the beginning of the arguments list. Right
    // now in the array is a callback function (if provided).
    args.unshift({ // Selector.
      _id: this._values._id
    }, { // Modifier.
      $set: values
    });
    // Update document.
    result = Collection.update.apply(Collection, args);
  } else {
    // Add values to insert into the list of arguments passed to the "insert"
    // method.
    args.unshift(values);
    // Insert document.
    result = this._values._id = Collection.insert.apply(Collection, args);
  }

  // Trigger "afterSave", "afterInsert" and "afterUpdate" event handlers on
  // current and parent schemas.
  _.each(this.constructor.schemas, function(schema) {
    if (update) {
      schema.triggerEvent('afterUpdate', this, true);
    } else {
      schema.triggerEvent('afterInsert', this, true);
    }
    // Trigger afterSave event handlers.
    schema.triggerEvent('afterSave', this, true);
  }, this);

  // Update values with new ones.
  _.extend(this._values, values);

  // Clear modified fields.
  this._modified = {};

  // Return result of executing Mongo query.
  return result;
};

methods.remove = function(callback) {
  // Get collection for given class or parent class.
  var Collection = this.constructor.schema.getCollection();
  if (!Collection) {
    throw new Error('There is no collection to remove from');
  }

  // Remove only when document has _id, so it's saved in the collection.
  if (!this._values._id) {
    return;
  }

  // Trigger "beforeRemove" event handlers on current and parent schemas.
  _.each(this.constructor.schemas, function(schema) {
    schema.triggerEvent('beforeRemove', this, true);
  }, this);

  // Add selector to arguments list.
  var args = [];
  args.push({
    _id: this._values._id
  });
  // Add callback to arguments list if provided.
  if (callback) {
    args.push(callback);
  }

  // Remove document and save result.
  var result = Collection.remove.apply(Collection, args);

  // Trigger "afterRemove" event handlers on current and parent schemas.
  _.each(this.constructor.schemas, function(schema) {
    schema.triggerEvent('afterRemove', this, true);
  }, this);

  // Clear "_id" attribute, so that user can save document one more time.
  this._values['_id'] = undefined;

  // Return result of removing document.
  return result;
};

methods.reload = function() {
  // Get collection for given class or parent class.
  var Collection = this.constructor.schema.getCollection();
  if (!Collection) {
    throw new Error('There is no collection to reload document from');
  }

  if (this._values._id) {
    // Get new values from collection without the transformation.
    this._values = Collection.findOne(this._values._id, {
      transform: null
    }) || this._values;
    // Clear modified fields list.
    this._modified = {};
  }
};

methods.clone = function(attrs, save) {
  save = save || false;

  // Get object constructor.
  var Class = this.constructor;
  // Create new instance.
  var cloned = new Class();

  // Copy values and modified values but without "_id" field.
  cloned._values = EJSON.clone(_.omit(this._values, '_id'));
  cloned._modified = EJSON.clone(_.omit(this._modified, '_id'));

  // Apply new values if provided.
  if (_.isObject(attrs)) {
    _.extend(cloned, attrs);
  }

  // Save clone to collection.
  if (save) {
    cloned.save();
  }

  return cloned;
};

var getOne = function(fieldName) {
  // Define var for returned value.
  var value;

  // Look for field's definition and schema. Field definition can be places in
  // this or parent schema.
  var fieldDefinition;
  var schema = _.find(this.constructor.schemas, function(schema) {
    return fieldDefinition = schema.getField(fieldName);
  });

  // If field's definition is not present then we just return "undefined".
  if (!fieldDefinition) {
    return value;
  }

  // Trigger "beforeGet" event handlers.
  schema.triggerEvent('beforeGet', this, true, [fieldName]);

  if (_.has(this._modified, fieldName)) {

    // Look for value in "_modified" property.
    value = this._modified[fieldName];

  } else if (_.has(this._values, fieldName)) {

    // Look for value in "_values" property.
    value = this._values[fieldName];

  } else {

    // If seek value is not present in the "_values" and "_modified" objects
    // then we have to look for default value. We already have field's
    // definition, so we only have to set value.
    value = fieldDefinition.default;

  }

  // Trigger "afterGet" event handlers.
  schema.triggerEvent('afterGet', this, true, [fieldName]);

  return value;
};

var getMany = function(fieldsNames) {
  var values = {};

  _.each(fieldsNames, function(fieldName) {
    values[fieldName] = this.get(fieldName);
  }, this);

  return values;
};

var getAll = function() {
  // Get list of all fields defined in this and parent schemas. "_.map" function
  // returns array of arrays of fields, so we have to flatten it to plain array.
  var fieldsNames = _.flatten(_.map(this.constructor.schemas, function(schema) {
    return _.keys(schema.getFields());
  }));

  // Get list of fields and their values.
  return this.get(fieldsNames);
};

methods.get = function() {
  if (arguments.length === 0) {
    return getAll.call(this);
  } else if (arguments.length === 1) {
    if (_.isArray(arguments[0])) {
      return getMany.apply(this, arguments);
    } else if (_.isString(arguments[0])) {
      return getOne.apply(this, arguments);
    }
  }
};

var setOne = function(fieldName, value) {
  // Deny changing _id of a document.
  if (fieldName === '_id' && this._values[fieldName]) {
    return;
  }

  // Loop through all parent schemas including this one and get field definition
  // in the first schema that has given field defined. We will also get schema
  // in which field is defined. It will be used to invoke events.
  var fieldDefinition;
  var schema = _.find(this.constructor.schemas, function(schema) {
    return fieldDefinition = schema.getField(fieldName);
  });

  // If there is no field definition then do not set field's value.
  if (!fieldDefinition) {
    return;
  }

  // Trigger "beforeSet" event handlers.
  schema.triggerEvent('beforeSet', this, true, [fieldName, value]);

  // The value being set has to be casted on the type defined in the schema.
  // We have to check in which parent schema given field is defined.
  if (fieldDefinition.type) {
    value = Types[fieldDefinition.type](value);
  }

  // Check if given value exists in the "_values" object and whether it
  // differs from old value.
  if (this._values[fieldName] && value === this._values[fieldName]) {
    return;
  }

  // Set new value.
  this._modified[fieldName] = value;

  // Trigger "afterSet" event handlers.
  schema.triggerEvent('afterSet', this, true, [fieldName, value]);
};

methods.set = function() {
  if (arguments.length === 1 && _.isObject(arguments[0])) {
    // Set multiple fields.
    _.each(arguments[0], function(value, fieldName) {
      // We don't call "setOne" function directly because we want to check
      // arguments' types.
      this.set(fieldName, value);
    }, this);
  } else if (arguments.length === 2 && _.isString(arguments[0])) {
    setOne.apply(this, arguments);
  }
};

methods.getModified = function(old) {
  old = old || false;

  // Get values of modified fields before modification.
  if (old) {
    // Get keys of modified values.
    var modifiedKeys = _.keys(this._modified);

    // Get old values of modified fields.
    var oldValues = _.pick(this._values, modifiedKeys);

    // Get keys of old values that are present in the given instance. It will be
    // needed to check if all old values have been fetched.
    var oldValuesKeys = _.keys(oldValues);

    // Check whether number of modified fields equals number of old values. If
    // there are some missing old values, then we have to get their default
    // values from this and parent schemas.
    if (modifiedKeys.length !== oldValuesKeys.length) {
      // Get difference in old and modified fields.
      var missingKeys = _.difference(modifiedKeys, oldValuesKeys);

      // For each missing field try getting its default value.
      _.each(missingKeys, function(missingKey) {

        // Look in all schemas for missing field.
        _.find(this.constructor.schemas, function(schema) {
          // If field is defined in given schema.
          if (schema.hasField(missingKey)) {
            // Then get its default value.
            oldValues[missingKey] = schema.getField(missingKey).default;
            return true;
          }
        });

      }, this);
    }

    return oldValues;
  }

  return this._modified;
};
<commit_msg>Clone default value instead of copying by reference<commit_after>methods = {};

methods.save = function(callback) {
  // Get collection for given class.
  var Collection = this.constructor.schema.getCollection();
  if (!Collection) {
    throw new Error('There is no collection to save to');
  }

  // Flag indicating whether we should update or insert document.
  var update = !!this._values._id;

  // Trigger "beforeSave", "beforeInsert" and "beforeUpdate" event handlers on
  // current and parent schemas.
  _.each(this.constructor.schemas, function(schema) {
    schema.triggerEvent('beforeSave', this, true);
    if (update) {
      schema.triggerEvent('beforeUpdate', this, true);
    } else {
      schema.triggerEvent('beforeInsert', this, true);
    }
  }, this);

  // Get values to update or insert.
  var values = update ? this.getModified() : this.get();
  // Remove "_id" field, if its value is null (object is new and have not been
  // saved yet) or it's not null but "update" flag is set what means that we are
  // updating document.
  if (!values['_id'] || update) {
    values = _.omit(values, '_id');
  }

  // Check if there are any values to update or insert. If there are no modified
  // fields, we shouldn't do anything.
  if (_.size(values) === 0) {
    return false;
  }

  // Add callback to arguments list if provided.
  var args = [];
  if (callback) {
    args.push(callback);
  }

  var result;
  if (update) {
    // Add selector and modifier at the beginning of the arguments list. Right
    // now in the array is a callback function (if provided).
    args.unshift({ // Selector.
      _id: this._values._id
    }, { // Modifier.
      $set: values
    });
    // Update document.
    result = Collection.update.apply(Collection, args);
  } else {
    // Add values to insert into the list of arguments passed to the "insert"
    // method.
    args.unshift(values);
    // Insert document.
    result = this._values._id = Collection.insert.apply(Collection, args);
  }

  // Trigger "afterSave", "afterInsert" and "afterUpdate" event handlers on
  // current and parent schemas.
  _.each(this.constructor.schemas, function(schema) {
    if (update) {
      schema.triggerEvent('afterUpdate', this, true);
    } else {
      schema.triggerEvent('afterInsert', this, true);
    }
    // Trigger afterSave event handlers.
    schema.triggerEvent('afterSave', this, true);
  }, this);

  // Update values with new ones.
  _.extend(this._values, values);

  // Clear modified fields.
  this._modified = {};

  // Return result of executing Mongo query.
  return result;
};

methods.remove = function(callback) {
  // Get collection for given class or parent class.
  var Collection = this.constructor.schema.getCollection();
  if (!Collection) {
    throw new Error('There is no collection to remove from');
  }

  // Remove only when document has _id, so it's saved in the collection.
  if (!this._values._id) {
    return;
  }

  // Trigger "beforeRemove" event handlers on current and parent schemas.
  _.each(this.constructor.schemas, function(schema) {
    schema.triggerEvent('beforeRemove', this, true);
  }, this);

  // Add selector to arguments list.
  var args = [];
  args.push({
    _id: this._values._id
  });
  // Add callback to arguments list if provided.
  if (callback) {
    args.push(callback);
  }

  // Remove document and save result.
  var result = Collection.remove.apply(Collection, args);

  // Trigger "afterRemove" event handlers on current and parent schemas.
  _.each(this.constructor.schemas, function(schema) {
    schema.triggerEvent('afterRemove', this, true);
  }, this);

  // Clear "_id" attribute, so that user can save document one more time.
  this._values['_id'] = undefined;

  // Return result of removing document.
  return result;
};

methods.reload = function() {
  // Get collection for given class or parent class.
  var Collection = this.constructor.schema.getCollection();
  if (!Collection) {
    throw new Error('There is no collection to reload document from');
  }

  if (this._values._id) {
    // Get new values from collection without the transformation.
    this._values = Collection.findOne(this._values._id, {
      transform: null
    }) || this._values;
    // Clear modified fields list.
    this._modified = {};
  }
};

methods.clone = function(attrs, save) {
  save = save || false;

  // Get object constructor.
  var Class = this.constructor;
  // Create new instance.
  var cloned = new Class();

  // Copy values and modified values but without "_id" field.
  cloned._values = EJSON.clone(_.omit(this._values, '_id'));
  cloned._modified = EJSON.clone(_.omit(this._modified, '_id'));

  // Apply new values if provided.
  if (_.isObject(attrs)) {
    _.extend(cloned, attrs);
  }

  // Save clone to collection.
  if (save) {
    cloned.save();
  }

  return cloned;
};

var getOne = function(fieldName) {
  // Define var for returned value.
  var value;

  // Look for field's definition and schema. Field definition can be places in
  // this or parent schema.
  var fieldDefinition;
  var schema = _.find(this.constructor.schemas, function(schema) {
    return fieldDefinition = schema.getField(fieldName);
  });

  // If field's definition is not present then we just return "undefined".
  if (!fieldDefinition) {
    return value;
  }

  // Trigger "beforeGet" event handlers.
  schema.triggerEvent('beforeGet', this, true, [fieldName]);

  if (_.has(this._modified, fieldName)) {

    // Look for value in "_modified" property.
    value = this._modified[fieldName];

  } else if (_.has(this._values, fieldName)) {

    // Look for value in "_values" property.
    value = this._values[fieldName];

  } else {

    // If seek value is not present in the "_values" and "_modified" objects
    // then we have to look for default value in the field's definition. We have
    // to use EJSON stringify and EJSON parse methods to make sure that set
    // value is a copy of default value and not a reference. At this stage it's
    // important to have defined custom types for EJSON thanks to which it will
    // be possible to clone any non standard value.
    value = EJSON.parse(EJSON.stringify(fieldDefinition.default));

    // At the same time, we can set the default value for that field in the
    // "_values" object so that checking for default value won't be needed any
    // more.
    this._values[fieldName] = value;
  }

  // Trigger "afterGet" event handlers.
  schema.triggerEvent('afterGet', this, true, [fieldName]);

  return value;
};

var getMany = function(fieldsNames) {
  var values = {};

  _.each(fieldsNames, function(fieldName) {
    values[fieldName] = this.get(fieldName);
  }, this);

  return values;
};

var getAll = function() {
  // Get list of all fields defined in this and parent schemas. "_.map" function
  // returns array of arrays of fields, so we have to flatten it to plain array.
  var fieldsNames = _.flatten(_.map(this.constructor.schemas, function(schema) {
    return _.keys(schema.getFields());
  }));

  // Get list of fields and their values.
  return this.get(fieldsNames);
};

methods.get = function() {
  if (arguments.length === 0) {
    return getAll.call(this);
  } else if (arguments.length === 1) {
    if (_.isArray(arguments[0])) {
      return getMany.apply(this, arguments);
    } else if (_.isString(arguments[0])) {
      return getOne.apply(this, arguments);
    }
  }
};

var setOne = function(fieldName, value) {
  // Deny changing _id of a document.
  if (fieldName === '_id' && this._values[fieldName]) {
    return;
  }

  // Loop through all parent schemas including this one and get field definition
  // in the first schema that has given field defined. We will also get schema
  // in which field is defined. It will be used to invoke events.
  var fieldDefinition;
  var schema = _.find(this.constructor.schemas, function(schema) {
    return fieldDefinition = schema.getField(fieldName);
  });

  // If there is no field definition then do not set field's value.
  if (!fieldDefinition) {
    return;
  }

  // Trigger "beforeSet" event handlers.
  schema.triggerEvent('beforeSet', this, true, [fieldName, value]);

  // The value being set has to be casted on the type defined in the schema.
  // We have to check in which parent schema given field is defined.
  if (fieldDefinition.type) {
    value = Types[fieldDefinition.type](value);
  }

  // Check if given value exists in the "_values" object and whether it
  // differs from old value.
  if (this._values[fieldName] && value === this._values[fieldName]) {
    return;
  }

  // Set new value.
  this._modified[fieldName] = value;

  // Trigger "afterSet" event handlers.
  schema.triggerEvent('afterSet', this, true, [fieldName, value]);
};

methods.set = function() {
  if (arguments.length === 1 && _.isObject(arguments[0])) {
    // Set multiple fields.
    _.each(arguments[0], function(value, fieldName) {
      // We don't call "setOne" function directly because we want to check
      // arguments' types.
      this.set(fieldName, value);
    }, this);
  } else if (arguments.length === 2 && _.isString(arguments[0])) {
    setOne.apply(this, arguments);
  }
};

methods.getModified = function(old) {
  old = old || false;

  // Get values of modified fields before modification.
  if (old) {
    // Get keys of modified values.
    var modifiedKeys = _.keys(this._modified);

    // Get old values of modified fields.
    var oldValues = _.pick(this._values, modifiedKeys);

    // Get keys of old values that are present in the given instance. It will be
    // needed to check if all old values have been fetched.
    var oldValuesKeys = _.keys(oldValues);

    // Check whether number of modified fields equals number of old values. If
    // there are some missing old values, then we have to get their default
    // values from this and parent schemas.
    if (modifiedKeys.length !== oldValuesKeys.length) {
      // Get difference in old and modified fields.
      var missingKeys = _.difference(modifiedKeys, oldValuesKeys);

      // For each missing field try getting its default value.
      _.each(missingKeys, function(missingKey) {

        // Look in all schemas for missing field.
        _.find(this.constructor.schemas, function(schema) {
          // If field is defined in given schema.
          if (schema.hasField(missingKey)) {
            // Then get its default value.
            oldValues[missingKey] = schema.getField(missingKey).default;
            return true;
          }
        });

      }, this);
    }

    return oldValues;
  }

  return this._modified;
};
<|endoftext|>


<commit_before>/*! Moment Duration Format v1.3.0
 *  https://github.com/jsmreese/moment-duration-format
 *  Date: 2014-07-15
 *
 *  Duration format plugin function for the Moment.js library
 *  http://momentjs.com/
 *
 *  Copyright 2014 John Madhavan-Reese
 *  Released under the MIT license
 */

(function (root, undefined) {

	// repeatZero(qty)
	// returns "0" repeated qty times
	function repeatZero(qty) {
		var result = "";

		// exit early
		// if qty is 0 or a negative number
		// or doesn't coerce to an integer
		qty = parseInt(qty, 10);
		if (!qty || qty < 1) { return result; }

		while (qty) {
			result += "0";
			qty -= 1;
		}

		return result;
	}

	// padZero(str, len [, isRight])
	// pads a string with zeros up to a specified length
	// will not pad a string if its length is aready
	// greater than or equal to the specified length
	// default output pads with zeros on the left
	// set isRight to `true` to pad with zeros on the right
	function padZero(str, len, isRight) {
		if (str == null) { str = ""; }
		str = "" + str;

		return (isRight ? str : "") + repeatZero(len - str.length) + (isRight ? "" : str);
	}

	// isArray
	function isArray(array) {
		return Object.prototype.toString.call(array) === "[object Array]";
	}

	// isObject
	function isObject(obj) {
		return Object.prototype.toString.call(obj) === "[object Object]";
	}

	// findLast
	function findLast(array, callback) {
		var index = array.length;

		while (index -= 1) {
			if (callback(array[index])) { return array[index]; }
		}
	}

	// find
	function find(array, callback) {
		var index = 0,
			max = array.length,
			match;

		if (typeof callback !== "function") {
			match = callback;
			callback = function (item) {
				return item === match;
			};
		}

		while (index < max) {
			if (callback(array[index])) { return array[index]; }
			index += 1;
		}
	}

	// each
	function each(array, callback) {
		var index = 0,
			max = array.length;

		if (!array || !max) { return; }

		while (index < max) {
			if (callback(array[index], index) === false) { return; }
			index += 1;
		}
	}

	// map
	function map(array, callback) {
		var index = 0,
			max = array.length,
			ret = [];

		if (!array || !max) { return ret; }

		while (index < max) {
			ret[index] = callback(array[index], index);
			index += 1;
		}

		return ret;
	}

	// pluck
	function pluck(array, prop) {
		return map(array, function (item) {
			return item[prop];
		});
	}

	// compact
	function compact(array) {
		var ret = [];

		each(array, function (item) {
			if (item) { ret.push(item); }
		});

		return ret;
	}

	// unique
	function unique(array) {
		var ret = [];

		each(array, function (_a) {
			if (!find(ret, _a)) { ret.push(_a); }
		});

		return ret;
	}

	// intersection
	function intersection(a, b) {
		var ret = [];

		each(a, function (_a) {
			each(b, function (_b) {
				if (_a === _b) { ret.push(_a); }
			});
		});

		return unique(ret);
	}

	// rest
	function rest(array, callback) {
		var ret = [];

		each(array, function (item, index) {
			if (!callback(item)) {
				ret = array.slice(index);
				return false;
			}
		});

		return ret;
	}

	// initial
	function initial(array, callback) {
		var reversed = array.slice().reverse();

		return rest(reversed, callback).reverse();
	}

	// extend
	// from http://stackoverflow.com/questions/11197247/javascript-equivalent-of-jquerys-extend-method
	function extend(a, b) {
		for (var key in b) {
			if (b.hasOwnProperty(key)) { a[key] = b[key]; }
		}

		return a;
	}

	// define internal moment and _ references
	var moment, _,
		hasRequire = (typeof require === "function");

	if (hasRequire) {
		// require lodash or underscore
		try {
			_ = require('lodash');
		} catch (e) {
			_ = require('underscore');
		}
	} else if (root._) {
		_ = root._;
	} else {
		throw "Moment Duration Format cannot find Lo-Dash or Underscore";
	}

	if (hasRequire) {
		// require moment
		moment = require('moment');
	} else if (root.moment) {
		moment = root.moment;
	} else {
		throw "Moment Duration Format cannot find Moment.js";
	}

	// moment.duration.format([template] [, precision] [, settings])
	moment.duration.fn.format = function () {

		var tokenizer, tokens, types, typeMap, momentTypes, foundFirst, trimIndex,
			args = [].slice.call(arguments),
			settings = extend({}, this.format.defaults),
			// keep a shadow copy of this moment for calculating remainders
			remainder = moment.duration(this);

		// add a reference to this duration object to the settings for use
		// in a template function
		settings.duration = this;

		// parse arguments
		each(args, function (arg) {
			if (typeof arg === "string" || typeof arg === "function") {
				settings.template = arg;
				return;
			}

			if (typeof arg === "number") {
				settings.precision = arg;
				return;
			}

			if (isObject(arg)) {
				extend(settings, arg);
			}
		});

		// types
		types = settings.types = (isArray(settings.types) ? settings.types : settings.types.split(" "));

		// template
		if (typeof settings.template === "function") {
			settings.template = settings.template.apply(settings);
		}

		// tokenizer regexp
		tokenizer = new RegExp(map(types, function (type) {
			return settings[type].source;
		}).join("|"), "g");

		// token type map function
		typeMap = function (token) {
			return find(types, function (type) {
				return settings[type].test(token);
			});
		};

		// tokens array
		tokens = map(settings.template.match(tokenizer), function (token, index) {
			var type = typeMap(token),
				length = token.length;

			return {
				index: index,
				length: length,

				// replace escaped tokens with the non-escaped token text
				token: (type === "escape" ? token.replace(settings.escape, "$1") : token),

				// ignore type on non-moment tokens
				type: ((type === "escape" || type === "general") ? null : type)

				// calculate base value for all moment tokens
				//baseValue: ((type === "escape" || type === "general") ? null : this.as(type))
			};
		}, this);

		// unique moment token types in the template (in order of descending magnitude)
		momentTypes = intersection(types, unique(compact(pluck(tokens, "type"))));

		// exit early if there are no momentTypes
		if (!momentTypes.length) {
			return pluck(tokens, "token").join("");
		}

		// calculate values for each token type in the template
		each(momentTypes, function (momentType, index) {
			var value, wholeValue, decimalValue, isLeast, isMost;

			// calculate integer and decimal value portions
			value = remainder.as(momentType);
			wholeValue = (value > 0 ? Math.floor(value) : Math.ceil(value));
			decimalValue = value - wholeValue;

			// is this the least-significant moment token found?
			isLeast = ((index + 1) === momentTypes.length);

			// is this the most-significant moment token found?
			isMost = (!index);

			// update tokens array
			// using this algorithm to not assume anything about
			// the order or frequency of any tokens
			each(tokens, function (token) {
				if (token.type === momentType) {
					extend(token, {
						value: value,
						wholeValue: wholeValue,
						decimalValue: decimalValue,
						isLeast: isLeast,
						isMost: isMost
					});

					if (isMost) {
						// note the length of the most-significant moment token:
						// if it is greater than one and forceLength is not set, default forceLength to `true`
						if (settings.forceLength == null && token.length > 1) {
							settings.forceLength = true;
						}

						// rationale is this:
						// if the template is "h:mm:ss" and the moment value is 5 minutes, the user-friendly output is "5:00", not "05:00"
						// shouldn't pad the `minutes` token even though it has length of two
						// if the template is "hh:mm:ss", the user clearly wanted everything padded so we should output "05:00"
						// if the user wanted the full padded output, they can set `{ trim: false }` to get "00:05:00"
					}
				}
			});

			// update remainder
			remainder.subtract(wholeValue, momentType);
		});

		// trim tokens array
		if (settings.trim) {
			tokens = (settings.trim === "left" ? rest : initial)(tokens, function (token) {
				// return `true` if:
				// the token is not the least moment token (don't trim the least moment token)
				// the token is a moment token that does not have a value (don't trim moment tokens that have a whole value)
				return !(token.isLeast || (token.type != null && token.wholeValue));
			});
		}

		// build output

		// the first moment token can have special handling
		foundFirst = false;

		// run the map in reverse order if trimming from the right
		if (settings.trim === "right") {
			tokens.reverse();
		}

		tokens = map(tokens, function (token) {
			var val,
				decVal;

			if (!token.type) {
				// if it is not a moment token, use the token as its own value
				return token.token;
			}

			// apply negative precision formatting to the least-significant moment token
			if (token.isLeast && (settings.precision < 0)) {
				val = (Math.floor(token.wholeValue * Math.pow(10, settings.precision)) * Math.pow(10, -settings.precision)).toString();
			} else {
				val = token.wholeValue.toString();
			}

			// remove negative sign from the beginning
			val = val.replace(/^\-/, "");

			// apply token length formatting
			// special handling for the first moment token that is not the most significant in a trimmed template
			if (token.length > 1 && (foundFirst || token.isMost || settings.forceLength)) {
				val = padZero(val, token.length);
			}

			// add decimal value if precision > 0
			if (token.isLeast && (settings.precision > 0)) {
				decVal = token.decimalValue.toString().replace(/^\-/, "").split(/\.|e\-/);
				switch (decVal.length) {
					case 1:
						val += "." + padZero(decVal[0], settings.precision, true).slice(0, settings.precision);
						break;

					case 2:
						val += "." + padZero(decVal[1], settings.precision, true).slice(0, settings.precision);
						break;

					case 3:
						val += "." + padZero(repeatZero((+decVal[2]) - 1) + (decVal[0] || "0") + decVal[1], settings.precision, true).slice(0, settings.precision);
						break;

					default:
						throw "Moment Duration Format: unable to parse token decimal value.";
				}
			}

			// add a negative sign if the value is negative and token is most significant
			if (token.isMost && token.value < 0) {
				val = "-" + val;
			}

			foundFirst = true;

			return val;
		});

		// undo the reverse if trimming from the right
		if (settings.trim === "right") {
			tokens.reverse();
		}

		return tokens.join("");
	};

	moment.duration.fn.format.defaults = {
		// token definitions
		escape: /\[(.+?)\]/,
		years: /[Yy]+/,
		months: /M+/,
		weeks: /[Ww]+/,
		days: /[Dd]+/,
		hours: /[Hh]+/,
		minutes: /m+/,
		seconds: /s+/,
		milliseconds: /S+/,
		general: /.+?/,

		// token type names
		// in order of descending magnitude
		// can be a space-separated token name list or an array of token names
		types: "escape years months weeks days hours minutes seconds milliseconds general",

		// format options

		// trim
		// "left" - template tokens are trimmed from the left until the first moment token that has a value >= 1
		// "right" - template tokens are trimmed from the right until the first moment token that has a value >= 1
		// (the final moment token is not trimmed, regardless of value)
		// `false` - template tokens are not trimmed
		trim: "left",

		// precision
		// number of decimal digits to include after (to the right of) the decimal point (positive integer)
		// or the number of digits to truncate to 0 before (to the left of) the decimal point (negative integer)
		precision: 0,

		// force first moment token with a value to render at full length even when template is trimmed and first moment token has length of 1
		forceLength: null,

		// template used to format duration
		// may be a function or a string
		// template functions are executed with the `this` binding of the settings object
		// so that template strings may be dynamically generated based on the duration object
		// (accessible via `this.duration`)
		// or any of the other settings
		template: function () {
			var types = this.types,
				dur = this.duration,
				lastType;

			if (typeof findLast === "function") {
				lastType = findLast(types, function (type) {
					return dur._data[type];
				});
			} else {
				lastType = findLast(types, function (type) {
					return dur._data[type];
				});
			}

			// default template strings for each duration dimension type
			switch (lastType) {
				case "seconds":
					return "h:mm:ss";
				case "minutes":
					return "d[d] h:mm";
				case "hours":
					return "d[d] h[h]";
				case "days":
					return "M[m] d[d]";
				case "weeks":
					return "y[y] w[w]";
				case "months":
					return "y[y] M[m]";
				case "years":
					return "y[y]";
				default:
					return "y[y] M[m] d[d] h:mm:ss";
			}
		}
	};

})(this);
<commit_msg>Removed comment.<commit_after>/*! Moment Duration Format v1.3.0
 *  https://github.com/jsmreese/moment-duration-format
 *  Date: 2014-07-15
 *
 *  Duration format plugin function for the Moment.js library
 *  http://momentjs.com/
 *
 *  Copyright 2014 John Madhavan-Reese
 *  Released under the MIT license
 */

(function (root, undefined) {

	// repeatZero(qty)
	// returns "0" repeated qty times
	function repeatZero(qty) {
		var result = "";

		// exit early
		// if qty is 0 or a negative number
		// or doesn't coerce to an integer
		qty = parseInt(qty, 10);
		if (!qty || qty < 1) { return result; }

		while (qty) {
			result += "0";
			qty -= 1;
		}

		return result;
	}

	// padZero(str, len [, isRight])
	// pads a string with zeros up to a specified length
	// will not pad a string if its length is aready
	// greater than or equal to the specified length
	// default output pads with zeros on the left
	// set isRight to `true` to pad with zeros on the right
	function padZero(str, len, isRight) {
		if (str == null) { str = ""; }
		str = "" + str;

		return (isRight ? str : "") + repeatZero(len - str.length) + (isRight ? "" : str);
	}

	// isArray
	function isArray(array) {
		return Object.prototype.toString.call(array) === "[object Array]";
	}

	// isObject
	function isObject(obj) {
		return Object.prototype.toString.call(obj) === "[object Object]";
	}

	// findLast
	function findLast(array, callback) {
		var index = array.length;

		while (index -= 1) {
			if (callback(array[index])) { return array[index]; }
		}
	}

	// find
	function find(array, callback) {
		var index = 0,
			max = array.length,
			match;

		if (typeof callback !== "function") {
			match = callback;
			callback = function (item) {
				return item === match;
			};
		}

		while (index < max) {
			if (callback(array[index])) { return array[index]; }
			index += 1;
		}
	}

	// each
	function each(array, callback) {
		var index = 0,
			max = array.length;

		if (!array || !max) { return; }

		while (index < max) {
			if (callback(array[index], index) === false) { return; }
			index += 1;
		}
	}

	// map
	function map(array, callback) {
		var index = 0,
			max = array.length,
			ret = [];

		if (!array || !max) { return ret; }

		while (index < max) {
			ret[index] = callback(array[index], index);
			index += 1;
		}

		return ret;
	}

	// pluck
	function pluck(array, prop) {
		return map(array, function (item) {
			return item[prop];
		});
	}

	// compact
	function compact(array) {
		var ret = [];

		each(array, function (item) {
			if (item) { ret.push(item); }
		});

		return ret;
	}

	// unique
	function unique(array) {
		var ret = [];

		each(array, function (_a) {
			if (!find(ret, _a)) { ret.push(_a); }
		});

		return ret;
	}

	// intersection
	function intersection(a, b) {
		var ret = [];

		each(a, function (_a) {
			each(b, function (_b) {
				if (_a === _b) { ret.push(_a); }
			});
		});

		return unique(ret);
	}

	// rest
	function rest(array, callback) {
		var ret = [];

		each(array, function (item, index) {
			if (!callback(item)) {
				ret = array.slice(index);
				return false;
			}
		});

		return ret;
	}

	// initial
	function initial(array, callback) {
		var reversed = array.slice().reverse();

		return rest(reversed, callback).reverse();
	}

	// extend
	function extend(a, b) {
		for (var key in b) {
			if (b.hasOwnProperty(key)) { a[key] = b[key]; }
		}

		return a;
	}

	// define internal moment and _ references
	var moment, _,
		hasRequire = (typeof require === "function");

	if (hasRequire) {
		// require lodash or underscore
		try {
			_ = require('lodash');
		} catch (e) {
			_ = require('underscore');
		}
	} else if (root._) {
		_ = root._;
	} else {
		throw "Moment Duration Format cannot find Lo-Dash or Underscore";
	}

	if (hasRequire) {
		// require moment
		moment = require('moment');
	} else if (root.moment) {
		moment = root.moment;
	} else {
		throw "Moment Duration Format cannot find Moment.js";
	}

	// moment.duration.format([template] [, precision] [, settings])
	moment.duration.fn.format = function () {

		var tokenizer, tokens, types, typeMap, momentTypes, foundFirst, trimIndex,
			args = [].slice.call(arguments),
			settings = extend({}, this.format.defaults),
			// keep a shadow copy of this moment for calculating remainders
			remainder = moment.duration(this);

		// add a reference to this duration object to the settings for use
		// in a template function
		settings.duration = this;

		// parse arguments
		each(args, function (arg) {
			if (typeof arg === "string" || typeof arg === "function") {
				settings.template = arg;
				return;
			}

			if (typeof arg === "number") {
				settings.precision = arg;
				return;
			}

			if (isObject(arg)) {
				extend(settings, arg);
			}
		});

		// types
		types = settings.types = (isArray(settings.types) ? settings.types : settings.types.split(" "));

		// template
		if (typeof settings.template === "function") {
			settings.template = settings.template.apply(settings);
		}

		// tokenizer regexp
		tokenizer = new RegExp(map(types, function (type) {
			return settings[type].source;
		}).join("|"), "g");

		// token type map function
		typeMap = function (token) {
			return find(types, function (type) {
				return settings[type].test(token);
			});
		};

		// tokens array
		tokens = map(settings.template.match(tokenizer), function (token, index) {
			var type = typeMap(token),
				length = token.length;

			return {
				index: index,
				length: length,

				// replace escaped tokens with the non-escaped token text
				token: (type === "escape" ? token.replace(settings.escape, "$1") : token),

				// ignore type on non-moment tokens
				type: ((type === "escape" || type === "general") ? null : type)

				// calculate base value for all moment tokens
				//baseValue: ((type === "escape" || type === "general") ? null : this.as(type))
			};
		}, this);

		// unique moment token types in the template (in order of descending magnitude)
		momentTypes = intersection(types, unique(compact(pluck(tokens, "type"))));

		// exit early if there are no momentTypes
		if (!momentTypes.length) {
			return pluck(tokens, "token").join("");
		}

		// calculate values for each token type in the template
		each(momentTypes, function (momentType, index) {
			var value, wholeValue, decimalValue, isLeast, isMost;

			// calculate integer and decimal value portions
			value = remainder.as(momentType);
			wholeValue = (value > 0 ? Math.floor(value) : Math.ceil(value));
			decimalValue = value - wholeValue;

			// is this the least-significant moment token found?
			isLeast = ((index + 1) === momentTypes.length);

			// is this the most-significant moment token found?
			isMost = (!index);

			// update tokens array
			// using this algorithm to not assume anything about
			// the order or frequency of any tokens
			each(tokens, function (token) {
				if (token.type === momentType) {
					extend(token, {
						value: value,
						wholeValue: wholeValue,
						decimalValue: decimalValue,
						isLeast: isLeast,
						isMost: isMost
					});

					if (isMost) {
						// note the length of the most-significant moment token:
						// if it is greater than one and forceLength is not set, default forceLength to `true`
						if (settings.forceLength == null && token.length > 1) {
							settings.forceLength = true;
						}

						// rationale is this:
						// if the template is "h:mm:ss" and the moment value is 5 minutes, the user-friendly output is "5:00", not "05:00"
						// shouldn't pad the `minutes` token even though it has length of two
						// if the template is "hh:mm:ss", the user clearly wanted everything padded so we should output "05:00"
						// if the user wanted the full padded output, they can set `{ trim: false }` to get "00:05:00"
					}
				}
			});

			// update remainder
			remainder.subtract(wholeValue, momentType);
		});

		// trim tokens array
		if (settings.trim) {
			tokens = (settings.trim === "left" ? rest : initial)(tokens, function (token) {
				// return `true` if:
				// the token is not the least moment token (don't trim the least moment token)
				// the token is a moment token that does not have a value (don't trim moment tokens that have a whole value)
				return !(token.isLeast || (token.type != null && token.wholeValue));
			});
		}

		// build output

		// the first moment token can have special handling
		foundFirst = false;

		// run the map in reverse order if trimming from the right
		if (settings.trim === "right") {
			tokens.reverse();
		}

		tokens = map(tokens, function (token) {
			var val,
				decVal;

			if (!token.type) {
				// if it is not a moment token, use the token as its own value
				return token.token;
			}

			// apply negative precision formatting to the least-significant moment token
			if (token.isLeast && (settings.precision < 0)) {
				val = (Math.floor(token.wholeValue * Math.pow(10, settings.precision)) * Math.pow(10, -settings.precision)).toString();
			} else {
				val = token.wholeValue.toString();
			}

			// remove negative sign from the beginning
			val = val.replace(/^\-/, "");

			// apply token length formatting
			// special handling for the first moment token that is not the most significant in a trimmed template
			if (token.length > 1 && (foundFirst || token.isMost || settings.forceLength)) {
				val = padZero(val, token.length);
			}

			// add decimal value if precision > 0
			if (token.isLeast && (settings.precision > 0)) {
				decVal = token.decimalValue.toString().replace(/^\-/, "").split(/\.|e\-/);
				switch (decVal.length) {
					case 1:
						val += "." + padZero(decVal[0], settings.precision, true).slice(0, settings.precision);
						break;

					case 2:
						val += "." + padZero(decVal[1], settings.precision, true).slice(0, settings.precision);
						break;

					case 3:
						val += "." + padZero(repeatZero((+decVal[2]) - 1) + (decVal[0] || "0") + decVal[1], settings.precision, true).slice(0, settings.precision);
						break;

					default:
						throw "Moment Duration Format: unable to parse token decimal value.";
				}
			}

			// add a negative sign if the value is negative and token is most significant
			if (token.isMost && token.value < 0) {
				val = "-" + val;
			}

			foundFirst = true;

			return val;
		});

		// undo the reverse if trimming from the right
		if (settings.trim === "right") {
			tokens.reverse();
		}

		return tokens.join("");
	};

	moment.duration.fn.format.defaults = {
		// token definitions
		escape: /\[(.+?)\]/,
		years: /[Yy]+/,
		months: /M+/,
		weeks: /[Ww]+/,
		days: /[Dd]+/,
		hours: /[Hh]+/,
		minutes: /m+/,
		seconds: /s+/,
		milliseconds: /S+/,
		general: /.+?/,

		// token type names
		// in order of descending magnitude
		// can be a space-separated token name list or an array of token names
		types: "escape years months weeks days hours minutes seconds milliseconds general",

		// format options

		// trim
		// "left" - template tokens are trimmed from the left until the first moment token that has a value >= 1
		// "right" - template tokens are trimmed from the right until the first moment token that has a value >= 1
		// (the final moment token is not trimmed, regardless of value)
		// `false` - template tokens are not trimmed
		trim: "left",

		// precision
		// number of decimal digits to include after (to the right of) the decimal point (positive integer)
		// or the number of digits to truncate to 0 before (to the left of) the decimal point (negative integer)
		precision: 0,

		// force first moment token with a value to render at full length even when template is trimmed and first moment token has length of 1
		forceLength: null,

		// template used to format duration
		// may be a function or a string
		// template functions are executed with the `this` binding of the settings object
		// so that template strings may be dynamically generated based on the duration object
		// (accessible via `this.duration`)
		// or any of the other settings
		template: function () {
			var types = this.types,
				dur = this.duration,
				lastType;

			if (typeof findLast === "function") {
				lastType = findLast(types, function (type) {
					return dur._data[type];
				});
			} else {
				lastType = findLast(types, function (type) {
					return dur._data[type];
				});
			}

			// default template strings for each duration dimension type
			switch (lastType) {
				case "seconds":
					return "h:mm:ss";
				case "minutes":
					return "d[d] h:mm";
				case "hours":
					return "d[d] h[h]";
				case "days":
					return "M[m] d[d]";
				case "weeks":
					return "y[y] w[w]";
				case "months":
					return "y[y] M[m]";
				case "years":
					return "y[y]";
				default:
					return "y[y] M[m] d[d] h:mm:ss";
			}
		}
	};

})(this);
<|endoftext|>


<commit_before>var _ = require("lodash");
var StatementTokenizer = require("./StatementTokenizer");

var StatementParser = module.exports = function StatementParser(input) {
    this.input = input;
};

StatementParser.prototype = {
    getStatements: function() {
        var tokenizer = StatementTokenizer(this.input);
        return tokenizer.getStatements();
    },

    getStatementUnderCaret: function(selectionStart, selectionEnd) {
        var value = this.input;
        if (selectionStart != selectionEnd) {
            return value.substring(selectionStart, selectionEnd);
        } else {
            var tokenizer = StatementTokenizer(value);
            var statements = tokenizer.getStatements();

            var statementObject = null;
            _.find(statements, function(q) {
                if (q.start > selectionStart) {
                    return true;
                } else {
                    statementObject = q;
                }
            });

            return statementObject ? statementObject.statement : "";
        }
    },

    getStatementAtPosition: function(line, ch) {
        var value = this.input;
        var caret = convertToCaret(value, line, ch);
        return this.getStatementUnderCaret(caret, caret);
    }
};

function convertToCaret(value, line, ch) {
    var lines = value.split("\n");
    var position = 0;
    for (var i = 0; i <= line; i++) {
        if (i === line) {
            return position + ch;
        } else {
            position += lines[i].length;
        }
    }
}

/*
function oldAlgorithm(value, selectionStart, selectionEnd) {
    if (selectionStart != selectionEnd) {
        return value.substring(selectionStart, selectionEnd);
    } else {
        var startSubstring = 0;
        while (true) {
            var indexOfSemicolon = value.indexOf(";", startSubstring);
            if (indexOfSemicolon === -1) {
                return value.substring(startSubstring, value.length);
            } else if (indexOfSemicolon < selectionStart) {
                startSubstring = indexOfSemicolon + 1;
            } else {
                return value.substring(startSubstring, indexOfSemicolon + 1);
            }
        }
    }
};
*/
<commit_msg>Fix off by 1 error.<commit_after>var _ = require("lodash");
var StatementTokenizer = require("./StatementTokenizer");

var StatementParser = module.exports = function StatementParser(input) {
    this.input = input;
};

StatementParser.prototype = {
    getStatements: function() {
        var tokenizer = StatementTokenizer(this.input);
        return tokenizer.getStatements();
    },

    getStatementUnderCaret: function(selectionStart, selectionEnd) {
        var value = this.input;
        if (selectionStart != selectionEnd) {
            return value.substring(selectionStart, selectionEnd);
        } else {
            var tokenizer = StatementTokenizer(value);
            var statements = tokenizer.getStatements();

            var statementObject = null;
            _.find(statements, function(q) {
                if (q.start > selectionStart) {
                    return true;
                } else {
                    statementObject = q;
                }
            });

            return statementObject ? statementObject.statement : "";
        }
    },

    getStatementAtPosition: function(line, ch) {
        var value = this.input;
        var caret = convertToCaret(value, line, ch);
        return this.getStatementUnderCaret(caret, caret);
    }
};

function convertToCaret(value, line, ch) {
    var lines = value.split("\n");
    var position = 0;
    for (var i = 0; i <= line; i++) {
        if (i === line) {
            return position + ch;
        } else {
            position += lines[i].length + 1; // The +1 accounts for the \n removed from the split
        }
    }
}

/*
function oldAlgorithm(value, selectionStart, selectionEnd) {
    if (selectionStart != selectionEnd) {
        return value.substring(selectionStart, selectionEnd);
    } else {
        var startSubstring = 0;
        while (true) {
            var indexOfSemicolon = value.indexOf(";", startSubstring);
            if (indexOfSemicolon === -1) {
                return value.substring(startSubstring, value.length);
            } else if (indexOfSemicolon < selectionStart) {
                startSubstring = indexOfSemicolon + 1;
            } else {
                return value.substring(startSubstring, indexOfSemicolon + 1);
            }
        }
    }
};
*/
<|endoftext|>


<commit_before>/*
 * client.js: Base client from which all AWS clients inherit from
 *
 * (C) 2012 Charlie Robbins, Ken Perkins, Ross Kukulinski & the Contributors.
 *
 */

var util = require('util'),
    AWS = require('aws-sdk'),
    base = require('../core/base');

var userAgent = AWS.util.userAgent();
var Client = exports.Client = function (options) {
  var self = this;

  base.Client.call(this, options);

  options = options || {};

  // Allow overriding serversUrl in child classes
  this.provider   = 'amazon';
  this.endpoint = options.endpoint;
  this.securityGroup = options.securityGroup;
  this.securityGroupId = options.securityGroupId;
  this.version = options.version || '2014-06-15';
  this.protocol = options.protocol || 'https://';

  // support either key/accessKey syntax
  this.config.key = this.config.key || options.accessKey;
  this.config.keyId = this.config.keyId || options.accessKeyId;

  this._awsConfig = {
    accessKeyId: this.config.keyId,
    secretAccessKey: this.config.key,
    region: options.region,
    s3ForcePathStyle: options.forcePathBucket
  };

  // TODO think about a proxy option for pkgcloud
  // enable forwarding to mock test server
  if (options.serversUrl) {
    this._awsConfig.httpOptions = {
      proxy: this.protocol + options.serversUrl
    };
  }

  if (options.endpoint) {
    this._awsConfig.endpoint = new AWS.Endpoint(options.endpoint);
  }

  this.userAgent = util.format('%s %s', self.getUserAgent(), userAgent);

  // Setup a custom user agent for pkgcloud
  AWS.util.userAgent = function () {
    return self.userAgent;
  };

  if (!this.before) {
    this.before = [];
  }
};

util.inherits(Client, base.Client);

Client.prototype._toArray = function toArray(obj) {
  if (typeof obj === 'undefined') {
    return [];
  }

  return Array.isArray(obj) ? obj : [obj];
};

Client.prototype.failCodes = {
  400: 'Bad Request',
  401: 'Unauthorized',
  403: 'Resize not allowed',
  404: 'Item not found',
  409: 'Build in progress',
  413: 'Over Limit',
  415: 'Bad Media Type',
  500: 'Fault',
  503: 'Service Unavailable'
};

Client.prototype.successCodes = {
  200: 'OK',
  201: 'Created',
  202: 'Accepted',
  203: 'Non-authoritative information',
  204: 'No content'
};
<commit_msg>[fix] support more auth scenarios for amazon with credentials object and session token (#678)<commit_after>/*
 * client.js: Base client from which all AWS clients inherit from
 *
 * (C) 2012 Charlie Robbins, Ken Perkins, Ross Kukulinski & the Contributors.
 *
 */

var util = require('util'),
    AWS = require('aws-sdk'),
    base = require('../core/base');

var userAgent = AWS.util.userAgent();
var Client = exports.Client = function (options) {
  var self = this;

  base.Client.call(this, options);

  options = options || {};

  // Allow overriding serversUrl in child classes
  this.provider   = 'amazon';
  this.endpoint = options.endpoint;
  this.securityGroup = options.securityGroup;
  this.securityGroupId = options.securityGroupId;
  this.version = options.version || '2014-06-15';
  this.protocol = options.protocol || 'https://';

  // support either key/accessKey syntax
  this.config.key = this.config.key || options.accessKey;
  this.config.keyId = this.config.keyId || options.accessKeyId;

  this._awsConfig = {
    accessKeyId: this.config.keyId,
    secretAccessKey: this.config.key,
    region: options.region,
    s3ForcePathStyle: options.forcePathBucket,
    sessionToken: options.sessionToken,
    credentials: options.credentials
  };

  // TODO think about a proxy option for pkgcloud
  // enable forwarding to mock test server
  if (options.serversUrl) {
    this._awsConfig.httpOptions = {
      proxy: this.protocol + options.serversUrl
    };
  }

  if (options.endpoint) {
    this._awsConfig.endpoint = new AWS.Endpoint(options.endpoint);
  }

  this.userAgent = util.format('%s %s', self.getUserAgent(), userAgent);

  // Setup a custom user agent for pkgcloud
  AWS.util.userAgent = function () {
    return self.userAgent;
  };

  if (!this.before) {
    this.before = [];
  }
};

util.inherits(Client, base.Client);

Client.prototype._toArray = function toArray(obj) {
  if (typeof obj === 'undefined') {
    return [];
  }

  return Array.isArray(obj) ? obj : [obj];
};

Client.prototype.failCodes = {
  400: 'Bad Request',
  401: 'Unauthorized',
  403: 'Resize not allowed',
  404: 'Item not found',
  409: 'Build in progress',
  413: 'Over Limit',
  415: 'Bad Media Type',
  500: 'Fault',
  503: 'Service Unavailable'
};

Client.prototype.successCodes = {
  200: 'OK',
  201: 'Created',
  202: 'Accepted',
  203: 'Non-authoritative information',
  204: 'No content'
};
<|endoftext|>


<commit_before>var parse_insee = require('./parse_insee');
/* typeModule : permet de gerer les différents cas de retour pour insee*/

module.exports =  function(query,typeModule){
    var result = {} ;

    for ( var name in query ){
		if ( name == 'insee' ){
            var inseeParts = parse_insee(query[name]) ;
            if ( null !== inseeParts ){
				if(typeModule =='commune') {
					result.code_insee = '\''+query[name]+'\'';;
				} else {
                    result.code_dep = '\'' + inseeParts.code_dep + '\'';
                    result.code_com = '\'' + inseeParts.code_com + '\'';
                }
            } else {
				return "ErreurInsee";
			}
        } else if (name == 'geom') {
            result.geom = '\''+query[name]+'\'';
        } else {
            result[name] = '\''+query[name]+'\'' ;
        }
    }
    return result ;
};
<commit_msg>Fix lint<commit_after>var parse_insee = require('./parse_insee');
/* typeModule : permet de gerer les différents cas de retour pour insee*/

module.exports =  function(query,typeModule){
    var result = {} ;

    for ( var name in query ){
        if ( name == 'insee' ){
            var inseeParts = parse_insee(query[name]) ;
            if ( null !== inseeParts ){
                if(typeModule =='commune') {
                    result.code_insee = '\''+query[name]+'\'';
                } else {
                    result.code_dep = '\'' + inseeParts.code_dep + '\'';
                    result.code_com = '\'' + inseeParts.code_com + '\'';
                }
            } else {
                return 'ErreurInsee';
            }
        } else if (name == 'geom') {
            result.geom = '\''+query[name]+'\'';
        } else {
            result[name] = '\''+query[name]+'\'' ;
        }
    }
    return result ;
};
<|endoftext|>


<commit_before>/**
 * Visual Blocks Language
 *
 * Copyright 2012 Google Inc.
 * http://code.google.com/p/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Generating Dart for control blocks.
 * @author fraser@google.com (Neil Fraser)
 */

Blockly.Dart = Blockly.Generator.get('Dart');

Blockly.Dart.controls_if = function() {
  // If/elseif/else condition.
  var n = 0;
  var argument = Blockly.Dart.valueToCode(this, 'IF' + n,
      Blockly.Dart.ORDER_NONE) || 'false';
  var branch = Blockly.Dart.statementToCode(this, 'DO' + n);
  var code = 'if (' + argument + ') {\n' + branch + '}';
  for (n = 1; n <= this.elseifCount_; n++) {
    argument = Blockly.Dart.valueToCode(this, 'IF' + n,
      Blockly.Dart.ORDER_NONE) || 'false';
    branch = Blockly.Dart.statementToCode(this, 'DO' + n);
    code += ' else if (' + argument + ') {\n' + branch + '}';
  }
  if (this.elseCount_) {
    branch = Blockly.Dart.statementToCode(this, 'ELSE');
    code += ' else {\n' + branch + '}';
  }
  return code + '\n';
};

Blockly.Dart.controls_whileUntil = function() {
  // Do while/until loop.
  var argument0 = Blockly.Dart.valueToCode(this, 'BOOL',
      Blockly.Dart.ORDER_NONE) || 'false';
  var branch0 = Blockly.Dart.statementToCode(this, 'DO');
  if (this.getTitleValue('MODE') == 'UNTIL') {
    if (!argument0.match(/^\w+$/)) {
      argument0 = '(' + argument0 + ')';
    }
    argument0 = '!' + argument0;
  }
  return 'while (' + argument0 + ') {\n' + branch0 + '}\n';
};

Blockly.Dart.controls_for = function() {
  // For loop.
  var variable0 = Blockly.Dart.variableDB_.getName(
      this.getTitleValue('VAR'), Blockly.Variables.NAME_TYPE);
  var argument0 = Blockly.Dart.valueToCode(this, 'FROM',
      Blockly.Dart.ORDER_ASSIGNMENT) || '0';
  var argument1 = Blockly.Dart.valueToCode(this, 'TO',
      Blockly.Dart.ORDER_ASSIGNMENT) || '0';
  var branch0 = Blockly.Dart.statementToCode(this, 'DO');
  var code;
  if (argument0.match(/^-?\d+(\.\d+)?$/) &&
      argument1.match(/^-?\d+(\.\d+)?$/)) {
    // Both arguments are simple numbers.
    var up = parseFloat(argument0) <= parseFloat(argument1);
    code = 'for (' + variable0 + ' = ' + argument0 + '; ' +
        variable0 + (up ? ' <= ' : ' >= ') + argument1 + '; ' +
        variable0 + (up ? '++' : '--') + ') {\n' +
        branch0 + '}\n';
  } else {
    code = '';
    // Cache non-trivial values to variables to prevent repeated look-ups.
    var startVar = argument0;
    if (!argument0.match(/^\w+$/) && !argument0.match(/^-?\d+(\.\d+)?$/)) {
      var startVar = Blockly.Dart.variableDB_.getDistinctName(
          variable0 + '_start', Blockly.Variables.NAME_TYPE);
      code += 'var ' + startVar + ' = ' + argument0 + ';\n';
    }
    var endVar = argument1;
    if (!argument1.match(/^\w+$/) && !argument1.match(/^-?\d+(\.\d+)?$/)) {
      var endVar = Blockly.Dart.variableDB_.getDistinctName(
          variable0 + '_end', Blockly.Variables.NAME_TYPE);
      code += 'var ' + endVar + ' = ' + argument1 + ';\n';
    }
    code += 'for (' + variable0 + ' = ' + startVar + ';\n' +
        '    (' + startVar + ' <= ' + endVar + ') ? ' +
        variable0 + ' <= ' + endVar + ' : ' +
        variable0 + ' >= ' + endVar + ';\n' +
        '    ' + variable0 + ' += (' + startVar + ' <= ' + endVar + ') ? 1 : -1) {\n' +
        branch0 + '}\n';
  }
  return code;
};

Blockly.Dart.controls_forEach = function() {
  // For each loop.
  var variable0 = Blockly.Dart.variableDB_.getName(
      this.getTitleValue('VAR'), Blockly.Variables.NAME_TYPE);
  var argument0 = Blockly.Dart.valueToCode(this, 'LIST',
      Blockly.Dart.ORDER_ASSIGNMENT) || '[]';
  var branch0 = Blockly.Dart.statementToCode(this, 'DO');
  var code;
  var indexVar = Blockly.Dart.variableDB_.getDistinctName(
      variable0 + '_index', Blockly.Variables.NAME_TYPE);
  if (argument0.match(/^\w+$/)) {
    branch0 = '  ' + variable0 + ' = ' + argument0 + '[' + indexVar + '];\n' +
        branch0;
    code = 'for (var ' + indexVar + ' in  ' + argument0 + ') {\n' +
        branch0 + '}\n';
  } else {
    // The list appears to be more complicated than a simple variable.
    // Cache it to a variable to prevent repeated look-ups.
    var listVar = Blockly.Dart.variableDB_.getDistinctName(
        variable0 + '_list', Blockly.Variables.NAME_TYPE);
    branch0 = '  ' + variable0 + ' = ' + listVar + '[' + indexVar + '];\n' +
        branch0;
    code = 'var ' + listVar + ' = ' + argument0 + ';\n' +
        'for (var ' + indexVar + ' in ' + listVar + ') {\n' +
        branch0 + '}\n';
  }
  return code;
};

Blockly.Dart.controls_flow_statements = function() {
  // Flow statements: continue, break.
  switch (this.getTitleValue('FLOW')) {
    case 'BREAK':
      return 'break;\n';
    case 'CONTINUE':
      return 'continue;\n';
  }
  throw 'Unknown flow statement.';
};
<commit_msg>Fix Dart for-in loop.<commit_after>/**
 * Visual Blocks Language
 *
 * Copyright 2012 Google Inc.
 * http://code.google.com/p/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Generating Dart for control blocks.
 * @author fraser@google.com (Neil Fraser)
 */

Blockly.Dart = Blockly.Generator.get('Dart');

Blockly.Dart.controls_if = function() {
  // If/elseif/else condition.
  var n = 0;
  var argument = Blockly.Dart.valueToCode(this, 'IF' + n,
      Blockly.Dart.ORDER_NONE) || 'false';
  var branch = Blockly.Dart.statementToCode(this, 'DO' + n);
  var code = 'if (' + argument + ') {\n' + branch + '}';
  for (n = 1; n <= this.elseifCount_; n++) {
    argument = Blockly.Dart.valueToCode(this, 'IF' + n,
      Blockly.Dart.ORDER_NONE) || 'false';
    branch = Blockly.Dart.statementToCode(this, 'DO' + n);
    code += ' else if (' + argument + ') {\n' + branch + '}';
  }
  if (this.elseCount_) {
    branch = Blockly.Dart.statementToCode(this, 'ELSE');
    code += ' else {\n' + branch + '}';
  }
  return code + '\n';
};

Blockly.Dart.controls_whileUntil = function() {
  // Do while/until loop.
  var argument0 = Blockly.Dart.valueToCode(this, 'BOOL',
      Blockly.Dart.ORDER_NONE) || 'false';
  var branch0 = Blockly.Dart.statementToCode(this, 'DO');
  if (this.getTitleValue('MODE') == 'UNTIL') {
    if (!argument0.match(/^\w+$/)) {
      argument0 = '(' + argument0 + ')';
    }
    argument0 = '!' + argument0;
  }
  return 'while (' + argument0 + ') {\n' + branch0 + '}\n';
};

Blockly.Dart.controls_for = function() {
  // For loop.
  var variable0 = Blockly.Dart.variableDB_.getName(
      this.getTitleValue('VAR'), Blockly.Variables.NAME_TYPE);
  var argument0 = Blockly.Dart.valueToCode(this, 'FROM',
      Blockly.Dart.ORDER_ASSIGNMENT) || '0';
  var argument1 = Blockly.Dart.valueToCode(this, 'TO',
      Blockly.Dart.ORDER_ASSIGNMENT) || '0';
  var branch0 = Blockly.Dart.statementToCode(this, 'DO');
  var code;
  if (argument0.match(/^-?\d+(\.\d+)?$/) &&
      argument1.match(/^-?\d+(\.\d+)?$/)) {
    // Both arguments are simple numbers.
    var up = parseFloat(argument0) <= parseFloat(argument1);
    code = 'for (' + variable0 + ' = ' + argument0 + '; ' +
        variable0 + (up ? ' <= ' : ' >= ') + argument1 + '; ' +
        variable0 + (up ? '++' : '--') + ') {\n' +
        branch0 + '}\n';
  } else {
    code = '';
    // Cache non-trivial values to variables to prevent repeated look-ups.
    var startVar = argument0;
    if (!argument0.match(/^\w+$/) && !argument0.match(/^-?\d+(\.\d+)?$/)) {
      var startVar = Blockly.Dart.variableDB_.getDistinctName(
          variable0 + '_start', Blockly.Variables.NAME_TYPE);
      code += 'var ' + startVar + ' = ' + argument0 + ';\n';
    }
    var endVar = argument1;
    if (!argument1.match(/^\w+$/) && !argument1.match(/^-?\d+(\.\d+)?$/)) {
      var endVar = Blockly.Dart.variableDB_.getDistinctName(
          variable0 + '_end', Blockly.Variables.NAME_TYPE);
      code += 'var ' + endVar + ' = ' + argument1 + ';\n';
    }
    code += 'for (' + variable0 + ' = ' + startVar + ';\n' +
        '    (' + startVar + ' <= ' + endVar + ') ? ' +
        variable0 + ' <= ' + endVar + ' : ' +
        variable0 + ' >= ' + endVar + ';\n' +
        '    ' + variable0 + ' += (' + startVar + ' <= ' + endVar + ') ? 1 : -1) {\n' +
        branch0 + '}\n';
  }
  return code;
};

Blockly.Dart.controls_forEach = function() {
  // For each loop.
  var variable0 = Blockly.Dart.variableDB_.getName(
      this.getTitleValue('VAR'), Blockly.Variables.NAME_TYPE);
  var argument0 = Blockly.Dart.valueToCode(this, 'LIST',
      Blockly.Dart.ORDER_ASSIGNMENT) || '[]';
  var branch0 = Blockly.Dart.statementToCode(this, 'DO');
  var code = 'for (var ' + variable0 + ' in  ' + argument0 + ') {\n' +
      branch0 + '}\n';
  return code;
};

Blockly.Dart.controls_flow_statements = function() {
  // Flow statements: continue, break.
  switch (this.getTitleValue('FLOW')) {
    case 'BREAK':
      return 'break;\n';
    case 'CONTINUE':
      return 'continue;\n';
  }
  throw 'Unknown flow statement.';
};
<|endoftext|>


<commit_before>/**
 * Visual Blocks Language
 *
 * Copyright 2012 Google Inc.
 * http://code.google.com/p/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Generating Python for list blocks.
 * @author fraser@google.com (Neil Fraser)
 */

Blockly.Python = Blockly.Generator.get('Python');

Blockly.Python.lists_create_empty = function() {
  // Create an empty list.
  return ['[]', Blockly.JavaScript.ORDER_ATOMIC];
};

Blockly.Python.lists_create_with = function() {
  // Create a list with any number of elements of any type.
  var code = new Array(this.itemCount_);
  for (var n = 0; n < this.itemCount_; n++) {
    code[n] = Blockly.Python.valueToCode(this, 'ADD' + n,
        Blockly.JavaScript.ORDER_NONE) || 'None';
  }
  code = '[' + code.join(', ') + ']';
  return [code, Blockly.JavaScript.ORDER_ATOMIC];
};

Blockly.Python.lists_repeat = function() {
  // Create a list with one element repeated.
  var argument0 = Blockly.Python.valueToCode(this, 'ITEM',
      Blockly.JavaScript.ORDER_NONE) || 'None';
  var argument1 = Blockly.Python.valueToCode(this, 'NUM',
      Blockly.JavaScript.ORDER_MULTIPLICATIVE) || '0';
  var code = '[' + argument0 + '] * ' + argument1;
  return [code, Blockly.JavaScript.ORDER_MULTIPLICATIVE];
};

Blockly.Python.lists_length = function() {
  // Testing the length of a list is the same as for a string.
  return Blockly.Python.text_length.call(this);
};

Blockly.Python.lists_isEmpty = function() {
  // Testing a list for being empty is the same as for a string.
  return Blockly.Python.text_isEmpty.call(this);
};

Blockly.Python.lists_indexOf = function() {
  // Searching a list for a value is the same as search for a substring.
  return Blockly.Python.text_indexOf.call(this);
};

Blockly.Python.lists_getIndex = function() {
  // Indexing into a list is the same as indexing into a string.
  return Blockly.Python.text_charAt.call(this);
};

Blockly.Python.lists_setIndex = function() {
  // Set element at index.
  var argument0 = Blockly.Python.valueToCode(this, 'AT',
      Blockly.Python.ORDER_NONE) || '1';
  var argument1 = Blockly.Python.valueToCode(this, 'LIST',
      Blockly.Python.ORDER_MEMBER) || '[]';
  var argument2 = Blockly.Python.valueToCode(this, 'TO',
      Blockly.Python.ORDER_NONE) || 'None';
  // Blockly uses one-based indicies.
  if (argument0.match(/^\d+$/)) {
    // If the index is a naked number, decrement it right now.
    // Except we don't allow negative index like in Python.
    argument0 = Math.max(0, parseInt(argument0, 10) - 1);
  } else {
    // If the index is dynamic, decrement it in code.
    argument0 += ' - 1';
  }
  var code = argument1 + '[' + argument0 + '] = ' + argument2 + '\n';
  return code;
};
<commit_msg>fix Issue 68, use Python generator order<commit_after>/**
 * Visual Blocks Language
 *
 * Copyright 2012 Google Inc.
 * http://code.google.com/p/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Generating Python for list blocks.
 * @author fraser@google.com (Neil Fraser)
 */

Blockly.Python = Blockly.Generator.get('Python');

Blockly.Python.lists_create_empty = function() {
  // Create an empty list.
  return ['[]', Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.lists_create_with = function() {
  // Create a list with any number of elements of any type.
  var code = new Array(this.itemCount_);
  for (var n = 0; n < this.itemCount_; n++) {
    code[n] = Blockly.Python.valueToCode(this, 'ADD' + n,
        Blockly.Python.ORDER_NONE) || 'None';
  }
  code = '[' + code.join(', ') + ']';
  return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python.lists_repeat = function() {
  // Create a list with one element repeated.
  var argument0 = Blockly.Python.valueToCode(this, 'ITEM',
      Blockly.Python.ORDER_NONE) || 'None';
  var argument1 = Blockly.Python.valueToCode(this, 'NUM',
      Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
  var code = '[' + argument0 + '] * ' + argument1;
  return [code, Blockly.Python.ORDER_MULTIPLICATIVE];
};

Blockly.Python.lists_length = function() {
  // Testing the length of a list is the same as for a string.
  return Blockly.Python.text_length.call(this);
};

Blockly.Python.lists_isEmpty = function() {
  // Testing a list for being empty is the same as for a string.
  return Blockly.Python.text_isEmpty.call(this);
};

Blockly.Python.lists_indexOf = function() {
  // Searching a list for a value is the same as search for a substring.
  return Blockly.Python.text_indexOf.call(this);
};

Blockly.Python.lists_getIndex = function() {
  // Indexing into a list is the same as indexing into a string.
  return Blockly.Python.text_charAt.call(this);
};

Blockly.Python.lists_setIndex = function() {
  // Set element at index.
  var argument0 = Blockly.Python.valueToCode(this, 'AT',
      Blockly.Python.ORDER_NONE) || '1';
  var argument1 = Blockly.Python.valueToCode(this, 'LIST',
      Blockly.Python.ORDER_MEMBER) || '[]';
  var argument2 = Blockly.Python.valueToCode(this, 'TO',
      Blockly.Python.ORDER_NONE) || 'None';
  // Blockly uses one-based indicies.
  if (argument0.match(/^\d+$/)) {
    // If the index is a naked number, decrement it right now.
    // Except we don't allow negative index like in Python.
    argument0 = Math.max(0, parseInt(argument0, 10) - 1);
  } else {
    // If the index is dynamic, decrement it in code.
    argument0 += ' - 1';
  }
  var code = argument1 + '[' + argument0 + '] = ' + argument2 + '\n';
  return code;
};
<|endoftext|>