<commit_before>/*
 * Copyright (c) 2015 peeracle contributors
 *
 * 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.
 */

// @exclude
var Peeracle = {
  DataStream: require('./dataStream')
};
var fs = require('fs');
// @endexclude

/* eslint-disable */
Peeracle.FileDataStream = (function () {
  /* eslint-enable */
  /**
   * @class FileDataStream
   * @memberof {Peeracle}
   * @constructor
   * @implements {DataStream}
   * @param {DataStreamOptions} options
   * @property {Number} offset - Current stream's offset
   */
  function FileDataStream(options) {
    // @exclude
    var stat;
    this.options = options;
    if (typeof module === 'undefined') {
    // @endexclude
      this.handle = options;
    // @exclude
    }
    // @endexclude
    this.offset = 0;
    this.littleEndian = this.options.littleEndian ?
      this.options.littleEndian : false;
    // @exclude
    if ((typeof this.options) !== 'object') {
      throw new TypeError('options should be an object');
    }

    if (!this.options.hasOwnProperty('path') ||
      (typeof this.options.path) !== 'string') {
      throw new TypeError('options.path should be a string');
    }

    if (!this.options.hasOwnProperty('mode') ||
      (typeof this.options.mode) !== 'string') {
      this.options.mode = 'r';
    }

    try {
      this.handle = fs.openSync(this.options.path, this.options.mode);
      stat = fs.fstatSync(this.handle);
      this.length = stat.size;
    } catch (e) {
      throw e;
    }
    // @endexclude
  }

  FileDataStream.prototype = Object.create(Peeracle.DataStream.prototype);
  FileDataStream.prototype.constructor = FileDataStream;

  FileDataStream.prototype.close = function close() {
    // @exclude
    fs.closeSync(this.handle);
    // @endexclude
  };

  FileDataStream.prototype.length = function length() {
    return this.length;
  };

  FileDataStream.prototype.tell = function tell() {
    return this.offset;
  };

  FileDataStream.prototype.seek = function seek(position) {
    this.offset = position;
  };

  FileDataStream.prototype.read = function read(length, cb) {
    var _this = this;

    this.peek(length, function peekCb(error, bytes, count) {
      if (error) {
        cb(error);
        return;
      }

      _this.offset += count;
      cb(null, bytes, count);
    });
  };

  FileDataStream.prototype.readChar = function readChar(cb) {
    this.read(1, function readCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes);
      cb(null, dataView.getInt8(), length);
    });
  };

  FileDataStream.prototype.readByte = function readByte(cb) {
    this.read(1, function readCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes);
      cb(null, dataView.getUint8(), length);
    });
  };

  FileDataStream.prototype.readShort = function readShort(cb) {
    this.read(2, function readCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes);
      cb(null, dataView.getInt16(), length);
    });
  };

  FileDataStream.prototype.readUShort = function readUShort(cb) {
    this.read(2, function readCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes);
      cb(null, dataView.getUint16(), length);
    });
  };

  FileDataStream.prototype.readInteger = function readInteger(cb) {
    this.read(4, function readCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes);
      cb(null, dataView.getInt32(), length);
    });
  };

  FileDataStream.prototype.readUInteger = function readUInteger(cb) {
    this.read(4, function readCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes);
      cb(null, dataView.getUint32(), length);
    });
  };

  FileDataStream.prototype.readFloat = function readFloat(cb) {
    this.read(4, function readCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes);
      cb(null, dataView.getFloat32(), length);
    });
  };

  FileDataStream.prototype.readDouble = function readDouble(cb) {
    this.read(4, function readCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes);
      cb(null, dataView.getFloat64(), length);
    });
  };

  FileDataStream.prototype.readString = function readString(cb) {
    var stringLength = 0;
    var str = '';

    this.readChar(function peekCharCb(error, value, length) {
      if (error) {
        cb(error);
        return;
      }

      if (!value || !length) {
        cb(null, str, stringLength);
        return;
      }

      str += value;
      ++stringLength;
      this.readChar(peekCharCb);
    });
  };

  FileDataStream.prototype.peek = function peek(length, cb) {
    var reader;
    // @exclude
    if (typeof module !== 'undefined') {
      fs.read(this.handle, new Buffer(length), 0, length, this.offset,
        function peekCb(error, bytesRead, buffer) {
          if (error) {
            cb(error);
            return;
          }

          cb(null, new Uint8Array(buffer), bytesRead);
        });
      return;
    }
    // @endexclude
    reader = new FileReader();
    reader.onabort = function onabortCb() {
      cb(new Error('Aborted'));
    };
    reader.onerror = function onerrorCb(e) {
      cb(e);
    };
    reader.onloadend = function onloadendCb(e) {
      var bytes = new Uint8Array(e.target.result);
      cb(null, bytes, bytes.length);
    };
    reader.readAsArrayBuffer(this.handle.slice(this.offset,
      this.offset + length));
  };

  FileDataStream.prototype.peekChar = function peekChar(cb) {
    this.peek(1, function peekCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes);
      cb(null, dataView.getInt8(), length);
    });
  };

  FileDataStream.prototype.peekByte = function peekByte(cb) {
    this.peek(1, function peekCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes);
      cb(null, dataView.getUint8(), length);
    });
  };

  FileDataStream.prototype.peekShort = function peekShort(cb) {
    this.peek(2, function peekCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes);
      cb(null, dataView.getInt16(), length);
    });
  };

  FileDataStream.prototype.peekUShort = function peekUShort(cb) {
    this.peek(2, function peekCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes);
      cb(null, dataView.getUint16(), length);
    });
  };

  FileDataStream.prototype.peekInteger = function peekInteger(cb) {
    this.peek(4, function peekCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes);
      cb(null, dataView.getInt32(), length);
    });
  };

  FileDataStream.prototype.peekUInteger = function peekUInteger(cb) {
    this.peek(4, function peekCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes);
      cb(null, dataView.getUint32(), length);
    });
  };

  FileDataStream.prototype.peekFloat = function peekFloat(cb) {
    this.peek(4, function peekCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes);
      cb(null, dataView.getFloat32(), length);
    });
  };

  FileDataStream.prototype.peekDouble = function peekDouble(cb) {
    this.peek(8, function peekCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes);
      cb(null, dataView.getFloat64(), length);
    });
  };

  FileDataStream.prototype.peekString = function peekString(cb) {
    var stringLength = 0;
    var str = '';

    this.peekChar(function peekCb(error, value, length) {
      if (error) {
        cb(error);
        return;
      }

      if (!value || !length) {
        cb(null, str, stringLength);
        return;
      }

      str += value;
      ++stringLength;
      this.readChar(peekCb);
    });
  };

  FileDataStream.prototype.write = function write(bytes, cb) {
    cb(null);
    return bytes;
  };

  FileDataStream.prototype.writeChar = function writeChar(value, cb) {
    cb(null);
    return value;
  };

  FileDataStream.prototype.writeByte = function writeByte(value, cb) {
    cb(null);
    return value;
  };

  FileDataStream.prototype.writeShort = function writeShort(value, cb) {
    cb(null);
    return value;
  };

  FileDataStream.prototype.writeUShort = function writeUShort(value, cb) {
    cb(null);
    return value;
  };

  FileDataStream.prototype.writeInteger = function writeInteger(value, cb) {
    cb(null);
    return value;
  };

  FileDataStream.prototype.writeUInteger = function writeUInteger(value, cb) {
    cb(null);
    return value;
  };

  FileDataStream.prototype.writeFloat = function writeFloat(value, cb) {
    cb(null);
    return value;
  };

  FileDataStream.prototype.writeDouble = function writeDouble(value, cb) {
    cb(null);
    return value;
  };

  FileDataStream.prototype.writeString = function writeString(str, cb) {
    cb(null);
    return str;
  };

  return FileDataStream;
})();

// @exclude
module.exports = Peeracle.FileDataStream;
// @endexclude
<commit_msg>FileDataStream: Fix file reading, add writing support<commit_after>/*
 * Copyright (c) 2015 peeracle contributors
 *
 * 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.
 */

// @exclude
var Peeracle = {
  DataStream: require('./dataStream')
};
var fs = require('fs');
// @endexclude

/* eslint-disable */
Peeracle.FileDataStream = (function () {
  /* eslint-enable */
  /**
   * @class FileDataStream
   * @memberof {Peeracle}
   * @constructor
   * @implements {DataStream}
   * @param {DataStreamOptions} options
   * @property {Number} offset - Current stream's offset
   */
  function FileDataStream(options) {
    // @exclude
    var stat;
    this.options = options;
    if (typeof module === 'undefined') {
    // @endexclude
      this.handle = options;
    // @exclude
    }
    // @endexclude
    this.offset = 0;
    this.littleEndian = this.options.littleEndian ?
      this.options.littleEndian : false;
    // @exclude
    if ((typeof this.options) !== 'object') {
      throw new TypeError('options should be an object');
    }

    if (!this.options.hasOwnProperty('path') ||
      (typeof this.options.path) !== 'string') {
      throw new TypeError('options.path should be a string');
    }

    if (!this.options.hasOwnProperty('mode') ||
      (typeof this.options.mode) !== 'string') {
      this.options.mode = 'r';
    }

    try {
      this.handle = fs.openSync(this.options.path, this.options.mode);
      stat = fs.fstatSync(this.handle);
      this.length = stat.size;
    } catch (e) {
      throw e;
    }
    // @endexclude
  }

  FileDataStream.prototype = Object.create(Peeracle.DataStream.prototype);
  FileDataStream.prototype.constructor = FileDataStream;

  FileDataStream.prototype.close = function close() {
    // @exclude
    fs.closeSync(this.handle);
    // @endexclude
  };

  FileDataStream.prototype.length = function length() {
    return this.length;
  };

  FileDataStream.prototype.tell = function tell() {
    return this.offset;
  };

  FileDataStream.prototype.seek = function seek(position) {
    this.offset = position;
  };

  FileDataStream.prototype.read = function read(length, cb) {
    var _this = this;

    this.peek(length, function peekCb(error, bytes, count) {
      if (error) {
        cb(error);
        return;
      }

      _this.offset += count;
      cb(null, bytes, count);
    });
  };

  FileDataStream.prototype.readChar = function readChar(cb) {
    this.read(1, function readCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes.buffer);
      cb(null, dataView.getInt8(), length);
    });
  };

  FileDataStream.prototype.readByte = function readByte(cb) {
    this.read(1, function readCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes.buffer);
      cb(null, dataView.getUint8(), length);
    });
  };

  FileDataStream.prototype.readShort = function readShort(cb) {
    var _this = this;
    this.read(2, function readCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes.buffer);
      cb(null, dataView.getInt16(0, _this.littleEndian), length);
    });
  };

  FileDataStream.prototype.readUShort = function readUShort(cb) {
    var _this = this;
    this.read(2, function readCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes.buffer);
      cb(null, dataView.getUint16(0, _this.littleEndian), length);
    });
  };

  FileDataStream.prototype.readInteger = function readInteger(cb) {
    var _this = this;
    this.read(4, function readCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes.buffer);
      cb(null, dataView.getInt32(0, _this.littleEndian), length);
    });
  };

  FileDataStream.prototype.readUInteger = function readUInteger(cb) {
    var _this = this;
    this.read(4, function readCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes.buffer);
      cb(null, dataView.getUint32(0, _this.littleEndian), length);
    });
  };

  FileDataStream.prototype.readFloat = function readFloat(cb) {
    var _this = this;
    this.read(4, function readCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes.buffer);
      cb(null, dataView.getFloat32(0, _this.littleEndian), length);
    });
  };

  FileDataStream.prototype.readDouble = function readDouble(cb) {
    var _this = this;
    this.read(4, function readCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes.buffer);
      cb(null, dataView.getFloat64(0, _this.littleEndian), length);
    });
  };

  FileDataStream.prototype.readString = function readString(cb) {
    var stringLength = 0;
    var str = '';

    this.readChar(function peekCharCb(error, value, length) {
      if (error) {
        cb(error);
        return;
      }

      if (!value || !length) {
        cb(null, str, stringLength);
        return;
      }

      str += value;
      ++stringLength;
      this.readChar(peekCharCb);
    });
  };

  FileDataStream.prototype.peek = function peek(length, cb) {
    var reader;
    // @exclude
    if (typeof module !== 'undefined') {
      fs.read(this.handle, new Buffer(length), 0, length, this.offset,
        function peekCb(error, bytesRead, buffer) {
          if (error) {
            cb(error);
            return;
          }

          cb(null, new Uint8Array(buffer), bytesRead);
        });
      return;
    }
    // @endexclude
    reader = new FileReader();
    reader.onabort = function onabortCb() {
      cb(new Error('Aborted'));
    };
    reader.onerror = function onerrorCb(e) {
      cb(e);
    };
    reader.onloadend = function onloadendCb(e) {
      var bytes = new Uint8Array(e.target.result);
      cb(null, bytes, bytes.length);
    };
    reader.readAsArrayBuffer(this.handle.slice(this.offset,
      this.offset + length));
  };

  FileDataStream.prototype.peekChar = function peekChar(cb) {
    this.peek(1, function peekCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes.buffer);
      cb(null, dataView.getInt8(), length);
    });
  };

  FileDataStream.prototype.peekByte = function peekByte(cb) {
    this.peek(1, function peekCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes.buffer);
      cb(null, dataView.getUint8(), length);
    });
  };

  FileDataStream.prototype.peekShort = function peekShort(cb) {
    var _this = this;
    this.peek(2, function peekCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes.buffer);
      cb(null, dataView.getInt16(0, _this.littleEndian), length);
    });
  };

  FileDataStream.prototype.peekUShort = function peekUShort(cb) {
    var _this = this;
    this.peek(2, function peekCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes.buffer);
      cb(null, dataView.getUint16(0, _this.littleEndian), length);
    });
  };

  FileDataStream.prototype.peekInteger = function peekInteger(cb) {
    var _this = this;
    this.peek(4, function peekCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes.buffer);
      cb(null, dataView.getInt32(0, _this.littleEndian), length);
    });
  };

  FileDataStream.prototype.peekUInteger = function peekUInteger(cb) {
    var _this = this;
    this.peek(4, function peekCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes.buffer);
      cb(null, dataView.getUint32(0, _this.littleEndian), length);
    });
  };

  FileDataStream.prototype.peekFloat = function peekFloat(cb) {
    var _this = this;
    this.peek(4, function peekCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes.buffer);
      cb(null, dataView.getFloat32(0, _this.littleEndian), length);
    });
  };

  FileDataStream.prototype.peekDouble = function peekDouble(cb) {
    var _this = this;
    this.peek(8, function peekCb(error, bytes, length) {
      /** @type {DataView} */
      var dataView;

      if (error) {
        cb(error);
        return;
      }

      dataView = new DataView(bytes.buffer);
      cb(null, dataView.getFloat64(0, _this.littleEndian), length);
    });
  };

  FileDataStream.prototype.peekString = function peekString(cb) {
    var stringLength = 0;
    var str = '';

    this.peekChar(function peekCb(error, value, length) {
      if (error) {
        cb(error);
        return;
      }

      if (!value || !length) {
        cb(null, str, stringLength);
        return;
      }

      str += value;
      ++stringLength;
      this.readChar(peekCb);
    });
  };

  FileDataStream.prototype.write = function write(bytes, cb) {
    // @exclude
    var _this = this;
    fs.write(this.handle, new Buffer(bytes), 0, bytes.length, this.offset,
      function writeCb(error, written) {
        if (error) {
          cb(error);
          return;
        }

        _this.offset += written;
        cb(null, written);
      });
    // @endexclude
  };

  FileDataStream.prototype.writeChar = function writeChar(value, cb) {
    // @exclude
    /** @type {DataView} */
    var dataView;
    var bytes = new Uint8Array(1);

    dataView = new DataView(bytes.buffer);
    dataView.setInt8(0, value);
    this.write(bytes, cb);
    // @endexclude
  };

  FileDataStream.prototype.writeByte = function writeByte(value, cb) {
    // @exclude
    /** @type {DataView} */
    var dataView;
    var bytes = new Uint8Array(1);

    dataView = new DataView(bytes.buffer);
    dataView.setUint8(0, value);
    this.write(bytes, cb);
    // @endexclude
  };

  FileDataStream.prototype.writeShort = function writeShort(value, cb) {
    // @exclude
    /** @type {DataView} */
    var dataView;
    var bytes = new Uint8Array(2);

    dataView = new DataView(bytes.buffer);
    dataView.setInt16(0, value, this.littleEndian);
    this.write(bytes, cb);
    // @endexclude
  };

  FileDataStream.prototype.writeUShort = function writeUShort(value, cb) {
    // @exclude
    /** @type {DataView} */
    var dataView;
    var bytes = new Uint8Array(2);

    dataView = new DataView(bytes.buffer);
    dataView.setUint16(0, value, this.littleEndian);
    this.write(bytes, cb);
    // @endexclude
  };

  FileDataStream.prototype.writeInteger = function writeInteger(value, cb) {
    // @exclude
    /** @type {DataView} */
    var dataView;
    var bytes = new Uint8Array(4);

    dataView = new DataView(bytes.buffer);
    dataView.setInt32(0, value, this.littleEndian);
    this.write(bytes, cb);
    // @endexclude
  };

  FileDataStream.prototype.writeUInteger = function writeUInteger(value, cb) {
    // @exclude
    /** @type {DataView} */
    var dataView;
    var bytes = new Uint8Array(4);

    dataView = new DataView(bytes.buffer);
    dataView.setUint32(0, value, this.littleEndian);
    this.write(bytes, cb);
    // @endexclude
  };

  FileDataStream.prototype.writeFloat = function writeFloat(value, cb) {
    // @exclude
    /** @type {DataView} */
    var dataView;
    var bytes = new Uint8Array(4);

    dataView = new DataView(bytes.buffer);
    dataView.setFloat32(0, value, this.littleEndian);
    this.write(bytes, cb);
    // @endexclude
  };

  FileDataStream.prototype.writeDouble = function writeDouble(value, cb) {
    // @exclude
    /** @type {DataView} */
    var dataView;
    var bytes = new Uint8Array(8);

    dataView = new DataView(bytes.buffer);
    dataView.setFloat64(0, value, this.littleEndian);
    this.write(bytes, cb);
    // @endexclude
  };

  FileDataStream.prototype.writeString = function writeString(str, cb) {
    // @exclude
    var index = 0;
    var length = str.length;
    var bytes = new Uint8Array(length + 1);

    while (index < length) {
      bytes.set([str.charCodeAt(index)], index);
      ++index;
    }

    bytes.set([0], index);
    this.write(bytes, cb);
    // @endexclude
  };

  return FileDataStream;
})();

// @exclude
module.exports = Peeracle.FileDataStream;
// @endexclude
<|endoftext|>


<commit_before>// Twitter
window.twttr = (function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0],
    t = window.twttr || {};
  if (d.getElementById(id)) return t;
  js = d.createElement(s);
  js.id = id;
  js.src = "https://platform.twitter.com/widgets.js";
  fjs.parentNode.insertBefore(js, fjs);

  t._e = [];
  t.ready = function(f) {
    t._e.push(f);
  };

  return t;
}(document, "script", "twitter-wjs"));

// Facebook
(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.9";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));<commit_msg>Add animations by Animate.css<commit_after>// Twitter
window.twttr = (function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0],
    t = window.twttr || {};
  if (d.getElementById(id)) return t;
  js = d.createElement(s);
  js.id = id;
  js.src = "https://platform.twitter.com/widgets.js";
  fjs.parentNode.insertBefore(js, fjs);

  t._e = [];
  t.ready = function(f) {
    t._e.push(f);
  };

  return t;
}(document, "script", "twitter-wjs"));

// Facebook
(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.9";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

// Animate.css
$('.home').addClass('animated fadeInUp');
$('.post-header').addClass('animated fadeIn');
$('.post-content').addClass('animated fadeIn');
$('.blog').addClass('animated fadeIn');
$('.email').addClass('animated fadeIn');
$('.social-media').addClass('animated zoomIn');<|endoftext|>


<commit_before>function test(){
	$('#green').click(function(){
});
	$('#red').click(function(){

}
<commit_msg>Mise en place de triggers<commit_after>function test(){
	$('#green').click(function(){
});
	$('#red').click(function(){

});

}
<|endoftext|>


<commit_before>//global vars
//

var numPosts = 0;
var craigslistItems = new Array();
var ebayHighPrice = 0;
var ebayAvgPrice = 0;
var ebayLowPrice = 0;

var clComplete = false;
var ebayComplete = false;

function search(_query){
    findCraigslistProducts(_query);
    findEbayItem(_query);

}

//generates a post to append to the list
//then appends it to the list
// variables:
//  _link: standard href stuff, the entire post will link here so choose carefully
//  _price: the price to purchase the item
//  _title: title of the post
function generatePost(_link, _price, _title){

    console.log('generate post called');

    //collapse code
    $("#list").append('

' + '$' + _price + ' - ' + _title +'

');

    var body = 'Link to Craigslist post';
    body += '
High: $' + ebayHighPrice + '
';
    body += '
Average: $' + ebayAvgPrice + '
';
    body += '
Low: $' + ebayLowPrice + '
';
    body += '
Gas expenses: $x
';
    body += '
Profit: $' + (ebayAvgPrice - _price) + '
';

    //item body
    $("#list").append('

' + body + '
<button class="btn" data-toggle="collapse" data-parent="#accordion" href="#collapse' + numPosts + '">Close</button>

');

    $("#list").append('');

    numPosts++;
}

//////
//
//   START CRAIGSLIST STUFF
//
//////
function findCraigslistProducts(search){
    $.ajax({
        type: "GET",
        url: "assets/php/proxy.php?search=" + search,
        dataType: "xml",
        success: parseXml
     });
}

function parseXml(xml) {
    console.log(xml);
    $(xml).find("item").each(function() {
        var title = $(this).find("title").text();
        var link = $(this).find("link").text();
        //parse title down so it's not super long
        var prettyTitle = title.substr(0, title.indexOf("$"));
        //parse price out of title
        var price = title.substr(title.indexOf("$"), title.indexOf(" ") + 1);

        var priceInt = parseInt(price.substr(1));

        var items = new Array();
        //this will get rid of TRADE items
        if ( priceInt >= 0 ) {
            generatePost(link, priceInt, prettyTitle);
            items.push( new Object(link, priceInt, prettyTitle));

        }
        //console.log(items);
        craigslistItems = items;
        clComplete = true;

    });
}

//////
//
//   END CRAIGSLIST STUFF
//
//////

//////
//
//   START EBAY STUFF
//
//////
function findEbayItem(search){

           $.ajax({
		type: "GET",
		url: "assets/php/proxyEbay.php?search=" + search,
		dataType: "xml",
		success: parseEbayXml
	     });

        }

	function parseEbayXml(xml) {
	console.log(xml);

	var numItems = 0;
	var price = 0;
	var maxPrice = 0;
	var minPrice = 99999999;

	$(xml).find("item").each(function() {
	    var condition =  $(this).find("conditionDisplayName").text();
	    //console.log(condition);
	    if((condition == 'New') || (condition == 'New other (see details)') || (condition == 'Manufacturer refurbished') || (condition == 'Used')){
		var currentPrice = $(this).find("currentPrice").text();
		currentPrice = parseInt(currentPrice);

		if(currentPrice > maxPrice){
		    maxPrice = currentPrice;
		}
		if(currentPrice < minPrice){
		    minPrice = currentPrice;
		}
		price += currentPrice;
		numItems++;
	    }
	});
	var avgPrice = price / numItems;

        ebayHighPrice = maxPrice;
        ebayAvgPrice = avgPrice;
        ebayLowPrice = minPrice;

        $('#list').find("highPrice").append(ebayHighPrice);
        ebayComplete = true;
	//console.log('Highest price: ' + maxPrice);
	//console.log('Average price: ' + avgPrice);
	//console.log('Lowest price: ' + minPrice);

	//console.log(numItems);

	//$('#content').append('
Highest price: '+ maxPrice + '
');
	//$('#content').append('
Average price: '+ avgPrice + '
');
	//$('#content').append('
Lowest price: '+ minPrice + '
');
}
//////
//
//   END EBAY STUFF
//
//////

<commit_msg>syntax<commit_after>//global vars
//

var numPosts = 0;
var craigslistItems = new Array();
var ebayHighPrice = 0;
var ebayAvgPrice = 0;
var ebayLowPrice = 0;

var clComplete = false;
var ebayComplete = false;

function search(_query){
    findCraigslistProducts(_query);
    findEbayItem(_query);

}

//generates a post to append to the list
//then appends it to the list
// variables:
//  _link: standard href stuff, the entire post will link here so choose carefully
//  _price: the price to purchase the item
//  _title: title of the post
function generatePost(_link, _price, _title){

    console.log('generate post called');

    //collapse code
    $("#list").append('

' + '$' + _price + ' - ' + _title +'

');

    var body = 'Link to Craigslist post';
    body += '
High: $' + ebayHighPrice + '
';
    body += '
Average: $' + ebayAvgPrice + '
';
    body += '
Low: $' + ebayLowPrice + '
';
    body += '
Gas expenses: $x
';
    body += '
Profit: $' + (ebayAvgPrice - _price) + '
';

    //item body
    $("#list").append('

' + body + '
<button class="btn" data-toggle="collapse" data-parent="#accordion" href="#collapse' + numPosts + '">Close</button>

');

    $("#list").append('');

    numPosts++;
}

//////
//
//   START CRAIGSLIST STUFF
//
//////
function findCraigslistProducts(search){
    $.ajax({
        type: "GET",
        url: "assets/php/proxy.php?search=" + search,
        dataType: "xml",
        success: parseXml
     });
}

function parseXml(xml) {
    console.log(xml);
    $(xml).find("item").each(function() {
        var title = $(this).find("title").text();
        var link = $(this).find("link").text();
        //parse title down so it's not super long
        var prettyTitle = title.substr(0, title.indexOf("$"));
        //parse price out of title
        var price = title.substr(title.indexOf("$"), title.indexOf(" ") + 1);

        var priceInt = parseInt(price.substr(1));

        var items = new Array();
        //this will get rid of TRADE items
        if ( priceInt >= 0 ) {
            generatePost(link, priceInt, prettyTitle);
            items.push( new Object(link, priceInt, prettyTitle));

        }
        //console.log(items);
        craigslistItems = items;
        clComplete = true;

    });
}

//////
//
//   END CRAIGSLIST STUFF
//
//////

//////
//
//   START EBAY STUFF
//
//////
function findEbayItem(search){

           $.ajax({
		type: "GET",
		url: "assets/php/proxyEbay.php?search=" + search,
		dataType: "xml",
		success: parseEbayXml
	     });

        }

	function parseEbayXml(xml) {
	console.log(xml);

	var numItems = 0;
	var price = 0;
	var maxPrice = 0;
	var minPrice = 99999999;

	$(xml).find("item").each(function() {
	    var condition =  $(this).find("conditionDisplayName").text();
	    //console.log(condition);
	    if((condition == 'New') || (condition == 'New other (see details)') || (condition == 'Manufacturer refurbished') || (condition == 'Used')){
		var currentPrice = $(this).find("currentPrice").text();
		currentPrice = parseInt(currentPrice);

		if(currentPrice > maxPrice){
		    maxPrice = currentPrice;
		}
		if(currentPrice < minPrice){
		    minPrice = currentPrice;
		}
		price += currentPrice;
		numItems++;
	    }
	});
	var avgPrice = price / numItems;

        ebayHighPrice = maxPrice;
        ebayAvgPrice = avgPrice;
        ebayLowPrice = minPrice;

        $('#list').find("highPrice").each(function(){
            $(this).append(ebayHighPrice);
        });

        ebayComplete = true;
	//console.log('Highest price: ' + maxPrice);
	//console.log('Average price: ' + avgPrice);
	//console.log('Lowest price: ' + minPrice);

	//console.log(numItems);

	//$('#content').append('
Highest price: '+ maxPrice + '
');
	//$('#content').append('
Average price: '+ avgPrice + '
');
	//$('#content').append('
Lowest price: '+ minPrice + '
');
}
//////
//
//   END EBAY STUFF
//
//////

<|endoftext|>


<commit_before>var accountSid = ''; // Fill this in when account is made.
var authToken = "{{ auth_token }}"; // Not sure what this is, do something here.
var client = require('twilio')(accountSid, authToken);

var app = require('express'); // Move this if necessary.
app.POST('/receive',function() {});

client.messages(message.sid).get(function(err, message) {
    var number_regex = /[1234567890]{1,50}/; // Change the latter number depending on the math constraints.
    var numbers = message.body.match(number_regex); // match should return an array with the matches in them, if any.
    if (numbers.length < 2) {
        client.messages.create({
            body: "You did not send enough numbers. Please try again.",
            to: message.from, // Not sure if this is correct, and the documentation doesn't seem to help.
            from: "" // Put number here.
        }, function(err, message) {
            process.stdout.write(message.sid); // Change this if needed; it's what was in the example on the Twilio documentation.
    } else if (numbers.length > 2) {
        client.messages.create({
        /* Right now, I'm assuming that we only want two numbers.
        Alternatively, we could just take the first two that they send in.
        If we want to do that, just change it. */
            body: "You sent too many numbers. Please try again.",
            to: message.from, // Again, unsure if this is correct.
            from: "" // Put number here.
        }, function(err, message) {
            process.stdout.write(message.sid);
    } else {} // Do something here.
});
<commit_msg>Fixed parentheses; changed a comment.<commit_after>var accountSid = ''; // Fill this in when account is made.
var authToken = "{{ auth_token }}"; // Not sure what this is, do something here.
var client = require('twilio')(accountSid, authToken);

var app = require('express'); // Move this if necessary.
app.POST('/receive',function() {});

client.messages(message.sid).get(function(err, message) {
    var number_regex = /[1234567890]{1,50}/; // Change the latter number depending on the math constraints.
    var numbers = message.body.match(number_regex); // match should return an array with the matches in them, if any.
    if (numbers.length < 2) {
        client.messages.create({
            body: "You did not send enough numbers. Please try again.",
            to: message.from, // Not sure if this is correct, and the documentation doesn't seem to help.
            from: "" // Put number here.
        }, function(err, message) {
            process.stdout.write(message.sid); } // Change this if needed; it was in the Twilio documentation.
    } else if (numbers.length > 2) {
        client.messages.create({
        /* Right now, I'm assuming that we only want two numbers.
        Alternatively, we could just take the first two that they send in.
        If we want to do that, just change it. */
            body: "You sent too many numbers. Please try again.",
            to: message.from, // Again, unsure if this is correct.
            from: "" // Put number here.
        }, function(err, message) {
            process.stdout.write(message.sid); }
    } else {} // Do something here.
});
<|endoftext|>


<commit_before>const BASE_URL = 'https://api.datausa.io/api/?show=geo&sumlevel=state&required=pop,age,income'
var states; // Global object that holds state information

// Loads state object
$(document).ready(function($) {
  $.ajax({
    url: 'https://raw.githubusercontent.com/takatanium/UCB-Project1/master/assets/json/states.json',
    dataType: 'json',
    method: 'GET',
    success: function(res) {
      states = res;

      for (let i = 0; i < states.length; i++) {
        states[i]['population'] = {}
        states[i]['median_age'] = {}
        states[i]['median_income'] = {}
      }
      getData();
    },
    error: function(e) {
      console.log(e);
    }
  })
});

/**
 * [getData description]
 * @return {[type]} [description]
 */
function getData() {
  $.ajax({
    url: BASE_URL,
    dataType: 'json',
    method: 'GET',
    success: function(res) {

      for(let i = 0; i < res.data.length; i++) {
        let id = res.data[i][1];

        for(let j = 0; j < states.length; j++) {
          if (id == states[j].id) {

            let year = res.data[i][0];

            if (!states[j]['population'].hasOwnProperty(res.data[i][0])) {
              states[j]['population'][year] = res.data[i][2];
            }

            if (!states[j]['median_age'].hasOwnProperty(res.data[i][0])) {
              states[j]['median_age'][year] = res.data[i][3];
            }

            if (!states[j]['median_income'].hasOwnProperty(res.data[i][0])) {
              states[j]['median_income'][year] = res.data[i][4];
            }
          }
        }
      }
      // end result

      console.log(states);
      createAllDivs();
      $.scrollify.move('#landing');
      $('#landing-page').fadeTo(2000, 1);
      initiateInput('landing');
      popDataInfo();
    },
    error: function(e) {
      console.log(e);
    }
  })
}

/**
 * [getWikipedia description]
 * @param  {[type]} state [description]
 * @return {[type]}       [description]
 */
function getWikipedia(state) {
  let BASEURL = 'https://api.wikipedia.com'
  let url = BASEURL + '?' + $.param({
    action: 'query',
    prop: 'extracts',
    exintro: null,
    explaintext: null,
    titles: state,
    format: 'json'
  });

  console.log(url);

  $.ajax({
    url: url,
    dataType: 'json',
    method: 'GET',
    success: function(res) {
      console.log(res);
    },
    error: function(e) {
      console.log(e);
    }
  })
}
<commit_msg>minor code fixes<commit_after>const BASE_URL = 'https://api.datausa.io/api/?show=geo&sumlevel=state&required=pop,age,income'
var states; // Global object that holds state information

// Loads state object
$(document).ready(function($) {

  getWikipedia("Rhode Island");

  $.ajax({
    url: 'https://raw.githubusercontent.com/takatanium/UCB-Project1/master/assets/json/states.json',
    dataType: 'json',
    method: 'GET',
    success: function(res) {
      states = res;

      for (let i = 0; i < states.length; i++) {
        states[i]['population'] = {}
        states[i]['median_age'] = {}
        states[i]['median_income'] = {}
      }
      getData();
    },
    error: function(e) {
      console.log(e);
    }
  })
});

/**
 * [getData description]
 * @return {[type]} [description]
 */
function getData() {
  $.ajax({
    url: BASE_URL,
    dataType: 'json',
    method: 'GET',
    success: function(res) {

      for (let i = 0; i < res.data.length; i++) {
        let id = res.data[i][1];

        for (let j = 0; j < states.length; j++) {
          if (id == states[j].id) {

            let year = res.data[i][0];

            if (!states[j]['population'].hasOwnProperty(year)) {
              states[j]['population'][year] = res.data[i][2];
            }

            if (!states[j]['median_age'].hasOwnProperty(year)) {
              states[j]['median_age'][year] = res.data[i][3];
            }

            if (!states[j]['median_income'].hasOwnProperty(year)) {
              states[j]['median_income'][year] = res.data[i][4];
            }
          }
        }
      }

      console.log(states);
      createAllDivs();
      $.scrollify.move('#landing');
      $('#landing-page').fadeTo(2000, 1);
      initiateInput('landing');
      popDataInfo();
    },
    error: function(e) {
      console.log(e);
    }
  })
}

/**
 * Formats a received Wikipedia Response Object
 * to make it ready for immediate insertion into DOM
 * @param  {obj} data Response object
 * @return {string}      Formatted string
 */
function formatWikipedia(data) {
  console.log(data);

  console.log(data.query.pages)

  for (var key in data.query.pages) {
    console.log(key);
  }
}

// TODO: specify the calls to be only of a category
// so calls return the expected articles back.

/**
 * Returns a Wikipedia API response object
 * @param  {string} state The state we are retrieving data for
 * @return {object}       Wikipedia API response
 */
function getWikipedia(state) {
  let BASEURL = 'https://en.wikipedia.org/w/api.php'
  let url = BASEURL + '?' + $.param({
    action: 'query',
    prop: 'extracts',
    exintro: null,
    explaintext: null,
    titles: state,
    format: 'json'
  });

  console.log(url);

  $.ajax({
    url: url,
    dataType: 'jsonp',
    crossDomain: true,
    method: 'GET',
    success: function(res) {
      formatWikipedia(res);

    },
    error: function(e) {
      console.log(e);
    }
  })
}
<|endoftext|>


<commit_before>var LOAD_AT_A_TIME = 25;

function httpGetAsync(theUrl, callback)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true);
    xmlHttp.send(null);
}

function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

function loadMore() {
    var image_block = document.getElementById("images");
    let count = image_block.children.length;
    var query = "/more?offset="+count;

    if (window.location.pathname.startsWith("/search")) {
        query = query + "&q=" + getUrlParameter("q");
    }

    httpGetAsync(query, function(text){
        var body = JSON.parse(text);
        if (body.length < LOAD_AT_A_TIME) {
            document.getElementById("more-button").parentNode.removeChild(document.getElementById("more-button"))
        }

        body.forEach(function(image) {
            var link = document.createElement("a");
            link.href = "/show/"+image.link;
            var im = document.createElement("div");
            im.title = image.tags.join(" ");
            im.className = "thumbnail";
            im.style.backgroundImage = "url(/images/"+image.name+")";

            link.appendChild(im);
            image_block.appendChild(link);
        });
    });
}

function showUploadForm() {
    var form = document.getElementById("upload-form");

    if (form.style.bottom != "7%") {
        form.style.bottom = "7%"
    } else {
        form.style.bottom = "-100%"
    }
}

window.onload = function() {
    loadMore();

    document.getElementById("tag-search-field").value = getUrlParameter("q");
}
<commit_msg>Тэги снова сбоку, теперь нормально<commit_after>var LOAD_AT_A_TIME = 25;
var TAGS_SET = false;

function httpGetAsync(theUrl, callback)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true);
    xmlHttp.send(null);
}

function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

function loadMore() {
    var image_block = document.getElementById("images");
    let count = image_block.children.length;
    var query = "/more?offset="+count;

    if (window.location.pathname.startsWith("/search")) {
        query = query + "&q=" + getUrlParameter("q");
    }

    httpGetAsync(query, function(text){
        var body = JSON.parse(text);
        if (body.length < LOAD_AT_A_TIME) {
            document.getElementById("more-button").parentNode.removeChild(document.getElementById("more-button"))
        }

        body.forEach(function(image) {
            var link = document.createElement("a");
            link.href = "/show/"+image.link;
            var im = document.createElement("div");
            im.title = image.tags.join(" ");
            im.className = "thumbnail";
            im.style.backgroundImage = "url(/images/"+image.name+")";

            link.appendChild(im);
            image_block.appendChild(link);
        });

        if (!TAGS_SET) {
            var imgs = Array.from(document.getElementsByClassName("thumbnail"));
            var tags_block = document.getElementById("tags");
            var tags = new Set(imgs.reduce(function(arr, im) {
                arr.push(im.title.split(" ")[0]);
                return arr
            },[]));

            tags.forEach(function(tag) {
                var link = document.createElement("a");
                link.textContent = tag;
                link.href = "/search?q=" + tag;
                tags_block.appendChild(link);
                tags_block.appendChild(document.createElement("br"));
            });
            TAGS_SET = true
        }
    });
}

function showUploadForm() {
    var form = document.getElementById("upload-form");

    if (form.style.bottom != "7%") {
        form.style.bottom = "7%"
    } else {
        form.style.bottom = "-100%"
    }
}

window.onload = function() {
    loadMore();

    document.getElementById("tag-search-field").value = getUrlParameter("q");
}
<|endoftext|>


<commit_before>$('document').ready(function() {
    user_pawonAPP.init();
})
var user_pawonAPP = {
    init: function() {
        var that = this;
        $('#btn').click(function() {
            that.addUser();
        });
        $('#btn-reload').click(function() {
            document.location.reload();
        }) ;
        $('#uid').val(pawonLib.guid());

    },
    addUser: function () {
        pawonLib.send('http://demo.ardea.me/pawoon/my_application_testing/pawoon_user/addUser',
            {
                data: $('#form').serialize(),
                success: function() {
                    pawonLib.notify('saved');
                }
            }
        )
    },

    deleteUser: function () {

    },
    doAjax: function () {

    },
}

<commit_msg>fix reload uid after save<commit_after>$('document').ready(function() {
    user_pawonAPP.init();
})
var user_pawonAPP = {
    init: function() {
        var that = this;
        $('#btn').click(function() {
            that.addUser();
        });
        $('#btn-reload').click(function() {
            document.location.reload();
        }) ;
        $('#uid').val(pawonLib.guid());

    },
    addUser: function () {
        pawonLib.send('http://demo.ardea.me/pawoon/my_application_testing/pawoon_user/addUser',
            {
                data: $('#form').serialize(),
                success: function() {
                    pawonLib.notify('saved');
                    $('#uid').val(pawonLib.guid());
                }
            }
        )
    },

    deleteUser: function () {

    },
    doAjax: function () {

    },

}

<|endoftext|>


<commit_before>///////////
// SNIPCART BAR & SNIPCART SETTINGS
///////////

if (typeof theBottleRoom !== 'object') {
  window.theBottleRoom = {};
}

theBottleRoom.menu = (function(){

  const cartBar = document.querySelector('#cart-bar');
  const buyButtons = document.querySelectorAll('.snipcart-add-item');
  const statusBar = document.querySelector('#menu-status-bar');
  let orderingEnabled = document.body.classList.contains('can-order');
  let isInitialized = false;
  let itemsCount = 0;

  const schedule = window.data.schedule

  const updateOpenToday = function(dayofweekName){

    dayofweekName = dayofweekName.toLowerCase();

    const openTodayLabel = document.querySelector('#open-today');
    const todayOpenTime = militaryToStandardTime(schedule[dayofweekName].open);
    const todayCloseTime = militaryToStandardTime(schedule[dayofweekName].restaurantClose);

    if (openTodayLabel){
      openTodayLabel.innerHTML = "Open Today: " + todayOpenTime + ' - ' + todayCloseTime;
    }

  };

  const militaryToStandardTime = function(militaryTime){
    let hours = militaryTime.slice(0, 2);
    let minutes = militaryTime.slice(3, 5);
    let period = '';

    if (hours >= 12) {
      period = 'PM';
      hours = hours - 12;
    } else if (hours <= 12) {
      period = 'AM';
    }

    return removeZeroPad(hours) + ':' + minutes + ' ' + period
  }

  const showBarIfNeeded = function(){

    itemsCount = Snipcart.api.getItemsCount();

    if (itemsCount > 0 && orderingEnabled){
      cartBar.classList.add('active');
    } else {
      cartBar.classList.remove('active');
    }

  };

  const disableOrdering = function(){

    for (let i = 0; i < buyButtons.length; i++){

      buyButtons[i].classList.add('disabled');

      let buyButtonText = buyButtons[i].querySelector('span');
      buyButtonText.innerHTML = 'Ordering Disabled';

    }

    Snipcart.api.closeCart();

    orderingEnabled = false;

  };

  const enableOrdering = function(){

    for (let i = 0; i < buyButtons.length; i++){

      buyButtons[i].classList.remove('disabled');

      let buyButtonText = buyButtons[i].querySelector('span');
      buyButtonText.innerHTML = 'Add to Order';

    }

    orderingEnabled = true;

  };

  const showStatus = function(statusMessage){

    if(statusBar){
      statusBar.innerHTML = statusMessage;
      statusBar.classList.add('active');
    }

  };

  const zeroPad = function(number, decimalPlaces){

    let numLength = number.toString().length;

    if (numLength >= decimalPlaces){
      return number;
    }

    for (numLength; numLength < decimalPlaces; numLength++){
      number = '0' + number;
    }

    return number;

  };

  const removeZeroPad = function(number){

    while(number.toString().slice(0,1) == '0'){
      number = number.toString().slice(1);
    }
    return number;

  };

  const isTimeWithin = function(time, start, end){

    const currentTimeHours = time.slice(0, 2);
    const currentTimeMinutes = time.slice(3, 5);

    const startTimeHours = start.slice(0, 2);
    const startTimeMinutes = start.slice(3, 5);
    const endTimeHours = end.slice(0, 2);
    const endTimeMinutes = end.slice(3, 5);

    if(currentTimeHours > startTimeHours && currentTimeHours < endTimeHours){
      return true;

    } else if (currentTimeHours == startTimeHours){

      if(currentTimeMinutes >= startTimeMinutes){
        return true;
      } else {
        return false;
      }

    } else if (currentTimeHours == endTimeHours){

      if(currentTimeMinutes <= endTimeMinutes){
        return true;
      } else {
        return false;
      }

    } else {
      return false;
    }

  };

  const isOrderingOpen = function(dateObject){

    const weekDayName = dateObject.dayofweekName.toLowerCase();
    const currentTimeHours = zeroPad(dateObject.hours, 2);
    const currentTimeMinutes = zeroPad(dateObject.minutes, 2);
    const currentTime = currentTimeHours + ":" + currentTimeMinutes;

    const orderingOpen = isTimeWithin(currentTime, schedule[weekDayName].open, schedule[weekDayName].close);

    console.log(currentTime);

    if(orderingOpen){
      return true;
    } else {
      return false;
    }

  };

  const willCloseSoon = function(dateObject){

    const weekDayName = dateObject.dayofweekName.toLowerCase();

    const currentTimeHours = zeroPad(dateObject.hours, 2);
    const currentTimeMinutes = zeroPad(dateObject.minutes, 2);
    const currentTime = currentTimeHours + ":" + currentTimeMinutes;

    const closeHours = schedule[weekDayName].close.slice(0, 2);
    const closeMinutes = schedule[weekDayName].close.slice(3, 5);
    const beforeClose = zeroPad(closeHours - 1, 2) + ':' + closeMinutes;

    return isTimeWithin(currentTime, beforeClose, schedule[weekDayName].close);

  }

  const getDateTime = function(callback){

    // Check sessionStorage for date object
    let storedDateObject = sessionStorage.getItem('dateTime');

    if(storedDateObject){

      // parse object from sessionStorage
      let parsedDateObject = JSON.parse(storedDateObject);

      // Update the stored object with time passed
      updateDateObject(parsedDateObject, function(err, updatedDateObject){
        if (err) {
          // If there is error clear sessionStorage and try again
          sessionStorage.clear();
          getDateTime(callback);
          return
        }
        if (callback && updatedDateObject) {
          callback(updatedDateObject);
          return
        }
      });

    } else {
      $.getJSON( "https://script.google.com/macros/s/AKfycbyd5AcbAnWi2Yn0xhFRbyzS4qMq1VucMVgVvhul5XqS9HkAyJY/exec?tz=America/Los_Angeles&callback=?", function( data ) {

        const dateObject = {
          day: data.day,
          dayofweekName: data.dayofweekName,
          hours: data.hours,
          minutes: data.minutes,
          localTime: new Date()
        }

        sessionStorage.setItem('dateTime', JSON.stringify(dateObject));
        if (callback) {
          callback(dateObject);
          return
        }
      });
    }

  };

  const updateDateObject = function(dateObject, callback){

    let now = new Date();
    let then = new Date(dateObject.localTime);

    // time difference in ms
    var timeDiff = now - then;
    // strip the ms
    timeDiff /= 1000;

    // get seconds
    var seconds = Math.round(timeDiff % 60);
    // remove seconds from the date
    timeDiff = Math.floor(timeDiff / 60);

    // get minutes
    var minutes = Math.round(timeDiff % 60);
    // remove minutes from the date
    timeDiff = Math.floor(timeDiff / 60);

    // get hours
    var hours = Math.round(timeDiff % 24);
    // remove hours from the date
    timeDiff = Math.floor(timeDiff / 24);

    // the rest of timeDiff is number of days
    var days = timeDiff;

    // console.log(minutes);
    // console.log(hours);
    // console.log(days);

    dateObject.hours = dateObject.hours + hours;
    dateObject.minutes = dateObject.minutes + minutes;

    if (dateObject.minutes >= 60) {
      dateObject.minutes = dateObject.minutes - 60;
      dateObject.hours = dateObject.hours + 1;
    }

    if (dateObject.hours >= 24 || days > 0) {
      return callback('error');
    }

    return callback(null, dateObject);

  }

  const checkAgainNextMin = function(){

    window.setTimeout(function(){
      init();
    }, 30000)

  };

  const init = function(){

    getDateTime(function(dateTime){

      updateOpenToday(dateTime.dayofweekName);

      if(!orderingEnabled) {
          return;
      }

      if (isOrderingOpen(dateTime)){

        enableOrdering();
        showBarIfNeeded();

        if(willCloseSoon(dateTime)){
          const todayCloseTime = militaryToStandardTime(schedule[dateTime.dayofweekName.toLowerCase()].close);
          showStatus('Ordering will be disabled at ' + todayCloseTime);
        }

      } else {
        disableOrdering();
        showBarIfNeeded();
        showStatus('Ordering is disabled');
      };

    });

    if (!isInitialized) {
      Snipcart.subscribe('cart.opened', theBottleRoom.disableBodyScroll);
      Snipcart.subscribe('cart.closed', theBottleRoom.enableBodyScroll);
      isInitialized = true;
    }

    checkAgainNextMin();

  };

  return {
    init: init
  };

})();
<commit_msg>fixed bug in militaryToStandardTime<commit_after>///////////
// SNIPCART BAR & SNIPCART SETTINGS
///////////

if (typeof theBottleRoom !== 'object') {
  window.theBottleRoom = {};
}

theBottleRoom.menu = (function(){

  const cartBar = document.querySelector('#cart-bar');
  const buyButtons = document.querySelectorAll('.snipcart-add-item');
  const statusBar = document.querySelector('#menu-status-bar');
  let orderingEnabled = document.body.classList.contains('can-order');
  let isInitialized = false;
  let itemsCount = 0;

  const schedule = window.data.schedule

  const updateOpenToday = function(dayofweekName){

    dayofweekName = dayofweekName.toLowerCase();

    const openTodayLabel = document.querySelector('#open-today');
    const todayOpenTime = militaryToStandardTime(schedule[dayofweekName].open);
    const todayCloseTime = militaryToStandardTime(schedule[dayofweekName].restaurantClose);

    if (openTodayLabel){
      openTodayLabel.innerHTML = "Open Today: " + todayOpenTime + ' - ' + todayCloseTime;
    }

  };

  const militaryToStandardTime = function(militaryTime){
    let hours = militaryTime.slice(0, 2);
    let minutes = militaryTime.slice(3, 5);
    let period = '';

    if (militaryTime.length != 5){
      console.warn(militaryTime + ' is not a valid 24hr time');
      return;
    }
    if (hours > 24) {
      console.warn(militaryTime + ' is not a valid 24hr time');
      return;
    }
    if (minutes > 59) {
      console.warn(militaryTime + ' is not a valid 24hr time');
      return;
    }

    if (hours > 12) {
      period = 'PM';
      hours = hours - 12;
    } else if (hours == 12) {
      period = 'PM';
    } else if (hours < 12) {
      period = 'AM';
    } else if (hours == 24) {
      period = 'AM';
    }

    hours = hours == '00' ? 12 : removeZeroPad(hours);

    return hours + ':' + minutes + ' ' + period;
  }

  const showBarIfNeeded = function(){

    itemsCount = Snipcart.api.getItemsCount();

    if (itemsCount > 0 && orderingEnabled){
      cartBar.classList.add('active');
    } else {
      cartBar.classList.remove('active');
    }

  };

  const disableOrdering = function(){

    for (let i = 0; i < buyButtons.length; i++){

      buyButtons[i].classList.add('disabled');

      let buyButtonText = buyButtons[i].querySelector('span');
      buyButtonText.innerHTML = 'Ordering Disabled';

    }

    Snipcart.api.closeCart();

    orderingEnabled = false;

  };

  const enableOrdering = function(){

    for (let i = 0; i < buyButtons.length; i++){

      buyButtons[i].classList.remove('disabled');

      let buyButtonText = buyButtons[i].querySelector('span');
      buyButtonText.innerHTML = 'Add to Order';

    }

    orderingEnabled = true;

  };

  const showStatus = function(statusMessage){

    if(statusBar){
      statusBar.innerHTML = statusMessage;
      statusBar.classList.add('active');
    }

  };

  const zeroPad = function(number, decimalPlaces){

    let numLength = number.toString().length;

    if (numLength >= decimalPlaces){
      return number;
    }

    for (numLength; numLength < decimalPlaces; numLength++){
      number = '0' + number;
    }

    return number;

  };

  const removeZeroPad = function(number){

    while(number.toString().slice(0,1) == '0'){
      number = number.toString().slice(1);
    }
    return number;

  };

  const isTimeWithin = function(time, start, end){

    const currentTimeHours = time.slice(0, 2);
    const currentTimeMinutes = time.slice(3, 5);

    const startTimeHours = start.slice(0, 2);
    const startTimeMinutes = start.slice(3, 5);
    const endTimeHours = end.slice(0, 2);
    const endTimeMinutes = end.slice(3, 5);

    if(currentTimeHours > startTimeHours && currentTimeHours < endTimeHours){
      return true;

    } else if (currentTimeHours == startTimeHours){

      if(currentTimeMinutes >= startTimeMinutes){
        return true;
      } else {
        return false;
      }

    } else if (currentTimeHours == endTimeHours){

      if(currentTimeMinutes <= endTimeMinutes){
        return true;
      } else {
        return false;
      }

    } else {
      return false;
    }

  };

  const isOrderingOpen = function(dateObject){

    const weekDayName = dateObject.dayofweekName.toLowerCase();
    const currentTimeHours = zeroPad(dateObject.hours, 2);
    const currentTimeMinutes = zeroPad(dateObject.minutes, 2);
    const currentTime = currentTimeHours + ":" + currentTimeMinutes;

    const orderingOpen = isTimeWithin(currentTime, schedule[weekDayName].open, schedule[weekDayName].close);

    console.log(currentTime);

    if(orderingOpen){
      return true;
    } else {
      return false;
    }

  };

  const willCloseSoon = function(dateObject){

    const weekDayName = dateObject.dayofweekName.toLowerCase();

    const currentTimeHours = zeroPad(dateObject.hours, 2);
    const currentTimeMinutes = zeroPad(dateObject.minutes, 2);
    const currentTime = currentTimeHours + ":" + currentTimeMinutes;

    const closeHours = schedule[weekDayName].close.slice(0, 2);
    const closeMinutes = schedule[weekDayName].close.slice(3, 5);
    const beforeClose = zeroPad(closeHours - 1, 2) + ':' + closeMinutes;

    return isTimeWithin(currentTime, beforeClose, schedule[weekDayName].close);

  }

  const getDateTime = function(callback){

    // Check sessionStorage for date object
    let storedDateObject = sessionStorage.getItem('dateTime');

    if(storedDateObject){

      // parse object from sessionStorage
      let parsedDateObject = JSON.parse(storedDateObject);

      // Update the stored object with time passed
      updateDateObject(parsedDateObject, function(err, updatedDateObject){
        if (err) {
          // If there is error clear sessionStorage and try again
          sessionStorage.clear();
          getDateTime(callback);
          return
        }
        if (callback && updatedDateObject) {
          callback(updatedDateObject);
          return
        }
      });

    } else {
      $.getJSON( "https://script.google.com/macros/s/AKfycbyd5AcbAnWi2Yn0xhFRbyzS4qMq1VucMVgVvhul5XqS9HkAyJY/exec?tz=America/Los_Angeles&callback=?", function( data ) {

        const dateObject = {
          day: data.day,
          dayofweekName: data.dayofweekName,
          hours: data.hours,
          minutes: data.minutes,
          localTime: new Date()
        }

        sessionStorage.setItem('dateTime', JSON.stringify(dateObject));
        if (callback) {
          callback(dateObject);
          return
        }
      });
    }

  };

  const updateDateObject = function(dateObject, callback){

    let now = new Date();
    let then = new Date(dateObject.localTime);

    // time difference in ms
    var timeDiff = now - then;
    // strip the ms
    timeDiff /= 1000;

    // get seconds
    var seconds = Math.round(timeDiff % 60);
    // remove seconds from the date
    timeDiff = Math.floor(timeDiff / 60);

    // get minutes
    var minutes = Math.round(timeDiff % 60);
    // remove minutes from the date
    timeDiff = Math.floor(timeDiff / 60);

    // get hours
    var hours = Math.round(timeDiff % 24);
    // remove hours from the date
    timeDiff = Math.floor(timeDiff / 24);

    // the rest of timeDiff is number of days
    var days = timeDiff;

    // console.log(minutes);
    // console.log(hours);
    // console.log(days);

    dateObject.hours = dateObject.hours + hours;
    dateObject.minutes = dateObject.minutes + minutes;

    if (dateObject.minutes >= 60) {
      dateObject.minutes = dateObject.minutes - 60;
      dateObject.hours = dateObject.hours + 1;
    }

    if (dateObject.hours >= 24 || days > 0) {
      return callback('error');
    }

    return callback(null, dateObject);

  }

  const checkAgainNextMin = function(){

    window.setTimeout(function(){
      init();
    }, 30000)

  };

  const init = function(){

    getDateTime(function(dateTime){

      updateOpenToday(dateTime.dayofweekName);

      if(!orderingEnabled) {
          return;
      }

      if (isOrderingOpen(dateTime)){

        enableOrdering();
        showBarIfNeeded();

        if(willCloseSoon(dateTime)){
          const todayCloseTime = militaryToStandardTime(schedule[dateTime.dayofweekName.toLowerCase()].close);
          showStatus('Ordering will be disabled at ' + todayCloseTime);
        }

      } else {
        disableOrdering();
        showBarIfNeeded();
        showStatus('Ordering is disabled');
      };

    });

    if (!isInitialized) {
      Snipcart.subscribe('cart.opened', theBottleRoom.disableBodyScroll);
      Snipcart.subscribe('cart.closed', theBottleRoom.enableBodyScroll);
      isInitialized = true;
    }

    checkAgainNextMin();

  };

  return {
    init: init
  };

})();
<|endoftext|>


<commit_before>var mousePos = view.center + [view.bounds.width / 3, 100];
var position = view.center;
var lastAngle = 180;
var frames = 0;
var earthFrames = 0;
var score = 0;

var txt = new PointText(new Point(200, 50));
txt.content = "Score: 0";
txt.fillColor = "white";
txt.fontSize = "1em";

function onFrame(event) {
    position += (mousePos - position) / 10;
    var vector = (view.center - position) / 10;
    moveStars(vector * 3);
    moveRainbow(vector, event);
    // earthImg.bringToFront();
    frames++;
    earthFrames++;
    if(frames > 60){
        frames = 0;
        if( whap.visible ){
            whap.visible = false;
            score = score + 1;
            txt.content = "Score: " + score;
        }
    }
    if(earthFrames > 180){
        earthFrames = 0;
        if (!earthImg.visible){
            earthImg.visible = true;
        }
    }
    txt.position = new Point(200,50);
}

function onMouseMove(event) {
    mousePos = event.point;
}

function onKeyDown(event) {
}

function keepInView(item) {
    var position = item.position;
    var viewBounds = view.bounds;
    if (position.isInside(viewBounds))
        return;
    var itemBounds = item.bounds;
    if (position.x > viewBounds.width + 5) {
        position.x = -item.bounds.width;
    }

    if (position.x < -itemBounds.width - 5) {
        position.x = viewBounds.width;
    }

    if (position.y > viewBounds.height + 5) {
        position.y = -itemBounds.height;
    }

    if (position.y < -itemBounds.height - 5) {
        position.y = viewBounds.height
    }
}

var earthImg = new Raster('earth');
var moveStars = new function() {
    // The amount of symbol we want to place;
    var count = 100;

    // Create a symbol, which we will use to place instances of later:
    var path = new Path.Circle({
        center: new Point(0, 0),
        radius: 5,
        fillColor: 'white',
        strokeColor: 'black'
    });

    var symbol = new Symbol(path);

    // Place the instances of the symbol:
    for (var i = 0; i < count; i++) {
        // The center position is a random point in the view:
        var center = Point.random() * view.size;
        var placed = symbol.place(center);
        placed.scale(i / count + 0.01);
        placed.data = {
            vector: new Point({
                angle: Math.random() * 360,
                length : (i / count) * Math.random() / 5
            })
        };
    }

    earthImg.data = {
        vector: new Point({
            angle: Math.random() * 360,
            length : 1 * Math.random() / 5
        })
    };

    var vector = new Point({
        angle: 45,
        length: 0
    });

    return function(vector) {
        // Run through the active layer's children list and change
        // the position of the placed symbols:
        var layer = project.activeLayer;
        for (var i = 0; i < count; i++) {
            var item = layer.children[i];
            var size = item.bounds.size;
            var length = vector.length / 10 * size.width / 10;
            item.position += vector.normalize(length) + item.data.vector;
            keepInView(item);
        }

        earthImg.position += earthImg.data.vector;
        keepInView(earthImg);
    };
};

var whap = new Raster('whap');
whap.visible = false;
var moveRainbow = new function() {
    var paths = [];
    var colors = ['red', 'orange', 'red', 'orange', 'red'];
    for (var i = 0; i < colors.length; i++) {
        var path = new Path({
            fillColor: colors[i]
        });
        paths.push(path);
    }

    var count = 30;
    var group = new Group(paths);
    var headGroup;

    var vector = (view.center - position) / 10;
    if (vector.length < 5)
        vector.length = 5;

    var handImg = new Raster('hand');
    handImg.position = view.center;
    // handImg.scale(0.2);

    var eyePosition = new Point();
    var eyeFollow = (Point.random() - 0.5);
    var blinkTime = 200;

    function createHead(vector, count) {
        var eyeVector = (eyePosition - eyeFollow);
        eyePosition -= eyeVector / 4;
        if (eyeVector.length < 0.00001)
            eyeFollow = (Point.random() - 0.5);
        if (headGroup)
            headGroup.remove();
        var top = paths[0].lastSegment.point;
        var bottom = paths[paths.length - 1].firstSegment.point;
        var radius = (bottom - top).length / 2;
        var circle = new Path.Circle({
            center: top + (bottom - top) / 2,
            radius: radius,
            fillColor: 'black'
        });
        circle.scale(vector.length / 100, 1);
        circle.rotate(vector.angle, circle.center);

        innerCircle = circle.clone();
        innerCircle.scale(0.5);
        innerCircle.fillColor = (count % blinkTime < 3)
            || (count % (blinkTime + 5) < 3) ? 'black' : 'white';
        if (count % (blinkTime + 40) == 0)
            blinkTime = Math.round(Math.random() * 40) + 200;
        var eye = circle.clone();
        eye.position += eyePosition * radius;
        eye.scale(0.15, innerCircle.position);
        eye.fillColor = 'black';
        headGroup = new Group(circle, innerCircle, eye);
    }

    return function(vector, event) {
        var vector = (view.center - position) / 10;

        if (vector.length < 5)
            vector.length = 5;
        count += vector.length / 100;
        group.translate(vector);
        var rotated = vector.rotate(90);
        var middle = paths.length / 2;
        for (var j = 0; j < paths.length; j++) {
            var path = paths[j];
            // resizing with time below:
            // var unitLength = vector.length * (2 + Math.sin(event.count / 10)) / 2;
            var unitLength = 10 * (2 + Math.sin(event.count / 10)) / 2;
            var length = (j - middle) * unitLength + 1;
            var top = view.center + rotated.normalize(length);
            var bottom = view.center + rotated.normalize(length + unitLength);
            path.add(top);
            path.insert(0, bottom);
            if (path.segments.length > 75) {
                var index = Math.round(path.segments.length / 2);
                path.segments[index].remove();
                path.segments[index - 1].remove();
            }
            path.smooth();
        }

        // handImg.scale(vector.length/100);
        handImg.rotate(rotated.angle - lastAngle);
        lastAngle = rotated.angle;
        if(earthImg.visible && handImg.hitTest(earthImg.position)){
            // Temporarily show "Wha-POW!" thing.
            whap.position = view.center + (0, -60);
            whap.visible  = true;
            earthImg.visible = false;
            whap.bringToFront();
        }

        // createHead(vector, event.count);
    }
}
<commit_msg>stars on top, fixes #6<commit_after>var mousePos = view.center + [view.bounds.width / 3, 100];
var position = view.center;
var lastAngle = 180;
var frames = 0;
var earthFrames = 0;
var score = 0;

var txt = new PointText(new Point(200, 50));
txt.content = "Score: 0";
txt.fillColor = "white";
txt.fontSize = "1em";

// var handImg = new Raster('hand');
// handImg.position = view.center;

function onResize(event) {
    // Whenever the window is resized, recenter the path:
    // path.position = view.center;
    // handImg.position = view.center;
}

function onFrame(event) {
    position += (mousePos - position) / 10;
    var vector = (view.center - position) / 10;
    moveStars(vector * 3);
    moveRainbow(vector, event);
    // earthImg.bringToFront();
    frames++;
    earthFrames++;
    if(frames > 60){
        frames = 0;
        if( whap.visible ){
            whap.visible = false;
            score = score + 1;
            txt.content = "Score: " + score;
        }
    }
    if(earthFrames > 180){
        earthFrames = 0;
        if (!earthImg.visible){
            earthImg.visible = true;
        }
    }
    txt.position = new Point(200,50);
}

function onMouseMove(event) {
    mousePos = event.point;
}

function onKeyDown(event) {
}

function keepInView(item) {
    var position = item.position;
    var viewBounds = view.bounds;
    if (position.isInside(viewBounds))
        return;
    var itemBounds = item.bounds;
    if (position.x > viewBounds.width + 5) {
        position.x = -item.bounds.width;
    }

    if (position.x < -itemBounds.width - 5) {
        position.x = viewBounds.width;
    }

    if (position.y > viewBounds.height + 5) {
        position.y = -itemBounds.height;
    }

    if (position.y < -itemBounds.height - 5) {
        position.y = viewBounds.height
    }
}

var earthImg = new Raster('earth');
var moveStars = new function() {
    earthImg.data = {
        vector: new Point({
            angle: Math.random() * 360,
            length : 1 * Math.random() / 5
        })
    };

    // The amount of symbol we want to place;
    var count = 100;

    // Create a symbol, which we will use to place instances of later:
    var path = new Path.Circle({
        center: new Point(0, 0),
        radius: 5,
        fillColor: 'white',
        strokeColor: 'black'
    });

    var symbol = new Symbol(path);

    // Place the instances of the symbol:
    for (var i = 0; i < count; i++) {
        // The center position is a random point in the view:
        var center = Point.random() * view.size;
        var placed = symbol.place(center);
        placed.scale(i / count + 0.01);
        placed.data = {
            vector: new Point({
                angle: Math.random() * 360,
                length : (i / count) * Math.random() / 5
            })
        };
    }

    var vector = new Point({
        angle: 45,
        length: 0
    });

    return function(vector) {
        // Run through the active layer's children list and change
        // the position of the placed symbols:
        earthImg.position += earthImg.data.vector;
        keepInView(earthImg);

        var layer = project.activeLayer;
        for (var i = 0; i < count; i++) {
            var item = layer.children[i];
            var size = item.bounds.size;
            var length = vector.length / 10 * size.width / 10;
            item.position += vector.normalize(length) + item.data.vector;
            keepInView(item);
        }
        earthImg.insertAbove(layer.children[count-1]);
    };
};

var whap = new Raster('whap');
whap.visible = false;
var moveRainbow = new function() {
    var paths = [];
    var colors = ['red', 'orange', 'red', 'orange', 'red'];
    for (var i = 0; i < colors.length; i++) {
        var path = new Path({
            fillColor: colors[i]
        });
        paths.push(path);
    }

    var count = 30;
    var group = new Group(paths);
    var headGroup;

    var vector = (view.center - position) / 10;
    if (vector.length < 5)
        vector.length = 5;

    var handImg = new Raster('hand');
    handImg.position = view.center;
    // handImg.scale(0.2);

    var eyePosition = new Point();
    var eyeFollow = (Point.random() - 0.5);
    var blinkTime = 200;

    function createHead(vector, count) {
        var eyeVector = (eyePosition - eyeFollow);
        eyePosition -= eyeVector / 4;
        if (eyeVector.length < 0.00001)
            eyeFollow = (Point.random() - 0.5);
        if (headGroup)
            headGroup.remove();
        var top = paths[0].lastSegment.point;
        var bottom = paths[paths.length - 1].firstSegment.point;
        var radius = (bottom - top).length / 2;
        var circle = new Path.Circle({
            center: top + (bottom - top) / 2,
            radius: radius,
            fillColor: 'black'
        });
        circle.scale(vector.length / 100, 1);
        circle.rotate(vector.angle, circle.center);

        innerCircle = circle.clone();
        innerCircle.scale(0.5);
        innerCircle.fillColor = (count % blinkTime < 3)
            || (count % (blinkTime + 5) < 3) ? 'black' : 'white';
        if (count % (blinkTime + 40) == 0)
            blinkTime = Math.round(Math.random() * 40) + 200;
        var eye = circle.clone();
        eye.position += eyePosition * radius;
        eye.scale(0.15, innerCircle.position);
        eye.fillColor = 'black';
        headGroup = new Group(circle, innerCircle, eye);
    }

    return function(vector, event) {
        var vector = (view.center - position) / 10;

        if (vector.length < 5)
            vector.length = 5;
        count += vector.length / 100;
        group.translate(vector);
        var rotated = vector.rotate(90);
        var middle = paths.length / 2;
        for (var j = 0; j < paths.length; j++) {
            var path = paths[j];
            // resizing with time below:
            // var unitLength = vector.length * (2 + Math.sin(event.count / 10)) / 2;
            var unitLength = 10 * (2 + Math.sin(event.count / 10)) / 2;
            var length = (j - middle) * unitLength + 1;
            var top = view.center + rotated.normalize(length);
            var bottom = view.center + rotated.normalize(length + unitLength);
            path.add(top);
            path.insert(0, bottom);
            if (path.segments.length > 75) {
                var index = Math.round(path.segments.length / 2);
                path.segments[index].remove();
                path.segments[index - 1].remove();
            }
            path.smooth();
        }

        // handImg.scale(vector.length/100);
        handImg.rotate(rotated.angle - lastAngle);
        lastAngle = rotated.angle;
        if(earthImg.visible && handImg.hitTest(earthImg.position)){
            // Temporarily show "Wha-POW!" thing.
            whap.position = view.center + (0, -60);
            whap.visible  = true;
            earthImg.visible = false;
            whap.bringToFront();
        }

        // createHead(vector, event.count);
    }
}
<|endoftext|>


<commit_before>(function() {

// var inputs = $("#fieldset > input");
// inputs.each(function(i){
// 	var that = $(this)
// 	that.bind("click",function(){
// 		if(that.val() === "slow") {
// 			clearTimeout(loopVariable)
// 			mutate(5000)
// 		} else if (that.val() === "normal") {
// 			clearTimeout(loopVariable)
// 			mutate(1000)
// 		} else {
// 			clearTimeout(loopVariable)
// 			mutate(100)
// 		}

// 	})
// })

var charSet = "aąbcćdeęfghijklłmnńoóprqsśtuwyzźżAĄBCĆDEĘFGHIJKLŁMNŃOÓPRSŚTUWYZŹŻ~1234567890-=+!@#$%^&*()_+[]{}:;'?><,./";
var info = $("#info-text")
var mutationInfo = $("#mutation-info")
var mutationCounter = 0

var button = $("#mutate")
var pause = $("#pauseButton")
var wznow = $("#wznow")
var empty = $("#empty")

var $txt = $("#text") // blast-root

empty.on("click",function(){
	$(this).hide();
	$txt.empty()
	$txt.attr('contenteditable','true')
	info.text("")
	mutationInfo.text("")
	mutationCounter = 0
})

button.on("click",function(){

	var that = $(this)
    if(that.val()==="stop"){
    	 // that.removeClass("yellowButton").addClass("greenButton")
         button.text("Mutuj")
         clearTimeout(loopVariable)
         button.val("start")

    } else {
    	mutate(1000)

    }

})

function deletionMutation(arr,place,whatColor,animationTime){
	mutationInfo.html("Nastąpiła mutacja delecji na " + (place+1) + " znaku.")
	arr.eq(place).css({color:whatColor})
		.velocity({
		    rotateZ: '720deg',
			top: -100,
			left:20,
			opacity:0.0
		  }, {
		    duration:animationTime,
			    complete: function() {
			     	arr.eq(place).remove()

			     	// button.prop('disabled', false)
			    }
			  })

}

function insertionMutation(arr,place,character,whatColor) {
	mutationInfo.html("Nastąpiła mutacja insercji. Po " + (place +1) + " znaku dodano znak: " + charSet.charAt(character))
	arr.eq(place).after(""+charSet.charAt(character)+"").next().css({color:whatColor})
		.velocity("transition.slideLeftIn", { stagger: 250 })
}

function substitutionMutation(arr,place,character,whatColor) {
	mutationInfo.html("Nastąpiła  mutacja substytucji na " + (place+1) + " znaku.")
	arr.eq(place).text(charSet.charAt(character)).css({color:whatColor})
		.velocity("transition.slideUpIn", { stagger: 250 })
}

var loopVariable

function mutate(speed) {
	// Blast the text apart by word.
	$txt.blast({
		delimiter: "character",
		tag: 'span',
		customClass: "" // Add a custom class to wrappers
	});
	var $spans = $(".blast")
	var len = $spans.length
	if(len !== 0) {
		empty.show()
		// button.removeClass("greenButton").addClass("yellowButton")
		button.val("stop")
		button.text("Zatrzymaj")
		$txt.attr('contenteditable','false');
		// button.prop('disabled', true)

		loopVariable = window.setInterval(function mainFunc(){

			$spans = $(".blast")
			len = $spans.length
			if(len !== 0 ) {
			mutationCounter += 1
			if(mutationCounter === 1) {
				info.text("Tekst po " + mutationCounter + " mutacji:")
			} else {
				info.text("Tekst po " + mutationCounter + " mutacjach:")
			}
			var whatMutation = Math.floor(Math.random(0,3)*3);

			var rand = Math.floor(Math.random(0,len)*len);
			var randomFromSet = Math.floor(Math.random(0,charSet.length)*charSet.length);

			// random color search:

			var randomColorFromArray = Math.floor(Math.random(0,colors.length)*colors.length);
			var randomColor = colors[randomColorFromArray]

			switch(whatMutation){
				case 0:
					deletionMutation($spans,rand,randomColor,speed-100)
					break
				case 1:
					substitutionMutation($spans,rand,randomFromSet,randomColor)
					break
				case 2:
					insertionMutation($spans,rand,randomFromSet,randomColor)
					break
			}
			return mainFunc
			}else{
				clearTimeout(loopVariable)
				button.prop('disabled', false)
				button.val("start")
				button.text("Mutuj")
				// button.removeClass("yellowButton").addClass("greenButton")
				$txt.attr('contenteditable','true');
				info.text("")
				mutationInfo.text("")
				empty.hide()
			}
		}(),speed)

	} else {
		$txt.velocity("callout.shake")
		mutationInfo.text("Proszę wprowadzić tekst do zmutowania!")
		mutationCounter = 0;
	}

}

var colors = [
    "#008B8B",
    "#BCE5E5",
    "#000000",
    "#0000ff",
    "#a52a2a",
    "#00ffff",
    "#00008b",
    "#008b8b",
    "#a9a9a9",
    "#006400",
    "#bdb76b",
    "#8b008b",
    "#556b2f",
    "#ff8c00",
    "#9932cc",
    "#8b0000",
    "#e9967a",
    "#9400d3",
    "#ff00ff",
    "#ffd700",
    "#008000",
    "#4b0082",
    "#f0e68c",
    "#00ff00",
    "#ff00ff",
    "#800000",
    "#000080",
    "#808000",
    "#ffa500",
    "#ffc0cb",
    "#800080",
    "#800080",
    "#ff0000",
    "#ffff00"
]

})();
 <commit_msg>Break lines added.<commit_after>(function() {

// var inputs = $("#fieldset > input");
// inputs.each(function(i){
// 	var that = $(this)
// 	that.bind("click",function(){
// 		if(that.val() === "slow") {
// 			clearTimeout(loopVariable)
// 			mutate(5000)
// 		} else if (that.val() === "normal") {
// 			clearTimeout(loopVariable)
// 			mutate(1000)
// 		} else {
// 			clearTimeout(loopVariable)
// 			mutate(100)
// 		}

// 	})
// })

var charSet = "aąbcćdeęfghijklłmnńoóprqsśtuwyzźżAĄBCĆDEĘFGHIJKLŁMNŃOÓPRSŚTUWYZŹŻ~1234567890-=+!@#$%^&*()_+[]{}:;'?><,./";
var info = $("#info-text")
var mutationInfo = $("#mutation-info")
var mutationCounter = 0

var button = $("#mutate")
var pause = $("#pauseButton")
var wznow = $("#wznow")
var empty = $("#empty")

var $txt = $("#text") // blast-root

empty.on("click",function(){
	$(this).hide();
	$txt.empty()
	$txt.text("

")
	$txt.attr('contenteditable','true')
	info.text("")
	mutationInfo.text("")
	mutationCounter = 0
})

button.on("click",function(){

	var that = $(this)
    if(that.val()==="stop"){
    	 // that.removeClass("yellowButton").addClass("greenButton")
         button.text("Mutuj")
         clearTimeout(loopVariable)
         button.val("start")

    } else {
    	mutate(1000)

    }

})

function deletionMutation(arr,place,whatColor,animationTime){
	mutationInfo.html("Nastąpiła mutacja delecji na " + (place+1) + " znaku.")
	arr.eq(place).css({color:whatColor})
		.velocity({
		    rotateZ: '720deg',
			top: -100,
			left:20,
			opacity:0.0
		  }, {
		    duration:animationTime,
			    complete: function() {
			     	arr.eq(place).remove()

			     	// button.prop('disabled', false)
			    }
			  })

}

function insertionMutation(arr,place,character,whatColor) {
	mutationInfo.html("Nastąpiła mutacja insercji. Po " + (place +1) + " znaku dodano znak: " + charSet.charAt(character))
	arr.eq(place).after(""+charSet.charAt(character)+"").next().css({color:whatColor})
		.velocity("transition.slideLeftIn", { stagger: 250 })
}

function substitutionMutation(arr,place,character,whatColor) {
	mutationInfo.html("Nastąpiła  mutacja substytucji na " + (place+1) + " znaku.")
	arr.eq(place).text(charSet.charAt(character)).css({color:whatColor})
		.velocity("transition.slideUpIn", { stagger: 250 })
}

var loopVariable

function mutate(speed) {
	// Blast the text apart by word.
	$txt.blast({
		delimiter: "character",
		tag: 'span',
		customClass: "" // Add a custom class to wrappers
	});
	var $spans = $(".blast")
	var len = $spans.length
	if(len !== 0) {
		empty.show()
		// button.removeClass("greenButton").addClass("yellowButton")
		button.val("stop")
		button.text("Zatrzymaj")
		$txt.attr('contenteditable','false');
		// button.prop('disabled', true)

		loopVariable = window.setInterval(function mainFunc(){

			$spans = $(".blast")
			len = $spans.length
			if(len !== 0 ) {
			mutationCounter += 1
			if(mutationCounter === 1) {
				info.text("Tekst po " + mutationCounter + " mutacji:")
			} else {
				info.text("Tekst po " + mutationCounter + " mutacjach:")
			}
			var whatMutation = Math.floor(Math.random(0,3)*3);

			var rand = Math.floor(Math.random(0,len)*len);
			var randomFromSet = Math.floor(Math.random(0,charSet.length)*charSet.length);

			// random color search:

			var randomColorFromArray = Math.floor(Math.random(0,colors.length)*colors.length);
			var randomColor = colors[randomColorFromArray]

			switch(whatMutation){
				case 0:
					deletionMutation($spans,rand,randomColor,speed-100)
					break
				case 1:
					substitutionMutation($spans,rand,randomFromSet,randomColor)
					break
				case 2:
					insertionMutation($spans,rand,randomFromSet,randomColor)
					break
			}
			return mainFunc
			}else{
				clearTimeout(loopVariable)
				button.prop('disabled', false)
				button.val("start")
				button.text("Mutuj")
				// button.removeClass("yellowButton").addClass("greenButton")
				$txt.attr('contenteditable','true');
				info.text("")
				mutationInfo.text("")
				empty.hide()
			}
		}(),speed)

	} else {
		$txt.velocity("callout.shake")
		mutationInfo.text("Proszę wprowadzić tekst do zmutowania!")
		mutationCounter = 0;
	}

}

var colors = [
    "#008B8B",
    "#BCE5E5",
    "#000000",
    "#0000ff",
    "#a52a2a",
    "#00ffff",
    "#00008b",
    "#008b8b",
    "#a9a9a9",
    "#006400",
    "#bdb76b",
    "#8b008b",
    "#556b2f",
    "#ff8c00",
    "#9932cc",
    "#8b0000",
    "#e9967a",
    "#9400d3",
    "#ff00ff",
    "#ffd700",
    "#008000",
    "#4b0082",
    "#f0e68c",
    "#00ff00",
    "#ff00ff",
    "#800000",
    "#000080",
    "#808000",
    "#ffa500",
    "#ffc0cb",
    "#800080",
    "#800080",
    "#ff0000",
    "#ffff00"
]

})();

<|endoftext|>


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

foam.CLASS({
  package: 'foam.java',
  name: 'Enum',
  extends: 'foam.java.Class',

  properties: [
    {
      class: 'Boolean',
      name: 'isEnum',
      value: true
    },
    {
      name: 'labelsOutput',
      expression: function() {
        var out = 'return new String[] { ';

        for ( var i = 0, value ; value = this.values[i] ; i++ ) {
          out += this.labelForValue(value);
          if ( i < this.values.length - 1 ) out += ', ';
        }

        out += ' };';

        return out;
      }
    },
    {
      name: 'forOrdinal',
      expression: function() {
        var out = 'switch (ordinal) {\n';

        for ( var i = 0, value ; value = this.values[i] ; i++ ) {
          out += '  case ' + value.ordinal + ': return ' + this.name + '.' + value.name + ';\n';
        }

        out += '}\nreturn null;';

        return out;
      }
    },
    {
      name: 'forLabel',
      expression: function() {
        var out = 'switch (label) {\n';

        for ( var i = 0, value ; value = this.values[i] ; i++ ) {
          out += '  case ' + '"' + value.label + '"' +
                  ': return ' + this.name + '.' + value.name + ';\n';
        }

        out += '}\nreturn null;';

        return out;
      }
    },
    {
      name: 'methods',
      factory: function() {
        return [
          {
            name: this.name,
            args: [
                    {
                      name: 'ordinal',
                      type: 'int'
                    },
                    {
                      name: 'label',
                      type: 'String'
                    },
                  ],
            body: 'setOrdinal(ordinal);\nsetLabel(label);\nsetName(name());'
          },
          {
            name: 'forOrdinal',
            type: this.name,
            visibility: 'public',
            static: true,
            args: [ { name: 'ordinal', type: 'int' } ],
            body: this.forOrdinal
          },
          {
            name: 'forLabel',
            type: this.name,
            visibility: 'public',
            static: true,
            args: [ { name: 'label', type: 'String' } ],
            body: this.forLabel
          },
          {
            name: 'labels',
            type: 'String[]',
            visibility: 'public',
            static: true,
            body: this.labelsOutput
          }
        ]
      }
    }
  ],

  methods: [
    function labelForValue(value) {
        return '"' + value.label + '"';
    },
    function writeDeclarations(o) {
      o.indent();

      // Outputs declared enums
      for ( var i = 0 ; i < this.values.length ; i++ ) {
        var value = this.values[i];
        o.out(value.name, '(', value.ordinal, ',', this.labelForValue(value),')');
        o.out(( i == this.values.length - 1 ) ? ';\n\n' : ', ');
      }

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

foam.CLASS({
  package: 'foam.java',
  name: 'Enum',
  extends: 'foam.java.Class',

  properties: [
    {
      class: 'Boolean',
      name: 'isEnum',
      value: true
    },
    {
      name: 'labelsOutput',
      expression: function() {
        var out = 'return new String[] { ';

        for ( var i = 0, value ; value = this.values[i] ; i++ ) {
          out += this.labelForValue(value);
          if ( i < this.values.length - 1 ) out += ', ';
        }

        out += ' };';

        return out;
      }
    },
    {
      name: 'forOrdinal',
      expression: function() {
        var out = 'switch (ordinal) {\n';

        for ( var i = 0, value ; value = this.values[i] ; i++ ) {
          out += '  case ' + value.ordinal + ': return ' + this.name + '.' + value.name + ';\n';
        }

        out += '}\nreturn null;';

        return out;
      }
    },
    {
      name: 'forLabel',
      expression: function() {
        var out = 'switch (label) {\n';

        for ( var i = 0, value ; value = this.values[i] ; i++ ) {
          out += '  case ' + '"' + value.label + '"' +
                  ': return ' + this.name + '.' + value.name + ';\n';
        }

        out += '}\nreturn null;';

        return out;
      }
    },
    {
      name: 'methods',
      factory: function() {
        return [
          {
            name: this.name,
            args: [
                    {
                      name: 'ordinal',
                      type: 'int'
                    },
                    {
                      name: 'label',
                      type: 'String'
                    },
                  ],
            body: 'setOrdinal(ordinal);\nsetLabel(label);\nsetName(name());'
          },
          {
            name: 'forOrdinal',
            type: this.name,
            visibility: 'public',
            static: true,
            args: [ { name: 'ordinal', type: 'int' } ],
            body: this.forOrdinal
          },
          {
            name: 'forLabel',
            type: this.name,
            visibility: 'public',
            static: true,
            args: [ { name: 'label', type: 'String' } ],
            body: this.forLabel
          },
          {
            name: 'labels',
            type: 'String[]',
            visibility: 'public',
            static: true,
            body: this.labelsOutput
          }
        ]
      }
    }
  ],

  methods: [
    function labelForValue(value) {
      return '"' + value.label + '"';
    },
    function writeDeclarations(o) {
      o.indent();

      // Outputs declared enums
      for ( var i = 0 ; i < this.values.length ; i++ ) {
        var value = this.values[i];
        o.out(value.name, '(', value.ordinal, ',', this.labelForValue(value),')');
        o.out(( i == this.values.length - 1 ) ? ';\n\n' : ', ');
      }

      this.out = o;
    }
  ]
});
<|endoftext|>