<commit_before>(function() {
  'use strict';

  var http = require('http');
  var https = require('https');
  var urlparse = require('url').parse;

  function EventTarget() {
    this._eventListeners = {};
  }

  (function(proto) {
    proto.addEventListener = function addEventListener(type, listener, useCapture) {
      this['on' + type] = listener;
    };

    proto.dispatchEvent = function dispatchEvent(event) {
      var _listener = this['on' + event.type];
      if (typeof(_listener) === 'function') {
        _listener.call(this, event);
      }
    };

    proto.removeEventListener = function removeEventListener(type, listener, useCapture) {
      // todo
    };
  })(EventTarget.prototype);

  function XMLHttpRequestEventTarget() {
    EventTarget.call(this);
  }
  XMLHttpRequestEventTarget.prototype = Object.create(EventTarget.prototype);

  (function(proto) {
    // Event handler
    (function(types) {
      types.forEach(function(type) {
        Object.defineProperty(proto, 'on' + type, {
          get: function() {
            var _listener = this._eventListeners[type];
            if (typeof(_listener) !== 'function') {
              return null;
            }
            return _listener;
          },
          set: function(listener) {
            if (typeof(listener) !== 'function') {
              delete this._eventListeners[type];
              return listener;
            }
            return this._eventListeners[type] = listener;
          },
          enumerble: false,
          configurable: false
        });
      });
    })([
      'loadstart',
      'progress',
      'abort',
      'error', // todo
      'load',
      'timeout', // todo
      'loadend'
    ]);
  })(XMLHttpRequestEventTarget.prototype);

  function XMLHttpRequestUpload() {
    if (!(this instanceof XMLHttpRequestUpload)) {
      throw new TypeError('DOM object constructor cannot be called as a function.');
    }
    XMLHttpRequestEventTarget.call(this);
  }
  XMLHttpRequestUpload.prototype = Object.create(XMLHttpRequestEventTarget.prototype);

  var XMLHttpRequestResponseType = [
    '',
    'arraybuffer',
    'blob',
    'document',
    'json',
    'text'
  ];

  function XMLHttpRequest() {
    if (!(this instanceof XMLHttpRequest)) {
      throw new TypeError('DOM object constructor cannot be called as a function.');
    }
    XMLHttpRequestEventTarget.call(this);

    // Private properties
    this._eventListeners = {};
    this._responseType = '';
    this._responseBuffer = null;
    this._async = true;
    this._client = null;
    this._options = {};
    this._requestHeaders = {};
    this._responseHeaders = {};

    // States
    this.readyState = XMLHttpRequest.UNSENT;

    // Request
    this.timeout = null; // todo
    this.withCredentials = false; // todo
    this.upload = new XMLHttpRequestUpload();

    // Response
    this.status = 0;
    this.statusText = '';
    this.responseType = ''; // todo
    this.response = ''; // todo
    this.responseText = '';
    this.responseXML = null; // not support
  }
  XMLHttpRequest.prototype = Object.create(XMLHttpRequestEventTarget.prototype);

  (function(proto) {
    // Event handler
    Object.defineProperty(proto, 'onreadystatechange', {
      get: function() {
        var _listener = this._eventListeners['readystatechange'];
        if (typeof(_listener) !== 'function') {
          return null;
        }
        return _listener;
      },
      set: function(listener) {
        if (typeof(listener) !== 'function') {
          this._eventListener['readystatechange'] = null;
          return listener;
        }
        return this._eventListeners['readystatechange'] = listener;
      },
      enumerble: false,
      configurable: false
    });

    // States
    (function(states) {
      var _objs = [XMLHttpRequest, proto];
      Object.keys(states).forEach(function(prop) {
        var _value = states[prop];
        _objs.forEach(function(_obj) {
          Object.defineProperty(_obj, prop, {
            value: _value,
            writable: false,
            enumerable: true,
            configurable: false
          });
        });
      });
    })({
      UNSENT: 0,
      OPENED: 1,
      HEADERS_RECEIVED: 2,
      LOADING: 3,
      DONE: 4
    });

    // Request
    proto.open = function open(method, url, async, user, password) {
      if (typeof(method) === 'undefined' || typeof(url) === 'undefined') {
        throw new TypeError('Not enought arguments');
      }
      this._options.method = method;
      (function(_parsedUrlObj) {
        this._options.protocol = (typeof(_parsedUrlObj.protocol) !== 'undefined') ? _parsedUrlObj.protocol : 'http:';
        this._options.agent = ((this._options.protocol === 'https:') ? https : http).globalAgent;
        this._options.host = (typeof(_parsedUrlObj.hostname) !== 'undefined') ? _parsedUrlObj.hostname : 'localhost';
        this._options.port = (typeof(_parsedUrlObj.port) !== 'undefined') ? _parsedUrlObj.port : ((this._options.protocol === 'https:') ? 443 : 80);
        this._options.path = (typeof(_parsedUrlObj.path) !== 'undefined') ? _parsedUrlObj.path : '/';
      }).call(this, urlparse(url));
      this._async = (typeof(async) !== 'undifined') ? async : true;
      if (typeof(user) === 'string' && typeof(password) === 'string') {
        this._options.auth = [user, password].join(':');
      }
      _readyStateChange.call(this, XMLHttpRequest.OPENED);
    };

    proto.setRequestHeader = function setRequestHeader(header, value) {
      if (this.readyState === XMLHttpRequest.UNSENT) {
        throw Error(''); // todo
      }
      this._requestHeaders[header] = value;
    };

    proto.send = function send(body) {
      if (this.readyState !== XMLHttpRequest.OPENED) {
        throw new Error(); // todo
      }
      this._client = new http.ClientRequest(this._options);
      this._client.on('response', _setDispatchProgressEvents(this.dispatchEvent.bind(this)));
      this._client.on('response', _receiveResponse.bind(this));
      this._client.on('socket', _setDispatchProgressEvents(this.upload.dispatchEvent.bind(this.upload)));
      Object.keys(this._requestHeaders).forEach(function(key) {
        this._client.setHeader(key, this._requestHeaders[key]);
      }, this);
      _readyStateChange.call(this, XMLHttpRequest.HEADERS_RECEIVED);
      if (typeof(body) !== 'undefined' && body !== null) {
        this._client.write(body);
      }
      this._client.end();
    };

    proto.abort = function abort() {
      if (!(this._client instanceof http.ClientRequest)) {
        return;
      }
      this._client.abort();
      this.dispatchEvent({type: 'abort'});
      this.upload.dispatchEvent({type: 'abort'});
    };

    // Response
    proto.getResponseHeader = function getResponseHeader(header) {
      if (this.readyState === XMLHttpRequest.UNSENT || this.readyState === XMLHttpRequest.OPENED) {
        throw new Error(''); // todo;
      }
      var value = this._responseHeaders[header.toLowerCase()];
      return (typeof(value) !== 'undefined') ? value : null;
    };

    proto.getAllResponseHeaders = function getAllResponseHeaders() {
      if (this.readyState === XMLHttpRequest.UNSENT || this.readyState === XMLHttpRequest.OPENED) {
        throw new Error(''); // todo
      }
      return Object.keys(this._responseHeaders).map(function(key) {
        return [key, this._responseHeaders[key]].join(': ');
      }, this).join('\n');
    };

    proto.overrideMimeType = function overrideMimeType(mime) {
      // todo
    };

    Object.defineProperties(proto, {
      'responseType': (function(responseTypes) {
        return {
          get: function() {
            var responseType = this._responseType;
            if (responseTypes.indexOf(responseType) < 0) {
              return '';
            }
            return this._responseType;
          },
          set: function(value) {
            var responseType = this._responseType;
            if (responseTypes.indexOf(responseType) < 0) {
              throw new Error(''); // todo
            }
            return this._responseType = value;
          },
          enumerable: true,
          configurable: false
        };
      })(XMLHttpRequestResponseType),

      'response': {
        get: function() {
          if (!(this._responseBuffer instanceof Buffer)) {
            return '';
          }
          switch (this.responseType) {
            case '':
              return this.responseText;
            case 'arraybuffer':
            case 'blob':
              return (new Uint8Array(this._responseBuffer)).buffer;
            case 'document':
              return null; // todo
            case 'json':
              return JSON.parse(this.responseText);
            case 'text':
              return this.responseText;
            default:
              return '';
          }
        },
        set: function(value) {
          return value;
        },
        enumerable: true,
        configurable: false
      },

      'responseText': {
        get: function() {
          if (!(this._responseBuffer instanceof Buffer)) {
            return '';
          }
          return this._responseBuffer.toString();
        },
        set: function(value) {
          return value;
        },
        enumerable: true,
        configurable: false
      },

      'responseXML': {
        value: null, // todo
        writable: false,
        enumerable: true,
        configurable: false
      }
    });

    // private methods
    var _readyStateChange = function _readyStateChange(readyState) {
      this.readyState = readyState;
      this.dispatchEvent({type: 'readystatechange'});
    };

    var _setDispatchProgressEvents = function _setDispatchProgressEvents(_dispatchEvent) {
      return function(stream) {
        _dispatchEvent({type: 'loadstart'});
        stream.on('data', function() {
          _dispatchEvent({type: 'progress'});
        });
        stream.on('end', function() {
          _dispatchEvent({type: 'load'});
          _dispatchEvent({type: 'loadend'});
        });
      };
    };

    var _receiveResponse = function _receiveResponse(response) {
      var contentLength = '0';
      var bufferLength = 0;
      var byteOffset = 0;
      this.status = response.statusCode;
      this.statusText = http.STATUS_CODES[this.status];
      this._responseHeaders = response.headers;
      if ((contentLength = response.headers['content-length'])) {
        bufferLength = +contentLength;
      }
      this._responseBuffer = new Buffer(bufferLength);
      _readyStateChange.call(this, XMLHttpRequest.LOADING);
      response.addListener('data', function(chunk) {
        var buffer;
        if (bufferLength === 0) {
          buffer = this._responseBuffer;
          this._responseBuffer = new Buffer(buffer.length + chunk.length);
          buffer.copy(this._responseBuffer);
        }
        chunk.copy(this._responseBuffer, byteOffset);
        byteOffset += chunk.length;
      }.bind(this));
      response.addListener('end', function() {
        _readyStateChange.call(this, XMLHttpRequest.DONE);
        this._client = null;
        this._options = {};
      }.bind(this));
    };
  })(XMLHttpRequest.prototype);

  function FormData() {
    if (!(this instanceof FormData)) {
      throw new TypeError('DOM object constructor cannot be called as a function.');
    }
  }

  (function(proto) {
    proto.append = function append(name, value, filename) {
      // todo
    };
  })(FormData.prototype);

  XMLHttpRequest.XMLHttpRequestUpload = XMLHttpRequestUpload;
  XMLHttpRequest.XMLHttpRequest = XMLHttpRequest;
  XMLHttpRequest.FormData = FormData;
  module.exports = XMLHttpRequest;
})();
<commit_msg>Forgetting to turn off<commit_after>(function() {
  'use strict';

  var http = require('http');
  var https = require('https');
  var urlparse = require('url').parse;

  function EventTarget() {
    this._eventListeners = {};
  }

  (function(proto) {
    proto.addEventListener = function addEventListener(type, listener, useCapture) {
      this['on' + type] = listener;
    };

    proto.dispatchEvent = function dispatchEvent(event) {
      var _listener = this['on' + event.type];
      if (typeof(_listener) === 'function') {
        _listener.call(this, event);
      }
    };

    proto.removeEventListener = function removeEventListener(type, listener, useCapture) {
      // todo
    };
  })(EventTarget.prototype);

  function XMLHttpRequestEventTarget() {
    EventTarget.call(this);
  }
  XMLHttpRequestEventTarget.prototype = Object.create(EventTarget.prototype);

  (function(proto) {
    // Event handler
    (function(types) {
      types.forEach(function(type) {
        Object.defineProperty(proto, 'on' + type, {
          get: function() {
            var _listener = this._eventListeners[type];
            if (typeof(_listener) !== 'function') {
              return null;
            }
            return _listener;
          },
          set: function(listener) {
            if (typeof(listener) !== 'function') {
              delete this._eventListeners[type];
              return listener;
            }
            return this._eventListeners[type] = listener;
          },
          enumerble: false,
          configurable: false
        });
      });
    })([
      'loadstart',
      'progress',
      'abort',
      'error', // todo
      'load',
      'timeout', // todo
      'loadend'
    ]);
  })(XMLHttpRequestEventTarget.prototype);

  function XMLHttpRequestUpload() {
    if (!(this instanceof XMLHttpRequestUpload)) {
      throw new TypeError('DOM object constructor cannot be called as a function.');
    }
    XMLHttpRequestEventTarget.call(this);
  }
  XMLHttpRequestUpload.prototype = Object.create(XMLHttpRequestEventTarget.prototype);

  var XMLHttpRequestResponseType = [
    '',
    'arraybuffer',
    'blob',
    'document',
    'json',
    'text'
  ];

  function XMLHttpRequest() {
    if (!(this instanceof XMLHttpRequest)) {
      throw new TypeError('DOM object constructor cannot be called as a function.');
    }
    XMLHttpRequestEventTarget.call(this);

    // Private properties
    this._eventListeners = {};
    this._responseType = '';
    this._responseBuffer = null;
    this._async = true;
    this._client = null;
    this._options = {};
    this._requestHeaders = {};
    this._responseHeaders = {};

    // States
    this.readyState = XMLHttpRequest.UNSENT;

    // Request
    this.timeout = null; // todo
    this.withCredentials = false; // todo
    this.upload = new XMLHttpRequestUpload();

    // Response
    this.status = 0;
    this.statusText = '';
  }
  XMLHttpRequest.prototype = Object.create(XMLHttpRequestEventTarget.prototype);

  (function(proto) {
    // Event handler
    Object.defineProperty(proto, 'onreadystatechange', {
      get: function() {
        var _listener = this._eventListeners['readystatechange'];
        if (typeof(_listener) !== 'function') {
          return null;
        }
        return _listener;
      },
      set: function(listener) {
        if (typeof(listener) !== 'function') {
          this._eventListener['readystatechange'] = null;
          return listener;
        }
        return this._eventListeners['readystatechange'] = listener;
      },
      enumerble: false,
      configurable: false
    });

    // States
    (function(states) {
      var _objs = [XMLHttpRequest, proto];
      Object.keys(states).forEach(function(prop) {
        var _value = states[prop];
        _objs.forEach(function(_obj) {
          Object.defineProperty(_obj, prop, {
            value: _value,
            writable: false,
            enumerable: true,
            configurable: false
          });
        });
      });
    })({
      UNSENT: 0,
      OPENED: 1,
      HEADERS_RECEIVED: 2,
      LOADING: 3,
      DONE: 4
    });

    // Request
    proto.open = function open(method, url, async, user, password) {
      if (typeof(method) === 'undefined' || typeof(url) === 'undefined') {
        throw new TypeError('Not enought arguments');
      }
      this._options.method = method;
      (function(_parsedUrlObj) {
        this._options.protocol = (typeof(_parsedUrlObj.protocol) !== 'undefined') ? _parsedUrlObj.protocol : 'http:';
        this._options.agent = ((this._options.protocol === 'https:') ? https : http).globalAgent;
        this._options.host = (typeof(_parsedUrlObj.hostname) !== 'undefined') ? _parsedUrlObj.hostname : 'localhost';
        this._options.port = (typeof(_parsedUrlObj.port) !== 'undefined') ? _parsedUrlObj.port : ((this._options.protocol === 'https:') ? 443 : 80);
        this._options.path = (typeof(_parsedUrlObj.path) !== 'undefined') ? _parsedUrlObj.path : '/';
      }).call(this, urlparse(url));
      this._async = (typeof(async) !== 'undifined') ? async : true;
      if (typeof(user) === 'string' && typeof(password) === 'string') {
        this._options.auth = [user, password].join(':');
      }
      _readyStateChange.call(this, XMLHttpRequest.OPENED);
    };

    proto.setRequestHeader = function setRequestHeader(header, value) {
      if (this.readyState === XMLHttpRequest.UNSENT) {
        throw Error(''); // todo
      }
      this._requestHeaders[header] = value;
    };

    proto.send = function send(body) {
      if (this.readyState !== XMLHttpRequest.OPENED) {
        throw new Error(); // todo
      }
      this._client = new http.ClientRequest(this._options);
      this._client.on('response', _setDispatchProgressEvents(this.dispatchEvent.bind(this)));
      this._client.on('response', _receiveResponse.bind(this));
      this._client.on('socket', _setDispatchProgressEvents(this.upload.dispatchEvent.bind(this.upload)));
      Object.keys(this._requestHeaders).forEach(function(key) {
        this._client.setHeader(key, this._requestHeaders[key]);
      }, this);
      _readyStateChange.call(this, XMLHttpRequest.HEADERS_RECEIVED);
      if (typeof(body) !== 'undefined' && body !== null) {
        this._client.write(body);
      }
      this._client.end();
    };

    proto.abort = function abort() {
      if (!(this._client instanceof http.ClientRequest)) {
        return;
      }
      this._client.abort();
      this.dispatchEvent({type: 'abort'});
      this.upload.dispatchEvent({type: 'abort'});
    };

    // Response
    proto.getResponseHeader = function getResponseHeader(header) {
      if (this.readyState === XMLHttpRequest.UNSENT || this.readyState === XMLHttpRequest.OPENED) {
        throw new Error(''); // todo;
      }
      var value = this._responseHeaders[header.toLowerCase()];
      return (typeof(value) !== 'undefined') ? value : null;
    };

    proto.getAllResponseHeaders = function getAllResponseHeaders() {
      if (this.readyState === XMLHttpRequest.UNSENT || this.readyState === XMLHttpRequest.OPENED) {
        throw new Error(''); // todo
      }
      return Object.keys(this._responseHeaders).map(function(key) {
        return [key, this._responseHeaders[key]].join(': ');
      }, this).join('\n');
    };

    proto.overrideMimeType = function overrideMimeType(mime) {
      // todo
    };

    Object.defineProperties(proto, {
      'responseType': (function(responseTypes) {
        return {
          get: function() {
            var responseType = this._responseType;
            if (responseTypes.indexOf(responseType) < 0) {
              return '';
            }
            return this._responseType;
          },
          set: function(value) {
            var responseType = this._responseType;
            if (responseTypes.indexOf(responseType) < 0) {
              throw new Error(''); // todo
            }
            return this._responseType = value;
          },
          enumerable: true,
          configurable: false
        };
      })(XMLHttpRequestResponseType),

      'response': {
        get: function() {
          if (!(this._responseBuffer instanceof Buffer)) {
            return '';
          }
          switch (this.responseType) {
            case '':
              return this.responseText;
            case 'arraybuffer':
            case 'blob':
              return (new Uint8Array(this._responseBuffer)).buffer;
            case 'document':
              return null; // todo
            case 'json':
              return JSON.parse(this.responseText);
            case 'text':
              return this.responseText;
            default:
              return '';
          }
        },
        set: function(value) {
          return value;
        },
        enumerable: true,
        configurable: false
      },

      'responseText': {
        get: function() {
          if (!(this._responseBuffer instanceof Buffer)) {
            return '';
          }
          return this._responseBuffer.toString();
        },
        set: function(value) {
          return value;
        },
        enumerable: true,
        configurable: false
      },

      'responseXML': {
        value: null, // todo
        writable: false,
        enumerable: true,
        configurable: false
      }
    });

    // private methods
    var _readyStateChange = function _readyStateChange(readyState) {
      this.readyState = readyState;
      this.dispatchEvent({type: 'readystatechange'});
    };

    var _setDispatchProgressEvents = function _setDispatchProgressEvents(_dispatchEvent) {
      return function(stream) {
        _dispatchEvent({type: 'loadstart'});
        stream.on('data', function() {
          _dispatchEvent({type: 'progress'});
        });
        stream.on('end', function() {
          _dispatchEvent({type: 'load'});
          _dispatchEvent({type: 'loadend'});
        });
      };
    };

    var _receiveResponse = function _receiveResponse(response) {
      var contentLength = '0';
      var bufferLength = 0;
      var byteOffset = 0;
      this.status = response.statusCode;
      this.statusText = http.STATUS_CODES[this.status];
      this._responseHeaders = response.headers;
      if ((contentLength = response.headers['content-length'])) {
        bufferLength = +contentLength;
      }
      this._responseBuffer = new Buffer(bufferLength);
      _readyStateChange.call(this, XMLHttpRequest.LOADING);
      response.addListener('data', function(chunk) {
        var buffer;
        if (bufferLength === 0) {
          buffer = this._responseBuffer;
          this._responseBuffer = new Buffer(buffer.length + chunk.length);
          buffer.copy(this._responseBuffer);
        }
        chunk.copy(this._responseBuffer, byteOffset);
        byteOffset += chunk.length;
      }.bind(this));
      response.addListener('end', function() {
        _readyStateChange.call(this, XMLHttpRequest.DONE);
        this._client = null;
        this._options = {};
      }.bind(this));
    };
  })(XMLHttpRequest.prototype);

  function FormData() {
    if (!(this instanceof FormData)) {
      throw new TypeError('DOM object constructor cannot be called as a function.');
    }
  }

  (function(proto) {
    proto.append = function append(name, value, filename) {
      // todo
    };
  })(FormData.prototype);

  XMLHttpRequest.XMLHttpRequestUpload = XMLHttpRequestUpload;
  XMLHttpRequest.XMLHttpRequest = XMLHttpRequest;
  XMLHttpRequest.FormData = FormData;
  module.exports = XMLHttpRequest;
})();
<|endoftext|>


<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2011-2013 Yamagishi Kazutoshi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
(function(global) {
  'use strict';

  var utils = require('./utils');
  var Event = require('./event');
  var ProgressEvent = require('./progressevent');
  var XMLHttpRequestEventTarget = require('./xmlhttprequesteventtarget');
  var XMLHttpRequestUpload = require('./xmlhttprequestupload');
  var STATUS_CODES = require('http').STATUS_CODES;

  function XMLHttpRequest(options) {
    if (!(this instanceof XMLHttpRequest)) {
      throw new TypeError('DOM object constructor cannot be called as a function.');
    }
    XMLHttpRequestEventTarget.call(this);
    options = options || {};
    this._flag.anonymous = !!options.anon;
    Object.defineProperty(this, 'upload', {
      configurable: true,
      enumerable: true,
      value: new XMLHttpRequestUpload(),
      writable: false
    });
  }

  XMLHttpRequest.prototype = Object.create(XMLHttpRequestEventTarget.prototype);

  var XMLHttpRequestResponseType = [
    '',
    'arraybuffer',
    'blob',
    'document',
    'json',
    'text'
  ];

  (function(proto) {
    (function() {
      var constants = {
        UNSENT: {
          configurable: false,
          enumerable: true,
          value: 0,
          writable: false
        },
        OPENED: {
          configurable: false,
          enumerable: true,
          value: 1,
          writable: false
        },
        HEADERS_RECEIVED: {
          configurable: false,
          enumerable: true,
          value: 2,
          writable: false
        },
        LOADING: {
          configurable: false,
          enumerable: true,
          value: 3,
          writable: false
        },
        DONE: {
          configurable: false,
          enumerable: true,
          value: 4,
          writable: false
        }
      };

      Object.defineProperties(XMLHttpRequest, constants);
      Object.defineProperties(proto, constants);
    })();

    Object.defineProperties(proto, {
      _flag: {
        configurable: false,
        enumerable: false,
        value: Object.create(Object.prototype, {
          anonymous: {
            configurable: false,
            enumerable: true,
            value: false,
            writable: true
          },
          synchronous: {
            configurable: false,
            enumerable: true,
            value: false,
            writable: true
          },
          uploadComplete: {
            configurable: false,
            enumerable: true,
            value: false,
            writable: true
          },
          uploadEvents: {
            configurable: false,
            enumerable: true,
            value: false,
            writable: true
          }
        }),
        writable: false
      },
      _properties: {
        configurable: false,
        enumerable: false,
        value: Object.create(Object.prototype, {
          auth: {
            configurable: false,
            enumerable: true,
            value: '',
            writable: true
          },
          client: {
            configurable: false,
            enumerable: true,
            value: null,
            writable: true,
          },
          method: {
            configurable: false,
            enumerable: true,
            value: undefined,
            writable: true
          },
          responseHeaders: {
            configurable: false,
            enumerable: true,
            value: {},
            writable: true,
          },
          responseBuffer: {
            configurable: false,
            enumerable: true,
            value: null,
            writable: true,
          },
          responseType: {
            configurable: false,
            enumerable: true,
            value: '',
            writable: true,
          },
          requestHeaders: {
            configurable: false,
            enumerable: true,
            value: {},
            writable: true,
          },
          uri: {
            configurable: true,
            enumerable: true,
            value: '',
            writable: true
          }
        }),
        writable: false
      },
      readyState: {
        configurable: true,
        enumerable: true,
        value: XMLHttpRequest.UNSENT,
        writable: false
      },
      responseType: {
        configurable: false,
        enumerable: true,
        get: function getter() {
          var responseType = this._properties.responseType;
          if (XMLHttpRequestResponseType.indexOf(responseType) < 0) {
            return '';
          }
          return responseType;
        },
        set: function setter(responseType) {
          if (XMLHttpRequestResponseType.indexOf(responseType) < 0) {
            throw new Error(''); // todo
          }
          return this._properties.responseType = responseType;
        }
      },
      response: {
        configurable: false,
        enumerable: true,
        get: function getter() {
          var responseBuffer = this._properties.responseBuffer;
          if (!(responseBuffer instanceof Buffer)) {
            return '';
          }
          switch (this.responseType) {
            case '':
              return this.responseText;
            case 'arraybuffer':
            case 'blob':
              return (new Uint8Array(responseBuffer)).buffer;
            case 'document':
              return null; // todo
            case 'json':
              return JSON.parse(this.responseText);
            case 'text':
              return this.responseText;
            default:
              return '';
          }
        }
      },
      responseText: {
        configurable: false,
        enumerable: true,
        get: function getter() {
          var responseBuffer = this._properties.responseBuffer;
          if (!(responseBuffer instanceof Buffer)) {
            return '';
          }
          return responseBuffer.toString();
        }
      },
      responseXML: {
        configurable: false,
        enumerable: true,
        value: null, // todo
        writable: false
      },
      status: {
        configurable: true,
        enumerable: true,
        value: 0,
        writable: false
      },
      statusText: {
        configurable: true,
        enumerable: true,
        value: '',
        writable: false
      },
      timeout: {
        configurable: true,
        enumerable: true,
        value: 0,
        writable: false
      },
      upload: {
        configurable: true,
        enumerable: true,
        value: null,
        writable: false
      },
      withCredentials: {
        configurable: true,
        enumerable: true,
        value: false,
        writable: false
      }
    });

    function _readyStateChange(readyState) {
      var readyStateChangeEvent = new Event('');
      readyStateChangeEvent.initEvent('readystatechange', false, false);
      Object.defineProperty(this, 'readyState', {
        configurable: true,
        enumerable: true,
        value: readyState,
        writable: false
      });
      this.dispatchEvent(readyStateChangeEvent);
    }

    function _receiveResponse(response) {
      var _properties = this._properties;
      var contentLength = '0';
      var bufferLength = 0;
      var byteOffset = 0;
      var statusCode = response.statusCode;
      Object.defineProperties(this, {
        status: {
          configurable: true,
          enumerable: true,
          value: statusCode,
          writable: false
        },
        statusText: {
          configurable: true,
          enumerable: true,
          value: STATUS_CODES[statusCode],
          writable: false
        }
      });
      _properties.responseHeaders = response.headers;
      contentLength = response.headers['content-length'] || contentLength;
      bufferLength = parseInt(contentLength, 10);
      _properties.responseBuffer = new Buffer(bufferLength);
      _readyStateChange.call(this, XMLHttpRequest.LOADING);
      response.addListener('data', function(chunk) {
        var buffer;
        if (bufferLength === 0) {
          buffer = this._properties.responseBuffer;
          this._properties.responseBuffer = new Buffer(buffer.length + chunk.length);
          buffer.copy(this._properties.responseBuffer);
        }
        chunk.copy(this._properties.responseBuffer, byteOffset);
        byteOffset += chunk.length;
      }.bind(this));
      response.addListener('end', function() {
        _readyStateChange.call(this, XMLHttpRequest.DONE);
        _properties.client = null;
      }.bind(this));
    }

    function _setDispatchProgressEvents(stream) {
      var loadStartEvent = new ProgressEvent('loadstart');
      this.dispatchEvent(loadStartEvent);;
      stream.on('data', function() {
        var progressEvent = new ProgressEvent('progress');
        this.dispatchEvent(progressEvent);
      }.bind(this));
      stream.on('end', function() {
        var loadEvent = new ProgressEvent('load');
        var loadEndEvent = new ProgressEvent('loadend')
        this.dispatchEvent(loadEvent);
        this.dispatchEvent(loadEndEvent);
      }.bind(this));
    }

    proto.abort = function abort() {
      var client = this._properties.client
      if (client && typeof client.abort === 'function') {
        client.abort();
      }
      this.dispatchEvent(new ProgressEvent('abort'));
      this.upload.dispatchEvent(new ProgressEvent('abort'));
    };

    proto.getAllResponseHeaders = function getAllResponseHeaders() {
      var readyState = this.readyState;
      if ([XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED].indexOf(readyState) >= 0) {
        throw new Error(''); // todo
      }
      return Object.keys(this._properties.responseHeaders).map(function(key) {
        return [key, this._properties.responseHeaders[key]].join(': ');
      }, this).join('\n');
    };

    proto.getResponseHeader = function getResponseHeader(header) {
      var readyState = this.readyState;
      var key;
      var value;
      if ([XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED].indexOf(readyState) >= 0) {
        throw new Error(''); // todo;
      }
      key = header.toLowerCase();
      value = this._properties.responseHeaders[key];
      return typeof value !== 'undefined' ? '' + value : null;
    };

    proto.open = function open(method, uri, async, user, password) {
      var argumentCount = arguments.length;
      if (argumentCount < 2) {
        throw new TypeError('Not enought arguments');
      }
      this._properties.method = method;
      this._properties.uri = uri;
      this._flag.synchronous = !!async;
      if (argumentCount >= 4) {
        this._properties.auth = [
          user || '',
          password || ''
        ].join(':');
      }
      _readyStateChange.call(this, XMLHttpRequest.OPENED);
    };

    proto.overrideMimeType = function overrideMimeType(mime) {
      // todo
    };

    proto.send = function send(body) {
      var _properties = this._properties;
      var client;
      var async;
      if (this.readyState !== XMLHttpRequest.OPENED) {
        throw new Error(); // todo
      }
      async = this._flag.synchronous;
      client = utils.createClient(this._properties, async, function() {
        _setDispatchProgressEvents.apply(this, arguments);
        _receiveResponse.apply(this, arguments);
      }.bind(this));
      _properties.client = client;
      Object.keys(_properties.requestHeaders).forEach(function(key) {
        var value = _properties.requestHeaders[key];
        client.setHeader(key, value);
      });
      _readyStateChange.call(this, XMLHttpRequest.HEADERS_RECEIVED);
      if (body) {
        client.on('socket', _setDispatchProgressEvents.bind(this.upload));
        client.write(body);
      }
      client.end();
    };

    proto.setRequestHeader = function setRequestHeader(header, value) {
      if (this.readyState === XMLHttpRequest.UNSENT) {
        throw new Error(''); // todo
      }
      this._properties.requestHeaders[header] = value;
    };
  })(XMLHttpRequest.prototype);

  module.exports = XMLHttpRequest;
})(this);
<commit_msg>Refactor to xmlhttprequest.js<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2011-2013 Yamagishi Kazutoshi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
(function(global) {
  'use strict';

  var HTTP_STATUS_CODES = require('http').STATUS_CODES;

  var Event = require('./event');
  var ProgressEvent = require('./progressevent');
  var XMLHttpRequestEventTarget = require('./xmlhttprequesteventtarget');
  var XMLHttpRequestUpload = require('./xmlhttprequestupload');
  var utils = require('./utils');

  function XMLHttpRequest(options) {
    if (!(this instanceof XMLHttpRequest)) {
      throw new TypeError('DOM object constructor cannot be called as a function.');
    }
    XMLHttpRequestEventTarget.call(this);
    options = options || {};
    this._flag.anonymous = !!options.anon;
    Object.defineProperty(this, 'upload', {
      configurable: true,
      enumerable: true,
      value: new XMLHttpRequestUpload(),
      writable: false
    });
  }

  XMLHttpRequest.prototype = Object.create(XMLHttpRequestEventTarget.prototype);

  var XMLHttpRequestResponseType = [
    '',
    'arraybuffer',
    'blob',
    'document',
    'json',
    'text'
  ];

  (function(proto) {
    (function() {
      var constants = {
        UNSENT: {
          configurable: false,
          enumerable: true,
          value: 0,
          writable: false
        },
        OPENED: {
          configurable: false,
          enumerable: true,
          value: 1,
          writable: false
        },
        HEADERS_RECEIVED: {
          configurable: false,
          enumerable: true,
          value: 2,
          writable: false
        },
        LOADING: {
          configurable: false,
          enumerable: true,
          value: 3,
          writable: false
        },
        DONE: {
          configurable: false,
          enumerable: true,
          value: 4,
          writable: false
        }
      };

      Object.defineProperties(XMLHttpRequest, constants);
      Object.defineProperties(proto, constants);
    })();

    Object.defineProperties(proto, {
      _flag: {
        configurable: false,
        enumerable: false,
        value: Object.create(Object.prototype, {
          anonymous: {
            configurable: false,
            enumerable: true,
            value: false,
            writable: true
          },
          synchronous: {
            configurable: false,
            enumerable: true,
            value: false,
            writable: true
          },
          uploadComplete: {
            configurable: false,
            enumerable: true,
            value: false,
            writable: true
          },
          uploadEvents: {
            configurable: false,
            enumerable: true,
            value: false,
            writable: true
          }
        }),
        writable: false
      },
      _properties: {
        configurable: false,
        enumerable: false,
        value: Object.create(Object.prototype, {
          auth: {
            configurable: false,
            enumerable: true,
            value: '',
            writable: true
          },
          client: {
            configurable: false,
            enumerable: true,
            value: null,
            writable: true,
          },
          method: {
            configurable: false,
            enumerable: true,
            value: undefined,
            writable: true
          },
          responseHeaders: {
            configurable: false,
            enumerable: true,
            value: {},
            writable: true,
          },
          responseBuffer: {
            configurable: false,
            enumerable: true,
            value: null,
            writable: true,
          },
          responseType: {
            configurable: false,
            enumerable: true,
            value: '',
            writable: true,
          },
          requestHeaders: {
            configurable: false,
            enumerable: true,
            value: {},
            writable: true,
          },
          uri: {
            configurable: true,
            enumerable: true,
            value: '',
            writable: true
          }
        }),
        writable: false
      },
      readyState: {
        configurable: true,
        enumerable: true,
        value: XMLHttpRequest.UNSENT,
        writable: false
      },
      responseType: {
        configurable: false,
        enumerable: true,
        get: function getter() {
          var responseType = this._properties.responseType;
          if (XMLHttpRequestResponseType.indexOf(responseType) < 0) {
            return '';
          }
          return responseType;
        },
        set: function setter(responseType) {
          if (XMLHttpRequestResponseType.indexOf(responseType) < 0) {
            throw new Error(''); // todo
          }
          return this._properties.responseType = responseType;
        }
      },
      response: {
        configurable: false,
        enumerable: true,
        get: function getter() {
          var responseBuffer = this._properties.responseBuffer;
          if (!(responseBuffer instanceof Buffer)) {
            return '';
          }
          switch (this.responseType) {
            case '':
              return this.responseText;
            case 'arraybuffer':
            case 'blob':
              return (new Uint8Array(responseBuffer)).buffer;
            case 'document':
              return null; // todo
            case 'json':
              return JSON.parse(this.responseText);
            case 'text':
              return this.responseText;
            default:
              return '';
          }
        }
      },
      responseText: {
        configurable: false,
        enumerable: true,
        get: function getter() {
          var responseBuffer = this._properties.responseBuffer;
          if (!(responseBuffer instanceof Buffer)) {
            return '';
          }
          return responseBuffer.toString();
        }
      },
      responseXML: {
        configurable: false,
        enumerable: true,
        value: null, // todo
        writable: false
      },
      status: {
        configurable: true,
        enumerable: true,
        value: 0,
        writable: false
      },
      statusText: {
        configurable: true,
        enumerable: true,
        value: '',
        writable: false
      },
      timeout: {
        configurable: true,
        enumerable: true,
        value: 0,
        writable: false
      },
      upload: {
        configurable: true,
        enumerable: true,
        value: null,
        writable: false
      },
      withCredentials: {
        configurable: true,
        enumerable: true,
        value: false,
        writable: false
      }
    });

    function _readyStateChange(readyState) {
      var readyStateChangeEvent = new Event('');
      readyStateChangeEvent.initEvent('readystatechange', false, false);
      Object.defineProperty(this, 'readyState', {
        configurable: true,
        enumerable: true,
        value: readyState,
        writable: false
      });
      this.dispatchEvent(readyStateChangeEvent);
    }

    function _receiveResponse(response) {
      var _properties = this._properties;
      var contentLength = '0';
      var bufferLength = 0;
      var byteOffset = 0;
      var statusCode = response.statusCode;
      Object.defineProperties(this, {
        status: {
          configurable: true,
          enumerable: true,
          value: statusCode,
          writable: false
        },
        statusText: {
          configurable: true,
          enumerable: true,
          value: HTTP_STATUS_CODES[statusCode],
          writable: false
        }
      });
      _properties.responseHeaders = response.headers;
      contentLength = response.headers['content-length'] || contentLength;
      bufferLength = parseInt(contentLength, 10);
      _properties.responseBuffer = new Buffer(bufferLength);
      _readyStateChange.call(this, XMLHttpRequest.LOADING);
      response.addListener('data', function(chunk) {
        var buffer;
        if (bufferLength === 0) {
          buffer = this._properties.responseBuffer;
          this._properties.responseBuffer = new Buffer(buffer.length + chunk.length);
          buffer.copy(this._properties.responseBuffer);
        }
        chunk.copy(this._properties.responseBuffer, byteOffset);
        byteOffset += chunk.length;
      }.bind(this));
      response.addListener('end', function() {
        _readyStateChange.call(this, XMLHttpRequest.DONE);
        _properties.client = null;
      }.bind(this));
    }

    function _setDispatchProgressEvents(stream) {
      var loadStartEvent = new ProgressEvent('loadstart');
      this.dispatchEvent(loadStartEvent);;
      stream.on('data', function() {
        var progressEvent = new ProgressEvent('progress');
        this.dispatchEvent(progressEvent);
      }.bind(this));
      stream.on('end', function() {
        var loadEvent = new ProgressEvent('load');
        var loadEndEvent = new ProgressEvent('loadend')
        this.dispatchEvent(loadEvent);
        this.dispatchEvent(loadEndEvent);
      }.bind(this));
    }

    proto.abort = function abort() {
      var client = this._properties.client
      if (client && typeof client.abort === 'function') {
        client.abort();
      }
      this.dispatchEvent(new ProgressEvent('abort'));
      this.upload.dispatchEvent(new ProgressEvent('abort'));
    };

    proto.getAllResponseHeaders = function getAllResponseHeaders() {
      var readyState = this.readyState;
      if ([XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED].indexOf(readyState) >= 0) {
        throw new Error(''); // todo
      }
      return Object.keys(this._properties.responseHeaders).map(function(key) {
        return [key, this._properties.responseHeaders[key]].join(': ');
      }, this).join('\n');
    };

    proto.getResponseHeader = function getResponseHeader(header) {
      var readyState = this.readyState;
      var key;
      var value;
      if ([XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED].indexOf(readyState) >= 0) {
        throw new Error(''); // todo;
      }
      key = header.toLowerCase();
      value = this._properties.responseHeaders[key];
      return typeof value !== 'undefined' ? '' + value : null;
    };

    proto.open = function open(method, uri, async, user, password) {
      var argumentCount = arguments.length;
      if (argumentCount < 2) {
        throw new TypeError('Not enought arguments');
      }
      this._properties.method = method;
      this._properties.uri = uri;
      this._flag.synchronous = !!async;
      if (argumentCount >= 4) {
        this._properties.auth = [
          user || '',
          password || ''
        ].join(':');
      }
      _readyStateChange.call(this, XMLHttpRequest.OPENED);
    };

    proto.overrideMimeType = function overrideMimeType(mime) {
      // todo
    };

    proto.send = function send(body) {
      var _properties = this._properties;
      var client;
      var async;
      if (this.readyState !== XMLHttpRequest.OPENED) {
        throw new Error(); // todo
      }
      async = this._flag.synchronous;
      client = utils.createClient(this._properties, async, function() {
        _setDispatchProgressEvents.apply(this, arguments);
        _receiveResponse.apply(this, arguments);
      }.bind(this));
      _properties.client = client;
      Object.keys(_properties.requestHeaders).forEach(function(key) {
        var value = _properties.requestHeaders[key];
        client.setHeader(key, value);
      });
      _readyStateChange.call(this, XMLHttpRequest.HEADERS_RECEIVED);
      if (body) {
        client.on('socket', _setDispatchProgressEvents.bind(this.upload));
        client.write(body);
      }
      client.end();
    };

    proto.setRequestHeader = function setRequestHeader(header, value) {
      if (this.readyState === XMLHttpRequest.UNSENT) {
        throw new Error(''); // todo
      }
      this._properties.requestHeaders[header] = value;
    };
  })(XMLHttpRequest.prototype);

  module.exports = XMLHttpRequest;
})(this);
<|endoftext|>


<commit_before>Function.prototype.bind = Function.prototype.bind || require('function-bind');

var simulant = require('simulant'),
  bespoke = require('bespoke'),
  classes = require('bespoke-classes'),
  keys = require('bespoke-keys'),
  breather = require('../../lib/bespoke-breather.js');

describe("bespoke-breather", function() {

  var deck,
    createDeck = function() {
      var parent = document.createElement('article');
      for (var i = 0; i < 10; i++) {
        var slide = document.createElement('section');
        parent.appendChild(slide);
      }

      deck = bespoke.from(parent, [
        classes(),
        keys(),
        breather()
      ]);
    },

    destroyDeck = function() {
      deck.fire('destroy');
      deck = null;
    },

    pressKey = function(which, element) {
      simulant.fire((element || document), 'keydown', { which: which });
    };

  describe("blank slide", function() {

    beforeEach(createDeck);
    afterEach(destroyDeck);

    it("should add the bespoke-paused class to the parent when pressing b", function() {
      expect(deck.parent.classList.contains('bespoke-paused')).toBe(false);
      pressKey(66);
      expect(deck.parent.classList.contains('bespoke-paused')).toBe(true);
      pressKey(66);
      expect(deck.parent.classList.contains('bespoke-paused')).toBe(false);
    });

    it("should add the bespoke-paused class to the parent when pressing .", function() {
      expect(deck.parent.classList.contains('bespoke-paused')).toBe(false);
      pressKey(190);
      expect(deck.parent.classList.contains('bespoke-paused')).toBe(true);
      pressKey(190);
      expect(deck.parent.classList.contains('bespoke-paused')).toBe(false);
    });

    it("should not advance slide when paused", function() {
      deck.slide(1);
      expect(deck.slide()).toBe(1);
      pressKey(66);
      pressKey(32);
      expect(deck.slide()).toBe(1);
    });

  });

});
<commit_msg>use single quotes, remove blank lines<commit_after>Function.prototype.bind = Function.prototype.bind || require('function-bind');

var simulant = require('simulant'),
  bespoke = require('bespoke'),
  classes = require('bespoke-classes'),
  keys = require('bespoke-keys'),
  breather = require('../../lib/bespoke-breather.js');

describe('bespoke-breather', function() {
  var deck,
    createDeck = function() {
      var parent = document.createElement('article');
      for (var i = 0; i < 10; i++) {
        var slide = document.createElement('section');
        parent.appendChild(slide);
      }
      deck = bespoke.from(parent, [
        classes(),
        keys(),
        breather()
      ]);
    },
    destroyDeck = function() {
      deck.fire('destroy');
      deck = null;
    },
    pressKey = function(which, element) {
      simulant.fire((element || document), 'keydown', { which: which });
    };

  describe('blank slide', function() {
    beforeEach(createDeck);
    afterEach(destroyDeck);

    it('should add the bespoke-paused class to the parent when pressing b', function() {
      expect(deck.parent.classList.contains('bespoke-paused')).toBe(false);
      pressKey(66);
      expect(deck.parent.classList.contains('bespoke-paused')).toBe(true);
      pressKey(66);
      expect(deck.parent.classList.contains('bespoke-paused')).toBe(false);
    });

    it('should add the bespoke-paused class to the parent when pressing .', function() {
      expect(deck.parent.classList.contains('bespoke-paused')).toBe(false);
      pressKey(190);
      expect(deck.parent.classList.contains('bespoke-paused')).toBe(true);
      pressKey(190);
      expect(deck.parent.classList.contains('bespoke-paused')).toBe(false);
    });

    it('should not advance slide when paused', function() {
      deck.slide(1);
      expect(deck.slide()).toBe(1);
      pressKey(66);
      pressKey(32);
      expect(deck.slide()).toBe(1);
    });
  });
});
<|endoftext|>


<commit_before>/* jshint node:true */
/* global phantom, console */

// PhantomJS driver for loading enyo-amf tests and checking for failures
var page = require('webpage').create();

page.settings.localToRemoteUrlAccessEnabled = true;

page.onConsoleMessage = function (msg) {
	console.log("JS: " + msg);
	if (msg === "TEST RUNNER FINISHED") {
		var pass = page.evaluate(function() {
			return (document.querySelector(".enyo-amf-testcase-failed") === null);
		});
		if (pass) {
			console.log("enyo-amf tests passed.");
			phantom.exit(0);
		} else {
			console.log("enyo-amf tests failed.");
			phantom.exit(1);
		}
	}
};

page.onError = function(msg, trace) {
	phantom.exit(2);
};

page.open("tools/test/amfx/index.html", function(status) {
	if (status !== "success") {
		console.log("error loading page, status: " + status);
		phantom.exit(3);
	}
});

setTimeout(function() {
	console.log("timed out after 1 minute");
	phantom.exit(4);
}, 60 * 1000);<commit_msg>phatomjs log msg onerror<commit_after>/* jshint node:true */
/* global phantom, console */

// PhantomJS driver for loading enyo-amf tests and checking for failures
var page = require('webpage').create();

page.settings.localToRemoteUrlAccessEnabled = true;

page.onConsoleMessage = function (msg) {
	console.log("JS: " + msg);
	if (msg === "TEST RUNNER FINISHED") {
		var pass = page.evaluate(function() {
			return (document.querySelector(".enyo-amf-testcase-failed") === null);
		});
		if (pass) {
			console.log("enyo-amf tests passed.");
			phantom.exit(0);
		} else {
			console.log("enyo-amf tests failed.");
			phantom.exit(1);
		}
	}
};

page.onError = function(msg, trace) {
	console.log("page error, msg: " + msg);
	phantom.exit(2);
};

page.open("tools/test/amfx/index.html", function(status) {
	if (status !== "success") {
		console.log("error loading page, status: " + status);
		phantom.exit(3);
	}
});

setTimeout(function() {
	console.log("timed out after 1 minute");
	phantom.exit(4);
}, 60 * 1000);<|endoftext|>


<commit_before>import moment from "moment";
import shared from "./imports/shared";
import {Meteor as ImportedMeteor} from "meteor/meteor";

describe("app modules", () => {
  it("can be imported using absolute identifiers", () => {
    assert.strictEqual(require("/tests"), exports);
  });

  it("can have different file extensions", () => {
    assert.strictEqual(
      require("./eager.jsx").extension,
      ".jsx"
    );

    assert.strictEqual(
      require("./eager.coffee").extension,
      ".coffee"
    );
  });

  it("are eagerly evaluated if outside imports/", () => {
    assert.strictEqual(shared["/eager.jsx"], "eager jsx");
    assert.strictEqual(shared["/eager.coffee"], "eager coffee");
  });

  it("are lazily evaluated if inside imports/", (done) => {
    const delayMs = 200;

    setTimeout(() => {
      assert.strictEqual(shared["/imports/lazy1.js"], void 0);
      assert.strictEqual(shared["/imports/lazy2.js"], void 0);

      var reset1 = require("./imports/lazy1").reset;

      assert.strictEqual(shared["/imports/lazy1.js"], 1);
      assert.strictEqual(shared["/imports/lazy2.js"], 2);

      // Make sure this test can run again without starting a new process.
      require("./imports/lazy2").reset();
      reset1();

      done();
    }, delayMs);
  });

  it("cannot import server modules on client", () => {
    let error;
    let result;
    try {
      result = require("./server/only").default;
    } catch (expectedOnClient) {
      error = expectedOnClient;
    }

    if (Meteor.isServer) {
      assert.strictEqual(typeof error, "undefined");
      assert.strictEqual(result, "/server/only.js");
      assert.strictEqual(require("./server/only"),
                         require("/server/only"));
    }

    if (Meteor.isClient) {
      assert.ok(error instanceof Error);
    }
  });

  it("cannot import client modules on server", () => {
    let error;
    let result;
    try {
      result = require("./client/only").default;
    } catch (expectedOnServer) {
      error = expectedOnServer;
    }

    if (Meteor.isClient) {
      assert.strictEqual(typeof error, "undefined");
      assert.strictEqual(result, "/client/only.js");
      assert.strictEqual(require("./client/only"),
                         require("/client/only"));
    }

    if (Meteor.isServer) {
      assert.ok(error instanceof Error);
    }
  });

  it("should not be parsed in strictMode", () => {
    let foo = 1234;
    delete foo;
  });

  it("should have access to filename and dirname", () => {
    assert.strictEqual(require(__filename), exports);
    assert.strictEqual(
      require("path").relative(__dirname, __filename),
      "tests.js"
    );
  });
});

describe("template modules", () => {
  Meteor.isClient &&
  it("should be importable on the client", () => {
    assert.strictEqual(typeof Template, "function");
    assert.ok(! _.has(Template, "lazy"));
    require("./imports/lazy.html");
    assert.ok(_.has(Template, "lazy"));
    assert.ok(Template.lazy instanceof Template);
  });

  Meteor.isServer &&
  it("should not be importable on the server", () => {
    let error;
    try {
      require("./imports/lazy.html");
    } catch (expected) {
      error = expected;
    }
    assert.ok(error instanceof Error);
  });
});

Meteor.isClient &&
describe("css modules", () => {
  it("should be loaded eagerly unless lazy", () => {
    assert.strictEqual(
      $(".app-eager-css").css("display"),
      "none"
    );

    let error;
    try {
      require("./eager.css");
    } catch (expected) {
      error = expected;
    }
    assert.ok(error instanceof Error);
  });

  it("should be importable by an app", () => {
    assert.strictEqual(
      $(".app-lazy-css").css("display"),
      "block"
    );

    require("./imports/lazy.css");

    assert.strictEqual(
      $(".app-lazy-css").css("display"),
      "none"
    );
  });

  it("should be importable by a package", () => {
    assert.strictEqual(
      $(".pkg-lazy-css.imported").css("display"),
      "none"
    );

    assert.strictEqual(
      $(".pkg-lazy-css.not-imported").css("display"),
      "block"
    );
  });
});

describe("native node_modules", () => {
  Meteor.isServer &&
  it("can be imported on the server", () => {
    assert.strictEqual(typeof require("fs").readFile, "function");
  });

  Meteor.isClient &&
  it("are imported as stubs on the client", () => {
    const inherits = require("util").inherits;
    assert.strictEqual(typeof inherits, "function");
    assert.strictEqual(require("util"),
                       require("util/util.js"));
  });

  Meteor.isServer &&
  it("cannot be overridden on the server", () => {
    assert.strictEqual(typeof require("repl").start, "function");
  });

  Meteor.isClient &&
  it("can be overridden on the client", () => {
    assert.strictEqual(require("repl").notEmpty, true);
  });

  it("can be implemented by wrapper npm packages", () => {
    const Stream = require("stream");
    assert.strictEqual(typeof Stream, "function");
    assert.strictEqual(typeof Stream.Readable, "function");
  });

  Meteor.isClient &&
  it("can be installed with aliases", () => {
    meteorInstall({
      node_modules: {
        http: "stream-http"
      }
    });

    assert.strictEqual(require("http"), require("stream-http"));
  });
});

describe("local node_modules", () => {
  it("should be importable", () => {
    assert.strictEqual(require("moment"), moment);
    const cal = moment().calendar();
    assert.ok(cal.match(/\bat\b/));
  });

  it("can be imported using absolute identifiers", () => {
    assert.strictEqual(
      require("moment"),
      require("/node_modules/moment")
    );
  });

  it("should be importable by packages", () => {
    // Defined in packages/modules-test-package/common.js.
    assert.strictEqual(typeof regeneratorRuntime, "object");
  });

  it('should expose "version" field of package.json', () => {
    const pkg = require("moment/package.json");
    assert.strictEqual(pkg.version, "2.11.1");
  });
});

describe("Meteor packages", () => {
  it("api.export should create named exports", () => {
    assert.strictEqual(typeof ImportedMeteor, "object");
    assert.strictEqual(Meteor, ImportedMeteor);
  });

  it("should be importable", () => {
    assert.strictEqual(require("meteor/underscore")._, _);

    const Blaze = require("meteor/blaze").Blaze;
    assert.strictEqual(typeof Blaze, "object");

    let error;
    try {
      require("meteor/nonexistent");
    } catch (expected) {
      error = expected;
    }
    assert.ok(error instanceof Error);
  });

  it("can be local", () => {
    assert.strictEqual(ModulesTestPackage, "loaded");
    const mtp = require("meteor/modules-test-package");
    assert.strictEqual(mtp.where, Meteor.isServer ? "server" : "client");
  });

  it("should expose their files for import", () => {
    const osStub = require("meteor/modules-test-package/os-stub");

    assert.strictEqual(
      osStub.platform(),
      "browser"
    );

    assert.strictEqual(
      osStub.name,
      "/node_modules/meteor/modules-test-package/os-stub.js"
    );
  });
});

describe("JSX syntax", () => {
  it("should work in .js files on both client and server", () => {
    const React = {
      createElement: function (name, attrs, children) {
        assert.strictEqual(name, "div");
        assert.strictEqual(attrs, null);
        assert.strictEqual(children, "hi");
        return "all good";
      }
    };

    assert.strictEqual(
hi
, "all good");
  });
});

describe("async functions", () => {
  it("should work on the client and server", async () => {
    assert.strictEqual(
      await 2 + 2,
      await new Promise(resolve => resolve(4))
    );
  });
});

Meteor.isClient &&
describe("client/compatibility directories", () => {
  it("should contain bare files", () => {
    assert.strictEqual(topLevelVariable, 1234);
  });
});

describe(".es5.js files", () => {
  it("should not be transpiled", () => {
    assert.strictEqual(require("./imports/plain.es5.js").let, "ok");
  });
});

describe("return statements at top level", () => {
  it("should be legal", () => {
    var ret = require("./imports/return.js");
    assert.strictEqual(ret.a, 1234);
    assert.strictEqual(ret.b, void 0);
  });
});

describe("circular package.json resolution chains", () => {
  it("should be broken appropriately", () => {
    assert.strictEqual(
      require("./lib").aMain,
      "/lib/a/index.js"
    );
  });
});
<commit_msg>Test that #6312 was fixed by the recent Babel upgrade.<commit_after>import moment from "moment";
import shared from "./imports/shared";
import {Meteor as ImportedMeteor} from "meteor/meteor";

describe("app modules", () => {
  it("can be imported using absolute identifiers", () => {
    assert.strictEqual(require("/tests"), exports);
  });

  it("can have different file extensions", () => {
    assert.strictEqual(
      require("./eager.jsx").extension,
      ".jsx"
    );

    assert.strictEqual(
      require("./eager.coffee").extension,
      ".coffee"
    );
  });

  it("are eagerly evaluated if outside imports/", () => {
    assert.strictEqual(shared["/eager.jsx"], "eager jsx");
    assert.strictEqual(shared["/eager.coffee"], "eager coffee");
  });

  it("are lazily evaluated if inside imports/", (done) => {
    const delayMs = 200;

    setTimeout(() => {
      assert.strictEqual(shared["/imports/lazy1.js"], void 0);
      assert.strictEqual(shared["/imports/lazy2.js"], void 0);

      var reset1 = require("./imports/lazy1").reset;

      assert.strictEqual(shared["/imports/lazy1.js"], 1);
      assert.strictEqual(shared["/imports/lazy2.js"], 2);

      // Make sure this test can run again without starting a new process.
      require("./imports/lazy2").reset();
      reset1();

      done();
    }, delayMs);
  });

  it("cannot import server modules on client", () => {
    let error;
    let result;
    try {
      result = require("./server/only").default;
    } catch (expectedOnClient) {
      error = expectedOnClient;
    }

    if (Meteor.isServer) {
      assert.strictEqual(typeof error, "undefined");
      assert.strictEqual(result, "/server/only.js");
      assert.strictEqual(require("./server/only"),
                         require("/server/only"));
    }

    if (Meteor.isClient) {
      assert.ok(error instanceof Error);
    }
  });

  it("cannot import client modules on server", () => {
    let error;
    let result;
    try {
      result = require("./client/only").default;
    } catch (expectedOnServer) {
      error = expectedOnServer;
    }

    if (Meteor.isClient) {
      assert.strictEqual(typeof error, "undefined");
      assert.strictEqual(result, "/client/only.js");
      assert.strictEqual(require("./client/only"),
                         require("/client/only"));
    }

    if (Meteor.isServer) {
      assert.ok(error instanceof Error);
    }
  });

  it("should not be parsed in strictMode", () => {
    let foo = 1234;
    delete foo;
  });

  it("should have access to filename and dirname", () => {
    assert.strictEqual(require(__filename), exports);
    assert.strictEqual(
      require("path").relative(__dirname, __filename),
      "tests.js"
    );
  });
});

describe("template modules", () => {
  Meteor.isClient &&
  it("should be importable on the client", () => {
    assert.strictEqual(typeof Template, "function");
    assert.ok(! _.has(Template, "lazy"));
    require("./imports/lazy.html");
    assert.ok(_.has(Template, "lazy"));
    assert.ok(Template.lazy instanceof Template);
  });

  Meteor.isServer &&
  it("should not be importable on the server", () => {
    let error;
    try {
      require("./imports/lazy.html");
    } catch (expected) {
      error = expected;
    }
    assert.ok(error instanceof Error);
  });
});

Meteor.isClient &&
describe("css modules", () => {
  it("should be loaded eagerly unless lazy", () => {
    assert.strictEqual(
      $(".app-eager-css").css("display"),
      "none"
    );

    let error;
    try {
      require("./eager.css");
    } catch (expected) {
      error = expected;
    }
    assert.ok(error instanceof Error);
  });

  it("should be importable by an app", () => {
    assert.strictEqual(
      $(".app-lazy-css").css("display"),
      "block"
    );

    require("./imports/lazy.css");

    assert.strictEqual(
      $(".app-lazy-css").css("display"),
      "none"
    );
  });

  it("should be importable by a package", () => {
    assert.strictEqual(
      $(".pkg-lazy-css.imported").css("display"),
      "none"
    );

    assert.strictEqual(
      $(".pkg-lazy-css.not-imported").css("display"),
      "block"
    );
  });
});

describe("native node_modules", () => {
  Meteor.isServer &&
  it("can be imported on the server", () => {
    assert.strictEqual(typeof require("fs").readFile, "function");
  });

  Meteor.isClient &&
  it("are imported as stubs on the client", () => {
    const inherits = require("util").inherits;
    assert.strictEqual(typeof inherits, "function");
    assert.strictEqual(require("util"),
                       require("util/util.js"));
  });

  Meteor.isServer &&
  it("cannot be overridden on the server", () => {
    assert.strictEqual(typeof require("repl").start, "function");
  });

  Meteor.isClient &&
  it("can be overridden on the client", () => {
    assert.strictEqual(require("repl").notEmpty, true);
  });

  it("can be implemented by wrapper npm packages", () => {
    const Stream = require("stream");
    assert.strictEqual(typeof Stream, "function");
    assert.strictEqual(typeof Stream.Readable, "function");
  });

  Meteor.isClient &&
  it("can be installed with aliases", () => {
    meteorInstall({
      node_modules: {
        http: "stream-http"
      }
    });

    assert.strictEqual(require("http"), require("stream-http"));
  });
});

describe("local node_modules", () => {
  it("should be importable", () => {
    assert.strictEqual(require("moment"), moment);
    const cal = moment().calendar();
    assert.ok(cal.match(/\bat\b/));
  });

  it("can be imported using absolute identifiers", () => {
    assert.strictEqual(
      require("moment"),
      require("/node_modules/moment")
    );
  });

  it("should be importable by packages", () => {
    // Defined in packages/modules-test-package/common.js.
    assert.strictEqual(typeof regeneratorRuntime, "object");
  });

  it('should expose "version" field of package.json', () => {
    const pkg = require("moment/package.json");
    assert.strictEqual(pkg.version, "2.11.1");
  });
});

describe("Meteor packages", () => {
  it("api.export should create named exports", () => {
    assert.strictEqual(typeof ImportedMeteor, "object");
    assert.strictEqual(Meteor, ImportedMeteor);
  });

  it("should be importable", () => {
    assert.strictEqual(require("meteor/underscore")._, _);

    const Blaze = require("meteor/blaze").Blaze;
    assert.strictEqual(typeof Blaze, "object");

    let error;
    try {
      require("meteor/nonexistent");
    } catch (expected) {
      error = expected;
    }
    assert.ok(error instanceof Error);
  });

  it("can be local", () => {
    assert.strictEqual(ModulesTestPackage, "loaded");
    const mtp = require("meteor/modules-test-package");
    assert.strictEqual(mtp.where, Meteor.isServer ? "server" : "client");
  });

  it("should expose their files for import", () => {
    const osStub = require("meteor/modules-test-package/os-stub");

    assert.strictEqual(
      osStub.platform(),
      "browser"
    );

    assert.strictEqual(
      osStub.name,
      "/node_modules/meteor/modules-test-package/os-stub.js"
    );
  });
});

describe("ecmascript miscellany", () => {
  it("JSX should work in .js files on both client and server", () => {
    const React = {
      createElement: function (name, attrs, children) {
        assert.strictEqual(name, "div");
        assert.strictEqual(attrs, null);
        assert.strictEqual(children, "hi");
        return "all good";
      }
    };

    assert.strictEqual(
hi
, "all good");
  });

  it("async functions should work on the client and server", async () => {
    assert.strictEqual(
      await 2 + 2,
      await new Promise(resolve => resolve(4))
    );
  });

  it("rest paramters in inner arrow functions (#6312)", () => {
    const rev = (...args) => args.reverse();
    assert.deepEqual(rev(1, 2, 3), [3, 2, 1]);
    assert.ok(rev.toString().match(/\barguments\b/));
  });
});

Meteor.isClient &&
describe("client/compatibility directories", () => {
  it("should contain bare files", () => {
    assert.strictEqual(topLevelVariable, 1234);
  });
});

describe(".es5.js files", () => {
  it("should not be transpiled", () => {
    assert.strictEqual(require("./imports/plain.es5.js").let, "ok");
  });
});

describe("return statements at top level", () => {
  it("should be legal", () => {
    var ret = require("./imports/return.js");
    assert.strictEqual(ret.a, 1234);
    assert.strictEqual(ret.b, void 0);
  });
});

describe("circular package.json resolution chains", () => {
  it("should be broken appropriately", () => {
    assert.strictEqual(
      require("./lib").aMain,
      "/lib/a/index.js"
    );
  });
});
<|endoftext|>


<commit_before>
// Get id of the view/* part of the URL
var pattern = /view\/[0-9a-z\-]+/;
var baseURL = document.URL.replace(pattern, '')

// Remove query string from BaseURL
if (baseURL.indexOf('?') > -1){
    baseURLparts = baseURL.split('?');
    baseURL = baseURLparts[0]
}

// Slickgrid formatter for making the _id field into a link
// and the dqi field into a traffic light!
var NHMFormatter = function(row, cell, value, columnDef, dataContext) {

    if(columnDef.id == "del"){
        return self.templates.deleterow
    }

    if(columnDef.id == "_id"){

        // Build URL, ensuring query is at the end
        var url = baseURL + 'record/' + value

        // Slickgrid uses preventDefault() preventing the link from working
        // So am using the onclick handler to change location
        return 'View';
    }

    if(columnDef.id == 'gbifIssue'){
      var dqi_class

        if(dataContext['gbifID'] === null){
            dqi_class = 'unknown'
            value = 'Unknown'
        }else if(value === null){
            dqi_class = 'no-errors'
            value = 'No errors'
        }else{
        // Match and major errors

        var major_errors = ['TAXON_MATCH_NONE', 'TYPE_STATUS_INVALID', 'BASIS_OF_RECORD_INVALID']
        // Loop through all the major errors, and see if they exist in the value
        for(i=0;i<major_errors.length;i++){
          if(value.indexOf(major_errors[i])!==-1){
              dqi_class = 'major-errors'
              break
          }
        }
        if(!dqi_class){
          dqi_class = 'minor-errors'
        }
        }

      return '

';
    }

    return value

};

<commit_msg>formatting<commit_after>
// Get id of the view/* part of the URL
var pattern = /view\/[0-9a-z\-]+/;
var baseURL = document.URL.replace(pattern, '')

// Remove query string from BaseURL
if (baseURL.indexOf('?') > -1){
    baseURLparts = baseURL.split('?');
    baseURL = baseURLparts[0]
}

// Slickgrid formatter for making the _id field into a link
// and the dqi field into a traffic light!
var NHMFormatter = function(row, cell, value, columnDef, dataContext) {

    if(columnDef.id == "del"){
        return self.templates.deleterow
    }

    if(columnDef.id == "_id"){

        // Build URL, ensuring query is at the end
        var url = baseURL + 'record/' + value

        // Slickgrid uses preventDefault() preventing the link from working
        // So am using the onclick handler to change location
        return 'View';
    }

    if(columnDef.id == 'gbifIssue'){
      var dqi_class;

        if(dataContext['gbifID'] === null){
            dqi_class = 'unknown'
            value = 'Unknown'
        }else if(value === null){
            dqi_class = 'no-errors'
            value = 'No errors'
        }else{
        // Match and major errors

        var major_errors = ['TAXON_MATCH_NONE', 'TYPE_STATUS_INVALID', 'BASIS_OF_RECORD_INVALID']
        // Loop through all the major errors, and see if they exist in the value
        for(i=0;i<major_errors.length;i++){
          if(value.indexOf(major_errors[i])!==-1){
              dqi_class = 'major-errors'
              break
          }
        }
        if(!dqi_class){
          dqi_class = 'minor-errors'
        }
        }

      return '

';
    }

    return value

};

<|endoftext|>


<commit_before>'use strict';

/* Filters */

var app = angular.module('myApp.locations.filters', []);

app.filter('humanData', function() {
  return function(bytes, precision) {
    if(bytes === 0 || bytes === '' || bytes === undefined || bytes === null) {
      return '0 Bytes';
    } else {
      var k = 1000;
      var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
      var i = Math.floor(Math.log(bytes) / Math.log(k));
      return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
    }
  };
});

app.filter('sentenceCase', function() {
  return function(input) {
    input = input || '';
    return input.charAt(0).toUpperCase() + input.slice(1);
  };
});

app.filter('titleCase', function() {
  return function(input) {
    if ( typeof input === 'string' ) {
      input = input || '';
      return input.replace(/_/g, ' ').replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    } else {
      return input;
    }
  };
});

app.filter('uppercase', function() {
  return function(input) {
    input = input || '';
    return input.toUpperCase();
  };
});

app.filter('lowercase', function() {
  return function(input) {
    input = input || '';
    return input.toLowerCase();
  };
});

app.filter('mbps', function() {
  return function(bytes, precision) {
    if (isNaN(parseFloat(bytes)) || !isFinite(bytes)) {
      return '-';
    }
    if (bytes === 0) {
      return '0 Mbps';
    }
    if (typeof precision === 'undefined') {
      precision = 1;
    }
    var units = ['Kbps', 'Mbps', 'Gbps', 'Tbps'],
      number = Math.floor(Math.log(bytes) / Math.log(1024));
    return (bytes / Math.pow(1024, Math.floor(number))).toFixed(precision) +  '' + units[number];
  };
});

app.filter('bitsToBytes', function() {
  return function(bits, precision) {
    if (isNaN(parseFloat(bits)) || !isFinite(bits)) {
      return '-';
    }
    if (bits === 0) {
      return '0 Mbps';
    }
    if (typeof precision === 'undefined') {
      precision = 1;
    }
    var i = Math.floor( Math.log(bits) / Math.log(1000) );
    return ( bits / Math.pow(1000, i) ).toFixed(2) * 1 + ' ' + ['b/s', 'Kb/s', 'Mb/s', 'Gb/s', 'Tb/s'][i];
  };
});

app.filter('humanDate', ['$window', 'gettextCatalog', function(window, gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null) {
      return gettextCatalog.getString('N/A');
    } else {
      return window.moment.unix(input).format('MMMM Do YYYY');
    }
  };
}]);

app.filter('humanTime', ['$window', 'gettextCatalog', function(window, gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null) {
      return gettextCatalog.getString('N/A');
    } else {
      return window.moment.unix(input).format('MMMM Do YYYY, h:mm:ss a');
    }
  };
}]);

app.filter('mysqlTime', ['$window', 'gettextCatalog', function(window, gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null) {
      return gettextCatalog.getString('N/A');
    } else {
      return window.moment(input).format('MMM Do, HH:mm:ss');
    }
  };
}]);

app.filter('humanTimeShort', ['gettextCatalog', function(gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null) {
      return gettextCatalog.getString('N/A');
    } else {
      var time = moment.unix(input).format('MMM Do, H:mm:ss');
      return time;
    }
  };
}]);

app.filter('humanTimeShortest', ['gettextCatalog', function(gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null) {
      return gettextCatalog.getString('N/A');
    } else {
      return window.moment.unix(input).format('MMMM D, H:mm:ss');
    }
  };
}]);

app.filter('humanised', ['$window', function(window) {
    return function(input) {
      if ( input === undefined || input === null) {
        return '-';
      } else {
        var d = '';
        if (input < 60) {
          d = 's';
        }
        // return window.moment.duration(input, 'seconds').format('hh:mm:ss');
        return window.moment.duration(input, 'seconds').format('HH:mm:ss') + d;
      }
    };
}]);

app.filter('lastSeen', ['gettextCatalog', function(gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null) {
      return gettextCatalog.getString('N/A');
    } else {
      return window.moment.unix(input).format('MMM Do h:mm:ssa');
      // return window.moment.utc(input*1000).format('MMM Do h:mm:ssa');
    }
  };
}]);

app.filter('humanBoolean', ['$window', 'gettextCatalog', function(window, gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null) {
      return gettextCatalog.getString('N/A');
    } else {
      if ( input === true ) {
        return gettextCatalog.getString('Enabled');
      } else {
        return gettextCatalog.getString('Disabled');
      }
    }
  };
}]);

app.filter('booleanToggle', ['$window', 'gettextCatalog', function(window, gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null) {
      return gettextCatalog.getString('N/A');
    } else {
      if ( input === true ) {
        return gettextCatalog.getString('Enable');
      } else {
        return gettextCatalog.getString('Disable');
      }
    }
  };
}]);

app.filter('updateCreate', ['$window', 'gettextCatalog', function(window, gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null || input === '') {
      return gettextCatalog.getString('Create');
    } else {
      return gettextCatalog.getString('Update');
    }
  };
}]);

app.filter('emptyFilter', ['$window', 'gettextCatalog', function(window, gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null || input === '') {
      return gettextCatalog.getString('N/A');
    } else {
      return input;
    }
  };
}]);

app.filter('splashStatus', ['$window', 'gettextCatalog', function(window, gettextCatalog) {
  return function(online,status) {
    if ( online ) {
      if ( status == 'dnat' ) {
        return gettextCatalog.getString('Not logged in');
      } else {
        return gettextCatalog.getString('Online');
      }
    } else {
      return gettextCatalog.getString('Offline');
    }
  };
}]);

app.filter('roleFilter', ['gettextCatalog', function(gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null || input === '') {
      return gettextCatalog.getString('N/A');
    } else {
      input = input.toString();
      switch(input) {
        case '100':
          return gettextCatalog.getString('Owner');
        case '110':
          return gettextCatalog.getString('Administrator');
        case '120':
          return gettextCatalog.getString('Editor');
        case '130':
          return gettextCatalog.getString('Supporter');
        case '140':
          return gettextCatalog.getString('Observer');
        case '200':
          return gettextCatalog.getString('Brand Owner');
        case '201':
          return gettextCatalog.getString('Member');
        case '205':
          return gettextCatalog.getString('Brand Ambassador');
        case '210':
          return gettextCatalog.getString('Brand Super');
        default:
          return gettextCatalog.getString('N/A');
      }
    }
  };
}]);

app.filter('policyType', ['gettextCatalog', function(gettextCatalog) {
  return function(input) {
    if ( input !== '' ) {
      switch(input) {
        case 'layer2':
          return gettextCatalog.getString('WiFi');
        case 'layer3':
          return gettextCatalog.getString('Firewall');
        case 'splash':
          return gettextCatalog.getString('Splash');
      }
    } else {
      return input;
    }
  };
}]);

app.filter('toString', [function() {
  return function(input) {
    if ( input !== '' ) {
      return input.join(', ');
    } else {
      return input;
    }
  };
}]);

app.filter('translatablePolicy', ['gettextCatalog', function(gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null || input === '') {
      return gettextCatalog.getString('N/A');
    } else {
      switch(input) {
        case 'allow':
          return gettextCatalog.getString('allow');
        case 'block':
          return gettextCatalog.getString('block');
        case 'filter':
          return gettextCatalog.getString('filter');
      }
    }
  };
}]);

app.filter('translatableNetworkAccess', ['gettextCatalog', function(gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null || input === '') {
      return gettextCatalog.getString('N/A');
    } else {
      switch(input) {
        case 'password':
          return gettextCatalog.getString('password');
        case 'open':
          return gettextCatalog.getString('open');
        case 'radius':
          return gettextCatalog.getString('radius');
      }
    }
  };
}]);
<commit_msg>display the 802.1x option correctly in the networks list<commit_after>'use strict';

/* Filters */

var app = angular.module('myApp.locations.filters', []);

app.filter('humanData', function() {
  return function(bytes, precision) {
    if(bytes === 0 || bytes === '' || bytes === undefined || bytes === null) {
      return '0 Bytes';
    } else {
      var k = 1000;
      var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
      var i = Math.floor(Math.log(bytes) / Math.log(k));
      return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
    }
  };
});

app.filter('sentenceCase', function() {
  return function(input) {
    input = input || '';
    return input.charAt(0).toUpperCase() + input.slice(1);
  };
});

app.filter('titleCase', function() {
  return function(input) {
    if ( typeof input === 'string' ) {
      input = input || '';
      return input.replace(/_/g, ' ').replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    } else {
      return input;
    }
  };
});

app.filter('uppercase', function() {
  return function(input) {
    input = input || '';
    return input.toUpperCase();
  };
});

app.filter('lowercase', function() {
  return function(input) {
    input = input || '';
    return input.toLowerCase();
  };
});

app.filter('mbps', function() {
  return function(bytes, precision) {
    if (isNaN(parseFloat(bytes)) || !isFinite(bytes)) {
      return '-';
    }
    if (bytes === 0) {
      return '0 Mbps';
    }
    if (typeof precision === 'undefined') {
      precision = 1;
    }
    var units = ['Kbps', 'Mbps', 'Gbps', 'Tbps'],
      number = Math.floor(Math.log(bytes) / Math.log(1024));
    return (bytes / Math.pow(1024, Math.floor(number))).toFixed(precision) +  '' + units[number];
  };
});

app.filter('bitsToBytes', function() {
  return function(bits, precision) {
    if (isNaN(parseFloat(bits)) || !isFinite(bits)) {
      return '-';
    }
    if (bits === 0) {
      return '0 Mbps';
    }
    if (typeof precision === 'undefined') {
      precision = 1;
    }
    var i = Math.floor( Math.log(bits) / Math.log(1000) );
    return ( bits / Math.pow(1000, i) ).toFixed(2) * 1 + ' ' + ['b/s', 'Kb/s', 'Mb/s', 'Gb/s', 'Tb/s'][i];
  };
});

app.filter('humanDate', ['$window', 'gettextCatalog', function(window, gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null) {
      return gettextCatalog.getString('N/A');
    } else {
      return window.moment.unix(input).format('MMMM Do YYYY');
    }
  };
}]);

app.filter('humanTime', ['$window', 'gettextCatalog', function(window, gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null) {
      return gettextCatalog.getString('N/A');
    } else {
      return window.moment.unix(input).format('MMMM Do YYYY, h:mm:ss a');
    }
  };
}]);

app.filter('mysqlTime', ['$window', 'gettextCatalog', function(window, gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null) {
      return gettextCatalog.getString('N/A');
    } else {
      return window.moment(input).format('MMM Do, HH:mm:ss');
    }
  };
}]);

app.filter('humanTimeShort', ['gettextCatalog', function(gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null) {
      return gettextCatalog.getString('N/A');
    } else {
      var time = moment.unix(input).format('MMM Do, H:mm:ss');
      return time;
    }
  };
}]);

app.filter('humanTimeShortest', ['gettextCatalog', function(gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null) {
      return gettextCatalog.getString('N/A');
    } else {
      return window.moment.unix(input).format('MMMM D, H:mm:ss');
    }
  };
}]);

app.filter('humanised', ['$window', function(window) {
    return function(input) {
      if ( input === undefined || input === null) {
        return '-';
      } else {
        var d = '';
        if (input < 60) {
          d = 's';
        }
        // return window.moment.duration(input, 'seconds').format('hh:mm:ss');
        return window.moment.duration(input, 'seconds').format('HH:mm:ss') + d;
      }
    };
}]);

app.filter('lastSeen', ['gettextCatalog', function(gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null) {
      return gettextCatalog.getString('N/A');
    } else {
      return window.moment.unix(input).format('MMM Do h:mm:ssa');
      // return window.moment.utc(input*1000).format('MMM Do h:mm:ssa');
    }
  };
}]);

app.filter('humanBoolean', ['$window', 'gettextCatalog', function(window, gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null) {
      return gettextCatalog.getString('N/A');
    } else {
      if ( input === true ) {
        return gettextCatalog.getString('Enabled');
      } else {
        return gettextCatalog.getString('Disabled');
      }
    }
  };
}]);

app.filter('booleanToggle', ['$window', 'gettextCatalog', function(window, gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null) {
      return gettextCatalog.getString('N/A');
    } else {
      if ( input === true ) {
        return gettextCatalog.getString('Enable');
      } else {
        return gettextCatalog.getString('Disable');
      }
    }
  };
}]);

app.filter('updateCreate', ['$window', 'gettextCatalog', function(window, gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null || input === '') {
      return gettextCatalog.getString('Create');
    } else {
      return gettextCatalog.getString('Update');
    }
  };
}]);

app.filter('emptyFilter', ['$window', 'gettextCatalog', function(window, gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null || input === '') {
      return gettextCatalog.getString('N/A');
    } else {
      return input;
    }
  };
}]);

app.filter('splashStatus', ['$window', 'gettextCatalog', function(window, gettextCatalog) {
  return function(online,status) {
    if ( online ) {
      if ( status == 'dnat' ) {
        return gettextCatalog.getString('Not logged in');
      } else {
        return gettextCatalog.getString('Online');
      }
    } else {
      return gettextCatalog.getString('Offline');
    }
  };
}]);

app.filter('roleFilter', ['gettextCatalog', function(gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null || input === '') {
      return gettextCatalog.getString('N/A');
    } else {
      input = input.toString();
      switch(input) {
        case '100':
          return gettextCatalog.getString('Owner');
        case '110':
          return gettextCatalog.getString('Administrator');
        case '120':
          return gettextCatalog.getString('Editor');
        case '130':
          return gettextCatalog.getString('Supporter');
        case '140':
          return gettextCatalog.getString('Observer');
        case '200':
          return gettextCatalog.getString('Brand Owner');
        case '201':
          return gettextCatalog.getString('Member');
        case '205':
          return gettextCatalog.getString('Brand Ambassador');
        case '210':
          return gettextCatalog.getString('Brand Super');
        default:
          return gettextCatalog.getString('N/A');
      }
    }
  };
}]);

app.filter('policyType', ['gettextCatalog', function(gettextCatalog) {
  return function(input) {
    if ( input !== '' ) {
      switch(input) {
        case 'layer2':
          return gettextCatalog.getString('WiFi');
        case 'layer3':
          return gettextCatalog.getString('Firewall');
        case 'splash':
          return gettextCatalog.getString('Splash');
      }
    } else {
      return input;
    }
  };
}]);

app.filter('toString', [function() {
  return function(input) {
    if ( input !== '' ) {
      return input.join(', ');
    } else {
      return input;
    }
  };
}]);

app.filter('translatablePolicy', ['gettextCatalog', function(gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null || input === '') {
      return gettextCatalog.getString('N/A');
    } else {
      switch(input) {
        case 'allow':
          return gettextCatalog.getString('allow');
        case 'block':
          return gettextCatalog.getString('block');
        case 'filter':
          return gettextCatalog.getString('filter');
      }
    }
  };
}]);

app.filter('translatableNetworkAccess', ['gettextCatalog', function(gettextCatalog) {
  return function(input) {
    if ( input === undefined || input === null || input === '') {
      return gettextCatalog.getString('N/A');
    } else {
      switch(input) {
        case 'password':
          return gettextCatalog.getString('password');
        case 'open':
          return gettextCatalog.getString('open');
        case 'radius':
          return gettextCatalog.getString('802.1x');
      }
    }
  };
}]);
<|endoftext|>


<commit_before>define(['marionette', 'modules/shipment/views/movecontainer',
    'utils',
    'tpl!templates/shipment/containerli.html'], function(Marionette, MoveContainerView,
        utils, template) {

    var EmptyDewar = Marionette.ItemView.extend({
        tagName: 'li',
        template: '
No Containers for this dewar
'
    })

    var ContainerItemView = Marionette.ItemView.extend({
        tagName: 'li',
        template: template,

        events: {
            'click a.move': 'moveContainer',
            'click a.print': utils.signHandler,
        },

        templateHelpers: {
            APIURL: app.apiurl,
            PROP: app.prop,
        },

        moveContainer: function(e) {
            e.preventDefault()
            app.dialog.show(new MoveContainerView({ model: this.model }))
            this.listenTo(app.dialog.currentView, 'container:moved', this.triggerRefresh, this)
        },

        triggerRefresh: function() {
            this.trigger('container:moved')
        },
    })

    return Marionette.CollectionView.extend({
        className: 'containers',
        tagName: 'ul',
        childView: ContainerItemView,
        emptyView: EmptyDewar,

        childEvents: {
            'container:moved': 'triggerRefresh',
        },

        triggerRefresh: function() {
            this.trigger('refresh:dewars')
        },
    })

})<commit_msg>add container paginator<commit_after>define(['marionette', 'modules/shipment/views/movecontainer',
    'views/pages',
    'utils',
    'tpl!templates/shipment/containerli.html'], function(Marionette, MoveContainerView, PagesView,
        utils, template) {

    var EmptyDewar = Marionette.ItemView.extend({
        tagName: 'li',
        template: '
No Containers for this dewar
'
    })

    var ContainerItemView = Marionette.ItemView.extend({
        tagName: 'li',
        template: template,

        events: {
            'click a.move': 'moveContainer',
            'click a.print': utils.signHandler,
        },

        templateHelpers: {
            APIURL: app.apiurl,
            PROP: app.prop,
        },

        moveContainer: function(e) {
            e.preventDefault()
            app.dialog.show(new MoveContainerView({ model: this.model }))
            this.listenTo(app.dialog.currentView, 'container:moved', this.triggerRefresh, this)
        },

        triggerRefresh: function() {
            this.trigger('container:moved')
        },
    })

    var ContainersView = Marionette.CollectionView.extend({
        className: 'containers',
        tagName: 'ul',
        childView: ContainerItemView,
        emptyView: EmptyDewar,

        childEvents: {
            'container:moved': 'triggerRefresh',
        },

        triggerRefresh: function() {
            this.trigger('refresh:dewars')
        },
    })

    return Marionette.LayoutView.extend({
        template: _.template('

'),
        regions: {
            rcont: '.rcont',
            rpages: '.rpages',
        },

        onRender: function() {
            this.rcont.show(new ContainersView({ collection: this.getOption('collection') }))
            this.rpages.show(new PagesView({ collection: this.getOption('collection') }))
        }
    })

})<|endoftext|>