<commit_before>var mongoose = require("mongoose"); // connect Mongoose (MongoDB ODM library)
var Schema = mongoose.Schema; // create Mongoose Schema
// exchange rate scheme definition
var ERScheme = new Schema({
  currency: {
    type: Schema.ObjectId,
    ref: 'Currency',
    required: true,
  },
  purchase_value: {
    type: Number,
    required: true,
  },
  sale_value: {
    type: Number,
    required: true,
  }
});

module.exports = mongoose.model('ER', ERScheme); // export model
<commit_msg>Unnecessary model<commit_after><|endoftext|>


<commit_before>function Mesh() {

	this.programLoaded = function(program) {
		program.vertexPositionAttribute = gl.getAttribLocation(program, 'aVertexPosition');
		program.vertexNormalAttribute = gl.getAttribLocation(program, 'aVertexNormal');
		program.vertexTextureCoordAttribute = gl.getAttribLocation(program, 'aVertexTextureCoord');
		program.mMatrixUniform = gl.getUniformLocation(program, 'uMMatrix');
		program.pMatrixUniform = gl.getUniformLocation(program, 'uPMatrix');
		program.vMatrixUniform = gl.getUniformLocation(program, 'uVMatrix');
		program.uDiffuseSampler = gl.getUniformLocation(program, 'uDiffuseSampler');
		program.uEmissiveSampler = gl.getUniformLocation(program, 'uEmissiveSampler');
		if (--this.materialsToLoad == 0) {
			this.callback();
		}
	};

	this.loadTex = function(filename) {
		var tex = gl.createTexture();
		var img = new Image();
		img.onload = function() {
			gl.bindTexture(gl.TEXTURE_2D, tex);
			gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
			gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
			gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
			gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
			gl.generateMipmap(gl.TEXTURE_2D);
			gl.bindTexture(gl.TEXTURE0, null);
		};
		img.src = filename;
		return tex;
	}

	this.init = function(jsonstring) {
		var mesh = JSON.parse(jsonstring);
		this.vertexPosBuffer = gl.createBuffer();
		gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexPosBuffer);
		gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(mesh.vertexPositions), gl.STATIC_DRAW);

		this.indexBuffer = gl.createBuffer();
		gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
		gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(mesh.indices), gl.STATIC_DRAW);

		if (mesh.vertexNormals) {
			this.vertexNormalBuffer = gl.createBuffer();
			gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexNormalBuffer);
			gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(mesh.vertexNormals), gl.STATIC_DRAW);
		}

		if (mesh.vertexTextureCoords) {
			this.vertexTextureCoordBuffer = gl.createBuffer();
			gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexTextureCoordBuffer);
			gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(mesh.vertexTextureCoords), gl.STATIC_DRAW);
		}

		this.materialsToLoad = mesh.materials.length;
		this.programs = [];
		var that = this;
		for (var m in mesh.materials) {
			var material = mesh.materials[m];
			var prog = loadProgram(material.vertexshader, material.fragmentshader, function(prog) { that.programLoaded(prog); });
			prog.numindices = material.numindices;
			if (material.diffuse) {
				prog.diffuseTexture = this.loadTex(material.diffuse);
			}
			if (material.emissive) {
				prog.emissiveTexture = this.loadTex(material.emissive);
			}
			this.programs.push(prog);
		}
	};

	this.load = function(file, callback) {
		this.callback = callback;
		var that = this;
		loadFile(file, function(x) { that.init(x); }, false, true);
	};

	this.setMatrixUniforms = function(program) {
		gl.uniformMatrix4fv(program.mMatrixUniform, false, modelMatrix().d);
		gl.uniformMatrix4fv(program.pMatrixUniform, false, projectionMatrix().d);
		gl.uniformMatrix4fv(program.vMatrixUniform, false, viewMatrix().d);
	}

	this.draw = function() {
		var start = 0;
		for (var p in this.programs) {
			var program = this.programs[p];
			gl.useProgram(program);
			gl.enableVertexAttribArray(program.vertexPositionAttribute);
			gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
			gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexPosBuffer);
			gl.vertexAttribPointer(program.vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);
			if (program.vertexNormalAttribute !== null) {
				gl.enableVertexAttribArray(program.vertexNormalAttribute);
				gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexNormalBuffer);
				gl.vertexAttribPointer(program.vertexNormalAttribute, 3, gl.FLOAT, false, 0, 0);
			}
			if (program.vertexTextureCoordAttribute !== null) {
				gl.enableVertexAttribArray(program.vertexTextureCoordAttribute);
				gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexTextureCoordBuffer);
				gl.vertexAttribPointer(program.vertexTextureCoordAttribute, 2, gl.FLOAT, false, 0, 0);
			}
			if (program.diffuseTexture) {
				gl.activeTexture(gl.TEXTURE0);
				gl.bindTexture(gl.TEXTURE_2D, program.diffuseTexture);
				gl.uniform1i(program.uDiffuseSampler, 0);
			}
			if (program.emissiveTexture) {
				gl.activeTexture(gl.TEXTURE1);
				gl.bindTexture(gl.TEXTURE_2D, program.emissiveTexture);
				gl.uniform1i(program.uEmissiveSampler, 1);
			}
			this.setMatrixUniforms(program);
			gl.drawElements(gl.TRIANGLES, program.numindices, gl.UNSIGNED_SHORT, start * 2);
			start += program.numindices;
		}
	};
}<commit_msg>Checking the correct return values from getAttribLocation.<commit_after>function Mesh() {

	this.programLoaded = function(program) {
		program.vertexPositionAttribute = gl.getAttribLocation(program, 'aVertexPosition');
		program.vertexNormalAttribute = gl.getAttribLocation(program, 'aVertexNormal');
		program.vertexTextureCoordAttribute = gl.getAttribLocation(program, 'aVertexTextureCoord');
		program.mMatrixUniform = gl.getUniformLocation(program, 'uMMatrix');
		program.pMatrixUniform = gl.getUniformLocation(program, 'uPMatrix');
		program.vMatrixUniform = gl.getUniformLocation(program, 'uVMatrix');
		program.uDiffuseSampler = gl.getUniformLocation(program, 'uDiffuseSampler');
		program.uEmissiveSampler = gl.getUniformLocation(program, 'uEmissiveSampler');
		if (--this.materialsToLoad == 0) {
			this.callback();
		}
	};

	this.loadTex = function(filename) {
		var tex = gl.createTexture();
		var img = new Image();
		img.onload = function() {
			gl.bindTexture(gl.TEXTURE_2D, tex);
			gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
			gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
			gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
			gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
			gl.generateMipmap(gl.TEXTURE_2D);
			gl.bindTexture(gl.TEXTURE0, null);
		};
		img.src = filename;
		return tex;
	}

	this.init = function(jsonstring) {
		var mesh = JSON.parse(jsonstring);
		this.vertexPosBuffer = gl.createBuffer();
		gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexPosBuffer);
		gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(mesh.vertexPositions), gl.STATIC_DRAW);

		this.indexBuffer = gl.createBuffer();
		gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
		gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(mesh.indices), gl.STATIC_DRAW);

		if (mesh.vertexNormals) {
			this.vertexNormalBuffer = gl.createBuffer();
			gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexNormalBuffer);
			gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(mesh.vertexNormals), gl.STATIC_DRAW);
		}

		if (mesh.vertexTextureCoords) {
			this.vertexTextureCoordBuffer = gl.createBuffer();
			gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexTextureCoordBuffer);
			gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(mesh.vertexTextureCoords), gl.STATIC_DRAW);
		}

		this.materialsToLoad = mesh.materials.length;
		this.programs = [];
		var that = this;
		for (var m in mesh.materials) {
			var material = mesh.materials[m];
			var prog = loadProgram(material.vertexshader, material.fragmentshader, function(prog) { that.programLoaded(prog); });
			prog.numindices = material.numindices;
			if (material.diffuse) {
				prog.diffuseTexture = this.loadTex(material.diffuse);
			}
			if (material.emissive) {
				prog.emissiveTexture = this.loadTex(material.emissive);
			}
			this.programs.push(prog);
		}
	};

	this.load = function(file, callback) {
		this.callback = callback;
		var that = this;
		loadFile(file, function(x) { that.init(x); }, false, true);
	};

	this.setMatrixUniforms = function(program) {
		gl.uniformMatrix4fv(program.mMatrixUniform, false, modelMatrix().d);
		gl.uniformMatrix4fv(program.pMatrixUniform, false, projectionMatrix().d);
		gl.uniformMatrix4fv(program.vMatrixUniform, false, viewMatrix().d);
	}

	this.draw = function() {
		var start = 0;
		for (var p in this.programs) {
			var program = this.programs[p];
			gl.useProgram(program);
			gl.enableVertexAttribArray(program.vertexPositionAttribute);
			gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
			gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexPosBuffer);
			gl.vertexAttribPointer(program.vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);
			if (program.vertexNormalAttribute !== -1) {
				gl.enableVertexAttribArray(program.vertexNormalAttribute);
				gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexNormalBuffer);
				gl.vertexAttribPointer(program.vertexNormalAttribute, 3, gl.FLOAT, false, 0, 0);
			}
			if (program.vertexTextureCoordAttribute !== -1) {
				gl.enableVertexAttribArray(program.vertexTextureCoordAttribute);
				gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexTextureCoordBuffer);
				gl.vertexAttribPointer(program.vertexTextureCoordAttribute, 2, gl.FLOAT, false, 0, 0);
			}
			if (program.diffuseTexture) {
				gl.activeTexture(gl.TEXTURE0);
				gl.bindTexture(gl.TEXTURE_2D, program.diffuseTexture);
				gl.uniform1i(program.uDiffuseSampler, 0);
			}
			if (program.emissiveTexture) {
				gl.activeTexture(gl.TEXTURE1);
				gl.bindTexture(gl.TEXTURE_2D, program.emissiveTexture);
				gl.uniform1i(program.uEmissiveSampler, 1);
			}
			this.setMatrixUniforms(program);
			gl.drawElements(gl.TRIANGLES, program.numindices, gl.UNSIGNED_SHORT, start * 2);
			start += program.numindices;
		}
	};
}<|endoftext|>


<commit_before>module.exports = {
    "prompts": {
        "name": {
            "type": "string",
            "required": true,
            "message": "Project name"
        },
        "description": {
            "type": "string",
            "required": false,
            "message": "Project description",
            "default": "A Vue.js project"
        },
        "author": {
            "type": "string",
            "message": "Author"
        },
        "router": {
            "type": "confirm",
            "message": "Install Vue router?"
        },
        "state manager": {
            "type": "confirm",
            "message": "Install Vuex?"
        }
    },
    "filters": {
        "src/router/*": "router",
        "src/store/*": "state manager"
    }
}
<commit_msg>update meta.js<commit_after>module.exports = {
    "prompts": {
        "name": {
            "type": "string",
            "required": true,
            "message": "Project name"
        },
        "description": {
            "type": "string",
            "required": false,
            "message": "Project description",
            "default": "A Vue.js project"
        },
        "author": {
            "type": "string",
            "message": "Author"
        },
        "router": {
            "type": "confirm",
            "message": "Install Vue router?"
        },
        "state manager": {
            "type": "confirm",
            "message": "Install Vuex?"
        }
    },
    "filters": {
        "src/router/*": "router",
        "src/store/*": "state manager"
    }
    "completeMessage": "To get started:\n\n  {{^inPlace}}cd {{destDirName}}\n  {{/inPlace}}npm install\n  npm run dev\n\nDocumentation can be found at https://github.com/rabbitmu/vue-boilerplate'
}
<|endoftext|>


<commit_before>'use strict'

module.exports = {
  prompts: {
    name: {
      type: 'string',
      required: true,
      message: 'Application Name'
    },
    description: {
      type: 'string',
      required: false,
      message: 'Project description',
      default: 'An electron-vue project'
    },
    vueVersion: {
      type: 'list',
      required: true,
      message: 'Which version of Vue.js would you like installed?',
      choices: ['2.x', '1.x']
    },
    eslint: {
      type: 'confirm',
      require: true,
      message: 'Use linting with ESLint?',
      default: true
    },
    eslintConfig: {
      when: 'eslint',
      type: 'list',
      message: 'Which eslint config would you like to use?',
      choices: [
        {
          name: 'Standard (https://github.com/feross/standard)',
          value: 'standard',
          short: 'Standard'
        },
        {
          name: 'AirBNB (https://github.com/airbnb/javascript)',
          value: 'airbnb',
          short: 'AirBNB'
        },
        {
          name: 'none (configure it yourself)',
          value: 'none',
          short: 'none'
        }
      ]
    },
    plugins: {
      type: 'checkbox',
      message: 'Select which Vue plugins to install',
      choices: ['vue-electron', 'vue-resource', 'vue-router', 'vuex'],
      default: ['vue-electron', 'vue-resource', 'vue-router', 'vuex']
    }
  },
  helpers: {
    isEnabled (list, check, opts) {
      if (list[check]) return opts.fn(this)
      else return opts.inverse(this)
    },
    deps (plugins, version) {
      let output = ''
      let dependencies = {
        'vue-electron': '^1.0.0',
        'vue-resource': '^1.0.3',
        'vue-router': version === '2.x' ? '^2.0.0' : '^0.7.13',
        'vuex': version === '2.x' ? '^2.0.0' : '^1.0.0'
      }

      if (Object.keys(plugins).length > 0) output += ',\n'

      Object.keys(plugins).forEach((p, i) => {
        output += `    "${p}": "${dependencies[p]}"`
        if (i !== Object.keys(plugins).length - 1) output += ',\n'
      })

      return output
    },
    ver (version, module) {
      let output = ''

      if (module === 'core') {
        output += '"vue": "'
        output += (version === '2.x') ? '^2.0.1' : '^1.0.28'
        output += '"'
      } else {
        output += '"vue-loader": "'
        output += (version === '2.x') ? '^9.5.1' : '^8.5.2'
        output += '",'
      }

      return output
    }
  },
  filters: {
    'app/src/routes.js': 'plugins[\'vue-router\']',
    'app/src/components/LandingPageView/CurrentPage.vue': 'plugins[\'vue-router\']',
    'app/src/vuex/**/*': 'plugins[\'vuex\']',
    'tasks/vue/**/*': 'plugins[\'vue-router\']',
    'tasks/vuex/**/*': 'plugins[\'vuex\']',
    '.eslintignore': 'eslint',
    '.eslintrc.js': 'eslint'
  },
  completeMessage: `---

All set. More configurations can be made at \x1b[33m{{destDirName}}/config.js\x1b[0m.

Make sure to check out the documentation for this boilerplate at \x1b[33mhttps://simulatedgreg.gitbooks.io/electron-vue/content/index.html\x1b[0m.

Next steps:
  1. \x1b[34mcd {{destDirName}}\x1b[0m
  2. \x1b[34mnpm install\x1b[0m
  3. \x1b[34mnpm run dev\x1b[0m`
}
<commit_msg>reorder inquirier questions<commit_after>'use strict'

module.exports = {
  prompts: {
    name: {
      type: 'string',
      required: true,
      message: 'Application Name'
    },
    description: {
      type: 'string',
      required: false,
      message: 'Project description',
      default: 'An electron-vue project'
    },
    vueVersion: {
      type: 'list',
      required: true,
      message: 'Which version of Vue.js would you like installed?',
      choices: ['2.x', '1.x']
    },
    plugins: {
      type: 'checkbox',
      message: 'Select which Vue plugins to install',
      choices: ['vue-electron', 'vue-resource', 'vue-router', 'vuex'],
      default: ['vue-electron', 'vue-resource', 'vue-router', 'vuex']
    },
    eslint: {
      type: 'confirm',
      require: true,
      message: 'Use linting with ESLint?',
      default: true
    },
    eslintConfig: {
      when: 'eslint',
      type: 'list',
      message: 'Which eslint config would you like to use?',
      choices: [
        {
          name: 'Standard (https://github.com/feross/standard)',
          value: 'standard',
          short: 'Standard'
        },
        {
          name: 'AirBNB (https://github.com/airbnb/javascript)',
          value: 'airbnb',
          short: 'AirBNB'
        },
        {
          name: 'none (configure it yourself)',
          value: 'none',
          short: 'none'
        }
      ]
    }
  },
  helpers: {
    isEnabled (list, check, opts) {
      if (list[check]) return opts.fn(this)
      else return opts.inverse(this)
    },
    deps (plugins, version) {
      let output = ''
      let dependencies = {
        'vue-electron': '^1.0.0',
        'vue-resource': '^1.0.3',
        'vue-router': version === '2.x' ? '^2.0.0' : '^0.7.13',
        'vuex': version === '2.x' ? '^2.0.0' : '^1.0.0'
      }

      if (Object.keys(plugins).length > 0) output += ',\n'

      Object.keys(plugins).forEach((p, i) => {
        output += `    "${p}": "${dependencies[p]}"`
        if (i !== Object.keys(plugins).length - 1) output += ',\n'
      })

      return output
    },
    ver (version, module) {
      let output = ''

      if (module === 'core') {
        output += '"vue": "'
        output += (version === '2.x') ? '^2.0.1' : '^1.0.28'
        output += '"'
      } else {
        output += '"vue-loader": "'
        output += (version === '2.x') ? '^9.5.1' : '^8.5.2'
        output += '",'
      }

      return output
    }
  },
  filters: {
    'app/src/routes.js': 'plugins[\'vue-router\']',
    'app/src/components/LandingPageView/CurrentPage.vue': 'plugins[\'vue-router\']',
    'app/src/vuex/**/*': 'plugins[\'vuex\']',
    'tasks/vue/**/*': 'plugins[\'vue-router\']',
    'tasks/vuex/**/*': 'plugins[\'vuex\']',
    '.eslintignore': 'eslint',
    '.eslintrc.js': 'eslint'
  },
  completeMessage: `---

All set. More configurations can be made at \x1b[33m{{destDirName}}/config.js\x1b[0m.

Make sure to check out the documentation for this boilerplate at \x1b[33mhttps://simulatedgreg.gitbooks.io/electron-vue/content/index.html\x1b[0m.

Next steps:
  1. \x1b[34mcd {{destDirName}}\x1b[0m
  2. \x1b[34mnpm install\x1b[0m
  3. \x1b[34mnpm run dev\x1b[0m`
}
<|endoftext|>


<commit_before>'use strict'

export default class MidiInterface {

  constructor({onPressNote, onReleaseNote}) {
    this.startMidiRequest()
    this.selectedInput = null
    this.activeNotes = []

    this.onPressNote = onPressNote
    this.onReleaseNote = onReleaseNote
  }

  startMidiRequest() {
    try {
      navigator.requestMIDIAccess()
      .then(this.onMidiSuccess.bind(this))
      .catch(this.onMidiFail.bind(this))
    } catch(err) {
      console.error('StartMidiRequest ERR:', err)
    }

  }

  frequencyFromNote( note ) {
    return 440 * Math.pow(2,(note-69)/12);
  }

  getActiveNotes() {
    return this.activeNotes.length
  }

  noteOn(noteNumber) {
    this.activeNotes.push(noteNumber);
    this.onPressNote(noteNumber, this.frequencyFromNote(noteNumber));

  }

  noteOff(noteNumber) {
    let position = this.activeNotes.indexOf(noteNumber);
    if (position != -1) {
      this.activeNotes.splice(position, 1);
    }
    this.onReleaseNote(noteNumber, this.frequencyFromNote(this.activeNotes[this.activeNotes.length-1]))

  }

  onMidiSuccess(midiAccess, midiOptions) {
    midiAccess.onstateChange = this.onMidiStateChange

    for (let input of midiAccess.inputs.values()) {
      if (midiAccess.inputs.size === 1) {
        this.selectedInput = input;
      }

      this.selectedInput.onmidimessage =  (evt) => this.onMidiInputMessage(evt)
      this.selectedInput.onstatechange = this.onMidiInputStateChange

    }

  }

  onMidiFail(err) {
    console.error('MIDI Failed to start', err)
  }

  onMidiStateChange(evt) {
    console.log('onMidiStateChange', evt, evt.port.name, evt.port.connection, evt.port.state)
  }

  onMidiInputMessage(evt) {
    switch (evt.data[0] & 0xf0) {
      case 0x90:
        if (evt.data[2]!=0) {
          return this.noteOn(evt.data[1])
        }
      case 0x80:
        return this.noteOff(evt.data[1]);
    }
  }

  onMidiInputStateChange(evt) {
    console.log('onMidiInputStateChange', evt)
  }

}
<commit_msg>style updates<commit_after>'use strict'

export default class MidiInterface {

  constructor({onPressNote, onReleaseNote}) {
    this.startMidiRequest()
    this.selectedInput = null
    this.activeNotes = []

    this.onPressNote = onPressNote
    this.onReleaseNote = onReleaseNote
  }

  getActiveNotes() {
    return this.activeNotes.length
  }

  startMidiRequest() {
    try {
      navigator.requestMIDIAccess()
      .then(this.onMidiSuccess.bind(this))
      .catch(this.onMidiFail.bind(this))
    } catch(err) {
      console.error('StartMidiRequest ERR:', err)
    }

  }

  frequencyFromNote( note ) {
    return 440 * Math.pow(2,(note-69)/12)
  }

  noteOn(noteNumber) {
    this.activeNotes.push(noteNumber)
    this.onPressNote(noteNumber, this.frequencyFromNote(noteNumber))
  }

  noteOff(noteNumber) {
    let position = this.activeNotes.indexOf(noteNumber)
    if (position != -1) {
      this.activeNotes.splice(position, 1)
    }
    this.onReleaseNote(noteNumber, this.frequencyFromNote(this.activeNotes[this.activeNotes.length-1]))
  }

  onMidiSuccess(midiAccess, midiOptions) {
    midiAccess.onstateChange = this.onMidiStateChange

    for (let input of midiAccess.inputs.values()) {
      if (midiAccess.inputs.size === 1) {
        this.selectedInput = input
      }

      this.selectedInput.onmidimessage =  (evt) => this.onMidiInputMessage(evt)
      this.selectedInput.onstatechange = this.onMidiInputStateChange

    }

  }

  onMidiFail(err) {
    console.error('MIDI Failed to start', err)
  }

  onMidiStateChange(evt) {
    console.log('onMidiStateChange', evt, evt.port.name, evt.port.connection, evt.port.state)
  }

  onMidiInputMessage(evt) {
    switch (evt.data[0] & 0xf0) {
      case 0x90:
        if (evt.data[2]!=0) {
          return this.noteOn(evt.data[1])
        }
      case 0x80:
        return this.noteOff(evt.data[1])
    }
  }

  onMidiInputStateChange(evt) {
    console.log('onMidiInputStateChange', evt)
  }

}
<|endoftext|>


<commit_before>/* jshint node: true */

/**
 * Benchmark various MAC address parsing methods.
 *
 */
(function () {
  'use strict';

  var utils = require('./utils'),
      addon = require('../build/Release');

  var benchmark = new utils.Benchmark();

  benchmark
    .addFn('pcap', wrap(function (buf, offset) {

      return [
        lpad(buf[offset].toString(16), 2),
        lpad(buf[offset + 1].toString(16), 2),
        lpad(buf[offset + 2].toString(16), 2),
        lpad(buf[offset + 3].toString(16), 2),
        lpad(buf[offset + 4].toString(16), 2),
        lpad(buf[offset + 5].toString(16), 2)
      ].join(':');

  }))
  .addFn('toString concat', wrap(function (buf, offset) {

    return buf.toString('hex', offset, offset + 1) + ':' +
      buf.toString('hex', offset + 1, offset + 2) + ':' +
      buf.toString('hex', offset + 2, offset + 3) + ':' +
      buf.toString('hex', offset + 3, offset + 4) + ':' +
      buf.toString('hex', offset + 4, offset + 5) + ':' +
      buf.toString('hex', offset + 5, offset + 6);

  }))
  .addFn('toString join', wrap(function (buf, offset) {

    return [
      buf.toString('hex', offset, offset + 1),
      buf.toString('hex', offset + 1, offset + 2),
      buf.toString('hex', offset + 2, offset + 3),
      buf.toString('hex', offset + 3, offset + 4),
      buf.toString('hex', offset + 4, offset + 5),
      buf.toString('hex', offset + 5, offset + 6)
    ].join(':');

  }))
  .addFn('slice join', wrap(function (buf, offset) {

    var s = buf.toString('hex', offset, offset + 6);
    return [
      s.slice(0, 2),
      s.slice(2, 4),
      s.slice(4, 6),
      s.slice(6, 8),
      s.slice(8, 10),
      s.slice(10, 12)
    ].join(':');

  }))
  .addFn('cpp function', wrap(function (buf, offset) {

    return addon.readMacAddr(buf, offset);

  }))
  .run(1e2, function (stats) {
    console.dir(stats);
  });

  // Helpers.

  function wrap(decoder) {

    var buf = new Buffer('80000000ffffffffffff06037f07a016', 'hex');

    return function (cb) {

      for (var i = 0; i < 1e4; i++) {
        decoder(buf, 10);
      }
      cb();

    };

  }

  function lpad(str, len) {
    while (str.length < len) {
      str = '0' + str;
    }
    return str;
  }

})();
<commit_msg>Use requireAddon in benchmark.<commit_after>/* jshint node: true */

/**
 * Benchmark various MAC address parsing methods.
 *
 */
(function () {
  'use strict';

  var utils = require('./utils'),
      addon = require('../src/js/utils').requireAddon();

  var benchmark = new utils.Benchmark();

  benchmark
    .addFn('pcap', wrap(function (buf, offset) {

      return [
        lpad(buf[offset].toString(16), 2),
        lpad(buf[offset + 1].toString(16), 2),
        lpad(buf[offset + 2].toString(16), 2),
        lpad(buf[offset + 3].toString(16), 2),
        lpad(buf[offset + 4].toString(16), 2),
        lpad(buf[offset + 5].toString(16), 2)
      ].join(':');

  }))
  .addFn('toString concat', wrap(function (buf, offset) {

    return buf.toString('hex', offset, offset + 1) + ':' +
      buf.toString('hex', offset + 1, offset + 2) + ':' +
      buf.toString('hex', offset + 2, offset + 3) + ':' +
      buf.toString('hex', offset + 3, offset + 4) + ':' +
      buf.toString('hex', offset + 4, offset + 5) + ':' +
      buf.toString('hex', offset + 5, offset + 6);

  }))
  .addFn('toString join', wrap(function (buf, offset) {

    return [
      buf.toString('hex', offset, offset + 1),
      buf.toString('hex', offset + 1, offset + 2),
      buf.toString('hex', offset + 2, offset + 3),
      buf.toString('hex', offset + 3, offset + 4),
      buf.toString('hex', offset + 4, offset + 5),
      buf.toString('hex', offset + 5, offset + 6)
    ].join(':');

  }))
  .addFn('slice join', wrap(function (buf, offset) {

    var s = buf.toString('hex', offset, offset + 6);
    return [
      s.slice(0, 2),
      s.slice(2, 4),
      s.slice(4, 6),
      s.slice(6, 8),
      s.slice(8, 10),
      s.slice(10, 12)
    ].join(':');

  }))
  .addFn('cpp function', wrap(function (buf, offset) {

    return addon.readMacAddr(buf, offset);

  }))
  .run(1e2, function (stats) {
    console.dir(stats);
  });

  // Helpers.

  function wrap(decoder) {

    var buf = new Buffer('80000000ffffffffffff06037f07a016', 'hex');

    return function (cb) {

      for (var i = 0; i < 1e4; i++) {
        decoder(buf, 10);
      }
      cb();

    };

  }

  function lpad(str, len) {
    while (str.length < len) {
      str = '0' + str;
    }
    return str;
  }

})();
<|endoftext|>


<commit_before>(function(){

    "use strict"

    importScripts('../pubnub-3.3-common.js')
    importScripts('../pubnub-3.3.js')

    var app = PUBNUB({
        publish_key   : 'demo',
        subscribe_key : 'demo'
    });
    var channel = 'webworker-test-channel' + '-' + app.uuid();
    app.publish({
        channel  : channel,
        message  : 'It Works!',
        callback : function(info) {
            postMessage(info);
            app.history({
                channel  : channel,
                limit    : 1,
                message  : 123,
                callback : postMessage
            });
            app.detailedHistory({
                channel  : channel,
                count    : 1,
                message  : 123,
                callback : postMessage
            })
        }
    });
    app.subscribe({
        channel  : channel,
        connect  : function() {

            setTimeout(function(){
                app.here_now({
                    channel  : channel,
                    callback : postMessage
                })}, 5000);

            setTimeout(function(){
                app.publish({
                    channel  : channel,
                    message  : "Subscribe Test Message",
                    callback :  postMessage
                })}, 5000);
        },
        callback : function(response) { postMessage(response); }
    })

})();
<commit_msg>replaced deprecated files import<commit_after>(function(){

    "use strict"

    importScripts('../pubnub.min.js')

    var app = PUBNUB({
        publish_key   : 'demo',
        subscribe_key : 'demo'
    });
    var channel = 'webworker-test-channel' + '-' + app.uuid();
    app.publish({
        channel  : channel,
        message  : 'It Works!',
        callback : function(info) {
            postMessage(info);
            app.history({
                channel  : channel,
                limit    : 1,
                message  : 123,
                callback : postMessage
            });
            app.detailedHistory({
                channel  : channel,
                count    : 1,
                message  : 123,
                callback : postMessage
            })
        }
    });
    app.subscribe({
        channel  : channel,
        connect  : function() {

            setTimeout(function(){
                app.here_now({
                    channel  : channel,
                    callback : postMessage
                })}, 5000);

            setTimeout(function(){
                app.publish({
                    channel  : channel,
                    message  : "Subscribe Test Message",
                    callback :  postMessage
                })}, 5000);
        },
        callback : function(response) { postMessage(response); }
    })

})();
<|endoftext|>


<commit_before>exports.BattleAbilities = {

	"snowskates": {
		desc: "This Pokemon's Ice-type moves have their priority increased by 1.",
		shortDesc: "Gives priority to Ice-type moves.",
		onModifyPriority: function (priority, pokemon, target, move) {
			if (move && move.type === 'Ice') return priority + 1;
		},
		id: "snowskates",
		name: "Snow Skates",
		rating: 4.5,
		num: 9000
	},
	"turbocharged": {
		desc: "This Pokemon's Steel-type moves have their priority increased by 1.",
		shortDesc: "Gives priority to Steel-type moves.",
		onModifyPriority: function (priority, pokemon, target, move) {
			if (move && move.type === 'Steel') return priority + 1;
		},
		id: "turbocharged",
		name: "Turbo Charged",
		rating: 4.5,
		num: 9001
	},

	"amplify": {
		desc: "This Pokemon's Electric-type moves have their priority increased by 1.",
		shortDesc: "Gives priority to Electric-type moves.",
		onModifyPriority: function (priority, pokemon, target, move) {
			if (move && move.type === 'Electric') return priority + 1;
		},
		id: "amplify",
		name: "Amplify",
		rating: 4.5,
		num: 9002
	},

	"steadyaim": {
		desc: "This Pokemon's STAB moves will not miss, but all moves will have their priority decreased by 1.",
		shortDesc: "Reduces priority, but STAB moves will not miss.",
		onModifyMove: function (move, pokemon) {
			if (pokemon,hasType(move.type)) {
				move.priority -= 1;
				move.accuracy = true;
			}
		},
		id: "steadyaim",
		name: "Steady Aim",
		rating: 3.5,
		num: 9003
	},

	"adrenaline": {
		desc: "The priority of this Pokémon's moves will be increased by 1 while it has 1/4th of its max HP or less.",
		shortDesc: "Increases priority when the pokemon is at 1/4th of its max HP or less.",
		onModifyPriority: function (priority, pokemon, target, move) {
			if (pokemon.hp <= pokemon.maxhp / 4) return priority + 1;
		},
		id: "adrenaline",
		name: "Adrenaline",
		rating: 3,
		num: 9004
	},

	"godswill": {
		desc: "This Pokemon's attacks that are the same type get +1 priority, but gain 1/6 recoil.",
		shortDesc: "This Pokemon's STAB moves get +1 priority, but gain 1/6 recoil.",
		onModifyPriority: function (priority, pokemon, target, move) {
			if (move.type === pokemon.typesData[0].type || move.type === pokemon.typesData[1].type) return priority + 1;
		},
		onModifyMove: function (move, pokemon) {
			if (move.type === pokemon.typesData[0].type || move.type === pokemon.typesData[1].type)
				if (!move.recoil) move.recoil = [1,6];
		},
		id: "godswill",
		name: "God's Will",
		rating: 3,
		num: 9005
	},

	"lightningchannel": {
		desc: "This Pokemon's thunder moves have their priority increased by 1.",
		shortDesc: "Gives priority to thunder moves.",
		onModifyPriority: function (priority, pokemon, target, move) {
			if (move.id.indexOf('thunder') > -1) return priority + 1;
		},
		id: "lightningchannel",
		name: "Lightning Channel",
		rating: 4,
		num: 9006
	}
};
<commit_msg>Update abilities.js<commit_after>exports.BattleAbilities = {

	"snowskates": {
		desc: "This Pokemon's Ice-type moves have their priority increased by 1.",
		shortDesc: "Gives priority to Ice-type moves.",
		onModifyPriority: function (priority, pokemon, target, move) {
			if (move && move.type === 'Ice') return priority + 1;
		},
		id: "snowskates",
		name: "Snow Skates",
		rating: 4.5,
		num: 9000
	},
	"turbocharged": {
		desc: "This Pokemon's Steel-type moves have their priority increased by 1.",
		shortDesc: "Gives priority to Steel-type moves.",
		onModifyPriority: function (priority, pokemon, target, move) {
			if (move && move.type === 'Steel') return priority + 1;
		},
		id: "turbocharged",
		name: "Turbo Charged",
		rating: 4.5,
		num: 9001
	},

	"amplify": {
		desc: "This Pokemon's Electric-type moves have their priority increased by 1.",
		shortDesc: "Gives priority to Electric-type moves.",
		onModifyPriority: function (priority, pokemon, target, move) {
			if (move && move.type === 'Electric') return priority + 1;
		},
		id: "amplify",
		name: "Amplify",
		rating: 4.5,
		num: 9002
	},

	"steadyaim": {
		desc: "This Pokemon's STAB moves will not miss, but all moves will have their priority decreased by 1.",
		shortDesc: "Reduces priority, but STAB moves will not miss.",
		onModifyMove: function (move, pokemon) {
			if (pokemon.hasType(move.type)) {
				move.priority -= 1;
				move.accuracy = true;
			}
		},
		id: "steadyaim",
		name: "Steady Aim",
		rating: 3.5,
		num: 9003
	},

	"adrenaline": {
		desc: "The priority of this Pokémon's moves will be increased by 1 while it has 1/4th of its max HP or less.",
		shortDesc: "Increases priority when the pokemon is at 1/4th of its max HP or less.",
		onModifyPriority: function (priority, pokemon, target, move) {
			if (pokemon.hp <= pokemon.maxhp / 4) return priority + 1;
		},
		id: "adrenaline",
		name: "Adrenaline",
		rating: 3,
		num: 9004
	},

	"godswill": {
		desc: "This Pokemon's attacks that are the same type get +1 priority, but gain 1/6 recoil.",
		shortDesc: "This Pokemon's STAB moves get +1 priority, but gain 1/6 recoil.",
		onModifyPriority: function (priority, pokemon, target, move) {
			if (move.type === pokemon.typesData[0].type || move.type === pokemon.typesData[1].type) return priority + 1;
		},
		onModifyMove: function (move, pokemon) {
			if (move.type === pokemon.typesData[0].type || move.type === pokemon.typesData[1].type)
				if (!move.recoil) move.recoil = [1,6];
		},
		id: "godswill",
		name: "God's Will",
		rating: 3,
		num: 9005
	},

	"lightningchannel": {
		desc: "This Pokemon's thunder moves have their priority increased by 1.",
		shortDesc: "Gives priority to thunder moves.",
		onModifyPriority: function (priority, pokemon, target, move) {
			if (move.id.indexOf('thunder') > -1) return priority + 1;
		},
		id: "lightningchannel",
		name: "Lightning Channel",
		rating: 4,
		num: 9006
	}
};
<|endoftext|>


<commit_before>/**
 * This file (misc.js) contains miscellaneous methods, usually entirely self-contained
 * They are put here since they do not require their own specific file for readability
 */

let config = require('./config');
let request = require('request-promise');
let fs = require('fs');

/**
 *  @param {message} message  A message object as defined in discord.js
 *  @param {string[]} cmds
 */
 function urbanDefine(message, cmds) {
   let term = cmds.slice(1).join('+');

   let options = {
     uri: config.urban_url + term,
     json: true
   };

   request(options)
      .then(function (body) {
        if (body.result_type == "no_results") {
          console.log('No results for ' + term);
          message.channel.send("There are no results for: " + term.replace('+', ' '))
            .catch( reason => { console.log("Rejected Urban Null Promise for " + reason); });
        } else {
          let firstDef = body.list[0];
          message.channel.send('**' + cmds.slice(1).join(' ') + ':**\n' + firstDef.definition + '\n' + firstDef.example)
            .catch( reason => { console.log("Rejected Urban Definition Promise for " + reason); });
        }
      }).catch(function (err) {
        console.log('Error accessing Urban Dictionary\'s API:\n' + err);
        message.channel.send("Error accessing Urban Dictionary")
          .catch( reason => { console.log("Rejected Urban Reject Promise for " + reason); });
      });
 }

/**
 * @param {message} message A message object as defined in discord.js
 * @param {string} user A string representation of the user either as an id or username
 */
 function getAvatar(message, user) {
   console.log("Looking for: " + user)
   let memberName = user.toLowerCase();
   let avatarURL = '';

   if (memberName.charAt(1) == '@') {
     let obj = message.guild.members.get(memberName.substring(2, memberName.length - 1));
     if (typeof obj !== 'undefined') {
      avatarURL = obj.user.displayAvatarURL;
      console.log("Found " + obj.displayName + "'s avatar at " + avatarURL);
     }
   } else {
     for (var [id, memberObj] of message.guild.members) {
       let displayName = memberObj.displayName.toLowerCase();
       let username = memberObj.user.username.toLowerCase();

       if (displayName == memberName || username == memberName) {
        avatarURL = memberObj.user.displayAvatarURL;
        console.log("Found " + memberObj.displayName + "'s avatar at " + avatarURL);
        break;
       }
     }
   }

   if (avatarURL) {
     avatarURL = avatarURL.replace('jpg', 'png');
     message.channel.send(avatarURL)
      .catch( reason => { console.log("Rejected Avatar Result for " + reason); });
   } else {
     console.log("Could not find member " + user);
     message.channel.send("I couldn't find that member!")
      .catch( reason => { console.log("Rejected Avatar Null Promise for " + reason); });
   }
 }

/**
* @param {message} message A message object as defined in discord.js
*/
 function coinFlip(message) {
   let coin = 'tails';
   let flip = (Math.floor(Math.random() * 2) == 0);

   if (flip) {
     coin = 'heads';
   }
   message.channel.send('You flipped **' + coin + '**');
   .catch( reason => { console.log("Rejected Coin Flip Promise for " + reason); });
 }

 /**
  *  @param {message} message  A message object as defined in discord.js
  *  @param {string[]} cmds Strings that need to be joined and rated
  * Consider replacing the random function with another thing, maybe tied to stocks or time
  */
 function rate(message, cmds) {
   let str = message.content.split(' ').slice(1).join(' ');
   let rating = rateAlgorithm(str);

   if (str.toLowerCase() == 'staed') {
     message.channel.send("Staeds are great! I'll give Staed a 10/10!")
      .catch( reason => { console.log("Rejected Rate Staed Promise for " + reason); });
     console.log('Rated a Staed');
   } else if (str.toLowerCase() == 'sawai') {
     message.channel.send("Sawais are :put_litter_in_its_place: I'll give Sawai a 0/10")
      .catch( reason => { console.log("Rejected Rate Sawai Promise for " + reason); });
     console.log('Rated a Sawai');
   } else {
     console.log('Rated ' + str + ' as ' + rating + '/10');
     message.channel.send("I'd rate " + str + ' ' + rating + '/10')
      .catch( reason => { console.log("Rejected Rate Response Promise for " + reason); });
   }
 }

/**
 * @param {string} text A string containing the thing to be rated
 * @return {int} A number between 1 and 10 inclusive
 */
 function rateAlgorithm(text) {
   return Math.floor(Math.random() * 10 + 1);
 }

 module.exports = {urbanDefine, getAvatar, coinFlip, rate};
<commit_msg>Removed a semicolon and added a missing tab<commit_after>/**
 * This file (misc.js) contains miscellaneous methods, usually entirely self-contained
 * They are put here since they do not require their own specific file for readability
 */

let config = require('./config');
let request = require('request-promise');
let fs = require('fs');

/**
 *  @param {message} message  A message object as defined in discord.js
 *  @param {string[]} cmds
 */
 function urbanDefine(message, cmds) {
   let term = cmds.slice(1).join('+');

   let options = {
     uri: config.urban_url + term,
     json: true
   };

   request(options)
      .then(function (body) {
        if (body.result_type == "no_results") {
          console.log('No results for ' + term);
          message.channel.send("There are no results for: " + term.replace('+', ' '))
            .catch( reason => { console.log("Rejected Urban Null Promise for " + reason); });
        } else {
          let firstDef = body.list[0];
          message.channel.send('**' + cmds.slice(1).join(' ') + ':**\n' + firstDef.definition + '\n' + firstDef.example)
            .catch( reason => { console.log("Rejected Urban Definition Promise for " + reason); });
        }
      }).catch(function (err) {
        console.log('Error accessing Urban Dictionary\'s API:\n' + err);
        message.channel.send("Error accessing Urban Dictionary")
          .catch( reason => { console.log("Rejected Urban Reject Promise for " + reason); });
      });
 }

/**
 * @param {message} message A message object as defined in discord.js
 * @param {string} user A string representation of the user either as an id or username
 */
 function getAvatar(message, user) {
   console.log("Looking for: " + user)
   let memberName = user.toLowerCase();
   let avatarURL = '';

   if (memberName.charAt(1) == '@') {
     let obj = message.guild.members.get(memberName.substring(2, memberName.length - 1));
     if (typeof obj !== 'undefined') {
      avatarURL = obj.user.displayAvatarURL;
      console.log("Found " + obj.displayName + "'s avatar at " + avatarURL);
     }
   } else {
     for (var [id, memberObj] of message.guild.members) {
       let displayName = memberObj.displayName.toLowerCase();
       let username = memberObj.user.username.toLowerCase();

       if (displayName == memberName || username == memberName) {
        avatarURL = memberObj.user.displayAvatarURL;
        console.log("Found " + memberObj.displayName + "'s avatar at " + avatarURL);
        break;
       }
     }
   }

   if (avatarURL) {
     avatarURL = avatarURL.replace('jpg', 'png');
     message.channel.send(avatarURL)
      .catch( reason => { console.log("Rejected Avatar Result for " + reason); });
   } else {
     console.log("Could not find member " + user);
     message.channel.send("I couldn't find that member!")
      .catch( reason => { console.log("Rejected Avatar Null Promise for " + reason); });
   }
 }

/**
* @param {message} message A message object as defined in discord.js
*/
 function coinFlip(message) {
   let coin = 'tails';
   let flip = (Math.floor(Math.random() * 2) == 0);

   if (flip) {
     coin = 'heads';
   }
   message.channel.send('You flipped **' + coin + '**')
    .catch( reason => { console.log("Rejected Coin Flip Promise for " + reason); });
 }

 /**
  *  @param {message} message  A message object as defined in discord.js
  *  @param {string[]} cmds Strings that need to be joined and rated
  * Consider replacing the random function with another thing, maybe tied to stocks or time
  */
 function rate(message, cmds) {
   let str = message.content.split(' ').slice(1).join(' ');
   let rating = rateAlgorithm(str);

   if (str.toLowerCase() == 'staed') {
     message.channel.send("Staeds are great! I'll give Staed a 10/10!")
      .catch( reason => { console.log("Rejected Rate Staed Promise for " + reason); });
     console.log('Rated a Staed');
   } else if (str.toLowerCase() == 'sawai') {
     message.channel.send("Sawais are :put_litter_in_its_place: I'll give Sawai a 0/10")
      .catch( reason => { console.log("Rejected Rate Sawai Promise for " + reason); });
     console.log('Rated a Sawai');
   } else {
     console.log('Rated ' + str + ' as ' + rating + '/10');
     message.channel.send("I'd rate " + str + ' ' + rating + '/10')
      .catch( reason => { console.log("Rejected Rate Response Promise for " + reason); });
   }
 }

/**
 * @param {string} text A string containing the thing to be rated
 * @return {int} A number between 1 and 10 inclusive
 */
 function rateAlgorithm(text) {
   return Math.floor(Math.random() * 10 + 1);
 }

 module.exports = {urbanDefine, getAvatar, coinFlip, rate};
<|endoftext|>


<commit_before>import { OrderedMap, fromJS } from 'immutable';
import { has } from 'lodash';
import consoleError from '../lib/consoleError';
import { CONFIG_SUCCESS } from '../actions/config';
import { FILES, FOLDER } from '../constants/collectionTypes';
import { INFERABLE_FIELDS } from '../constants/fieldInference';

const collections = (state = null, action) => {
  const configCollections = action.payload && action.payload.collections;
  switch (action.type) {
    case CONFIG_SUCCESS:
      return OrderedMap().withMutations((map) => {
        (configCollections || []).forEach((configCollection) => {
          if (has(configCollection, 'folder')) {
            configCollection.type = FOLDER; // eslint-disable-line no-param-reassign
          } else if (has(configCollection, 'files')) {
            configCollection.type = FILES; // eslint-disable-line no-param-reassign
          } else {
            throw new Error('Unknown collection type. Collections can be either Folder based or File based. Please verify your site configuration');
          }
          map.set(configCollection.name, fromJS(configCollection));
        });
      });
    default:
      return state;
  }
};

const formatToExtension = format => ({
  markdown: 'md',
  yaml: 'yml',
  json: 'json',
  html: 'html',
}[format]);

const selectors = {
  [FOLDER]: {
    entryExtension(collection) {
      return collection.get('extension') || formatToExtension(collection.get('format') || 'markdown');
    },
    fields(collection) {
      return collection.get('fields');
    },
    entryPath(collection, slug) {
      return `${ collection.get('folder').replace(/\/$/, '') }/${ slug }.${ this.entryExtension(collection) }`;
    },
    entrySlug(collection, path) {
      return path.split('/').pop().replace(/\.[^\.]+$/, '');
    },
    listMethod() {
      return 'entriesByFolder';
    },
    allowNewEntries(collection) {
      return collection.get('create');
    },
    templateName(collection) {
      return collection.get('name');
    },
  },
  [FILES]: {
    fileForEntry(collection, slug) {
      const files = collection.get('files');
      return files.filter(f => f.get('name') === slug).get(0);
    },
    fields(collection, slug) {
      const file = this.fileForEntry(collection, slug);
      return file && file.get('fields');
    },
    entryPath(collection, slug) {
      const file = this.fileForEntry(collection, slug);
      return file && file.get('file');
    },
    entrySlug(collection, path) {
      const file = collection.get('files').filter(f => f.get('file') === path).get(0);
      return file && file.get('name');
    },
    listMethod() {
      return 'entriesByFiles';
    },
    allowNewEntries() {
      return false;
    },
    templateName(collection, slug) {
      return slug;
    },
  },
};

export const selectFields = (collection, slug) => selectors[collection.get('type')].fields(collection, slug);
export const selectFolderEntryExtension = (collection) => selectors[FOLDER].entryExtension(collection);
export const selectEntryPath = (collection, slug) => selectors[collection.get('type')].entryPath(collection, slug);
export const selectEntrySlug = (collection, path) => selectors[collection.get('type')].entrySlug(collection, path);
export const selectListMethod = collection => selectors[collection.get('type')].listMethod();
export const selectAllowNewEntries = collection => selectors[collection.get('type')].allowNewEntries(collection);
export const selectTemplateName = (collection, slug) => selectors[collection.get('type')].templateName(collection, slug);
export const selectInferedField = (collection, fieldName) => {
  const inferableField = INFERABLE_FIELDS[fieldName];
  const fields = collection.get('fields');
  let field;

  // If colllection has no fields or fieldName is not defined within inferables list, return null
  if (!fields || !inferableField) return null;
  // Try to return a field of the specified type with one of the synonyms
  const mainTypeFields = fields.filter(f => f.get('widget', 'string') === inferableField.type).map(f => f.get('name'));
  field = mainTypeFields.filter(f => inferableField.synonyms.indexOf(f) !== -1);
  if (field && field.size > 0) return field.first();

  // Try to return a field for each of the specified secondary types
  const secondaryTypeFields = fields.filter(f => inferableField.secondaryTypes.indexOf(f.get('widget', 'string')) !== -1).map(f => f.get('name'));
  field = secondaryTypeFields.filter(f => inferableField.synonyms.indexOf(f) !== -1);
  if (field && field.size > 0) return field.first();

  // Try to return the first field of the specified type
  if (inferableField.fallbackToFirstField && mainTypeFields.size > 0) return mainTypeFields.first();

  // Coundn't infer the field. Show error and return null.
  if (inferableField.showError) {
    consoleError(
      `The Field ${ fieldName } is missing for the collection “${ collection.get('name') }”`,
      `Netlify CMS tries to infer the entry ${ fieldName } automatically, but one couldn\'t be found for entries of the collection “${ collection.get('name') }”. Please check your site configuration.`
    );
  }

  return null;
};

export default collections;
<commit_msg>Fix TOML files not being saved with correct file extension.<commit_after>import { OrderedMap, fromJS } from 'immutable';
import { has } from 'lodash';
import consoleError from '../lib/consoleError';
import { CONFIG_SUCCESS } from '../actions/config';
import { FILES, FOLDER } from '../constants/collectionTypes';
import { INFERABLE_FIELDS } from '../constants/fieldInference';

const collections = (state = null, action) => {
  const configCollections = action.payload && action.payload.collections;
  switch (action.type) {
    case CONFIG_SUCCESS:
      return OrderedMap().withMutations((map) => {
        (configCollections || []).forEach((configCollection) => {
          if (has(configCollection, 'folder')) {
            configCollection.type = FOLDER; // eslint-disable-line no-param-reassign
          } else if (has(configCollection, 'files')) {
            configCollection.type = FILES; // eslint-disable-line no-param-reassign
          } else {
            throw new Error('Unknown collection type. Collections can be either Folder based or File based. Please verify your site configuration');
          }
          map.set(configCollection.name, fromJS(configCollection));
        });
      });
    default:
      return state;
  }
};

const formatToExtension = format => ({
  markdown: 'md',
  yaml: 'yml',
  toml: 'toml',
  json: 'json',
  html: 'html',
}[format]);

const selectors = {
  [FOLDER]: {
    entryExtension(collection) {
      return collection.get('extension') || formatToExtension(collection.get('format') || 'markdown');
    },
    fields(collection) {
      return collection.get('fields');
    },
    entryPath(collection, slug) {
      return `${ collection.get('folder').replace(/\/$/, '') }/${ slug }.${ this.entryExtension(collection) }`;
    },
    entrySlug(collection, path) {
      return path.split('/').pop().replace(/\.[^\.]+$/, '');
    },
    listMethod() {
      return 'entriesByFolder';
    },
    allowNewEntries(collection) {
      return collection.get('create');
    },
    templateName(collection) {
      return collection.get('name');
    },
  },
  [FILES]: {
    fileForEntry(collection, slug) {
      const files = collection.get('files');
      return files.filter(f => f.get('name') === slug).get(0);
    },
    fields(collection, slug) {
      const file = this.fileForEntry(collection, slug);
      return file && file.get('fields');
    },
    entryPath(collection, slug) {
      const file = this.fileForEntry(collection, slug);
      return file && file.get('file');
    },
    entrySlug(collection, path) {
      const file = collection.get('files').filter(f => f.get('file') === path).get(0);
      return file && file.get('name');
    },
    listMethod() {
      return 'entriesByFiles';
    },
    allowNewEntries() {
      return false;
    },
    templateName(collection, slug) {
      return slug;
    },
  },
};

export const selectFields = (collection, slug) => selectors[collection.get('type')].fields(collection, slug);
export const selectFolderEntryExtension = (collection) => selectors[FOLDER].entryExtension(collection);
export const selectEntryPath = (collection, slug) => selectors[collection.get('type')].entryPath(collection, slug);
export const selectEntrySlug = (collection, path) => selectors[collection.get('type')].entrySlug(collection, path);
export const selectListMethod = collection => selectors[collection.get('type')].listMethod();
export const selectAllowNewEntries = collection => selectors[collection.get('type')].allowNewEntries(collection);
export const selectTemplateName = (collection, slug) => selectors[collection.get('type')].templateName(collection, slug);
export const selectInferedField = (collection, fieldName) => {
  const inferableField = INFERABLE_FIELDS[fieldName];
  const fields = collection.get('fields');
  let field;

  // If colllection has no fields or fieldName is not defined within inferables list, return null
  if (!fields || !inferableField) return null;
  // Try to return a field of the specified type with one of the synonyms
  const mainTypeFields = fields.filter(f => f.get('widget', 'string') === inferableField.type).map(f => f.get('name'));
  field = mainTypeFields.filter(f => inferableField.synonyms.indexOf(f) !== -1);
  if (field && field.size > 0) return field.first();

  // Try to return a field for each of the specified secondary types
  const secondaryTypeFields = fields.filter(f => inferableField.secondaryTypes.indexOf(f.get('widget', 'string')) !== -1).map(f => f.get('name'));
  field = secondaryTypeFields.filter(f => inferableField.synonyms.indexOf(f) !== -1);
  if (field && field.size > 0) return field.first();

  // Try to return the first field of the specified type
  if (inferableField.fallbackToFirstField && mainTypeFields.size > 0) return mainTypeFields.first();

  // Coundn't infer the field. Show error and return null.
  if (inferableField.showError) {
    consoleError(
      `The Field ${ fieldName } is missing for the collection “${ collection.get('name') }”`,
      `Netlify CMS tries to infer the entry ${ fieldName } automatically, but one couldn\'t be found for entries of the collection “${ collection.get('name') }”. Please check your site configuration.`
    );
  }

  return null;
};

export default collections;
<|endoftext|>


<commit_before>'use strict';

let AFrameSystem = {
    schema: {
        traceLevel: { default: 4 }
    },

    init: () => {

        // TODO: Sometimes an object is "simple".  For example it uses
        //       existing AFrame asstes (an OBJ file and a material)
        //       in this case, we can auto-generate the DOM element,
        //       setting the quaternion, position, material, game-object-id
        //       and obj-model.  Same goes for objects which use primitive
        //       geometric objects.  Then developers don't need to create
        //       a class for each simple object type.
        //
        //       Remember to also remove them.
    },

    tick: () => {
        if (!this.gameEngine)
            return;

        // for each object in the world, update the a-frame element
        this.gameEngine.world.forEachObject((id, o) => {
            let el = o.renderEl;
            if (el) {
                let q = o.quaternion;
                let p = o.position;
                el.setAttribute('position', `${p.x} ${p.y} ${p.z}`);
                el.object3D.quaternion.set(q.x, q.y, q.z, q.w);
            }
        });
    },

    setGameEngine: (gameEngine) => {
        this.gameEngine = gameEngine;
    }
};

module.exports = AFrameSystem;
<commit_msg>Aframe system: mixing ES6 style fat arrow functions and a non-class object is problematic<commit_after>'use strict';

let AFrameSystem = {
    schema: {
        traceLevel: { default: 4 }
    },

    init: function() {

        // TODO: Sometimes an object is "simple".  For example it uses
        //       existing AFrame asstes (an OBJ file and a material)
        //       in this case, we can auto-generate the DOM element,
        //       setting the quaternion, position, material, game-object-id
        //       and obj-model.  Same goes for objects which use primitive
        //       geometric objects.  Then developers don't need to create
        //       a class for each simple object type.
        //
        //       Remember to also remove them.
    },

    tick: function() {
        if (!this.gameEngine)
            return;

        // for each object in the world, update the a-frame element
        this.gameEngine.world.forEachObject((id, o) => {
            let el = o.renderEl;
            if (el) {
                let q = o.quaternion;
                let p = o.position;
                el.setAttribute('position', `${p.x} ${p.y} ${p.z}`);
                el.object3D.quaternion.set(q.x, q.y, q.z, q.w);
            }
        });
    },

    setGameEngine: function(gameEngine){
        this.gameEngine = gameEngine;
    }
};

module.exports = AFrameSystem;
<|endoftext|>


<commit_before>const chalk = require( 'chalk' );

const loadPage = require( '../load.js' );
const flair = require( '../flair/' );
const notifyy = require( '../notifyy.js' );

const POSTS_PER_PAGE = 25;
const JSON_INDENT = 4;
const REDDIT_PAGES = 1;
const NOTIFYY_DELAY = 1500;
const NEW_FLAIR_PRINT_LIMIT = 3;

class Reddit {
    constructor ( game, sections, accounts ) {
        this.sections = sections;
        this.accounts = accounts || [];
        this.game = game;

        this.newFlairs = [];
    }

    getUsersInPost ( post ) {
        let users = [];

        if ( typeof post === 'string' || typeof post === 'undefined' ) {
            return users;
        }

        if ( post.kind === 'more' ) {
            for ( let i = 0; i < post.data.count; i = i + 1 ) {
                users = users.concat( this.getUsersInPost( post.data.children[ i ] ) );
            }

            return users;
        }

        const user = {
            username: post.data.author,
        };

        /* eslint-disable camelcase */
        if ( post.data.author_flair_css_class ) {
            user.author_flair_css_class = String( post.data.author_flair_css_class ).trim();
        }

        if ( post.data.author_flair_text ) {
            user.author_flair_text = String( post.data.author_flair_text ).trim();
        }

        /* eslint-enable camelcase */

        users.push( user );

        if ( post.data.replies && post.data.replies.kind && post.data.replies.kind === 'Listing' ) {
            for ( let i = 0; i < post.data.replies.data.children.length; i = i + 1 ) {
                users = users.concat( this.getUsersInPost( post.data.replies.data.children[ i ] ) );
            }
        }

        return users;
    }

    loadRedditPage ( id, after, page ) {
        return new Promise( ( resolve ) => {
            let url = `https://www.reddit.com/r/${ id }.json`;
            let users = [];

            if ( after ) {
                url = `${ url }?count=${ POSTS_PER_PAGE * page }&after=${ after }`;
            }

            console.log( `Getting reddit page ${ page + 1 } for r/${ id }` );
            loadPage( url )
                .then( ( topicBody ) => {
                    const posts = JSON.parse( topicBody );
                    const xhrList = [];

                    for ( let i = 0; i < posts.data.children.length; i = i + 1 ) {
                        const user = {
                            username: posts.data.children[ i ].data.author,
                        };

                        /* eslint-disable camelcase */
                        if ( posts.data.children[ i ].data.author_flair_css_class ) {
                            user.author_flair_css_class = String( posts.data.children[ i ].data.author_flair_css_class ).trim();
                        }

                        if ( posts.data.children[ i ].data.author_flair_text ) {
                            user.author_flair_text = String( posts.data.children[ i ].data.author_flair_text ).trim();
                        }

                        /* eslint-enable camelcase */

                        users.push( user );

                        const xhr = loadPage( `https://www.reddit.com${ posts.data.children[ i ].data.permalink }.json` )
                            // eslint-disable-next-line no-loop-func
                            .then( ( commentsBody ) => {
                                const replies = JSON.parse( commentsBody );

                                for ( const replyIndex in replies[ 1 ].data.children ) {
                                    if ( !Reflect.apply( {}.hasOwnProperty, replies[ 1 ].data.children, [ replyIndex ] ) ) {
                                        continue;
                                    }

                                    users = users.concat( this.getUsersInPost( replies[ 1 ].data.children[ replyIndex ] ) );
                                }
                            } )
                            .catch( ( error ) => {
                                console.log( error.message );
                            } );

                        xhrList.push( xhr );
                    }

                    Promise.all( xhrList )
                        .then( () => {
                            resolve( {
                                after: posts.data.after,
                                users: users,
                            } );
                        } )
                        .catch( ( error ) => {
                            console.log( error.message );
                        } );
                } )
                .catch( ( error ) => {
                    console.log( error.message );
                } );
        } );
    }

    filter ( users, flairs ) {
        const accountCache = [];
        let flairList = flairs.getFlairs();

        flairList = flairList.map( ( value ) => {
            return value.toLowerCase();
        } );

        return users.filter( ( user ) => {
            if ( accountCache.indexOf( user.username ) > -1 ) {
                return false;
            }

            if ( this.accounts.indexOf( user.username ) > -1 ) {
                return false;
            }

            if ( !user[ flairs.type ] ) {
                return false;
            }

            // Skip everything with a flair we've setup to skip
            if ( flairList.indexOf( user[ flairs.type ].toLowerCase() ) > -1 ) {
                return false;
            }

            this.newFlairs.push( user[ flairs.type ].toLowerCase() );

            accountCache.push( user.username );

            return true;
        } );
    }

    get ( subreddit, pages ) {
        let page = 0;
        let allUsers = [];
        // eslint-disable-next-line consistent-this
        const that = this;

        const getUsers = function getUsers ( redditPage, next, currentPage ) {
            return new Promise( ( loadResolve ) => {
                that.loadRedditPage( redditPage, next, currentPage )
                    .then( ( response ) => {
                        page = page + 1;
                        allUsers = allUsers.concat( response.users );

                        if ( page < pages ) {
                            getUsers( subreddit, response.after, page )
                                .then( ( newUsers ) => {
                                    loadResolve( newUsers );
                                } )
                                .catch( ( error ) => {
                                    console.log( error.message );
                                } );
                        } else {
                            loadResolve( allUsers );
                        }
                    } )
                    .catch( ( error ) => {
                        console.log( error.message );
                    } );
            } );
        };

        return new Promise( ( resolve ) => {
            getUsers( subreddit, false, 0 )
                .then( ( users  ) => {
                    resolve( users );
                } )
                .catch( ( error ) => {
                    console.log( error.message );
                } );
        } );
    }

    run () {
        return new Promise( ( resolve ) => {
            for ( let subredditIndex = 0; subredditIndex < this.sections.length; subredditIndex = subredditIndex + 1 ) {
                const subreddit = this.sections[ subredditIndex ];

                if ( !flair[ subreddit ] ) {
                    console.log( `Found no flairs for ${ subreddit }, won't check it for new devs` );

                    continue;
                }

                console.log( `Starting with r/${ subreddit }` );
                this.get( subreddit, REDDIT_PAGES )
                    .then( ( topUsers ) => {
                        this.get( `${ subreddit }/new`, REDDIT_PAGES )
                            .then( ( newUsers ) => {
                                const allUsers = topUsers.concat( newUsers );
                                const filteredUsers = this.filter( allUsers, flair[ subreddit ] );

                                console.log( chalk.green( `Found ${ filteredUsers.length }/${ allUsers.length } new developers on /r/${ subreddit } for ${ this.game }` ) );

                                resolve();

                                if ( filteredUsers.length > 0 ) {
                                    console.log( chalk.green( JSON.stringify( filteredUsers, null, JSON_INDENT ) ) );
                                    const newFlairs = [ ...new Set( this.newFlairs ) ];

                                    if ( newFlairs.length >= NEW_FLAIR_PRINT_LIMIT ) {
                                        console.log( newFlairs );
                                    }

                                    for ( let i = 0; i < filteredUsers.length; i = i + 1 ) {
                                        setTimeout( notifyy.bind( this, this.game, 'reddit', filteredUsers[ i ] ), i * NOTIFYY_DELAY );
                                    }
                                }
                            } )
                            .catch( ( error ) => {
                                console.log( error );
                            } );
                    } )
                    .catch( ( error ) => {
                        console.log( error );
                    } );
            }
        } );
    }
}

module.exports = Reddit;
<commit_msg>Make 0 reddit pages actually work<commit_after>const chalk = require( 'chalk' );

const loadPage = require( '../load.js' );
const flair = require( '../flair/' );
const notifyy = require( '../notifyy.js' );

const POSTS_PER_PAGE = 25;
const JSON_INDENT = 4;
const REDDIT_PAGES = 1;
const NOTIFYY_DELAY = 1500;
const NEW_FLAIR_PRINT_LIMIT = 3;

class Reddit {
    constructor ( game, sections, accounts ) {
        this.sections = sections;
        this.accounts = accounts || [];
        this.game = game;

        this.newFlairs = [];
    }

    getUsersInPost ( post ) {
        let users = [];

        if ( typeof post === 'string' || typeof post === 'undefined' ) {
            return users;
        }

        if ( post.kind === 'more' ) {
            for ( let i = 0; i < post.data.count; i = i + 1 ) {
                users = users.concat( this.getUsersInPost( post.data.children[ i ] ) );
            }

            return users;
        }

        const user = {
            username: post.data.author,
        };

        /* eslint-disable camelcase */
        if ( post.data.author_flair_css_class ) {
            user.author_flair_css_class = String( post.data.author_flair_css_class ).trim();
        }

        if ( post.data.author_flair_text ) {
            user.author_flair_text = String( post.data.author_flair_text ).trim();
        }

        /* eslint-enable camelcase */

        users.push( user );

        if ( post.data.replies && post.data.replies.kind && post.data.replies.kind === 'Listing' ) {
            for ( let i = 0; i < post.data.replies.data.children.length; i = i + 1 ) {
                users = users.concat( this.getUsersInPost( post.data.replies.data.children[ i ] ) );
            }
        }

        return users;
    }

    loadRedditPage ( id, after, page ) {
        return new Promise( ( resolve ) => {
            let url = `https://www.reddit.com/r/${ id }.json`;
            let users = [];

            if ( after ) {
                url = `${ url }?count=${ POSTS_PER_PAGE * page }&after=${ after }`;
            }

            console.log( `Getting reddit page ${ page + 1 } for r/${ id }` );
            loadPage( url )
                .then( ( topicBody ) => {
                    const posts = JSON.parse( topicBody );
                    const xhrList = [];

                    for ( let i = 0; i < posts.data.children.length; i = i + 1 ) {
                        const user = {
                            username: posts.data.children[ i ].data.author,
                        };

                        /* eslint-disable camelcase */
                        if ( posts.data.children[ i ].data.author_flair_css_class ) {
                            user.author_flair_css_class = String( posts.data.children[ i ].data.author_flair_css_class ).trim();
                        }

                        if ( posts.data.children[ i ].data.author_flair_text ) {
                            user.author_flair_text = String( posts.data.children[ i ].data.author_flair_text ).trim();
                        }

                        /* eslint-enable camelcase */

                        users.push( user );

                        const xhr = loadPage( `https://www.reddit.com${ posts.data.children[ i ].data.permalink }.json` )
                            // eslint-disable-next-line no-loop-func
                            .then( ( commentsBody ) => {
                                const replies = JSON.parse( commentsBody );

                                for ( const replyIndex in replies[ 1 ].data.children ) {
                                    if ( !Reflect.apply( {}.hasOwnProperty, replies[ 1 ].data.children, [ replyIndex ] ) ) {
                                        continue;
                                    }

                                    users = users.concat( this.getUsersInPost( replies[ 1 ].data.children[ replyIndex ] ) );
                                }
                            } )
                            .catch( ( error ) => {
                                console.log( error.message );
                            } );

                        xhrList.push( xhr );
                    }

                    Promise.all( xhrList )
                        .then( () => {
                            resolve( {
                                after: posts.data.after,
                                users: users,
                            } );
                        } )
                        .catch( ( error ) => {
                            console.log( error.message );
                        } );
                } )
                .catch( ( error ) => {
                    console.log( error.message );
                } );
        } );
    }

    filter ( users, flairs ) {
        const accountCache = [];
        let flairList = flairs.getFlairs();

        flairList = flairList.map( ( value ) => {
            return value.toLowerCase();
        } );

        return users.filter( ( user ) => {
            if ( accountCache.indexOf( user.username ) > -1 ) {
                return false;
            }

            if ( this.accounts.indexOf( user.username ) > -1 ) {
                return false;
            }

            if ( !user[ flairs.type ] ) {
                return false;
            }

            // Skip everything with a flair we've setup to skip
            if ( flairList.indexOf( user[ flairs.type ].toLowerCase() ) > -1 ) {
                return false;
            }

            this.newFlairs.push( user[ flairs.type ].toLowerCase() );

            accountCache.push( user.username );

            return true;
        } );
    }

    get ( subreddit, pages ) {
        let page = 0;
        let allUsers = [];
        // eslint-disable-next-line consistent-this
        const that = this;

        if ( page <= pages ) {
            return Promise.resolve( [] );
        }

        const getUsers = function getUsers ( redditPage, next, currentPage ) {
            return new Promise( ( loadResolve ) => {
                that.loadRedditPage( redditPage, next, currentPage )
                    .then( ( response ) => {
                        page = page + 1;
                        allUsers = allUsers.concat( response.users );

                        if ( page < pages ) {
                            getUsers( subreddit, response.after, page )
                                .then( ( newUsers ) => {
                                    loadResolve( newUsers );
                                } )
                                .catch( ( error ) => {
                                    console.log( error.message );
                                } );
                        } else {
                            loadResolve( allUsers );
                        }
                    } )
                    .catch( ( error ) => {
                        console.log( error.message );
                    } );
            } );
        };

        return new Promise( ( resolve ) => {
            getUsers( subreddit, false, 0 )
                .then( ( users  ) => {
                    resolve( users );
                } )
                .catch( ( error ) => {
                    console.log( error.message );
                } );
        } );
    }

    run () {
        return new Promise( ( resolve ) => {
            for ( let subredditIndex = 0; subredditIndex < this.sections.length; subredditIndex = subredditIndex + 1 ) {
                const subreddit = this.sections[ subredditIndex ];

                if ( !flair[ subreddit ] ) {
                    console.log( `Found no flairs for ${ subreddit }, won't check it for new devs` );

                    continue;
                }

                console.log( `Starting with r/${ subreddit }` );
                this.get( subreddit, REDDIT_PAGES )
                    .then( ( topUsers ) => {
                        this.get( `${ subreddit }/new`, REDDIT_PAGES )
                            .then( ( newUsers ) => {
                                const allUsers = topUsers.concat( newUsers );
                                const filteredUsers = this.filter( allUsers, flair[ subreddit ] );

                                console.log( chalk.green( `Found ${ filteredUsers.length }/${ allUsers.length } new developers on /r/${ subreddit } for ${ this.game }` ) );

                                resolve();

                                if ( filteredUsers.length > 0 ) {
                                    console.log( chalk.green( JSON.stringify( filteredUsers, null, JSON_INDENT ) ) );
                                    const newFlairs = [ ...new Set( this.newFlairs ) ];

                                    if ( newFlairs.length >= NEW_FLAIR_PRINT_LIMIT ) {
                                        console.log( newFlairs );
                                    }

                                    for ( let i = 0; i < filteredUsers.length; i = i + 1 ) {
                                        setTimeout( notifyy.bind( this, this.game, 'reddit', filteredUsers[ i ] ), i * NOTIFYY_DELAY );
                                    }
                                }
                            } )
                            .catch( ( error ) => {
                                console.log( error );
                            } );
                    } )
                    .catch( ( error ) => {
                        console.log( error );
                    } );
            }
        } );
    }
}

module.exports = Reddit;
<|endoftext|>


<commit_before>"use strict";

var React = require('react');

var smooth = require('./smooth');

var easing = smooth.defaultEasing;

var cancelEvents = require('./cancel-events');

/*
 * Sets the cancel trigger
 */

cancelEvents.register(function() {
  __cancel = true;
});

/*
 * Spy helper
 */

 var spyCallbacks = [];
 var spySetState = [];

 document.addEventListener('scroll', function() {
  for(var i = 0; i < spyCallbacks.length; i = i + 1) {
    spyCallbacks[i](currentPositionY());
  }
 });

/*
 * Helper function to never extend 60fps on the webpage.
 */
var requestAnimationFrame = (function () {
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          function (callback, element, delay) {
              window.setTimeout(callback, delay || (1000/60));
          };
})();

var __activeLink;
var __mapped            = {};
var __currentPositionY  = 0;
var __startPositionY    = 0;
var __targetPositionY   = 0;
var __progress          = 0;
var __duration          = 0;
var __cancel            = false;

var __start;
var __deltaTop;
var __percent;

var currentPositionY = function() {
  var supportPageOffset = window.pageXOffset !== undefined;
  var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");
  return  supportPageOffset ? window.pageYOffset : isCSS1Compat ?
          document.documentElement.scrollTop : document.body.scrollTop;
};

var animateTopScroll = function(timestamp) {
  // Cancel on specific events
  if(__cancel) { return };

  __deltaTop = Math.round(__targetPositionY - __startPositionY);

  if (__start === null) {
    __start = timestamp;
  }

  __progress = timestamp - __start;

  __percent = (__progress >= __duration ? 1 : easing(__progress/__duration));

  __currentPositionY = __startPositionY + Math.ceil(__deltaTop * __percent);

  window.scrollTo(0, __currentPositionY);

  if(__percent < 1) {
    requestAnimationFrame(animateTopScroll);
  }

};

var startAnimateTopScroll = function(y, options) {
  __start           = null;
  __cancel          = false;
  __startPositionY  = currentPositionY();
  __targetPositionY = y + __startPositionY;
  __duration        = options.duration || 1000;

  requestAnimationFrame(animateTopScroll);
};

var Helpers = {
  Scroll: {
    propTypes: {
      to: React.PropTypes.string.isRequired,
      offset: React.PropTypes.number
    },
    getDefaultProps: function() {
      return {offset: 0};
    },
    scrollTo : function(to) {

      /*
       * get the mapped DOM element
       */

      var target = __mapped[to];

      if(!target) {
        throw new Error("target Element not found");
      }

      var cordinates = target.getBoundingClientRect();

      /*
       * if smooth is not provided just scroll into the view
       */

      if(!this.props.smooth) {
        window.scrollTo(0, cordinates.top);
        return;
      }

      /*
       * Animate scrolling
       */

      var options = {
        duration : this.props.duration
      };

      startAnimateTopScroll(cordinates.top + this.props.offset, options);

    },
    onClick: function(event) {
      /*
       * give the posibility to override onClick
       */

      if(this.props.onClick) {
        this.props.onClick(event);
      }

      /*
       * dont bubble the navigation
       */

      if (event.stopPropagation) event.stopPropagation();
      if (event.preventDefault) event.preventDefault();

      /*
       * do the magic!
       */

      this.scrollTo(this.props.to);

    },
    componentDidMount: function() {
      if(this.props.spy) {
        var to = this.props.to;
        var element = __mapped[to];
        var top = 0;
        var height = 0;
        var self = this;

        spySetState.push(function() {
          if(__activeLink != to) {
            self.setState({ active : false });
          }
        });

        spyCallbacks.push(function(y) {

          if(!element) {
            element = __mapped[to];
            var cords = element.getBoundingClientRect();
            top = (cords.top + y);
            height = top + cords.height;
          }

          var offsetY = y - self.props.offset;

          if(offsetY >= top && offsetY <= height && __activeLink != to) {

            __activeLink = to;

            self.setState({ active : true });

            var length = spySetState.length;

            for(var i = 0; i < length; i = i + 1) {
              spySetState[i]();
            }

          }
        });
      }
    }
  },
  Element: {
    propTypes: {
      name: React.PropTypes.string.isRequired
    },
    componentDidMount: function() {
      __mapped[this.props.name] = this.getDOMNode();
    },
    componentWillUnmount: function() {
      delete __mapped[this.props.name];
    }
  }
};

module.exports = Helpers;

<commit_msg>Fix issue where top/height always 0<commit_after>"use strict";

var React = require('react');

var smooth = require('./smooth');

var easing = smooth.defaultEasing;

var cancelEvents = require('./cancel-events');

/*
 * Sets the cancel trigger
 */

cancelEvents.register(function() {
  __cancel = true;
});

/*
 * Spy helper
 */

 var spyCallbacks = [];
 var spySetState = [];

 document.addEventListener('scroll', function() {
  for(var i = 0; i < spyCallbacks.length; i = i + 1) {
    spyCallbacks[i](currentPositionY());
  }
 });

/*
 * Helper function to never extend 60fps on the webpage.
 */
var requestAnimationFrame = (function () {
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          function (callback, element, delay) {
              window.setTimeout(callback, delay || (1000/60));
          };
})();

var __activeLink;
var __mapped            = {};
var __currentPositionY  = 0;
var __startPositionY    = 0;
var __targetPositionY   = 0;
var __progress          = 0;
var __duration          = 0;
var __cancel            = false;

var __start;
var __deltaTop;
var __percent;

var currentPositionY = function() {
  var supportPageOffset = window.pageXOffset !== undefined;
  var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");
  return  supportPageOffset ? window.pageYOffset : isCSS1Compat ?
          document.documentElement.scrollTop : document.body.scrollTop;
};

var animateTopScroll = function(timestamp) {
  // Cancel on specific events
  if(__cancel) { return };

  __deltaTop = Math.round(__targetPositionY - __startPositionY);

  if (__start === null) {
    __start = timestamp;
  }

  __progress = timestamp - __start;

  __percent = (__progress >= __duration ? 1 : easing(__progress/__duration));

  __currentPositionY = __startPositionY + Math.ceil(__deltaTop * __percent);

  window.scrollTo(0, __currentPositionY);

  if(__percent < 1) {
    requestAnimationFrame(animateTopScroll);
  }

};

var startAnimateTopScroll = function(y, options) {
  __start           = null;
  __cancel          = false;
  __startPositionY  = currentPositionY();
  __targetPositionY = y + __startPositionY;
  __duration        = options.duration || 1000;

  requestAnimationFrame(animateTopScroll);
};

var Helpers = {
  Scroll: {
    propTypes: {
      to: React.PropTypes.string.isRequired,
      offset: React.PropTypes.number
    },
    getDefaultProps: function() {
      return {offset: 0};
    },
    scrollTo : function(to) {

      /*
       * get the mapped DOM element
       */

      var target = __mapped[to];

      if(!target) {
        throw new Error("target Element not found");
      }

      var cordinates = target.getBoundingClientRect();

      /*
       * if smooth is not provided just scroll into the view
       */

      if(!this.props.smooth) {
        window.scrollTo(0, cordinates.top);
        return;
      }

      /*
       * Animate scrolling
       */

      var options = {
        duration : this.props.duration
      };

      startAnimateTopScroll(cordinates.top + this.props.offset, options);

    },
    onClick: function(event) {
      /*
       * give the posibility to override onClick
       */

      if(this.props.onClick) {
        this.props.onClick(event);
      }

      /*
       * dont bubble the navigation
       */

      if (event.stopPropagation) event.stopPropagation();
      if (event.preventDefault) event.preventDefault();

      /*
       * do the magic!
       */

      this.scrollTo(this.props.to);

    },
    componentDidMount: function() {
      if(this.props.spy) {
        var to = this.props.to;
        var element = null;
        var top = 0;
        var height = 0;
        var self = this;

        spySetState.push(function() {
          if(__activeLink != to) {
            self.setState({ active : false });
          }
        });

        spyCallbacks.push(function(y) {

          if(!element) {
            element = __mapped[to];
            var cords = element.getBoundingClientRect();
            top = (cords.top + y);
            height = top + cords.height;
          }

          var offsetY = y - self.props.offset;

          if(offsetY >= top && offsetY <= height && __activeLink != to) {

            __activeLink = to;

            self.setState({ active : true });

            var length = spySetState.length;

            for(var i = 0; i < length; i = i + 1) {
              spySetState[i]();
            }

          }
        });
      }
    }
  },
  Element: {
    propTypes: {
      name: React.PropTypes.string.isRequired
    },
    componentDidMount: function() {
      __mapped[this.props.name] = this.getDOMNode();
    },
    componentWillUnmount: function() {
      delete __mapped[this.props.name];
    }
  }
};

module.exports = Helpers;

<|endoftext|>