<commit_before>var request = require('request');
var safeParse = require("safe-json-parse/callback")
var parseXMLString = require('xml2js').parseString;
var PlexTv = require('./PlexTv.js')
var PlexClient = require('./PlexClient.js')
var PlexConnection = require('./PlexConnection.js')
var PlexAuth = require('./PlexAuth.js')
module.exports = function PlexServer(){
    this.name;
    this.product;
    this.productVersion;
    this.platform;
    this.platformVersion;
    this.device;
    this.clientIdentifier;
    this.createdAt;
    this.lastSeenAt;
    this.provides;
    this.owned;
    this.httpsRequired;
    this.ownerId;
    this.home;
    this.accessToken
    this.sourceTitle;
    this.synced;
    this.relay;
    this.publicAddressMatches;
    this.presence;
    this.plexConnections;
    this.chosenConnection = null;

    //Functions
    this.hitApi = function(command,params,callback){
        var that = this
        var query = "";
        for (key in params) {
            query += encodeURIComponent(key)+'='+encodeURIComponent(params[key])+'&';
        }
        global.log.info('Hitting server ' + this.name + ' via ' + this.chosenConnection.uri)
        var _url = this.chosenConnection.uri + command + '?' + query
        var options = PlexAuth.getApiOptions(_url, this.accessToken, 15000);
        //global.log.info('Hitting server ' + this.name + ' with command ' + command)
        //global.log.info(options)
        request(options, function (error, response, body) {
            if (!error) {
                safeParse(body, function (err, json){
                    if (err){
                        return callback(null,that,connection)
                    }
                    return callback(json,that,connection)
                })
            } else {
                return callback(null,that,connection)
            }
        })
    }
    this.hitApiTestConnections = function(command,connection,callback){
        //For use with #findConnection
        if (connection == null){
            if (this.chosenConnection == null){
                global.log.info('You need to specify a connection!')
                return(callback(false,connection))
            }
        }
        var _url = connection.uri + command
        var options = PlexAuth.getApiOptions(_url, this.accessToken, 7500);
        request(options, function (error, response, body) {
            if (!error) {
                safeParse(body, function (err, json){
                    if (err){
                        return callback(null,connection)
                    }
                    return callback(json,connection)
                })
            } else {
                return callback(null,connection)
            }
        })
    }
    this.setChosenConnection = function(con) {
        console.log('Setting the used connection for ' + this.name + ' to ' + con.uri)
        this.chosenConnection = con
        return
    }
    this.findConnection = function(){
        //This function iterates through all available connections and
        // if any of them return a valid response we'll set that connection
        // as the chosen connection for future use.
        var that = this;
        for (var i in this.plexConnections){
            var connection = this.plexConnections[i]
            this.hitApiTestConnections('',connection,function(result,connectionUsed){
                //global.log.info('Connection attempt result below for ' + that.name)
                //global.log.info(connectionUsed)
                if (result == null || result == undefined) {
                    global.log.info('Connection failed: ' + connectionUsed.uri)
                    //global.log.info(result)
                    return
                }
                if (that.chosenConnection != null){
                    //Looks like we've already found a good connection
                    // lets disregard this connection
                    global.log.info('Already have a working connection for ' + that.name + ' which is ' + that.chosenConnection.uri)
                    return
                }
                if (result.MediaContainer != undefined || result._elementType != undefined){
                    global.log.info('Found the first working connection for ' + that.name + ' which is ' + connectionUsed.uri)
                    that.setChosenConnection(connectionUsed)
                    return
                }

                //global.log.info('Unsure of what this result is for connection to PMS. Probably failed. Server: ' + that.name)
                //global.log.info(result)
                return
            })
        }
    }

    //Functions for dealing with media
    this.search = function(searchTerm,callback){
        //This function hits the PMS using the /search endpoint and returns what the server returns if valid
        var that = this
        this.hitApi('/search',{'query':searchTerm},function(result){
            validResults = []
            if (result){
                for (var i in result._children){
                    var res = result._children[i]
                    if (res._elementType == 'Directory' || res._elementType == 'Media' || res._elementType == 'Video'){
                        validResults.push(res)
                    }
                }
                return callback(validResults,that)
            }
            return callback(null,that)
        })
    }

    this.getMediaByRatingKey = function(ratingKey,callback){
        //This function hits the PMS and returns the item at the ratingKey
        this.hitApi('/library/metadata/'+ratingKey,{},function(result,that){
            validResults = []
            global.log.info('Response back from metadata request')
            //global.log.info(result)
            if (result != null){
                if (result._children) {
                    // Old Server version compatibility
                    for (var i in result._children){
                        var res = result._children[i]
                        if (res._elementType == 'Directory' || res._elementType == 'Media' || res._elementType == 'Video'){
                            return callback(res,that)
                        }
                    }
                } else {
                    // New Server compatibility
                    return callback(result.MediaContainer.Metadata[0],that)
                }
                global.log.info('Didnt find a compatible PMS Metadata object. Result from the server is below')
                global.log.info(result)
                return callback(null,that)
            }
            global.log.info('Didnt find a compatible PMS Metadata object because result == null. Result from the server is below')
            global.log.info(result)
            return callback(null,that)
        })
    }
};<commit_msg>fix missing http method<commit_after>var request = require('request');
var safeParse = require("safe-json-parse/callback")
var parseXMLString = require('xml2js').parseString;
var PlexTv = require('./PlexTv.js')
var PlexClient = require('./PlexClient.js')
var PlexConnection = require('./PlexConnection.js')
var PlexAuth = require('./PlexAuth.js')
module.exports = function PlexServer(){
    this.name;
    this.product;
    this.productVersion;
    this.platform;
    this.platformVersion;
    this.device;
    this.clientIdentifier;
    this.createdAt;
    this.lastSeenAt;
    this.provides;
    this.owned;
    this.httpsRequired;
    this.ownerId;
    this.home;
    this.accessToken
    this.sourceTitle;
    this.synced;
    this.relay;
    this.publicAddressMatches;
    this.presence;
    this.plexConnections;
    this.chosenConnection = null;

    //Functions
    this.hitApi = function(command,params,callback){
        var that = this
        var query = "";
        for (key in params) {
            query += encodeURIComponent(key)+'='+encodeURIComponent(params[key])+'&';
        }
        global.log.info('Hitting server ' + this.name + ' via ' + this.chosenConnection.uri)
        var _url = this.chosenConnection.uri + command + '?' + query
        var options = PlexAuth.getApiOptions(_url, this.accessToken, 15000, 'GET');
        //global.log.info('Hitting server ' + this.name + ' with command ' + command)
        //global.log.info(options)
        request(options, function (error, response, body) {
            if (!error) {
                safeParse(body, function (err, json){
                    if (err){
                        return callback(null,that,connection)
                    }
                    return callback(json,that,connection)
                })
            } else {
                return callback(null,that,connection)
            }
        })
    }
    this.hitApiTestConnections = function(command,connection,callback){
        //For use with #findConnection
        if (connection == null){
            if (this.chosenConnection == null){
                global.log.info('You need to specify a connection!')
                return(callback(false,connection))
            }
        }
        var _url = connection.uri + command
        var options = PlexAuth.getApiOptions(_url, this.accessToken, 7500, 'GET');
        request(options, function (error, response, body) {
            if (!error) {
                safeParse(body, function (err, json){
                    if (err){
                        return callback(null,connection)
                    }
                    return callback(json,connection)
                })
            } else {
                return callback(null,connection)
            }
        })
    }
    this.setChosenConnection = function(con) {
        console.log('Setting the used connection for ' + this.name + ' to ' + con.uri)
        this.chosenConnection = con
        return
    }
    this.findConnection = function(){
        //This function iterates through all available connections and
        // if any of them return a valid response we'll set that connection
        // as the chosen connection for future use.
        var that = this;
        for (var i in this.plexConnections){
            var connection = this.plexConnections[i]
            this.hitApiTestConnections('',connection,function(result,connectionUsed){
                //global.log.info('Connection attempt result below for ' + that.name)
                //global.log.info(connectionUsed)
                if (result == null || result == undefined) {
                    global.log.info('Connection failed: ' + connectionUsed.uri)
                    //global.log.info(result)
                    return
                }
                if (that.chosenConnection != null){
                    //Looks like we've already found a good connection
                    // lets disregard this connection
                    global.log.info('Already have a working connection for ' + that.name + ' which is ' + that.chosenConnection.uri)
                    return
                }
                if (result.MediaContainer != undefined || result._elementType != undefined){
                    global.log.info('Found the first working connection for ' + that.name + ' which is ' + connectionUsed.uri)
                    that.setChosenConnection(connectionUsed)
                    return
                }

                //global.log.info('Unsure of what this result is for connection to PMS. Probably failed. Server: ' + that.name)
                //global.log.info(result)
                return
            })
        }
    }

    //Functions for dealing with media
    this.search = function(searchTerm,callback){
        //This function hits the PMS using the /search endpoint and returns what the server returns if valid
        var that = this
        this.hitApi('/search',{'query':searchTerm},function(result){
            validResults = []
            if (result){
                for (var i in result._children){
                    var res = result._children[i]
                    if (res._elementType == 'Directory' || res._elementType == 'Media' || res._elementType == 'Video'){
                        validResults.push(res)
                    }
                }
                return callback(validResults,that)
            }
            return callback(null,that)
        })
    }

    this.getMediaByRatingKey = function(ratingKey,callback){
        //This function hits the PMS and returns the item at the ratingKey
        this.hitApi('/library/metadata/'+ratingKey,{},function(result,that){
            validResults = []
            global.log.info('Response back from metadata request')
            //global.log.info(result)
            if (result != null){
                if (result._children) {
                    // Old Server version compatibility
                    for (var i in result._children){
                        var res = result._children[i]
                        if (res._elementType == 'Directory' || res._elementType == 'Media' || res._elementType == 'Video'){
                            return callback(res,that)
                        }
                    }
                } else {
                    // New Server compatibility
                    return callback(result.MediaContainer.Metadata[0],that)
                }
                global.log.info('Didnt find a compatible PMS Metadata object. Result from the server is below')
                global.log.info(result)
                return callback(null,that)
            }
            global.log.info('Didnt find a compatible PMS Metadata object because result == null. Result from the server is below')
            global.log.info(result)
            return callback(null,that)
        })
    }
};<|endoftext|>


<commit_before>TD.factory('EditSession', function() {
  return ace.require("ace/edit_session").EditSession;
});

// TODO(vojta): lazy load handlers
TD.factory('VimHandler', function() {
  return ace.require("ace/keyboard/vim").handler;
});

TD.factory('EmacsHandler', function() {
  return ace.require("ace/keyboard/emacs").handler;
});

TD.factory('ace', function() {
  return ace.edit('editor');
});

TD.factory('AceRange', function() {
  return ace.require('ace/range').Range;
});

TD.factory('FilterFolding', function(AceRange) {
  return function(regexp) {
    var cache = [];

    this.getFoldWidget = function(session, foldStyle, row) {
      var previousMatch = cache[row - 1];
      var line = session.getLine(row);
      var currentMatch = cache[row] = regexp.test(line);

      if (row === 0) {
        return currentMatch ? '' : 'start';
      } else {
        if (!previousMatch) {
          return '';
        } else {
          return currentMatch ? '' : 'start';
        }
      }
    };

    this.getFoldWidgetRange = function(session, foldStyle, row) {
      var start = {row: row, column: 0};
      var end = {};

      while (!cache[row]) {
        if (typeof cache[row] === 'undefined') {
          if (row >= session.getLength()) {
            break;
          }
          this.getFoldWidget(session, foldStyle, row);
          if (cache[row]) {
            break;
          }
        }
        row++;
      }

      end.row = row - 1;
      end.column = session.getLine(end.row).length;

      return AceRange.fromPoints(start, end);
    };
  };
});

TD.factory('editor', function(EditSession, FilterFolding, settings, ace) {

  var updateSoftWrapSettings = function(wrap, session) {
    switch (wrap) {
      case -1:
        session.setUseWrapMode(false);
        ace.setShowPrintMargin(false);
        break;
      case 0:
        session.setUseWrapMode(true);
        session.setWrapLimitRange(null, null);
        ace.setShowPrintMargin(false);
        break;
      default:
        session.setUseWrapMode(true);
        session.setWrapLimitRange(wrap, wrap);
        ace.setPrintMarginColumn(wrap);
        ace.setShowPrintMargin(true);
    }
  };

  var updateSoftTabs = function(tabs, session) {
    if (tabs === -1) {
      session.setUseSoftTabs(false);
      session.setTabSize(4);
    } else {
      session.setUseSoftTabs(true);
      session.setTabSize(tabs);
    }
  };

  // listen on settings changes
  settings.on('theme', function(theme) {
    ace.setTheme(theme.id);
  });

  settings.on('keyMode', function(mode) {
    ace.setKeyboardHandler(mode.handler);
  });

  settings.on('softTabs', function(tabs) {
    updateSoftTabs(tabs, ace.getSession());
  });

  settings.on('softWrap', function(wrap) {
    updateSoftWrapSettings(wrap, ace.getSession());
  });

  var isFiltered = false;

  return {
    focus: function() {
      setTimeout(function() {
        ace.focus();
      }, 0);
    },

    setSession: function(session) {
      session.setFoldStyle('markbegin');

      // apply current settings
      updateSoftTabs(settings.softTabs, session);
      updateSoftWrapSettings(settings.softWrap, session);

      ace.setSession(session);
      ace.setReadOnly(false);
    },

    clearSession: function() {
      ace.setSession(new EditSession(''));
      ace.setReadOnly(true);
    },

    goToLine: function(lineNumber) {
      ace.gotoLine(lineNumber);
    },

    filter: function(regexp) {
      var session = ace.getSession();

      session.unfold();
      session.$setFolding(new FilterFolding(regexp));
      session.foldAll();
      isFiltered = true;
    },

    clearFilter: function() {
      if (!isFiltered) {
        return;
      }

      var session = ace.getSession();

      session.unfold();
      session.$setFolding(null);
      isFiltered = false;
    },

    goToFirstFiltered: function() {
      var session = ace.getSession();
      var firstFilteredRow = session.getNextFoldLine(0).end.row + 2;

      this.goToLine(firstFilteredRow);
    },

    _editor: ace
  };
});
<commit_msg>Go to first filtered line only if filtered<commit_after>TD.factory('EditSession', function() {
  return ace.require("ace/edit_session").EditSession;
});

// TODO(vojta): lazy load handlers
TD.factory('VimHandler', function() {
  return ace.require("ace/keyboard/vim").handler;
});

TD.factory('EmacsHandler', function() {
  return ace.require("ace/keyboard/emacs").handler;
});

TD.factory('ace', function() {
  return ace.edit('editor');
});

TD.factory('AceRange', function() {
  return ace.require('ace/range').Range;
});

TD.factory('FilterFolding', function(AceRange) {
  return function(regexp) {
    var cache = [];

    this.getFoldWidget = function(session, foldStyle, row) {
      var previousMatch = cache[row - 1];
      var line = session.getLine(row);
      var currentMatch = cache[row] = regexp.test(line);

      if (row === 0) {
        return currentMatch ? '' : 'start';
      } else {
        if (!previousMatch) {
          return '';
        } else {
          return currentMatch ? '' : 'start';
        }
      }
    };

    this.getFoldWidgetRange = function(session, foldStyle, row) {
      var start = {row: row, column: 0};
      var end = {};

      while (!cache[row]) {
        if (typeof cache[row] === 'undefined') {
          if (row >= session.getLength()) {
            break;
          }
          this.getFoldWidget(session, foldStyle, row);
          if (cache[row]) {
            break;
          }
        }
        row++;
      }

      end.row = row - 1;
      end.column = session.getLine(end.row).length;

      return AceRange.fromPoints(start, end);
    };
  };
});

TD.factory('editor', function(EditSession, FilterFolding, settings, ace) {

  var updateSoftWrapSettings = function(wrap, session) {
    switch (wrap) {
      case -1:
        session.setUseWrapMode(false);
        ace.setShowPrintMargin(false);
        break;
      case 0:
        session.setUseWrapMode(true);
        session.setWrapLimitRange(null, null);
        ace.setShowPrintMargin(false);
        break;
      default:
        session.setUseWrapMode(true);
        session.setWrapLimitRange(wrap, wrap);
        ace.setPrintMarginColumn(wrap);
        ace.setShowPrintMargin(true);
    }
  };

  var updateSoftTabs = function(tabs, session) {
    if (tabs === -1) {
      session.setUseSoftTabs(false);
      session.setTabSize(4);
    } else {
      session.setUseSoftTabs(true);
      session.setTabSize(tabs);
    }
  };

  // listen on settings changes
  settings.on('theme', function(theme) {
    ace.setTheme(theme.id);
  });

  settings.on('keyMode', function(mode) {
    ace.setKeyboardHandler(mode.handler);
  });

  settings.on('softTabs', function(tabs) {
    updateSoftTabs(tabs, ace.getSession());
  });

  settings.on('softWrap', function(wrap) {
    updateSoftWrapSettings(wrap, ace.getSession());
  });

  var isFiltered = false;

  return {
    focus: function() {
      setTimeout(function() {
        ace.focus();
      }, 0);
    },

    setSession: function(session) {
      session.setFoldStyle('markbegin');

      // apply current settings
      updateSoftTabs(settings.softTabs, session);
      updateSoftWrapSettings(settings.softWrap, session);

      ace.setSession(session);
      ace.setReadOnly(false);
    },

    clearSession: function() {
      ace.setSession(new EditSession(''));
      ace.setReadOnly(true);
    },

    goToLine: function(lineNumber) {
      ace.gotoLine(lineNumber);
    },

    filter: function(regexp) {
      var session = ace.getSession();

      session.unfold();
      session.$setFolding(new FilterFolding(regexp));
      session.foldAll();
      isFiltered = true;
    },

    clearFilter: function() {
      if (!isFiltered) {
        return;
      }

      var session = ace.getSession();

      session.unfold();
      session.$setFolding(null);
      isFiltered = false;
    },

    goToFirstFiltered: function() {
      var session = ace.getSession();
      var nextFoldLine = session.getNextFoldLine(0);

      if (nextFoldLine) {
        this.goToLine(nextFoldLine.end.row + 2);
      }
    },

    _editor: ace
  };
});
<|endoftext|>


<commit_before>/* backfeed.js */
var Backfeed = (function() {
  "use strict";
  //define classes to add/remove
  const errorStatusClass = 'glyphicon-remove';
  const errorGroupClass = 'has-error';
  const successStatusClass = 'glyphicon-ok';
  const successGroupClass = 'has-success';
  const formGroupClass = 'form-group';
  const formControlFeedbackClass = 'form-control-feedback';

  //attach change listeners to each input
  var watchInputs = function(inputList) {
    for (let formInput in inputList) {
      var currInput = inputList[formInput];
      _registerListener('keyup', currInput['input']);
    }
  };

  //Traverse upward through the DOM to the nearest form group
  var _getParentFormGroup = function(element) {
    while (! element.parentNode.classList.contains(formGroupClass)) {
      element = element.parentNode;
    }
    return element.parentNode;
  };

  //Traverse input siblings to find sibling form-control-feedback
  var _getSiblingFormControlFeedback = function(element) {
    var siblingsInclusive = element.parentNode.children;
    var sibling;
    for (var i = 0; i < siblingsInclusive.length; i ++) {
      sibling = siblingsInclusive[i];
      if (sibling !== element) {
        if (sibling.classList.contains(formControlFeedbackClass)) {
          return sibling;
        }
      }
    }
    return null;
  };

  //Add an event listener to a single form input
  var _registerListener = function(eventName, element) {
    element = document.getElementById(element);
    var status = _getSiblingFormControlFeedback(element);
    var group = _getParentFormGroup(element);
    element.addEventListener(eventName, function invoke(event) {
      _updateStatus(event, status, group);
    }, false);
  };

  //update the classes of the usernameInput field
  var _updateStatus = function(event, statusTag, groupTag) {
    var statusClasses = statusTag.classList;
    var groupClasses = groupTag.classList;
    if (event.target.checkValidity()) {
      //contents are valid
      if (!statusClasses.contains(successStatusClass)) {
        statusClasses.add(successStatusClass);
      }
      if (!groupClasses.contains(successGroupClass)) {
        groupClasses.add(successGroupClass);
      }
      if (statusClasses.contains(errorStatusClass)) {
        statusClasses.remove(errorStatusClass);
      }
      if (groupClasses.contains(errorGroupClass)) {
        groupClasses.remove(errorGroupClass);
      }
    } else {
      //contents are invalid
      if (statusClasses.contains(successStatusClass)) {
        statusClasses.remove(successStatusClass);
      }
      if (groupClasses.contains(successGroupClass)) {
        groupClasses.remove(successGroupClass);
      }
      if (!statusClasses.contains(errorStatusClass)) {
        statusClasses.add(errorStatusClass);
      }
      if (!groupClasses.contains(errorGroupClass)) {
        groupClasses.add(errorGroupClass);
      }
    }
  };

  return {
    watch: watchInputs
  }
})();
<commit_msg>Create logic to insert sibling status span if it doesn't exist.<commit_after>/* backfeed.js */
var Backfeed = (function() {
  "use strict";
  //define classes to add/remove
  const errorStatusClass = 'glyphicon-remove';
  const errorGroupClass = 'has-error';
  const successStatusClass = 'glyphicon-ok';
  const successGroupClass = 'has-success';
  const formGroupClass = 'form-group';
  const formControlFeedbackClass = 'form-control-feedback';
  const baseStatusClass = 'glyphicon';

  //attach change listeners to each input
  var watchInputs = function(inputList) {
    for (let formInput in inputList) {
      var currInput = inputList[formInput];
      _registerListener('keyup', currInput['input']);
    }
  };

  //Traverse upward through the DOM to the nearest form group
  var _getParentFormGroup = function(element) {
    while (! element.parentNode.classList.contains(formGroupClass)) {
      element = element.parentNode;
    }
    return element.parentNode;
  };

  //Traverse input siblings to find sibling form-control-feedback
  var _getSiblingFormControlFeedback = function(element) {
    var siblingsInclusive = element.parentNode.children;
    var sibling;
    for (var i = 0; i < siblingsInclusive.length; i ++) {
      sibling = siblingsInclusive[i];
      if (sibling !== element) {
        //if there is a proper sibling, return it
        if (sibling.classList.contains(formControlFeedbackClass)) {
          return sibling;
        }
      }
    }
    //if no sibling was found, create one and return it.
    var status = document.createElement('span');
    status.classList.add(baseStatusClass);
    status.classList.add(formControlFeedbackClass)
    element.parentNode.appendChild(status);
    return status;
  };

  //Add an event listener to a single form input
  var _registerListener = function(eventName, element) {
    element = document.getElementById(element);
    var status = _getSiblingFormControlFeedback(element);
    var group = _getParentFormGroup(element);
    element.addEventListener(eventName, function invoke(event) {
      _updateStatus(event, status, group);
    }, false);
  };

  //update the classes of the usernameInput field
  var _updateStatus = function(event, statusTag, groupTag) {
    var statusClasses = statusTag.classList;
    var groupClasses = groupTag.classList;
    if (event.target.checkValidity()) {
      //contents are valid
      if (!statusClasses.contains(successStatusClass)) {
        statusClasses.add(successStatusClass);
      }
      if (!groupClasses.contains(successGroupClass)) {
        groupClasses.add(successGroupClass);
      }
      if (statusClasses.contains(errorStatusClass)) {
        statusClasses.remove(errorStatusClass);
      }
      if (groupClasses.contains(errorGroupClass)) {
        groupClasses.remove(errorGroupClass);
      }
    } else {
      //contents are invalid
      if (statusClasses.contains(successStatusClass)) {
        statusClasses.remove(successStatusClass);
      }
      if (groupClasses.contains(successGroupClass)) {
        groupClasses.remove(successGroupClass);
      }
      if (!statusClasses.contains(errorStatusClass)) {
        statusClasses.add(errorStatusClass);
      }
      if (!groupClasses.contains(errorGroupClass)) {
        groupClasses.add(errorGroupClass);
      }
    }
  };

  return {
    watch: watchInputs
  }
})();
<|endoftext|>


<commit_before>(function () {
	var $D = Date;
	var __ = function (key) {
		var output, split, length, last;
		if (Date.CultureStrings[key]) {
			output = Date.CultureStrings[key];
		} else {
			output = key;
			split = key.split("_");
			length = split.length;
			if (length > 1 && key.charAt(0) !== "^") {
				// if the key isn't a regex and it has a split.
				last = split[(length - 1)].toLowerCase();
				if (last === "initial" || last === "abbr") {
					output = split[0];
				}
			}
		}
		if (key.charAt(0) === "^") {
			// it's a regex
			output = new RegExp(key);
		}
		return output;
	};

	var CultureInfo = function () {
		var buildTimeZones = function (data) {
			var zone;
			for (zone in data.abbreviatedTimeZoneStandard) {
				if (data.abbreviatedTimeZoneStandard.hasOwnProperty(zone)) {
					data.timezones.push({ name: zone, offset: data.abbreviatedTimeZoneStandard[zone]});
				}
			}
			for (zone in data.abbreviatedTimeZoneDST) {
				if (data.abbreviatedTimeZoneDST.hasOwnProperty(zone)) {
					data.timezones.push({ name: zone, offset: data.abbreviatedTimeZoneDST[zone]});
				}
			}
			return data.timezones;
		};
		var info =  {
			name: __("name"),
			englishName: __("englishName"),
			nativeName: __("nativeName"),
			/* Day Name Strings */
			dayNames: [
				__("Sunday"),
				__("Monday"),
				__("Tuesday"),
				__("Wednesday"),
				__("Thursday"),
				__("Friday"),
				__("Saturday")
			],
			abbreviatedDayNames: [
				__("Sun"),
				__("Mon"),
				__("Tue"),
				__("Wed"),
				__("Thu"),
				__("Fri"),
				__("Sat")
			],
			shortestDayNames: [
				__("Su"),
				__("Mo"),
				__("Tu"),
				__("We"),
				__("Th"),
				__("Fr"),
				__("Sa")
			],
			firstLetterDayNames: [
				__("S_Sun_Initial"),
				__("M_Mon_Initial"),
				__("T_Tues_Initial"),
				__("W_Wed_Initial"),
				__("T_Thu_Initial"),
				__("F_Fri_Initial"),
				__("S_Sat_Initial")
			],

			/* Month Name Strings */
			monthNames: [
				__("January"),
				__("February"),
				__("March"),
				__("April"),
				__("May"),
				__("June"),
				__("July"),
				__("August"),
				__("September"),
				__("October"),
				__("November"),
				__("December")
			],
			abbreviatedMonthNames: [
				__("Jan_Abbr"),
				__("Feb_Abbr"),
				__("Mar_Abbr"),
				__("Apr_Abbr"),
				__("May_Abbr"),
				__("Jun_Abbr"),
				__("Jul_Abbr"),
				__("Aug_Abbr"),
				__("Sep_Abbr"),
				__("Oct_Abbr"),
				__("Nov_Abbr"),
				__("Dec_Abbr")
			],
			/* AM/PM Designators */
			amDesignator: __("AM"),
			pmDesignator: __("PM"),
			firstDayOfWeek: __("firstDayOfWeek"),
			twoDigitYearMax: __("twoDigitYearMax"),
			dateElementOrder: __("mdy"),
			/* Standard date and time format patterns */
			formatPatterns: {
				shortDate: __("M/d/yyyy"),
				longDate: __("dddd, MMMM dd, yyyy"),
				shortTime: __("h:mm tt"),
				longTime: __("h:mm:ss tt"),
				fullDateTime: __("dddd, MMMM dd, yyyy h:mm:ss tt"),
				sortableDateTime: __("yyyy-MM-ddTHH:mm:ss"),
				universalSortableDateTime: __("yyyy-MM-dd HH:mm:ssZ"),
				rfc1123: __("ddd, dd MMM yyyy HH:mm:ss GMT"),
				monthDay: __("MMMM dd"),
				yearMonth: __("MMMM, yyyy")
			},
			regexPatterns: {
				jan: __("^jan(uary)?/i"),
				feb: __("^feb(ruary)?/i"),
				mar: __("^mar(ch)?/i"),
				apr: __("^apr(il)?/i"),
				may: __("^may/i"),
				jun: __("^jun(e)?/i"),
				jul: __("^jul(y)?/i"),
				aug: __("^aug(ust)?/i"),
				sep: __("^sep(t(ember)?)?/i"),
				oct: __("^oct(ober)?/i"),
				nov: __("^nov(ember)?/i"),
				dec: __("^dec(ember)?/i"),
				sun: __("^su(n(day)?)?/i"),
				mon: __("^mo(n(day)?)?/i"),
				tue: __("^tu(e(s(day)?)?)?/i"),
				wed: __("^we(d(nesday)?)?/i"),
				thu: __("^th(u(r(s(day)?)?)?)?/i"),
				fri: __("^fr(i(day)?)?/i"),
				sat: __("^sa(t(urday)?)?/i"),
				future: __("^next/i"),
				past: __("^last|past|prev(ious)?/i"),
				add: __("^(\\+|aft(er)?|from|hence)/i"),
				subtract: __("^(\\-|bef(ore)?|ago)/i"),
				yesterday: __("^yes(terday)?/i"),
				today: __("^t(od(ay)?)?/i"),
				tomorrow: __("^tom(orrow)?/i"),
				now: __("^n(ow)?/i"),
				millisecond: __("^ms|milli(second)?s?/i"),
				second: __("^sec(ond)?s?/i"),
				minute: __("^mn|min(ute)?s?/i"),
				hour: __("^h(our)?s?/i"),
				week: __("^w(eek)?s?/i"),
				month: __("^m(onth)?s?/i"),
				day: __("^d(ay)?s?/i"),
				year: __("^y(ear)?s?/i"),
				shortMeridian: __("^(a|p)/i"),
				longMeridian: __("^(a\\.?m?\\.?|p\\.?m?\\.?)/i"),
				timezone: __("^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)/i"),
				ordinalSuffix: __("^\\s*(st|nd|rd|th)/i"),
				timeContext: __("^\\s*(\\:|a(?!u|p)|p)/i")
			},
			timezones: [
				// { name: "UTC", offset: "-000"},
				// { name: "GMT", offset: "-000"},
				// { name: "EST", offset: "-0500"},
				// { name: "EDT", offset: "-0400"},
				// { name: "CST", offset: "-0600"},
				// { name: "CDT", offset: "-0500"},
				// { name: "MST", offset: "-0700"},
				// { name: "MDT", offset: "-0600"},
				// { name: "PST", offset: "-0800"},
				// { name: "PDT", offset: "-0700"}
			],
			abbreviatedTimeZoneDST: {},
			abbreviatedTimeZoneStandard: {}
		};

		info.abbreviatedTimeZoneDST[__("CHADT")] = "+1345";
		info.abbreviatedTimeZoneDST[__("NZDT")] = "+1300";
		info.abbreviatedTimeZoneDST[__("AEDT")] = "+1100";
		info.abbreviatedTimeZoneDST[__("ACDT")] = "+1030";
		info.abbreviatedTimeZoneDST[__("AZST")] = "+0500";
		info.abbreviatedTimeZoneDST[__("IRDT")] = "+0430";
		info.abbreviatedTimeZoneDST[__("EEST")] = "+0300";
		info.abbreviatedTimeZoneDST[__("CEST")] = "+0200";
		info.abbreviatedTimeZoneDST[__("BST")] = "+0100";
		info.abbreviatedTimeZoneDST[__("PMDT")] = "-0200";
		info.abbreviatedTimeZoneDST[__("ADT")] = "-0300";
		info.abbreviatedTimeZoneDST[__("NDT")] = "-0230";
		info.abbreviatedTimeZoneDST[__("EDT")] = "-0400";
		info.abbreviatedTimeZoneDST[__("CDT")] = "-0500";
		info.abbreviatedTimeZoneDST[__("MDT")] = "-0600";
		info.abbreviatedTimeZoneDST[__("PDT")] = "-0700";
		info.abbreviatedTimeZoneDST[__("AKDT")] = "-0800";
		info.abbreviatedTimeZoneDST[__("HADT")] = "-0900";

		info.abbreviatedTimeZoneStandard[__("LINT")] = "+1400";
		info.abbreviatedTimeZoneStandard[__("TOT")] = "+1300";
		info.abbreviatedTimeZoneStandard[__("CHAST")] = "+1245";
		info.abbreviatedTimeZoneStandard[__("NZST")] = "+1200";
		info.abbreviatedTimeZoneStandard[__("NFT")] = "+1130";
		info.abbreviatedTimeZoneStandard[__("SBT")] = "+1100";
		info.abbreviatedTimeZoneStandard[__("AEST")] = "+1000";
		info.abbreviatedTimeZoneStandard[__("ACST")] = "+0930";
		info.abbreviatedTimeZoneStandard[__("JST")] = "+0900";
		info.abbreviatedTimeZoneStandard[__("CWST")] = "+0845";
		info.abbreviatedTimeZoneStandard[__("CT")] = "+0800";
		info.abbreviatedTimeZoneStandard[__("ICT")] = "+0700";
		info.abbreviatedTimeZoneStandard[__("MMT")] = "+0630";
		info.abbreviatedTimeZoneStandard[__("BST")] = "+0600";
		info.abbreviatedTimeZoneStandard[__("NPT")] = "+0545";
		info.abbreviatedTimeZoneStandard[__("IST")] = "+0530";
		info.abbreviatedTimeZoneStandard[__("PKT")] = "+0500";
		info.abbreviatedTimeZoneStandard[__("AFT")] = "+0430";
		info.abbreviatedTimeZoneStandard[__("MSK")] = "+0400";
		info.abbreviatedTimeZoneStandard[__("IRST")] = "+0330";
		info.abbreviatedTimeZoneStandard[__("FET")] = "+0300";
		info.abbreviatedTimeZoneStandard[__("EET")] = "+0200";
		info.abbreviatedTimeZoneStandard[__("CET")] = "+0100";
		info.abbreviatedTimeZoneStandard[__("UTC")] = "+000";
		info.abbreviatedTimeZoneStandard[__("GMT")] = "+000";
		info.abbreviatedTimeZoneStandard[__("CVT")] = "-0100";
		info.abbreviatedTimeZoneStandard[__("GST")] = "-0200";
		info.abbreviatedTimeZoneStandard[__("BRT")] = "-0300";
		info.abbreviatedTimeZoneStandard[__("NST")] = "-0330";
		info.abbreviatedTimeZoneStandard[__("AST")] = "-0400";
		info.abbreviatedTimeZoneStandard[__("EST")] = "-0500";
		info.abbreviatedTimeZoneStandard[__("CST")] = "-0600";
		info.abbreviatedTimeZoneStandard[__("MST")] = "-0700";
		info.abbreviatedTimeZoneStandard[__("PST")] = "-0800";
		info.abbreviatedTimeZoneStandard[__("AKST")] = "-0900";
		info.abbreviatedTimeZoneStandard[__("MIT")] = "-0930";
		info.abbreviatedTimeZoneStandard[__("HST")] = "-1000";
		info.abbreviatedTimeZoneStandard[__("SST")] = "-1100";
		info.abbreviatedTimeZoneStandard[__("BIT")] = "-1200";

		buildTimeZones(info);

		return info;
	};

	$D.l18n = {
		__: function (key) {
			return __(key);
		},
		updateCultureInfo: function () {
			$D.CultureInfo = CultureInfo();
		},
	};
	$D.l18n.updateCultureInfo(); // run automatically
}());<commit_msg>fixing stray comma<commit_after>(function () {
	var $D = Date;
	var __ = function (key) {
		var output, split, length, last;
		if (Date.CultureStrings[key]) {
			output = Date.CultureStrings[key];
		} else {
			output = key;
			split = key.split("_");
			length = split.length;
			if (length > 1 && key.charAt(0) !== "^") {
				// if the key isn't a regex and it has a split.
				last = split[(length - 1)].toLowerCase();
				if (last === "initial" || last === "abbr") {
					output = split[0];
				}
			}
		}
		if (key.charAt(0) === "^") {
			// it's a regex
			output = new RegExp(key);
		}
		return output;
	};

	var CultureInfo = function () {
		var buildTimeZones = function (data) {
			var zone;
			for (zone in data.abbreviatedTimeZoneStandard) {
				if (data.abbreviatedTimeZoneStandard.hasOwnProperty(zone)) {
					data.timezones.push({ name: zone, offset: data.abbreviatedTimeZoneStandard[zone]});
				}
			}
			for (zone in data.abbreviatedTimeZoneDST) {
				if (data.abbreviatedTimeZoneDST.hasOwnProperty(zone)) {
					data.timezones.push({ name: zone, offset: data.abbreviatedTimeZoneDST[zone]});
				}
			}
			return data.timezones;
		};
		var info =  {
			name: __("name"),
			englishName: __("englishName"),
			nativeName: __("nativeName"),
			/* Day Name Strings */
			dayNames: [
				__("Sunday"),
				__("Monday"),
				__("Tuesday"),
				__("Wednesday"),
				__("Thursday"),
				__("Friday"),
				__("Saturday")
			],
			abbreviatedDayNames: [
				__("Sun"),
				__("Mon"),
				__("Tue"),
				__("Wed"),
				__("Thu"),
				__("Fri"),
				__("Sat")
			],
			shortestDayNames: [
				__("Su"),
				__("Mo"),
				__("Tu"),
				__("We"),
				__("Th"),
				__("Fr"),
				__("Sa")
			],
			firstLetterDayNames: [
				__("S_Sun_Initial"),
				__("M_Mon_Initial"),
				__("T_Tues_Initial"),
				__("W_Wed_Initial"),
				__("T_Thu_Initial"),
				__("F_Fri_Initial"),
				__("S_Sat_Initial")
			],

			/* Month Name Strings */
			monthNames: [
				__("January"),
				__("February"),
				__("March"),
				__("April"),
				__("May"),
				__("June"),
				__("July"),
				__("August"),
				__("September"),
				__("October"),
				__("November"),
				__("December")
			],
			abbreviatedMonthNames: [
				__("Jan_Abbr"),
				__("Feb_Abbr"),
				__("Mar_Abbr"),
				__("Apr_Abbr"),
				__("May_Abbr"),
				__("Jun_Abbr"),
				__("Jul_Abbr"),
				__("Aug_Abbr"),
				__("Sep_Abbr"),
				__("Oct_Abbr"),
				__("Nov_Abbr"),
				__("Dec_Abbr")
			],
			/* AM/PM Designators */
			amDesignator: __("AM"),
			pmDesignator: __("PM"),
			firstDayOfWeek: __("firstDayOfWeek"),
			twoDigitYearMax: __("twoDigitYearMax"),
			dateElementOrder: __("mdy"),
			/* Standard date and time format patterns */
			formatPatterns: {
				shortDate: __("M/d/yyyy"),
				longDate: __("dddd, MMMM dd, yyyy"),
				shortTime: __("h:mm tt"),
				longTime: __("h:mm:ss tt"),
				fullDateTime: __("dddd, MMMM dd, yyyy h:mm:ss tt"),
				sortableDateTime: __("yyyy-MM-ddTHH:mm:ss"),
				universalSortableDateTime: __("yyyy-MM-dd HH:mm:ssZ"),
				rfc1123: __("ddd, dd MMM yyyy HH:mm:ss GMT"),
				monthDay: __("MMMM dd"),
				yearMonth: __("MMMM, yyyy")
			},
			regexPatterns: {
				jan: __("^jan(uary)?/i"),
				feb: __("^feb(ruary)?/i"),
				mar: __("^mar(ch)?/i"),
				apr: __("^apr(il)?/i"),
				may: __("^may/i"),
				jun: __("^jun(e)?/i"),
				jul: __("^jul(y)?/i"),
				aug: __("^aug(ust)?/i"),
				sep: __("^sep(t(ember)?)?/i"),
				oct: __("^oct(ober)?/i"),
				nov: __("^nov(ember)?/i"),
				dec: __("^dec(ember)?/i"),
				sun: __("^su(n(day)?)?/i"),
				mon: __("^mo(n(day)?)?/i"),
				tue: __("^tu(e(s(day)?)?)?/i"),
				wed: __("^we(d(nesday)?)?/i"),
				thu: __("^th(u(r(s(day)?)?)?)?/i"),
				fri: __("^fr(i(day)?)?/i"),
				sat: __("^sa(t(urday)?)?/i"),
				future: __("^next/i"),
				past: __("^last|past|prev(ious)?/i"),
				add: __("^(\\+|aft(er)?|from|hence)/i"),
				subtract: __("^(\\-|bef(ore)?|ago)/i"),
				yesterday: __("^yes(terday)?/i"),
				today: __("^t(od(ay)?)?/i"),
				tomorrow: __("^tom(orrow)?/i"),
				now: __("^n(ow)?/i"),
				millisecond: __("^ms|milli(second)?s?/i"),
				second: __("^sec(ond)?s?/i"),
				minute: __("^mn|min(ute)?s?/i"),
				hour: __("^h(our)?s?/i"),
				week: __("^w(eek)?s?/i"),
				month: __("^m(onth)?s?/i"),
				day: __("^d(ay)?s?/i"),
				year: __("^y(ear)?s?/i"),
				shortMeridian: __("^(a|p)/i"),
				longMeridian: __("^(a\\.?m?\\.?|p\\.?m?\\.?)/i"),
				timezone: __("^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)/i"),
				ordinalSuffix: __("^\\s*(st|nd|rd|th)/i"),
				timeContext: __("^\\s*(\\:|a(?!u|p)|p)/i")
			},
			timezones: [
				// { name: "UTC", offset: "-000"},
				// { name: "GMT", offset: "-000"},
				// { name: "EST", offset: "-0500"},
				// { name: "EDT", offset: "-0400"},
				// { name: "CST", offset: "-0600"},
				// { name: "CDT", offset: "-0500"},
				// { name: "MST", offset: "-0700"},
				// { name: "MDT", offset: "-0600"},
				// { name: "PST", offset: "-0800"},
				// { name: "PDT", offset: "-0700"}
			],
			abbreviatedTimeZoneDST: {},
			abbreviatedTimeZoneStandard: {}
		};

		info.abbreviatedTimeZoneDST[__("CHADT")] = "+1345";
		info.abbreviatedTimeZoneDST[__("NZDT")] = "+1300";
		info.abbreviatedTimeZoneDST[__("AEDT")] = "+1100";
		info.abbreviatedTimeZoneDST[__("ACDT")] = "+1030";
		info.abbreviatedTimeZoneDST[__("AZST")] = "+0500";
		info.abbreviatedTimeZoneDST[__("IRDT")] = "+0430";
		info.abbreviatedTimeZoneDST[__("EEST")] = "+0300";
		info.abbreviatedTimeZoneDST[__("CEST")] = "+0200";
		info.abbreviatedTimeZoneDST[__("BST")] = "+0100";
		info.abbreviatedTimeZoneDST[__("PMDT")] = "-0200";
		info.abbreviatedTimeZoneDST[__("ADT")] = "-0300";
		info.abbreviatedTimeZoneDST[__("NDT")] = "-0230";
		info.abbreviatedTimeZoneDST[__("EDT")] = "-0400";
		info.abbreviatedTimeZoneDST[__("CDT")] = "-0500";
		info.abbreviatedTimeZoneDST[__("MDT")] = "-0600";
		info.abbreviatedTimeZoneDST[__("PDT")] = "-0700";
		info.abbreviatedTimeZoneDST[__("AKDT")] = "-0800";
		info.abbreviatedTimeZoneDST[__("HADT")] = "-0900";

		info.abbreviatedTimeZoneStandard[__("LINT")] = "+1400";
		info.abbreviatedTimeZoneStandard[__("TOT")] = "+1300";
		info.abbreviatedTimeZoneStandard[__("CHAST")] = "+1245";
		info.abbreviatedTimeZoneStandard[__("NZST")] = "+1200";
		info.abbreviatedTimeZoneStandard[__("NFT")] = "+1130";
		info.abbreviatedTimeZoneStandard[__("SBT")] = "+1100";
		info.abbreviatedTimeZoneStandard[__("AEST")] = "+1000";
		info.abbreviatedTimeZoneStandard[__("ACST")] = "+0930";
		info.abbreviatedTimeZoneStandard[__("JST")] = "+0900";
		info.abbreviatedTimeZoneStandard[__("CWST")] = "+0845";
		info.abbreviatedTimeZoneStandard[__("CT")] = "+0800";
		info.abbreviatedTimeZoneStandard[__("ICT")] = "+0700";
		info.abbreviatedTimeZoneStandard[__("MMT")] = "+0630";
		info.abbreviatedTimeZoneStandard[__("BST")] = "+0600";
		info.abbreviatedTimeZoneStandard[__("NPT")] = "+0545";
		info.abbreviatedTimeZoneStandard[__("IST")] = "+0530";
		info.abbreviatedTimeZoneStandard[__("PKT")] = "+0500";
		info.abbreviatedTimeZoneStandard[__("AFT")] = "+0430";
		info.abbreviatedTimeZoneStandard[__("MSK")] = "+0400";
		info.abbreviatedTimeZoneStandard[__("IRST")] = "+0330";
		info.abbreviatedTimeZoneStandard[__("FET")] = "+0300";
		info.abbreviatedTimeZoneStandard[__("EET")] = "+0200";
		info.abbreviatedTimeZoneStandard[__("CET")] = "+0100";
		info.abbreviatedTimeZoneStandard[__("UTC")] = "+000";
		info.abbreviatedTimeZoneStandard[__("GMT")] = "+000";
		info.abbreviatedTimeZoneStandard[__("CVT")] = "-0100";
		info.abbreviatedTimeZoneStandard[__("GST")] = "-0200";
		info.abbreviatedTimeZoneStandard[__("BRT")] = "-0300";
		info.abbreviatedTimeZoneStandard[__("NST")] = "-0330";
		info.abbreviatedTimeZoneStandard[__("AST")] = "-0400";
		info.abbreviatedTimeZoneStandard[__("EST")] = "-0500";
		info.abbreviatedTimeZoneStandard[__("CST")] = "-0600";
		info.abbreviatedTimeZoneStandard[__("MST")] = "-0700";
		info.abbreviatedTimeZoneStandard[__("PST")] = "-0800";
		info.abbreviatedTimeZoneStandard[__("AKST")] = "-0900";
		info.abbreviatedTimeZoneStandard[__("MIT")] = "-0930";
		info.abbreviatedTimeZoneStandard[__("HST")] = "-1000";
		info.abbreviatedTimeZoneStandard[__("SST")] = "-1100";
		info.abbreviatedTimeZoneStandard[__("BIT")] = "-1200";

		buildTimeZones(info);

		return info;
	};

	$D.l18n = {
		__: function (key) {
			return __(key);
		},
		updateCultureInfo: function () {
			$D.CultureInfo = CultureInfo();
		}
	};
	$D.l18n.updateCultureInfo(); // run automatically
}());<|endoftext|>


<commit_before>/* Defines the Cube object
   TODO
*/

var JUMP = 50;

function Cube() {
  this.c;
  this.faces;
  this.vertices;

  // X, Y, Z  = center
  this.createCube = function (x, y, z) {
    var a = new Vertex(x-JUMP, y+JUMP, z-JUMP);
    var b = new Vertex(x+JUMP, y+JUMP, z-JUMP);
    var c = new Vertex(x+JUMP, y-JUMP, z-JUMP);
    var d = new Vertex(x-JUMP, y-JUMP, z-JUMP);
    var e = new Vertex(x-JUMP, y+JUMP, z+JUMP);
    var f = new Vertex(x+JUMP, y+JUMP, z+JUMP);
    var g = new Vertex(x+JUMP, y-JUMP, z+JUMP);
    var h = new Vertex(x-JUMP, y-JUMP, z+JUMP);
    //só tem que confirmar se está na ordem certa e tb se é antihorário
    this.vertices = [a, b, c, d, e, f, g, h];
    this.faces = [[0,1,2,3],[1,5,6,2],[5,4,7,6],[4,0,3,7],[0,4,5,1],[3,2,6,7]];
  }

  this.updateColor = function(c) {
    this.c = c
  }

  this.cube2matrix = function () {
    var matrix = [];
    for (var i = 0; i < 6; i++) {
      aux = this.vertices[i].vertex2array();
      matrix.push(aux);
    }
    return matrix;
  }

  this.matrix2cube = function (matrix) {
    for (var i = 0; i < 6; i++) {
      this.vertices[i].array2vertex(matrix[i]);
    }
  }

  //Parameter: Face index.
  this.normal = function(i){
    a = this.vertices[this.faces[i][0]];
    b = this.vertices[this.faces[i][1]];
    c = this.vertices[this.faces[i][2]];
    var bc = [c.x - b.x, c.y - b.y, c.z - b.z];
    var ba = [a.x - b.x, a.y - b.y, a.z - b.z];
    var normal = [
      (bc[1] * ba[2]) - (ba[2] * ba[1]),
      (bc[2] * ba[0]) - (bc[0] * ba[2]),
      (bc[0] * ba[1]) - (bc[1] * ba[0])
    ];
    var m_normal = Math.sqrt(
      Math.pow(normal[0], 2) + Math.pow(normal[1], 2) + Math.pow(normal[2], 2)
    );
    var n_normal = [normal[0]/m_normal, normal[1]/m_normal, normal[2]/m_normal];
    return n_normal;
  }

}
<commit_msg>Removed useless comments.<commit_after>/* Defines the Cube object
   TODO
*/

var JUMP = 50;

function Cube() {
  this.c;
  this.faces;
  this.vertices;

  this.createCube = function (x, y, z) {
    var a = new Vertex(x-JUMP, y+JUMP, z-JUMP);
    var b = new Vertex(x+JUMP, y+JUMP, z-JUMP);
    var c = new Vertex(x+JUMP, y-JUMP, z-JUMP);
    var d = new Vertex(x-JUMP, y-JUMP, z-JUMP);
    var e = new Vertex(x-JUMP, y+JUMP, z+JUMP);
    var f = new Vertex(x+JUMP, y+JUMP, z+JUMP);
    var g = new Vertex(x+JUMP, y-JUMP, z+JUMP);
    var h = new Vertex(x-JUMP, y-JUMP, z+JUMP);
    this.vertices = [a, b, c, d, e, f, g, h];
    this.faces = [[0,1,2,3],[1,5,6,2],[5,4,7,6],[4,0,3,7],[0,4,5,1],[3,2,6,7]];
  }

  this.updateColor = function(c) {
    this.c = c
  }

  this.cube2matrix = function () {
    var matrix = [];
    for (var i = 0; i < 6; i++) {
      aux = this.vertices[i].vertex2array();
      matrix.push(aux);
    }
    return matrix;
  }

  this.matrix2cube = function (matrix) {
    for (var i = 0; i < 6; i++) {
      this.vertices[i].array2vertex(matrix[i]);
    }
  }

  //Parameter: Face index.
  this.normal = function(i){
    a = this.vertices[this.faces[i][0]];
    b = this.vertices[this.faces[i][1]];
    c = this.vertices[this.faces[i][2]];
    var bc = [c.x - b.x, c.y - b.y, c.z - b.z];
    var ba = [a.x - b.x, a.y - b.y, a.z - b.z];
    var normal = [
      (bc[1] * ba[2]) - (ba[2] * ba[1]),
      (bc[2] * ba[0]) - (bc[0] * ba[2]),
      (bc[0] * ba[1]) - (bc[1] * ba[0])
    ];
    var m_normal = Math.sqrt(
      Math.pow(normal[0], 2) + Math.pow(normal[1], 2) + Math.pow(normal[2], 2)
    );
    var n_normal = [normal[0]/m_normal, normal[1]/m_normal, normal[2]/m_normal];
    return n_normal;
  }

}
<|endoftext|>


<commit_before>'use strict';
// https://github.com/tc39/proposal-iterator-helpers
var $ = require('../internals/export');
var anInstance = require('../internals/an-instance');
var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
var has = require('../internals/has');
var wellKnownSymbol = require('../internals/well-known-symbol');
var AsyncIteratorPrototype = require('../internals/async-iterator-prototype');
var IS_PURE = require('../internals/is-pure');

var TO_STRING_TAG = wellKnownSymbol('toStringTag');

var AsyncIteratorConstructor = function AsyncIterator() {
  anInstance(this, AsyncIteratorConstructor);
};

AsyncIteratorConstructor.prototype = AsyncIteratorPrototype;

if (!has(AsyncIteratorPrototype, TO_STRING_TAG)) {
  createNonEnumerableProperty(AsyncIteratorPrototype, TO_STRING_TAG, 'AsyncIterator');
}

if (!has(AsyncIteratorPrototype, 'constructor') || AsyncIteratorPrototype.constructor === Object) {
  createNonEnumerableProperty(AsyncIteratorPrototype, 'constructor', AsyncIteratorConstructor);
}

$({ global: true, forced: IS_PURE }, {
  AsyncIterator: AsyncIteratorConstructor
});
<commit_msg>one more fix related to extension of `%AsyncIteratorPrototype%`<commit_after>'use strict';
// https://github.com/tc39/proposal-iterator-helpers
var $ = require('../internals/export');
var anInstance = require('../internals/an-instance');
var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
var has = require('../internals/has');
var wellKnownSymbol = require('../internals/well-known-symbol');
var AsyncIteratorPrototype = require('../internals/async-iterator-prototype');
var IS_PURE = require('../internals/is-pure');

var TO_STRING_TAG = wellKnownSymbol('toStringTag');

var AsyncIteratorConstructor = function AsyncIterator() {
  anInstance(this, AsyncIteratorConstructor);
};

AsyncIteratorConstructor.prototype = AsyncIteratorPrototype;

if (!has(AsyncIteratorPrototype, TO_STRING_TAG)) {
  createNonEnumerableProperty(AsyncIteratorPrototype, TO_STRING_TAG, 'AsyncIterator');
}

if (IS_PURE || !has(AsyncIteratorPrototype, 'constructor') || AsyncIteratorPrototype.constructor === Object) {
  createNonEnumerableProperty(AsyncIteratorPrototype, 'constructor', AsyncIteratorConstructor);
}

$({ global: true, forced: IS_PURE }, {
  AsyncIterator: AsyncIteratorConstructor
});
<|endoftext|>


<commit_before>{
  type: OPEN_MODAL,
}

{
  type: CLOSE_MODAL,
}

{
  type: UPDATE_DUCK_TEXT,
  newDuckText
}

const initialState = {
  duckText: '',
  isOpen: false,
}

export default function modal (state = initialState, action) {
  switch (action.type) {
    case OPEN_MODAL :
      return {
        ...state,
        isOpen: true,
      }
    case CLOSE_MODAL :
      return {
        duckText: '',
        isOpen: false,
      }
    case UPDATE_DUCK_TEXT :
      return {
        ...state,
        duckText: action.newDuckText,
      }
    default :
      return state
  }
}
<commit_msg>Convert modal actions to action creators<commit_after>function openModal () {
  return {
    type: OPEN_MODAL,
  }
}

function closeModal () {
  return {
    type: CLOSE_MODAL,
  }
}

function updateDuckText () {
  return {
    type: UPDATE_DUCK_TEXT,
    newDuckText
  }
}

const initialState = {
  duckText: '',
  isOpen: false,
}

export default function modal (state = initialState, action) {
  switch (action.type) {
    case OPEN_MODAL :
      return {
        ...state,
        isOpen: true,
      }
    case CLOSE_MODAL :
      return {
        duckText: '',
        isOpen: false,
      }
    case UPDATE_DUCK_TEXT :
      return {
        ...state,
        duckText: action.newDuckText,
      }
    default :
      return state
  }
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

var child_process = require('child_process'),
    fs = require('fs'),
    os = require('os'),
    path = require('path');

var urls = require('./benchmarks');
var fileNames = Object.keys(urls).sort();

function git() {
  var args = [].concat.apply([], [].slice.call(arguments, 0, -1));
  var callback = arguments[arguments.length - 1];
  var task = child_process.spawn('git', args, { stdio: [ 'ignore', 'pipe', 'ignore' ] });
  var output = '';
  task.stdout.setEncoding('utf8');
  task.stdout.on('data', function(data) {
    output += data;
  });
  task.on('exit', function(code) {
    callback(code, output);
  });
}

function readText(filePath, callback) {
  fs.readFile(filePath, { encoding: 'utf8' }, callback);
}

function loadModule() {
  try {
    require('./src/htmlparser');
    return require('./src/htmlminifier').minify;
  }
  catch (e) {
    require('./htmlparser');
    return require('./master').minify;
  }
}

function getOptions(fileName, options) {
  var result = {
    minifyURLs: {
      site: urls[fileName]
    }
  };
  for (var key in options) {
    result[key] = options[key];
  }
  return result;
}

function minify(hash, options) {
  var minify = loadModule();
  process.send('ready');
  var count = fileNames.length;
  fileNames.forEach(function(fileName) {
    readText(path.join('benchmarks/', fileName + '.html'), function(err, data) {
      if (err) {
        throw err;
      }
      else {
        try {
          var minified = minify(data, getOptions(fileName, options));
          if (minified) {
            process.send({ name: fileName, size: minified.length });
          }
          else {
            throw new Error('unexpected result: ' + minified);
          }
        }
        catch (e) {
          console.error('[' + fileName + ']', e.stack || e);
        }
        finally {
          if (!--count) {
            process.disconnect();
          }
        }
      }
    });
  });
}

function print(table) {
  var output = [];
  var row = fileNames.slice(0);
  row.unshift('hash', 'date');
  output.push(row.join(','));
  for (var hash in table) {
    var data = table[hash];
    row = [ hash, '"' + data.date + '"' ];
    for (var i = 0; i < fileNames.length; i++) {
      row.push(data[fileNames[i]]);
    }
    output.push(row.join(','));
  }
  fs.writeFile('backtest.csv', output.join('\n'), { encoding: 'utf8' }, function(err) {
    if (err) {
      throw err;
    }
  });
}

if (process.argv.length > 2) {
  var count = +process.argv[2];
  if (count) {
    git('log', '--date=iso', '--pretty=format:%h %cd', '-' + count, function(code, data) {
      var table = {};
      var commits = data.split(/\s*?\n/).map(function(line) {
        var index = line.indexOf(' ');
        var hash = line.substr(0, index);
        table[hash] = {
          date: line.substr(index + 1).replace('+', '').replace(/ 0000$/, '')
        };
        return hash;
      });
      var nThreads = os.cpus().length;
      var running = 0, ready = true;

      function fork() {
        if (commits.length && running < nThreads) {
          var hash = commits.shift();
          var task = child_process.fork('./backtest', { silent: true });
          var error = '';
          var id = setTimeout(function() {
            if (task.connected) {
              error += 'task timed out\n';
              task.kill();
            }
          }, 60000);
          task.on('message', function(data) {
            if (data === 'ready') {
              ready = true;
              fork();
            }
            else {
              table[hash][data.name] = data.size;
            }
          }).on('exit', function() {
            clearTimeout(id);
            if (error) {
              console.error(hash, '-', error);
            }
            if (!--running && !commits.length) {
              print(table);
            }
            else {
              fork();
            }
          });
          task.stderr.setEncoding('utf8');
          task.stderr.on('data', function(data) {
            error += data;
          });
          task.stdout.resume();
          task.send(hash);
          running++;
        }
      }

      fork();
    });
  }
  else {
    console.error('Invalid input:', process.argv[2]);
  }
}
else {
  process.on('message', function(hash) {
    var paths = ['src', 'benchmark.conf', 'sample-cli-config-file.conf'];
    git('reset', 'HEAD', '--', paths, function() {
      var conf = 'sample-cli-config-file.conf';

      function checkout() {
        var path = paths.shift();
        git('checkout', hash, '--', path, function(code) {
          if (code === 0 && path === 'benchmark.conf') {
            conf = path;
          }
          if (paths.length) {
            checkout();
          }
          else {
            readText(conf, function(err, data) {
              if (err) {
                throw err;
              }
              else {
                /* global JSON: true */
                minify(hash, JSON.parse(data));
              }
            });
          }
        });
      }

      checkout();
    });
  });
}
<commit_msg>implement progress bar output errors to file<commit_after>#!/usr/bin/env node

'use strict';

var child_process = require('child_process'),
    fs = require('fs'),
    os = require('os'),
    path = require('path'),
    Progress = require('progress');

var urls = require('./benchmarks');
var fileNames = Object.keys(urls).sort();

function git() {
  var args = [].concat.apply([], [].slice.call(arguments, 0, -1));
  var callback = arguments[arguments.length - 1];
  var task = child_process.spawn('git', args, { stdio: [ 'ignore', 'pipe', 'ignore' ] });
  var output = '';
  task.stdout.setEncoding('utf8');
  task.stdout.on('data', function(data) {
    output += data;
  });
  task.on('exit', function(code) {
    callback(code, output);
  });
}

function readText(filePath, callback) {
  fs.readFile(filePath, { encoding: 'utf8' }, callback);
}

function writeText(filePath, data) {
  fs.writeFile(filePath, data, { encoding: 'utf8' }, function (err) {
    if (err) {
      throw err;
    }
  });
}

function loadModule() {
  try {
    require('./src/htmlparser');
    return require('./src/htmlminifier').minify;
  }
  catch (e) {
    require('./htmlparser');
    return require('./master').minify;
  }
}

function getOptions(fileName, options) {
  var result = {
    minifyURLs: {
      site: urls[fileName]
    }
  };
  for (var key in options) {
    result[key] = options[key];
  }
  return result;
}

function minify(hash, options) {
  var minify = loadModule();
  process.send('ready');
  var count = fileNames.length;
  fileNames.forEach(function(fileName) {
    readText(path.join('benchmarks/', fileName + '.html'), function(err, data) {
      if (err) {
        throw err;
      }
      else {
        try {
          var minified = minify(data, getOptions(fileName, options));
          if (minified) {
            process.send({ name: fileName, size: minified.length });
          }
          else {
            throw new Error('unexpected result: ' + minified);
          }
        }
        catch (e) {
          console.error('[' + fileName + ']', e.stack || e);
        }
        finally {
          if (!--count) {
            process.disconnect();
          }
        }
      }
    });
  });
}

function print(table) {
  var output = [];
  var errors = [];
  var row = fileNames.slice(0);
  row.unshift('hash', 'date');
  output.push(row.join(','));
  for (var hash in table) {
    var data = table[hash];
    row = [ hash, '"' + data.date + '"' ];
    for (var i = 0; i < fileNames.length; i++) {
      row.push(data[fileNames[i]]);
    }
    output.push(row.join(','));
    if (data.error) {
      errors.push(hash + ' - ' + data.error);
    }
  }
  writeText('backtest.csv', output.join('\n'));
  writeText('backtest.log', errors.join('\n'));
}

if (process.argv.length > 2) {
  var count = +process.argv[2];
  if (count) {
    git('log', '--date=iso', '--pretty=format:%h %cd', '-' + count, function(code, data) {
      var table = {};
      var commits = data.split(/\s*?\n/).map(function(line) {
        var index = line.indexOf(' ');
        var hash = line.substr(0, index);
        table[hash] = {
          date: line.substr(index + 1).replace('+', '').replace(/ 0000$/, '')
        };
        return hash;
      });
      var nThreads = os.cpus().length;
      var running = 0, ready = true;
      var progress = new Progress('[:bar] :etas', {
        width: 50,
        total: commits.length
      });

      function fork() {
        if (commits.length && running < nThreads) {
          progress.tick(1);
          var hash = commits.shift();
          var task = child_process.fork('./backtest', { silent: true });
          var error = '';
          var id = setTimeout(function() {
            if (task.connected) {
              error += 'task timed out\n';
              task.kill();
            }
          }, 60000);
          task.on('message', function(data) {
            if (data === 'ready') {
              ready = true;
              fork();
            }
            else {
              table[hash][data.name] = data.size;
            }
          }).on('exit', function() {
            clearTimeout(id);
            if (error) {
              table[hash].error = error;
            }
            if (!--running && !commits.length) {
              print(table);
            }
            else {
              fork();
            }
          });
          task.stderr.setEncoding('utf8');
          task.stderr.on('data', function(data) {
            error += data;
          });
          task.stdout.resume();
          task.send(hash);
          running++;
        }
      }

      fork();
    });
  }
  else {
    console.error('Invalid input:', process.argv[2]);
  }
}
else {
  process.on('message', function(hash) {
    var paths = ['src', 'benchmark.conf', 'sample-cli-config-file.conf'];
    git('reset', 'HEAD', '--', paths, function() {
      var conf = 'sample-cli-config-file.conf';

      function checkout() {
        var path = paths.shift();
        git('checkout', hash, '--', path, function(code) {
          if (code === 0 && path === 'benchmark.conf') {
            conf = path;
          }
          if (paths.length) {
            checkout();
          }
          else {
            readText(conf, function(err, data) {
              if (err) {
                throw err;
              }
              else {
                /* global JSON: true */
                minify(hash, JSON.parse(data));
              }
            });
          }
        });
      }

      checkout();
    });
  });
}
<|endoftext|>


<commit_before>/**
 * Module Dependencies
 */

var _ = require('@sailshq/lodash');
var forgeStageTwoQuery = require('../utils/query/forge-stage-two-query');
var forgeStageThreeQuery = require('../utils/query/forge-stage-three-query');
var Deferred = require('../utils/query/deferred');

/**
 * createEach()
 *
 * Create a set of records in the database.
 *
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 *
 * Usage without deferred object:
 * ================================================
 *
 * @param {Array?} newRecords
 *
 * @param {Function?} done
 *        Callback function to run when query has either finished successfully or errored.
 *        (If unspecified, will return a Deferred object instead of actually doing anything.)
 *
 * @param {Ref?} meta
 *     For internal use.
 *
 * @returns {Ref?} Deferred object if no `done` callback was provided
 *
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 */

module.exports = function createEach( /* newRecords?, done?, meta? */ ) {

  // Build query w/ initial, universal keys.
  var query = {
    method: 'createEach',
    using: this.identity
  };

  //  ██╗   ██╗ █████╗ ██████╗ ██╗ █████╗ ██████╗ ██╗ ██████╗███████╗
  //  ██║   ██║██╔══██╗██╔══██╗██║██╔══██╗██╔══██╗██║██╔════╝██╔════╝
  //  ██║   ██║███████║██████╔╝██║███████║██║  ██║██║██║     ███████╗
  //  ╚██╗ ██╔╝██╔══██║██╔══██╗██║██╔══██║██║  ██║██║██║     ╚════██║
  //   ╚████╔╝ ██║  ██║██║  ██║██║██║  ██║██████╔╝██║╚██████╗███████║
  //    ╚═══╝  ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝╚═╝  ╚═╝╚═════╝ ╚═╝ ╚═════╝╚══════╝
  //

  // The `done` callback, if one was provided.
  var done;

  // Handle the various supported usage possibilities
  // (locate the `done` callback)
  //
  // > Note that we define `args` so that we can insulate access
  // > to the arguments provided to this function.
  var args = arguments;
  (function _handleVariadicUsage(){

    // The metadata container, if one was provided.
    var _meta;

    // Handle first argument:
    //
    // • createEach(newRecords, ...)
    query.newRecords = args[0];

    // • createEach(..., done, _meta)
    done = args[1];
    _meta = args[2];

    // Fold in `_meta`, if relevant.
    if (_meta) {
      query.meta = _meta;
    } // >-

  })();

  //  ██████╗ ███████╗███████╗███████╗██████╗
  //  ██╔══██╗██╔════╝██╔════╝██╔════╝██╔══██╗
  //  ██║  ██║█████╗  █████╗  █████╗  ██████╔╝
  //  ██║  ██║██╔══╝  ██╔══╝  ██╔══╝  ██╔══██╗
  //  ██████╔╝███████╗██║     ███████╗██║  ██║
  //  ╚═════╝ ╚══════╝╚═╝     ╚══════╝╚═╝  ╚═╝
  //
  //   ██╗███╗   ███╗ █████╗ ██╗   ██╗██████╗ ███████╗██╗
  //  ██╔╝████╗ ████║██╔══██╗╚██╗ ██╔╝██╔══██╗██╔════╝╚██╗
  //  ██║ ██╔████╔██║███████║ ╚████╔╝ ██████╔╝█████╗   ██║
  //  ██║ ██║╚██╔╝██║██╔══██║  ╚██╔╝  ██╔══██╗██╔══╝   ██║
  //  ╚██╗██║ ╚═╝ ██║██║  ██║   ██║   ██████╔╝███████╗██╔╝
  //   ╚═╝╚═╝     ╚═╝╚═╝  ╚═╝   ╚═╝   ╚═════╝ ╚══════╝╚═╝
  //
  //  ┌┐ ┬ ┬┬┬  ┌┬┐   ┬   ┬─┐┌─┐┌┬┐┬ ┬┬─┐┌┐┌  ┌┐┌┌─┐┬ ┬  ┌┬┐┌─┐┌─┐┌─┐┬─┐┬─┐┌─┐┌┬┐
  //  ├┴┐│ │││   ││  ┌┼─  ├┬┘├┤  │ │ │├┬┘│││  │││├┤ │││   ││├┤ ├┤ ├┤ ├┬┘├┬┘├┤  ││
  //  └─┘└─┘┴┴─┘─┴┘  └┘   ┴└─└─┘ ┴ └─┘┴└─┘└┘  ┘└┘└─┘└┴┘  ─┴┘└─┘└  └─┘┴└─┴└─└─┘─┴┘
  //  ┌─    ┬┌─┐  ┬─┐┌─┐┬  ┌─┐┬  ┬┌─┐┌┐┌┌┬┐    ─┐
  //  │───  │├┤   ├┬┘├┤ │  ├┤ └┐┌┘├─┤│││ │   ───│
  //  └─    ┴└    ┴└─└─┘┴─┘└─┘ └┘ ┴ ┴┘└┘ ┴     ─┘
  // If a callback function was not specified, then build a new `Deferred` and bail now.
  //
  // > This method will be called AGAIN automatically when the Deferred is executed.
  // > and next time, it'll have a callback.
  if (!done) {
    return new Deferred(this, createEach, query);
  } // --•

  // Otherwise, IWMIH, we know that a callback was specified.
  // So...
  //
  //  ███████╗██╗  ██╗███████╗ ██████╗██╗   ██╗████████╗███████╗
  //  ██╔════╝╚██╗██╔╝██╔════╝██╔════╝██║   ██║╚══██╔══╝██╔════╝
  //  █████╗   ╚███╔╝ █████╗  ██║     ██║   ██║   ██║   █████╗
  //  ██╔══╝   ██╔██╗ ██╔══╝  ██║     ██║   ██║   ██║   ██╔══╝
  //  ███████╗██╔╝ ██╗███████╗╚██████╗╚██████╔╝   ██║   ███████╗
  //  ╚══════╝╚═╝  ╚═╝╚══════╝ ╚═════╝ ╚═════╝    ╚═╝   ╚══════╝

  //  ╔═╗╔═╗╦═╗╔═╗╔═╗  ┌─┐┌┬┐┌─┐┌─┐┌─┐  ┌┬┐┬ ┬┌─┐  ┌─┐ ┬ ┬┌─┐┬─┐┬ ┬
  //  ╠╣ ║ ║╠╦╝║ ╦║╣   └─┐ │ ├─┤│ ┬├┤    │ ││││ │  │─┼┐│ │├┤ ├┬┘└┬┘
  //  ╚  ╚═╝╩╚═╚═╝╚═╝  └─┘ ┴ ┴ ┴└─┘└─┘   ┴ └┴┘└─┘  └─┘└└─┘└─┘┴└─ ┴
  //
  // Forge a stage 2 query (aka logical protostatement)
  try {
    forgeStageTwoQuery(query, this.waterline);
  } catch (e) {
    switch (e.code) {

      case 'E_INVALID_NEW_RECORDS':
      case 'E_INVALID_META':
        return done(e);
        // ^ when the standard usage error is good enough as-is, without any further customization

      default:
        return done(e);
        // ^ when an internal, miscellaneous, or unexpected error occurs
    }
  } // >-•

  //  ████████╗██╗███╗   ███╗███████╗███████╗████████╗ █████╗ ███╗   ███╗██████╗ ███████╗
  //  ╚══██╔══╝██║████╗ ████║██╔════╝██╔════╝╚══██╔══╝██╔══██╗████╗ ████║██╔══██╗██╔════╝
  //     ██║   ██║██╔████╔██║█████╗  ███████╗   ██║   ███████║██╔████╔██║██████╔╝███████╗
  //     ██║   ██║██║╚██╔╝██║██╔══╝  ╚════██║   ██║   ██╔══██║██║╚██╔╝██║██╔═══╝ ╚════██║
  //     ██║   ██║██║ ╚═╝ ██║███████╗███████║   ██║   ██║  ██║██║ ╚═╝ ██║██║     ███████║
  //     ╚═╝   ╚═╝╚═╝     ╚═╝╚══════╝╚══════╝   ╚═╝   ╚═╝  ╚═╝╚═╝     ╚═╝╚═╝     ╚══════╝
  //
  // Attach any generated timestamps to the records before they are turned into
  // stage three queries.

  // Generate the timestamps so that both createdAt and updatedAt have the
  // same initial value.
  var self = this;
  var numDate = Date.now();
  var strDate = new Date();

  _.each(query.newRecords, function(record) {
    //  ╔═╗╦═╗╔═╗╔═╗╔╦╗╔═╗╔╦╗  ╔═╗╔╦╗  ┌┬┐┬┌┬┐┌─┐┌─┐┌┬┐┌─┐┌┬┐┌─┐
    //  ║  ╠╦╝║╣ ╠═╣ ║ ║╣  ║║  ╠═╣ ║    │ ││││├┤ └─┐ │ ├─┤│││├─┘
    //  ╚═╝╩╚═╚═╝╩ ╩ ╩ ╚═╝═╩╝  ╩ ╩ ╩    ┴ ┴┴ ┴└─┘└─┘ ┴ ┴ ┴┴ ┴┴
    _.each(self.attributes, function(val, name) {
      if (_.has(val, 'autoCreatedAt') && val.autoCreatedAt) {
        var attributeVal;

        // Check the type to determine which type of value to generate
        if (val.type === 'number') {
          attributeVal = numDate;
        } else {
          attributeVal = strDate;
        }

        if (!record[name]) {
          record[name] = attributeVal;
        }
      }
    });

    //  ╦ ╦╔═╗╔╦╗╔═╗╔╦╗╔═╗╔╦╗  ╔═╗╔╦╗  ┌┬┐┬┌┬┐┌─┐┌─┐┌┬┐┌─┐┌┬┐┌─┐
    //  ║ ║╠═╝ ║║╠═╣ ║ ║╣  ║║  ╠═╣ ║    │ ││││├┤ └─┐ │ ├─┤│││├─┘
    //  ╚═╝╩  ═╩╝╩ ╩ ╩ ╚═╝═╩╝  ╩ ╩ ╩    ┴ ┴┴ ┴└─┘└─┘ ┴ ┴ ┴┴ ┴┴
    _.each(self.attributes, function(val, name) {
      if (_.has(val, 'autoUpdatedAt') && val.autoUpdatedAt) {
        var attributeVal;

        // Check the type to determine which type of value to generate
        if (val.type === 'number') {
          attributeVal = numDate;
        } else {
          attributeVal = strDate;
        }

        if (!record[name]) {
          record[name] = attributeVal;
        }
      }
    });
  });

  //  ╔═╗╔═╗╦═╗╔═╗╔═╗  ┌─┐┌┬┐┌─┐┌─┐┌─┐  ┌┬┐┬ ┬┬─┐┌─┐┌─┐  ┌─┐ ┬ ┬┌─┐┬─┐┬ ┬
  //  ╠╣ ║ ║╠╦╝║ ╦║╣   └─┐ │ ├─┤│ ┬├┤    │ ├─┤├┬┘├┤ ├┤   │─┼┐│ │├┤ ├┬┘└┬┘
  //  ╚  ╚═╝╩╚═╚═╝╚═╝  └─┘ ┴ ┴ ┴└─┘└─┘   ┴ ┴ ┴┴└─└─┘└─┘  └─┘└└─┘└─┘┴└─ ┴
  var stageThreeQuery;
  try {
    stageThreeQuery = forgeStageThreeQuery({
      stageTwoQuery: query,
      identity: this.identity,
      transformer: this._transformer,
      originalModels: this.waterline.collections
    });
  } catch (e) {
    return done(e);
  }

  //  ┌┐┌┌─┐┬ ┬  ╔═╗╔═╗╔╦╗╦ ╦╔═╗╦  ╦ ╦ ╦  ┌┬┐┌─┐┬  ┬┌─  ┌┬┐┌─┐  ┌┬┐┬ ┬┌─┐  ┌┬┐┌┐ ┌─┐
  //  ││││ ││││  ╠═╣║   ║ ║ ║╠═╣║  ║ ╚╦╝   │ ├─┤│  ├┴┐   │ │ │   │ ├─┤├┤    ││├┴┐└─┐
  //  ┘└┘└─┘└┴┘  ╩ ╩╚═╝ ╩ ╚═╝╩ ╩╩═╝╩═╝╩    ┴ ┴ ┴┴─┘┴ ┴   ┴ └─┘   ┴ ┴ ┴└─┘  ─┴┘└─┘└─┘

  // Grab the adapter to perform the query on
  var connectionName = this.adapterDictionary.createEach;
  if (!connectionName) {
    return done(new Error('The adapter used in the ' + this.identity + ' model doesn\'t support the `createEach` method.)'));
  }

  // Grab the adapter
  var adapter = this.connections[connectionName].adapter;

  // Run the operation
  adapter.createEach(connectionName, stageThreeQuery, function(err, values) {
    if (err) {
      return done(err);
    }

    return done(undefined, values);
  }, query.meta);
};
<commit_msg>add place holders for create each lifecycle callbacks<commit_after>/**
 * Module Dependencies
 */

var _ = require('@sailshq/lodash');
var forgeStageTwoQuery = require('../utils/query/forge-stage-two-query');
var forgeStageThreeQuery = require('../utils/query/forge-stage-three-query');
var Deferred = require('../utils/query/deferred');

/**
 * createEach()
 *
 * Create a set of records in the database.
 *
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 *
 * Usage without deferred object:
 * ================================================
 *
 * @param {Array?} newRecords
 *
 * @param {Function?} done
 *        Callback function to run when query has either finished successfully or errored.
 *        (If unspecified, will return a Deferred object instead of actually doing anything.)
 *
 * @param {Ref?} meta
 *     For internal use.
 *
 * @returns {Ref?} Deferred object if no `done` callback was provided
 *
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 */

module.exports = function createEach( /* newRecords?, done?, meta? */ ) {

  // Build query w/ initial, universal keys.
  var query = {
    method: 'createEach',
    using: this.identity
  };

  //  ██╗   ██╗ █████╗ ██████╗ ██╗ █████╗ ██████╗ ██╗ ██████╗███████╗
  //  ██║   ██║██╔══██╗██╔══██╗██║██╔══██╗██╔══██╗██║██╔════╝██╔════╝
  //  ██║   ██║███████║██████╔╝██║███████║██║  ██║██║██║     ███████╗
  //  ╚██╗ ██╔╝██╔══██║██╔══██╗██║██╔══██║██║  ██║██║██║     ╚════██║
  //   ╚████╔╝ ██║  ██║██║  ██║██║██║  ██║██████╔╝██║╚██████╗███████║
  //    ╚═══╝  ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝╚═╝  ╚═╝╚═════╝ ╚═╝ ╚═════╝╚══════╝
  //

  // The `done` callback, if one was provided.
  var done;

  // Handle the various supported usage possibilities
  // (locate the `done` callback)
  //
  // > Note that we define `args` so that we can insulate access
  // > to the arguments provided to this function.
  var args = arguments;
  (function _handleVariadicUsage(){

    // The metadata container, if one was provided.
    var _meta;

    // Handle first argument:
    //
    // • createEach(newRecords, ...)
    query.newRecords = args[0];

    // • createEach(..., done, _meta)
    done = args[1];
    _meta = args[2];

    // Fold in `_meta`, if relevant.
    if (_meta) {
      query.meta = _meta;
    } // >-

  })();

  //  ██████╗ ███████╗███████╗███████╗██████╗
  //  ██╔══██╗██╔════╝██╔════╝██╔════╝██╔══██╗
  //  ██║  ██║█████╗  █████╗  █████╗  ██████╔╝
  //  ██║  ██║██╔══╝  ██╔══╝  ██╔══╝  ██╔══██╗
  //  ██████╔╝███████╗██║     ███████╗██║  ██║
  //  ╚═════╝ ╚══════╝╚═╝     ╚══════╝╚═╝  ╚═╝
  //
  //   ██╗███╗   ███╗ █████╗ ██╗   ██╗██████╗ ███████╗██╗
  //  ██╔╝████╗ ████║██╔══██╗╚██╗ ██╔╝██╔══██╗██╔════╝╚██╗
  //  ██║ ██╔████╔██║███████║ ╚████╔╝ ██████╔╝█████╗   ██║
  //  ██║ ██║╚██╔╝██║██╔══██║  ╚██╔╝  ██╔══██╗██╔══╝   ██║
  //  ╚██╗██║ ╚═╝ ██║██║  ██║   ██║   ██████╔╝███████╗██╔╝
  //   ╚═╝╚═╝     ╚═╝╚═╝  ╚═╝   ╚═╝   ╚═════╝ ╚══════╝╚═╝
  //
  //  ┌┐ ┬ ┬┬┬  ┌┬┐   ┬   ┬─┐┌─┐┌┬┐┬ ┬┬─┐┌┐┌  ┌┐┌┌─┐┬ ┬  ┌┬┐┌─┐┌─┐┌─┐┬─┐┬─┐┌─┐┌┬┐
  //  ├┴┐│ │││   ││  ┌┼─  ├┬┘├┤  │ │ │├┬┘│││  │││├┤ │││   ││├┤ ├┤ ├┤ ├┬┘├┬┘├┤  ││
  //  └─┘└─┘┴┴─┘─┴┘  └┘   ┴└─└─┘ ┴ └─┘┴└─┘└┘  ┘└┘└─┘└┴┘  ─┴┘└─┘└  └─┘┴└─┴└─└─┘─┴┘
  //  ┌─    ┬┌─┐  ┬─┐┌─┐┬  ┌─┐┬  ┬┌─┐┌┐┌┌┬┐    ─┐
  //  │───  │├┤   ├┬┘├┤ │  ├┤ └┐┌┘├─┤│││ │   ───│
  //  └─    ┴└    ┴└─└─┘┴─┘└─┘ └┘ ┴ ┴┘└┘ ┴     ─┘
  // If a callback function was not specified, then build a new `Deferred` and bail now.
  //
  // > This method will be called AGAIN automatically when the Deferred is executed.
  // > and next time, it'll have a callback.
  if (!done) {
    return new Deferred(this, createEach, query);
  } // --•

  // Otherwise, IWMIH, we know that a callback was specified.
  // So...
  //
  //  ███████╗██╗  ██╗███████╗ ██████╗██╗   ██╗████████╗███████╗
  //  ██╔════╝╚██╗██╔╝██╔════╝██╔════╝██║   ██║╚══██╔══╝██╔════╝
  //  █████╗   ╚███╔╝ █████╗  ██║     ██║   ██║   ██║   █████╗
  //  ██╔══╝   ██╔██╗ ██╔══╝  ██║     ██║   ██║   ██║   ██╔══╝
  //  ███████╗██╔╝ ██╗███████╗╚██████╗╚██████╔╝   ██║   ███████╗
  //  ╚══════╝╚═╝  ╚═╝╚══════╝ ╚═════╝ ╚═════╝    ╚═╝   ╚══════╝

  //  ╔═╗╔═╗╦═╗╔═╗╔═╗  ┌─┐┌┬┐┌─┐┌─┐┌─┐  ┌┬┐┬ ┬┌─┐  ┌─┐ ┬ ┬┌─┐┬─┐┬ ┬
  //  ╠╣ ║ ║╠╦╝║ ╦║╣   └─┐ │ ├─┤│ ┬├┤    │ ││││ │  │─┼┐│ │├┤ ├┬┘└┬┘
  //  ╚  ╚═╝╩╚═╚═╝╚═╝  └─┘ ┴ ┴ ┴└─┘└─┘   ┴ └┴┘└─┘  └─┘└└─┘└─┘┴└─ ┴
  //
  // Forge a stage 2 query (aka logical protostatement)
  try {
    forgeStageTwoQuery(query, this.waterline);
  } catch (e) {
    switch (e.code) {

      case 'E_INVALID_NEW_RECORDS':
      case 'E_INVALID_META':
        return done(e);
        // ^ when the standard usage error is good enough as-is, without any further customization

      default:
        return done(e);
        // ^ when an internal, miscellaneous, or unexpected error occurs
    }
  } // >-•

  //  ╦ ╦╔═╗╔╗╔╔╦╗╦  ╔═╗  ┬  ┬┌─┐┌─┐┌─┐┬ ┬┌─┐┬  ┌─┐  ┌─┐┌─┐┬  ┬  ┌┐ ┌─┐┌─┐┬┌─┌─┐
  //  ╠═╣╠═╣║║║ ║║║  ║╣   │  │├┤ ├┤ │  └┬┘│  │  ├┤   │  ├─┤│  │  ├┴┐├─┤│  ├┴┐└─┐
  //  ╩ ╩╩ ╩╝╚╝═╩╝╩═╝╚═╝  ┴─┘┴└  └─┘└─┘ ┴ └─┘┴─┘└─┘  └─┘┴ ┴┴─┘┴─┘└─┘┴ ┴└─┘┴ ┴└─┘
  // Determine what to do about running any lifecycle callbacks
  // TODO

  //  ████████╗██╗███╗   ███╗███████╗███████╗████████╗ █████╗ ███╗   ███╗██████╗ ███████╗
  //  ╚══██╔══╝██║████╗ ████║██╔════╝██╔════╝╚══██╔══╝██╔══██╗████╗ ████║██╔══██╗██╔════╝
  //     ██║   ██║██╔████╔██║█████╗  ███████╗   ██║   ███████║██╔████╔██║██████╔╝███████╗
  //     ██║   ██║██║╚██╔╝██║██╔══╝  ╚════██║   ██║   ██╔══██║██║╚██╔╝██║██╔═══╝ ╚════██║
  //     ██║   ██║██║ ╚═╝ ██║███████╗███████║   ██║   ██║  ██║██║ ╚═╝ ██║██║     ███████║
  //     ╚═╝   ╚═╝╚═╝     ╚═╝╚══════╝╚══════╝   ╚═╝   ╚═╝  ╚═╝╚═╝     ╚═╝╚═╝     ╚══════╝
  //
  // Attach any generated timestamps to the records before they are turned into
  // stage three queries.

  // Generate the timestamps so that both createdAt and updatedAt have the
  // same initial value.
  var self = this;
  var numDate = Date.now();
  var strDate = new Date();

  _.each(query.newRecords, function(record) {
    //  ╔═╗╦═╗╔═╗╔═╗╔╦╗╔═╗╔╦╗  ╔═╗╔╦╗  ┌┬┐┬┌┬┐┌─┐┌─┐┌┬┐┌─┐┌┬┐┌─┐
    //  ║  ╠╦╝║╣ ╠═╣ ║ ║╣  ║║  ╠═╣ ║    │ ││││├┤ └─┐ │ ├─┤│││├─┘
    //  ╚═╝╩╚═╚═╝╩ ╩ ╩ ╚═╝═╩╝  ╩ ╩ ╩    ┴ ┴┴ ┴└─┘└─┘ ┴ ┴ ┴┴ ┴┴
    _.each(self.attributes, function(val, name) {
      if (_.has(val, 'autoCreatedAt') && val.autoCreatedAt) {
        var attributeVal;

        // Check the type to determine which type of value to generate
        if (val.type === 'number') {
          attributeVal = numDate;
        } else {
          attributeVal = strDate;
        }

        if (!record[name]) {
          record[name] = attributeVal;
        }
      }
    });

    //  ╦ ╦╔═╗╔╦╗╔═╗╔╦╗╔═╗╔╦╗  ╔═╗╔╦╗  ┌┬┐┬┌┬┐┌─┐┌─┐┌┬┐┌─┐┌┬┐┌─┐
    //  ║ ║╠═╝ ║║╠═╣ ║ ║╣  ║║  ╠═╣ ║    │ ││││├┤ └─┐ │ ├─┤│││├─┘
    //  ╚═╝╩  ═╩╝╩ ╩ ╩ ╚═╝═╩╝  ╩ ╩ ╩    ┴ ┴┴ ┴└─┘└─┘ ┴ ┴ ┴┴ ┴┴
    _.each(self.attributes, function(val, name) {
      if (_.has(val, 'autoUpdatedAt') && val.autoUpdatedAt) {
        var attributeVal;

        // Check the type to determine which type of value to generate
        if (val.type === 'number') {
          attributeVal = numDate;
        } else {
          attributeVal = strDate;
        }

        if (!record[name]) {
          record[name] = attributeVal;
        }
      }
    });
  });

  //  ╔═╗╔═╗╦═╗╔═╗╔═╗  ┌─┐┌┬┐┌─┐┌─┐┌─┐  ┌┬┐┬ ┬┬─┐┌─┐┌─┐  ┌─┐ ┬ ┬┌─┐┬─┐┬ ┬
  //  ╠╣ ║ ║╠╦╝║ ╦║╣   └─┐ │ ├─┤│ ┬├┤    │ ├─┤├┬┘├┤ ├┤   │─┼┐│ │├┤ ├┬┘└┬┘
  //  ╚  ╚═╝╩╚═╚═╝╚═╝  └─┘ ┴ ┴ ┴└─┘└─┘   ┴ ┴ ┴┴└─└─┘└─┘  └─┘└└─┘└─┘┴└─ ┴
  var stageThreeQuery;
  try {
    stageThreeQuery = forgeStageThreeQuery({
      stageTwoQuery: query,
      identity: this.identity,
      transformer: this._transformer,
      originalModels: this.waterline.collections
    });
  } catch (e) {
    return done(e);
  }

  //  ┌┐┌┌─┐┬ ┬  ╔═╗╔═╗╔╦╗╦ ╦╔═╗╦  ╦ ╦ ╦  ┌┬┐┌─┐┬  ┬┌─  ┌┬┐┌─┐  ┌┬┐┬ ┬┌─┐  ┌┬┐┌┐ ┌─┐
  //  ││││ ││││  ╠═╣║   ║ ║ ║╠═╣║  ║ ╚╦╝   │ ├─┤│  ├┴┐   │ │ │   │ ├─┤├┤    ││├┴┐└─┐
  //  ┘└┘└─┘└┴┘  ╩ ╩╚═╝ ╩ ╚═╝╩ ╩╩═╝╩═╝╩    ┴ ┴ ┴┴─┘┴ ┴   ┴ └─┘   ┴ ┴ ┴└─┘  ─┴┘└─┘└─┘

  // Grab the adapter to perform the query on
  var connectionName = this.adapterDictionary.createEach;
  if (!connectionName) {
    return done(new Error('The adapter used in the ' + this.identity + ' model doesn\'t support the `createEach` method.)'));
  }

  // Grab the adapter
  var adapter = this.connections[connectionName].adapter;

  // Run the operation
  adapter.createEach(connectionName, stageThreeQuery, function(err, values) {
    if (err) {
      return done(err);
    }

    //  ╔═╗╔═╗╔╦╗╔═╗╦═╗  ┌─┐┬─┐┌─┐┌─┐┌┬┐┌─┐  ┌─┐┌─┐┬  ┬  ┌┐ ┌─┐┌─┐┬┌─
    //  ╠═╣╠╣  ║ ║╣ ╠╦╝  │  ├┬┘├┤ ├─┤ │ ├┤   │  ├─┤│  │  ├┴┐├─┤│  ├┴┐
    //  ╩ ╩╚   ╩ ╚═╝╩╚═  └─┘┴└─└─┘┴ ┴ ┴ └─┘  └─┘┴ ┴┴─┘┴─┘└─┘┴ ┴└─┘┴ ┴
    // TODO

    return done(undefined, values);
  }, query.meta);
};
<|endoftext|>