<commit_before>var tv = require('intervalometer/time-value.js');
var interpolate = require('intervalometer/interpolate.js');

var exp = {};
var local = {};
exp.status = {};
exp.config = {};

exp.init = function(minEv, maxEv, nightCompensation) {
    if (nightCompensation === null) nightCompensation = 'auto';

    if(nightCompensation != 'auto') {
        nightCompensation = parseFloat(nightCompensation);
    }

    local = {
        lumArray: [],
        evArray: [],
        historyArray: [],
        rateHistoryArray: [],
        targetLum: null,
        first: true
    };

    exp.status = {
        rampEv: null,
        rate: null,
        direction: null
    };

    exp.config = {
        sunrise: {
            p: 0.9,
            i: 0.4,
            d: 0.6,
            targetTimeSeconds: 300,
            evIntegrationSeconds: 300,
            historyIntegrationSeconds: 480,
        },
        sunset: {
            p: 1.1,
            i: 0.6,
            d: 0.4,
            targetTimeSeconds: 480,
            evIntegrationSeconds: 480,
            historyIntegrationSeconds: 480,
        },
        maxEv: maxEv,
        minEv: minEv,
        maxRate: 30,
        hysteresis: 0.4,
        nightCompensationDayEv: 10,
        nightCompensationNightEv: -2,
        nightCompensation: nightCompensation
    };

    return exp.config;
}

exp.calculate = function(algorithm, currentEv, lastPhotoLum, lastPhotoHistogram, minEv, maxEv) {
    if(minEv != null) exp.config.minEv = minEv;
    if(maxEv != null) exp.config.maxEv = maxEv;

    if(algorithm == "lrt") {
        return exp.calculate_LRTtimelapse(currentEv, lastPhotoLum, lastPhotoHistogram, minEv, maxEv);
    } else {
        return exp.calculate_TLPAuto(currentEv, lastPhotoLum, lastPhotoHistogram, minEv, maxEv);
    }
}

exp.calculate_LRTtimelapse = function(currentEv, lastPhotoLum, lastPhotoHistogram, minEv, maxEv) {
    var lum = 0;
    for(var i = 0; i < 256; i++) {
        lum += Math.pow(i, i / 256) / 256 * lastPhotoHistogram[i];
    }

    lum -= (lum * getEvOffsetScale(currentEv, lastPhotoLum)) / 2; // apply night compensation

    if(local.targetLum === null) {  // first time
        exp.status.rampEv = currentEv;
        local.lrtLumArray = [];
        local.targetLum = lum;
        local.direction = 0;
    }

    local.lrtLumArray.push(lum);
    if(local.lrtLumArray.length > 3) {
        local.lrtLumArray.shift();
    }
    lum = (local.lrtLumArray.reduce(function(sum, l) { return sum + l; }, 0)) / local.lrtLumArray.length;

    var directionFactor;
    directionFactor = (local.direction >= 0) ? 1 : 8;
    if(lum > local.targetLum * (1 + 0.2 * directionFactor)) {
        exp.status.rampEv = currentEv + 1/3;
        local.direction = 1;
    }
    directionFactor = (local.direction <= 0) ? 1 : 8;
    if(lum < local.targetLum / (1 + 0.2 * directionFactor)) {
        exp.status.rampEv = currentEv -  1/3;
        local.direction = -1;
    }

    console.log("LRT Lum:", lum, local.direction, local.targetLum);

    return exp.status.rampEv;
}

exp.calculate_TLPAuto = function(currentEv, lastPhotoLum, lastPhotoHistogram, minEv, maxEv) {
    // measure the interval
    exp.status.intervalSeconds = 0;
    var thisPhotoTime = new Date();
    if (local.lastPhotoTime) {
        exp.status.intervalSeconds = (thisPhotoTime - local.lastPhotoTime) / 1000;
    }
    local.lastPhotoTime = thisPhotoTime;

    // get config based on rate up/down
    var config = exp.config.sunset;
    if (exp.status.direction && exp.status.direction > 0) {
        config = exp.config.sunrise;
    }

    // get the current rate of change
    exp.status.rate = calculateRate(currentEv, lastPhotoLum, config);
    console.log("rate: ", exp.status.rate);

    // don't change if within hysteresis setting
    if (Math.abs(exp.status.rate) < exp.config.hysteresis) exp.status.rate = 0;

    // limit to max rate
    if(exp.status.rate > exp.config.maxRate) exp.status.rate = exp.config.maxRate;
    if(exp.status.rate < -exp.config.maxRate) exp.status.rate = -exp.config.maxRate;

    // don't swing quickly past zero (stops oscillation)
    if (exp.status.rate > 3 && exp.status.direction < -0.5) exp.status.rate = 0;
    if (exp.status.rate < -3 && exp.status.direction > 0.5) exp.status.rate = 0;

    // adjust exposure according to rate in stops/hour
    exp.status.rampEv += (exp.status.rate / 3600) * exp.status.intervalSeconds;

    console.log("status: ", exp.status);
    //console.log("local: ", local);

    return exp.status.rampEv;
}

// ******* Private Functions ******* //

function filteredMean(tvArr, trim) {
    if (!trim) trim = 1;
    return tv.mean(tv.insideArray(tvArr, trim));
}

function filteredSlope(tvArr, trim) {
    if (!trim) trim = 1;
    return tv.mean(tv.insideArray(tv.slopes(tvArr), trim));
}

function calculateRate(currentEv, lastPhotoLum, config) {
    var diff = calculateDelta(currentEv, lastPhotoLum, config);
    exp.status.targetEv = currentEv + diff;
    if (exp.status.targetEv < exp.config.minEv) exp.status.targetEv = exp.config.minEv;
    if (exp.status.targetEv > exp.config.maxEv) exp.status.targetEv = exp.config.maxEv;
    if (exp.status.rampEv === null) exp.status.rampEv = exp.status.targetEv;
    var delta = exp.status.targetEv - exp.status.rampEv;
    local.historyArray.push({
        val: delta,
        time: new Date()
    });
    local.historyArray = tv.purgeArray(local.historyArray, config.historyIntegrationSeconds);

    exp.status.pastError = tv.mean(local.historyArray);

    exp.status.pComponent = delta * config.p;
    exp.status.iComponent = exp.status.pastError * config.i;
    exp.status.dComponent = exp.status.evSlope * config.d;

    delta *= config.p;
    delta += exp.status.pastError * config.i;
    delta += exp.status.evSlope * config.d;

    var rate = delta * (3600 / config.targetTimeSeconds);

    local.rateHistoryArray.push({
        val: rate,
        time: new Date()
    });
    local.rateHistoryArray = tv.purgeArray(local.rateHistoryArray, config.historyIntegrationSeconds);
    exp.status.direction = tv.mean(local.rateHistoryArray);

    return rate;
}

function calculateDelta(currentEv, lastPhotoLum, config) {
    local.lumArray.push({
        val: lastPhotoLum,
        time: new Date()
    });

    local.evArray.push({
        val: currentEv + lastPhotoLum,
        time: new Date()
    });

    if (local.first) {
        exp.status.offsetEv = lastPhotoLum - getEvOffsetScale(currentEv, lastPhotoLum);
        local.first = false;
    }

    local.lumArray = tv.purgeArray(local.lumArray, config.evIntegrationSeconds);
    local.evArray = tv.purgeArray(local.evArray, config.evIntegrationSeconds);

    var trim = 1;
    if (exp.status.intervalSeconds) {
        trim = Math.ceil((config.evIntegrationSeconds / exp.status.intervalSeconds) * 0.2); // trim outer 20% from sorted array
    }

    exp.status.evMean = filteredMean(local.lumArray, trim);
    exp.status.evSlope = filteredSlope(local.evArray, trim) * config.targetTimeSeconds;

    return lastPhotoLum - exp.status.offsetEv - getEvOffsetScale(currentEv, lastPhotoLum);
}

function getEvOffsetScale(ev, lastPhotoLum, noAuto) {
    var evScale
    if(exp.config.nightCompensation == 'auto') {
        if(noAuto) { // for LRT algorithm
            evScale = [{
                ev: exp.config.nightCompensationNightEv,
                offset: -1.333333;
            }, {
                ev: exp.config.nightCompensationDayEv,
                offset: 0
            }]
        } else { // auto calculate night exposure
            evScale = [{
                ev: exp.config.nightCompensationNightEv,
                offset: -(lastPhotoLum - -1.5)
            }, {
                ev: exp.config.nightCompensationDayEv,
                offset: -(lastPhotoLum - 0.0)
            }]
        }
    } else {
        evScale = [{
            ev: exp.config.nightCompensationNightEv,
            offset: exp.config.nightCompensation
        }, {
            ev: exp.config.nightCompensationDayEv,
            offset: 0
        }]
    }

    var values = evScale.map(function(item) {
        return {
            x: item.ev,
            y: item.offset
        }
    });
    return interpolate.linear(values, ev);
}

module.exports = exp;<commit_msg>lrt and sun/moon times improvements<commit_after>var tv = require('intervalometer/time-value.js');
var interpolate = require('intervalometer/interpolate.js');

var exp = {};
var local = {};
exp.status = {};
exp.config = {};

exp.init = function(minEv, maxEv, nightCompensation) {
    if (nightCompensation === null) nightCompensation = 'auto';

    if(nightCompensation != 'auto') {
        nightCompensation = parseFloat(nightCompensation);
    }

    local = {
        lumArray: [],
        evArray: [],
        historyArray: [],
        rateHistoryArray: [],
        targetLum: null,
        first: true
    };

    exp.status = {
        rampEv: null,
        rate: null,
        direction: null
    };

    exp.config = {
        sunrise: {
            p: 0.9,
            i: 0.4,
            d: 0.6,
            targetTimeSeconds: 300,
            evIntegrationSeconds: 300,
            historyIntegrationSeconds: 480,
        },
        sunset: {
            p: 1.1,
            i: 0.6,
            d: 0.4,
            targetTimeSeconds: 480,
            evIntegrationSeconds: 480,
            historyIntegrationSeconds: 480,
        },
        maxEv: maxEv,
        minEv: minEv,
        maxRate: 30,
        hysteresis: 0.4,
        nightCompensationDayEv: 10,
        nightCompensationNightEv: -2,
        nightCompensation: nightCompensation
    };

    return exp.config;
}

exp.calculate = function(algorithm, currentEv, lastPhotoLum, lastPhotoHistogram, minEv, maxEv) {
    if(minEv != null) exp.config.minEv = minEv;
    if(maxEv != null) exp.config.maxEv = maxEv;

    if(algorithm == "lrt") {
        return exp.calculate_LRTtimelapse(currentEv, lastPhotoLum, lastPhotoHistogram, minEv, maxEv);
    } else {
        return exp.calculate_TLPAuto(currentEv, lastPhotoLum, lastPhotoHistogram, minEv, maxEv);
    }
}

exp.calculate_LRTtimelapse = function(currentEv, lastPhotoLum, lastPhotoHistogram, minEv, maxEv) {
    var lum = 0;
    for(var i = 0; i < 256; i++) {
        lum += Math.pow(i, i / 256) / 256 * lastPhotoHistogram[i];
    }

    lum -= (lum * getEvOffsetScale(currentEv, lastPhotoLum)) / 2; // apply night compensation

    if(local.targetLum === null) {  // first time
        exp.status.rampEv = currentEv;
        local.lrtLumArray = [];
        local.targetLum = lum;
        local.direction = 0;
    }

    local.lrtLumArray.push(lum);
    if(local.lrtLumArray.length > 3) {
        local.lrtLumArray.shift();
    }
    lum = (local.lrtLumArray.reduce(function(sum, l) { return sum + l; }, 0)) / local.lrtLumArray.length;

    var directionFactor;
    directionFactor = (local.direction >= 0) ? 1 : 8;
    if(lum > local.targetLum * (1 + 0.2 * directionFactor)) {
        exp.status.rampEv = currentEv + 1/3;
        local.direction = 1;
    }
    directionFactor = (local.direction <= 0) ? 1 : 8;
    if(lum < local.targetLum / (1 + 0.2 * directionFactor)) {
        exp.status.rampEv = currentEv -  1/3;
        local.direction = -1;
    }

    console.log("LRT Lum:", lum, local.direction, local.targetLum);

    return exp.status.rampEv;
}

exp.calculate_TLPAuto = function(currentEv, lastPhotoLum, lastPhotoHistogram, minEv, maxEv) {
    // measure the interval
    exp.status.intervalSeconds = 0;
    var thisPhotoTime = new Date();
    if (local.lastPhotoTime) {
        exp.status.intervalSeconds = (thisPhotoTime - local.lastPhotoTime) / 1000;
    }
    local.lastPhotoTime = thisPhotoTime;

    // get config based on rate up/down
    var config = exp.config.sunset;
    if (exp.status.direction && exp.status.direction > 0) {
        config = exp.config.sunrise;
    }

    // get the current rate of change
    exp.status.rate = calculateRate(currentEv, lastPhotoLum, config);
    console.log("rate: ", exp.status.rate);

    // don't change if within hysteresis setting
    if (Math.abs(exp.status.rate) < exp.config.hysteresis) exp.status.rate = 0;

    // limit to max rate
    if(exp.status.rate > exp.config.maxRate) exp.status.rate = exp.config.maxRate;
    if(exp.status.rate < -exp.config.maxRate) exp.status.rate = -exp.config.maxRate;

    // don't swing quickly past zero (stops oscillation)
    if (exp.status.rate > 3 && exp.status.direction < -0.5) exp.status.rate = 0;
    if (exp.status.rate < -3 && exp.status.direction > 0.5) exp.status.rate = 0;

    // adjust exposure according to rate in stops/hour
    exp.status.rampEv += (exp.status.rate / 3600) * exp.status.intervalSeconds;

    console.log("status: ", exp.status);
    //console.log("local: ", local);

    return exp.status.rampEv;
}

// ******* Private Functions ******* //

function filteredMean(tvArr, trim) {
    if (!trim) trim = 1;
    return tv.mean(tv.insideArray(tvArr, trim));
}

function filteredSlope(tvArr, trim) {
    if (!trim) trim = 1;
    return tv.mean(tv.insideArray(tv.slopes(tvArr), trim));
}

function calculateRate(currentEv, lastPhotoLum, config) {
    var diff = calculateDelta(currentEv, lastPhotoLum, config);
    exp.status.targetEv = currentEv + diff;
    if (exp.status.targetEv < exp.config.minEv) exp.status.targetEv = exp.config.minEv;
    if (exp.status.targetEv > exp.config.maxEv) exp.status.targetEv = exp.config.maxEv;
    if (exp.status.rampEv === null) exp.status.rampEv = exp.status.targetEv;
    var delta = exp.status.targetEv - exp.status.rampEv;
    local.historyArray.push({
        val: delta,
        time: new Date()
    });
    local.historyArray = tv.purgeArray(local.historyArray, config.historyIntegrationSeconds);

    exp.status.pastError = tv.mean(local.historyArray);

    exp.status.pComponent = delta * config.p;
    exp.status.iComponent = exp.status.pastError * config.i;
    exp.status.dComponent = exp.status.evSlope * config.d;

    delta *= config.p;
    delta += exp.status.pastError * config.i;
    delta += exp.status.evSlope * config.d;

    var rate = delta * (3600 / config.targetTimeSeconds);

    local.rateHistoryArray.push({
        val: rate,
        time: new Date()
    });
    local.rateHistoryArray = tv.purgeArray(local.rateHistoryArray, config.historyIntegrationSeconds);
    exp.status.direction = tv.mean(local.rateHistoryArray);

    return rate;
}

function calculateDelta(currentEv, lastPhotoLum, config) {
    local.lumArray.push({
        val: lastPhotoLum,
        time: new Date()
    });

    local.evArray.push({
        val: currentEv + lastPhotoLum,
        time: new Date()
    });

    if (local.first) {
        exp.status.offsetEv = lastPhotoLum - getEvOffsetScale(currentEv, lastPhotoLum);
        local.first = false;
    }

    local.lumArray = tv.purgeArray(local.lumArray, config.evIntegrationSeconds);
    local.evArray = tv.purgeArray(local.evArray, config.evIntegrationSeconds);

    var trim = 1;
    if (exp.status.intervalSeconds) {
        trim = Math.ceil((config.evIntegrationSeconds / exp.status.intervalSeconds) * 0.2); // trim outer 20% from sorted array
    }

    exp.status.evMean = filteredMean(local.lumArray, trim);
    exp.status.evSlope = filteredSlope(local.evArray, trim) * config.targetTimeSeconds;

    return lastPhotoLum - exp.status.offsetEv - getEvOffsetScale(currentEv, lastPhotoLum);
}

function getEvOffsetScale(ev, lastPhotoLum, noAuto) {
    var evScale
    if(exp.config.nightCompensation == 'auto') {
        if(noAuto) { // for LRT algorithm
            evScale = [{
                ev: exp.config.nightCompensationNightEv,
                offset: -1.333333
            }, {
                ev: exp.config.nightCompensationDayEv,
                offset: 0
            }]
        } else { // auto calculate night exposure
            evScale = [{
                ev: exp.config.nightCompensationNightEv,
                offset: -(lastPhotoLum - -1.5)
            }, {
                ev: exp.config.nightCompensationDayEv,
                offset: -(lastPhotoLum - 0.0)
            }]
        }
    } else {
        evScale = [{
            ev: exp.config.nightCompensationNightEv,
            offset: exp.config.nightCompensation
        }, {
            ev: exp.config.nightCompensationDayEv,
            offset: 0
        }]
    }

    var values = evScale.map(function(item) {
        return {
            x: item.ev,
            y: item.offset
        }
    });
    return interpolate.linear(values, ev);
}

module.exports = exp;<|endoftext|>


<commit_before>// [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010.
// Author Radosaw Eichler 2012

import { Flow } from './tables';
import { Modifier } from './modifier';
import { StaveModifier } from './stavemodifier';
import { Glyph } from './glyph';

export class StaveTempo extends StaveModifier {
  static get CATEGORY() { return 'stavetempo'; }

  constructor(tempo, x, shift_y) {
    super();
    this.setAttribute('type', 'StaveTempo');

    this.tempo = tempo;
    this.position = Modifier.Position.ABOVE;
    this.x = x;
    this.shift_x = 10;
    this.shift_y = shift_y;
    this.font = {
      family: 'times',
      size: 14,
      weight: 'bold',
    };
    this.render_options = {
      glyph_font_scale: 30,  // font size for note
    };
  }
  getCategory() { return StaveTempo.CATEGORY; }
  setTempo(tempo) { this.tempo = tempo; return this; }
  setShiftX(x) { this.shift_x = x; return this; }
  setShiftY(y) { this.shift_y = y; return this; }

  draw(stave, shift_x) {
    const ctx = stave.checkContext();
    this.setRendered();

    const options = this.render_options;
    // FIXME: What does the '38' mean? Why 38? Is that supposed to
    // be the default font size for standard notation?
    const scale = options.glyph_font_scale / 38;
    const name = this.tempo.name;
    const duration = this.tempo.duration;
    const dots = this.tempo.dots;
    const bpm = this.tempo.bpm;
    const font = this.font;
    let x = this.x + this.shift_x + shift_x;
    const y = stave.getYForTopText(1) + this.shift_y;

    ctx.save();

    if (name) {
      ctx.setFont(font.family, font.size, font.weight);
      ctx.fillText(name, x, y);
      x += ctx.measureText(name).width;
    }

    if (duration && bpm) {
      ctx.setFont(font.family, font.size, 'normal');

      if (name) {
        x += ctx.measureText(' ').width;
        ctx.fillText('(', x, y);
        x += ctx.measureText('(').width;
      }

      const code = Flow.getGlyphProps(duration);

      x += 3 * scale;
      Glyph.renderGlyph(ctx, x, y, options.glyph_font_scale, code.code_head);
      x += code.getWidth() * scale;

      // Draw stem and flags
      if (code.stem) {
        let stem_height = 30;

        if (code.beam_count) stem_height += 3 * (code.beam_count - 1);

        stem_height *= scale;

        const y_top = y - stem_height;
        ctx.fillRect(x - scale, y_top, scale, stem_height);

        if (code.flag) {
          Glyph.renderGlyph(ctx, x, y_top, options.glyph_font_scale, code.code_flag_upstem);

          if (!dots) x += 6 * scale;
        }
      }

      // Draw dot
      for (let i = 0; i < dots; i++) {
        x += 6 * scale;
        ctx.beginPath();
        ctx.arc(x, y + 2 * scale, 2 * scale, 0, Math.PI * 2, false);
        ctx.fill();
      }

      ctx.fillText(' = ' + bpm + (name ? ')' : ''), x + 3 * scale, y);
    }

    ctx.restore();
    return this;
  }
}
<commit_msg>Fix broken StaveTempo test<commit_after>// [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010.
// Author Radosaw Eichler 2012

import { Flow } from './tables';
import { Modifier } from './modifier';
import { StaveModifier } from './stavemodifier';
import { Glyph } from './glyph';

export class StaveTempo extends StaveModifier {
  static get CATEGORY() { return 'stavetempo'; }

  constructor(tempo, x, shift_y) {
    super();
    this.setAttribute('type', 'StaveTempo');

    this.tempo = tempo;
    this.position = Modifier.Position.ABOVE;
    this.x = x;
    this.shift_x = 10;
    this.shift_y = shift_y;
    this.font = {
      family: 'times',
      size: 14,
      weight: 'bold',
    };
    this.render_options = {
      glyph_font_scale: 30,  // font size for note
    };
  }
  getCategory() { return StaveTempo.CATEGORY; }
  setTempo(tempo) { this.tempo = tempo; return this; }
  setShiftX(x) { this.shift_x = x; return this; }
  setShiftY(y) { this.shift_y = y; return this; }

  draw(stave, shift_x) {
    const ctx = stave.checkContext();
    this.setRendered();

    const options = this.render_options;
    // FIXME: What does the '38' mean? Why 38? Is that supposed to
    // be the default font size for standard notation?
    const scale = options.glyph_font_scale / 38;
    const name = this.tempo.name;
    const duration = this.tempo.duration;
    const dots = this.tempo.dots;
    const bpm = this.tempo.bpm;
    const font = this.font;
    let x = this.x + this.shift_x + shift_x;
    const y = stave.getYForTopText(1) + this.shift_y;

    ctx.save();

    if (name) {
      ctx.setFont(font.family, font.size, font.weight);
      ctx.fillText(name, x, y);
      x += ctx.measureText(name).width;
    }

    if (duration && bpm) {
      ctx.setFont(font.family, font.size, 'normal');

      if (name) {
        x += ctx.measureText(' ').width;
        ctx.fillText('(', x, y);
        x += ctx.measureText('(').width;
      }

      const code = Flow.getGlyphProps(duration);

      x += 3 * scale;
      Glyph.renderGlyph(ctx, x, y, options.glyph_font_scale, code.code_head, this.getMusicFont());
      x += code.getWidth() * scale;

      // Draw stem and flags
      if (code.stem) {
        let stem_height = 30;

        if (code.beam_count) stem_height += 3 * (code.beam_count - 1);

        stem_height *= scale;

        const y_top = y - stem_height;
        ctx.fillRect(x - scale, y_top, scale, stem_height);

        if (code.flag) {
          Glyph.renderGlyph(ctx, x, y_top, options.glyph_font_scale, code.code_flag_upstem, this.getMusicFont());

          if (!dots) x += 6 * scale;
        }
      }

      // Draw dot
      for (let i = 0; i < dots; i++) {
        x += 6 * scale;
        ctx.beginPath();
        ctx.arc(x, y + 2 * scale, 2 * scale, 0, Math.PI * 2, false);
        ctx.fill();
      }

      ctx.fillText(' = ' + bpm + (name ? ')' : ''), x + 3 * scale, y);
    }

    ctx.restore();
    return this;
  }
}
<|endoftext|>


<commit_before>var reader = new java.io.BufferedReader(new java.io.InputStreamReader(java.lang.System.in));

var synth = javax.sound.midi.MidiSystem.getSynthesizer();
synth.open();

var channels = synth.getChannels();
instruments = synth.getDefaultSoundbank().getInstruments();

java.lang.System.out.println("Initialized");

while(true) {
    var line = reader.readLine();
    if(line == null) {
        break;
    }
    java.lang.System.out.println("Line " + line.trim());
    var data = JSON.parse(line);
    if(data["type"].toLowerCase() == "note on") {
        channels[0].noteOn(data["pitch"], data["velocity"]);
    } else if(data["type"].toLowerCase() == "note off") {
        channels[0].noteOff(data["pitch"]);
    }
}
java.lang.System.out.println("Ended");
<commit_msg>output for alex debugging<commit_after>var reader = new java.io.BufferedReader(new java.io.InputStreamReader(java.lang.System.in));

var synth = javax.sound.midi.MidiSystem.getSynthesizer();
synth.open();

var channels = synth.getChannels();
instruments = synth.getDefaultSoundbank().getInstruments();

java.lang.System.out.println("Initialized");

while(true) {
    var line = reader.readLine();
    if(line == null) {
        break;
    }
    var data = JSON.parse(line);
    java.lang.System.out.println(data["velocity"] ? ["C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"][data["pitch"] % 12] : "--");
    if(data["type"].toLowerCase() == "note on") {
        channels[0].noteOn(data["pitch"], data["velocity"]);
    } else if(data["type"].toLowerCase() == "note off") {
        channels[0].noteOff(data["pitch"]);
    }
}
java.lang.System.out.println("Ended");
<|endoftext|>


<commit_before>/**
 * @fileoverview Description of file, its uses and information
 * about its dependencies.
 */

'use strict';

/**
 *
 * @type {*|exports|module.exports}
 */
var urlparser = require('./urlparser');

/**
 * @type {string}
 */
var db = urlparser.db;

/**
 * @type {Object}
 */
var cloud;

/**
 *
 * @type {boolean}
 */
var ready = false;

/**
 *
 * @type {boolean}
 */
var cartoDbLayersready = false;

/**
 *
 * @type {string}
 */
var BACKEND = require('../../config/config.js').backend;

/**
 *
 */
var meta;

/**
 *
 */
var backboneEvents;

var host = require("./connection").getHost();

var switchLayer;

var array = [];

var uri = null

/**
 *
 * @type {{set: module.exports.set, init: module.exports.init, getMetaDataKeys: module.exports.getMetaDataKeys, ready: module.exports.ready}}
 */
module.exports = {
    /**
     *
     * @param o
     * @returns {exports}
     */
    set: function (o) {
        cloud = o.cloud;
        meta = o.meta;
        backboneEvents = o.backboneEvents;
        switchLayer = o.switchLayer;
        return this;
    },

    /**
     *
     */
    init: function () {

    },

    ready: function () {
        // If CartoDB, we wait for cartodb.createLayer to finish
        if (BACKEND === "cartodb") {
            return (ready && cartoDbLayersready);
        }
        // GC2 layers are direct tile request
        else {
            return ready;
        }
    },

    getLayers: function (separator, includeHidden) {
        var layerArr = [];
        var layers = cloud.get().map._layers;
        for (var key in layers) {
            if (layers.hasOwnProperty(key)) {
                if (layers[key].baseLayer !== true && (typeof layers[key]._tiles === "object" || typeof layers[key].wmsParams === "object")) {
                    if (typeof layers[key].id === "undefined" || (typeof layers[key].id !== "undefined" && (layers[key].id.split(".")[0] !== "__hidden") || includeHidden === true)) {
                        layerArr.push(layers[key].id);
                    }
                }
            }
        }
        if (layerArr.length > 0) {
            return layerArr.join(separator ? separator : ",");
        }
        else {
            return false;
        }
    },

    removeHidden: function () {
        var layers = cloud.get().map._layers;
        for (var key in layers) {
            if (layers.hasOwnProperty(key)) {
                if (typeof layers[key].id !== "undefined" && layers[key].id.split(".")[0] === "__hidden") {
                    cloud.get().map.removeLayer(layers[key]);
                }
            }
        }
    },
    resetCount: function (i) {
        ready = cartoDbLayersready = false;
    },

    incrementCountLoading: function (i) {
        if (array.indexOf(i) === -1) {
            array.push(i)
        }
        return array.length;
    },

    decrementCountLoading: function (i) {
        array.splice(array.indexOf(i), 1);
        return array.length;
    },

    getCountLoading: function () {
        return array.length;
    },

    getArray: function () {
        return array;
    },

    setUri: function (str) {
      uri = str;
    },

    /**
     *
     * @param l
     * @returns {Promise}
     */
    addLayer: function (l) {
        var me = this;

        return new Promise(function (resolve, reject) {

            var isBaseLayer, layers = [], metaData = meta.getMetaData();

            console.log(metaData);
            console.log(l);

            $.each(metaData.data, function (i, v) {

                var layer = v.f_table_schema + "." + v.f_table_name,
                    singleTiled = (JSON.parse(v.meta) !== null && JSON.parse(v.meta).single_tile !== undefined && JSON.parse(v.meta).single_tile === true);

                if (layer === l) {
                    isBaseLayer = !!v.baselayer;
                    layers[[layer]] = cloud.get().addTileLayers({
                        host: host,
                        layers: [layer],
                        db: db,
                        isBaseLayer: isBaseLayer,
                        tileCached: !singleTiled,
                        singleTile: singleTiled,
                        visibility: false,
                        wrapDateLine: false,
                        displayInLayerSwitcher: true,
                        name: v.f_table_name,
                        // Single tile option
                        type: !singleTiled ? "tms" : "wms",
                        format: "image/png",
                        uri: uri,
                        loadEvent: function () {
                            me.decrementCountLoading(layer);
                            backboneEvents.get().trigger("doneLoading:layers", layer);
                        },
                        loadingEvent: function () {
                            me.incrementCountLoading(layer);
                            backboneEvents.get().trigger("startLoading:layers", layer);
                        },
                        subdomains: window.gc2Options.subDomainsForTiles
                    });

                    layers[[layer]][0].setZIndex(v.sort_id + 10000);

                    resolve();

                }
            });
            reject();
            console.info(l + " added to the map.");
        })
    }
};<commit_msg>Remove some console.log<commit_after>/**
 * @fileoverview Description of file, its uses and information
 * about its dependencies.
 */

'use strict';

/**
 *
 * @type {*|exports|module.exports}
 */
var urlparser = require('./urlparser');

/**
 * @type {string}
 */
var db = urlparser.db;

/**
 * @type {Object}
 */
var cloud;

/**
 *
 * @type {boolean}
 */
var ready = false;

/**
 *
 * @type {boolean}
 */
var cartoDbLayersready = false;

/**
 *
 * @type {string}
 */
var BACKEND = require('../../config/config.js').backend;

/**
 *
 */
var meta;

/**
 *
 */
var backboneEvents;

var host = require("./connection").getHost();

var switchLayer;

var array = [];

var uri = null

/**
 *
 * @type {{set: module.exports.set, init: module.exports.init, getMetaDataKeys: module.exports.getMetaDataKeys, ready: module.exports.ready}}
 */
module.exports = {
    /**
     *
     * @param o
     * @returns {exports}
     */
    set: function (o) {
        cloud = o.cloud;
        meta = o.meta;
        backboneEvents = o.backboneEvents;
        switchLayer = o.switchLayer;
        return this;
    },

    /**
     *
     */
    init: function () {

    },

    ready: function () {
        // If CartoDB, we wait for cartodb.createLayer to finish
        if (BACKEND === "cartodb") {
            return (ready && cartoDbLayersready);
        }
        // GC2 layers are direct tile request
        else {
            return ready;
        }
    },

    getLayers: function (separator, includeHidden) {
        var layerArr = [];
        var layers = cloud.get().map._layers;
        for (var key in layers) {
            if (layers.hasOwnProperty(key)) {
                if (layers[key].baseLayer !== true && (typeof layers[key]._tiles === "object" || typeof layers[key].wmsParams === "object")) {
                    if (typeof layers[key].id === "undefined" || (typeof layers[key].id !== "undefined" && (layers[key].id.split(".")[0] !== "__hidden") || includeHidden === true)) {
                        layerArr.push(layers[key].id);
                    }
                }
            }
        }
        if (layerArr.length > 0) {
            return layerArr.join(separator ? separator : ",");
        }
        else {
            return false;
        }
    },

    removeHidden: function () {
        var layers = cloud.get().map._layers;
        for (var key in layers) {
            if (layers.hasOwnProperty(key)) {
                if (typeof layers[key].id !== "undefined" && layers[key].id.split(".")[0] === "__hidden") {
                    cloud.get().map.removeLayer(layers[key]);
                }
            }
        }
    },
    resetCount: function (i) {
        ready = cartoDbLayersready = false;
    },

    incrementCountLoading: function (i) {
        if (array.indexOf(i) === -1) {
            array.push(i)
        }
        return array.length;
    },

    decrementCountLoading: function (i) {
        array.splice(array.indexOf(i), 1);
        return array.length;
    },

    getCountLoading: function () {
        return array.length;
    },

    getArray: function () {
        return array;
    },

    setUri: function (str) {
      uri = str;
    },

    /**
     *
     * @param l
     * @returns {Promise}
     */
    addLayer: function (l) {
        var me = this;

        return new Promise(function (resolve, reject) {

            var isBaseLayer, layers = [], metaData = meta.getMetaData();

            $.each(metaData.data, function (i, v) {

                var layer = v.f_table_schema + "." + v.f_table_name,
                    singleTiled = (JSON.parse(v.meta) !== null && JSON.parse(v.meta).single_tile !== undefined && JSON.parse(v.meta).single_tile === true);

                if (layer === l) {
                    isBaseLayer = !!v.baselayer;
                    layers[[layer]] = cloud.get().addTileLayers({
                        host: host,
                        layers: [layer],
                        db: db,
                        isBaseLayer: isBaseLayer,
                        tileCached: !singleTiled,
                        singleTile: singleTiled,
                        visibility: false,
                        wrapDateLine: false,
                        displayInLayerSwitcher: true,
                        name: v.f_table_name,
                        // Single tile option
                        type: !singleTiled ? "tms" : "wms",
                        format: "image/png",
                        uri: uri,
                        loadEvent: function () {
                            me.decrementCountLoading(layer);
                            backboneEvents.get().trigger("doneLoading:layers", layer);
                        },
                        loadingEvent: function () {
                            me.incrementCountLoading(layer);
                            backboneEvents.get().trigger("startLoading:layers", layer);
                        },
                        subdomains: window.gc2Options.subDomainsForTiles
                    });

                    layers[[layer]][0].setZIndex(v.sort_id + 10000);

                    resolve();

                }
            });
            reject();
            console.info(l + " added to the map.");
        })
    }
};<|endoftext|>


<commit_before>import React from 'react';

class StepLabel extends React.Component {
  getLabelIndicator() {
    const { completed, stepNumber } = this.props;
    let indicator = ({stepNumber});

    if (completed) {
      indicator = (check);
    }

    return (

      {indicator}

    );
  }
  render() {
    const { children } = this.props;
    return (

        {children}
        {this.getLabelIndicator()}

    );
  }
}

export default StepLabel;
<commit_msg>Add propTypes to StepLabel<commit_after>import React, { PropTypes } from 'react';

class StepLabel extends React.Component {
  getLabelIndicator() {
    const { completed, stepNumber } = this.props;
    let indicator = ({stepNumber});

    if (completed) {
      indicator = (check);
    }

    return (

      {indicator}

    );
  }
  render() {
    const { children } = this.props;
    return (

        {children}
        {this.getLabelIndicator()}

    );
  }
}

StepLabel.propTypes = {
  completed: PropTypes.bool,
  stepNumber: PropTypes.number.isRequired,
  children: PropTypes.object,
};

export default StepLabel;
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

(() => {
  "use strict";

  const MARKUP = `

      <button id="play-pause-button"></button>
      <input id="progress" type="range" value="0" min="0" max="100" step="1"></input>

        #1
         / #2

      <button id="volume-switch"></button>
      <input id="volume-level" type="range" value="100" min="0" max="100" step="1"></input>

  `;

  // States.
  const BUFFERING = "buffering";
  const ENDED = "ended";
  const ERRORED = "errored";
  const PAUSED = "paused";
  const PLAYING = "playing";

  // State transitions.
  const TRANSITIONS = {
    buffer: {
      "paused": BUFFERING,
    },
    end: {
      "playing": ENDED,
      "paused": ENDED,
    },
    error: {
      "buffering": ERRORED,
      "playing": ERRORED,
      "paused": ERRORED,
    },
    pause: {
      "buffering": PAUSED,
      "playing": PAUSED,
    },
    play: {
      "buffering": PLAYING,
      "ended": PLAYING,
      "paused": PLAYING,
    },
  };

  function camelCase(str) {
    const rdashes = /-(.)/g;
    return str.replace(rdashes, (str, p1) => {
      return p1.toUpperCase();
    });
  }

  function formatTime(time, showHours = false) {
      // Format the duration as "h:mm:ss" or "m:ss"
      time = Math.round(time / 1000);
      let hours = Math.floor(time / 3600);
      let mins  = Math.floor((time % 3600) / 60);
      let secs  = Math.floor(time % 60);
      let timeString;
      if (secs < 10) {
        secs = "0" + secs;
      }
      if (hours || showHours) {
        if (mins < 10) {
          mins = "0" + mins;
        }
        timeString = hours + ":" + mins + ":" + secs;
      } else {
        timeString = mins + ":" + secs;
      }
      return timeString;
  }

  class MediaControls {
    constructor() {
      // Get the instance of the shadow root where these controls live.
      this.controls = document.servoGetMediaControls("@@@id@@@");
      // Get the instance of the host of these controls.
      this.media = this.controls.host;

      // Create root element and load markup.
      this.root = document.createElement("div");
      this.root.classList.add("root");
      this.root.innerHTML = MARKUP;
      this.controls.appendChild(this.root);

      // Import elements.
      this.elements = {};
      [
        "duration",
        "play-pause-button",
        "position-duration-box",
        "progress",
        "volume-switch",
        "volume-level"
      ].forEach(id => {
        this.elements[camelCase(id)] = this.controls.getElementById(id);
      });

      // Init position duration box.
      const positionTextNode = Array.prototype.find.call(
        this.elements.positionDurationBox.childNodes,
        (n) => !!~n.textContent.search("#1")
      );
      const durationSpan = this.elements.duration;
      const durationFormat = durationSpan.textContent;
      const positionFormat = positionTextNode.textContent;

      durationSpan.classList.add("duration");
      durationSpan.setAttribute("role", "none");
      durationSpan.id = "durationSpan";

      Object.defineProperties(this.elements.positionDurationBox, {
        durationSpan: {
          value: durationSpan,
        },
        position: {
          get: () => {
            return positionTextNode.textContent;
          },
          set: (v) => {
            positionTextNode.textContent = positionFormat.replace("#1", v);
          },
        },
        duration: {
          get: () => {
            return durationSpan.textContent;
          },
          set: (v) => {
            durationSpan.textContent = v ? durationFormat.replace("#2", v) : "";
          },
        },
        show:{
          value: (currentTime, duration) => {
            const self = this.elements.positionDurationBox;
            if (self.position != currentTime) {
              self.position = currentTime;
            }
            if (self.duration != duration) {
              self.duration = duration;
            }
            self.classList.remove("hidden");
          },
        },
      });

      // Add event listeners.
      this.mediaEvents = [
        "play", "pause", "ended", "volumechange", "loadeddata",
        "loadstart", "timeupdate", "progress", "playing",
        "waiting", "canplay", "canplaythrough", "seeking",
        "seeked", "emptied", "loadedmetadata", "error", "suspend"];
      this.mediaEvents.forEach(event => {
        this.media.addEventListener(event, this);
      });

      this.controlEvents = [
        { el: this.elements.playPauseButton, type: "click"},
        { el: this.elements.volumeSwitch, type: "click" },
        { el: this.elements.volumeLevel, type: "input" },
      ];
      this.controlEvents.forEach(({ el, type }) => {
        el.addEventListener(type, this);
      });

      // Create state transitions.
      //
      // It exposes one method per transition. i.e. this.pause(), this.play(), etc.
      // For each transition, we check that the transition is possible and call
      // the `onStateChange` handler.
      for (let name in TRANSITIONS) {
        if (!TRANSITIONS.hasOwnProperty(name)) {
          continue;
        }
        this[name] = () => {
          const from = this.state;

          // Checks if the transition is valid in the current state.
          if (!TRANSITIONS[name][from]) {
            const error = `Transition "${name}" invalid for the current state "${from}"`;
            console.error(error);
            throw new Error(error);
          }

          const to = TRANSITIONS[name][from];

          if (from == to) {
            return;
          }

          // Transition to the next state.
          this.state = to;
          this.onStateChange(from);
        };
      }

      // Set initial state.
      this.state = this.media.paused ? PAUSED : PLAYING;
      this.onStateChange(null);
    }

    // State change handler
    onStateChange(from) {
      this.render(from);
    }

    render(from = this.state) {
      const isAudioOnly = this.media.localName == "audio";
      if (!isAudioOnly) {
        // XXX This should ideally use clientHeight/clientWidth,
        //     but for some reason I couldn't figure out yet,
        //     using it breaks layout.
        this.root.style.height = this.media.videoHeight;
        this.root.style.width = this.media.videoWidth;
      }

      // Error
      if (this.state == ERRORED) {
        //XXX render errored state
        return;
      }

      if (this.state != from) {
        // Play/Pause button.
        const playPauseButton = this.elements.playPauseButton;
        playPauseButton.classList.remove(from);
        playPauseButton.classList.add(this.state);
      }

      // Progress.
      const positionPercent = this.media.currentTime / this.media.duration * 100;
      if (!isNaN(positionPercent) && positionPercent != Infinity) {
        this.elements.progress.value = positionPercent;
      } else {
        this.elements.progress.value = 0;
      }

      // Current time and duration.
      let currentTime = "0:00";
      let duration = "0:00";
      if (!isNaN(this.media.currentTime) && !isNaN(this.media.duration)) {
        currentTime = formatTime(Math.round(this.media.currentTime * 1000));
        duration = formatTime(Math.round(this.media.duration * 1000));
      }
      this.elements.positionDurationBox.show(currentTime, duration);

      // Volume.
      const volumeSwitchClass = this.media.muted || this.media.volume == 0 ? "muted" : "volumeup";
      if (!this.elements.volumeSwitch.classList.contains(volumeSwitchClass)) {
        this.elements.volumeSwitch.classList = "";
        this.elements.volumeSwitch.classList.add(volumeSwitchClass);
      }
      const volumeLevelValue = Math.round((this.media.muted ? 0 : this.media.volume) * 100);
      if (this.elements.volumeLevel.value != volumeLevelValue) {
        this.elements.volumeLevel.value = volumeLevelValue;
      }
    }

    handleEvent(event) {
      if (!event.isTrusted) {
        console.warn(`Drop untrusted event ${event.type}`);
        return;
      }

      if (this.mediaEvents.includes(event.type)) {
        this.onMediaEvent(event);
      } else {
        this.onControlEvent(event);
      }
    }

    onControlEvent(event) {
      switch (event.type) {
        case "click":
          switch (event.currentTarget) {
            case this.elements.playPauseButton:
              this.playOrPause();
              break;
            case this.elements.volumeSwitch:
              this.muteUnmute();
              break;
          }
          break;
        case "input":
          switch (event.currentTarget) {
            case this.elements.volumeLevel:
              this.changeVolume();
              break;
          }
          break;
        break;
          throw new Error(`Unknown event ${event.type}`);
      }
    }

    // HTMLMediaElement event handler
    onMediaEvent(event) {
      switch (event.type) {
        case "ended":
          this.end();
          break;
        case "play":
        case "pause":
          // Transition to PLAYING or PAUSED state.
          this[event.type]();
          break;
        case "volumechange":
        case "timeupdate":
        case "resize":
          this.render();
          break;
        case "loadedmetadata":
          break;
      }
    }

    /* Media actions */

    playOrPause() {
      switch(this.state) {
        case PLAYING:
          this.media.pause();
          break;
        case BUFFERING:
        case ENDED:
        case PAUSED:
          this.media.play();
          break;
        default:
          throw new Error(`Invalid state ${this.state}`);
      }
    }

    muteUnmute() {
      this.media.muted = !this.media.muted;
    }

    changeVolume() {
      const volume = parseInt(this.elements.volumeLevel.value);
      if (!isNaN(volume)) {
        this.media.volume = volume / 100;
      }
    }
  }

  new MediaControls();
})();
<commit_msg>Use template literals for 'formatTime'<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

(() => {
  "use strict";

  const MARKUP = `

      <button id="play-pause-button"></button>
      <input id="progress" type="range" value="0" min="0" max="100" step="1"></input>

        #1
         / #2

      <button id="volume-switch"></button>
      <input id="volume-level" type="range" value="100" min="0" max="100" step="1"></input>

  `;

  // States.
  const BUFFERING = "buffering";
  const ENDED = "ended";
  const ERRORED = "errored";
  const PAUSED = "paused";
  const PLAYING = "playing";

  // State transitions.
  const TRANSITIONS = {
    buffer: {
      "paused": BUFFERING,
    },
    end: {
      "playing": ENDED,
      "paused": ENDED,
    },
    error: {
      "buffering": ERRORED,
      "playing": ERRORED,
      "paused": ERRORED,
    },
    pause: {
      "buffering": PAUSED,
      "playing": PAUSED,
    },
    play: {
      "buffering": PLAYING,
      "ended": PLAYING,
      "paused": PLAYING,
    },
  };

  function camelCase(str) {
    const rdashes = /-(.)/g;
    return str.replace(rdashes, (str, p1) => {
      return p1.toUpperCase();
    });
  }

  function formatTime(time, showHours = false) {
    // Format the duration as "h:mm:ss" or "m:ss"
    time = Math.round(time / 1000);

    const hours = Math.floor(time / 3600);
    const mins  = Math.floor((time % 3600) / 60);
    const secs  = Math.floor(time % 60);

    const formattedHours = hours || showHours ?
      `${hours.toString().padStart(2, "0")}:` :
      "";

    return `${formattedHours}${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
  }

  class MediaControls {
    constructor() {
      // Get the instance of the shadow root where these controls live.
      this.controls = document.servoGetMediaControls("@@@id@@@");
      // Get the instance of the host of these controls.
      this.media = this.controls.host;

      // Create root element and load markup.
      this.root = document.createElement("div");
      this.root.classList.add("root");
      this.root.innerHTML = MARKUP;
      this.controls.appendChild(this.root);

      // Import elements.
      this.elements = {};
      [
        "duration",
        "play-pause-button",
        "position-duration-box",
        "progress",
        "volume-switch",
        "volume-level"
      ].forEach(id => {
        this.elements[camelCase(id)] = this.controls.getElementById(id);
      });

      // Init position duration box.
      const positionTextNode = Array.prototype.find.call(
        this.elements.positionDurationBox.childNodes,
        (n) => !!~n.textContent.search("#1")
      );
      const durationSpan = this.elements.duration;
      const durationFormat = durationSpan.textContent;
      const positionFormat = positionTextNode.textContent;

      durationSpan.classList.add("duration");
      durationSpan.setAttribute("role", "none");
      durationSpan.id = "durationSpan";

      Object.defineProperties(this.elements.positionDurationBox, {
        durationSpan: {
          value: durationSpan,
        },
        position: {
          get: () => {
            return positionTextNode.textContent;
          },
          set: (v) => {
            positionTextNode.textContent = positionFormat.replace("#1", v);
          },
        },
        duration: {
          get: () => {
            return durationSpan.textContent;
          },
          set: (v) => {
            durationSpan.textContent = v ? durationFormat.replace("#2", v) : "";
          },
        },
        show:{
          value: (currentTime, duration) => {
            const self = this.elements.positionDurationBox;
            if (self.position != currentTime) {
              self.position = currentTime;
            }
            if (self.duration != duration) {
              self.duration = duration;
            }
            self.classList.remove("hidden");
          },
        },
      });

      // Add event listeners.
      this.mediaEvents = [
        "play", "pause", "ended", "volumechange", "loadeddata",
        "loadstart", "timeupdate", "progress", "playing",
        "waiting", "canplay", "canplaythrough", "seeking",
        "seeked", "emptied", "loadedmetadata", "error", "suspend"];
      this.mediaEvents.forEach(event => {
        this.media.addEventListener(event, this);
      });

      this.controlEvents = [
        { el: this.elements.playPauseButton, type: "click"},
        { el: this.elements.volumeSwitch, type: "click" },
        { el: this.elements.volumeLevel, type: "input" },
      ];
      this.controlEvents.forEach(({ el, type }) => {
        el.addEventListener(type, this);
      });

      // Create state transitions.
      //
      // It exposes one method per transition. i.e. this.pause(), this.play(), etc.
      // For each transition, we check that the transition is possible and call
      // the `onStateChange` handler.
      for (let name in TRANSITIONS) {
        if (!TRANSITIONS.hasOwnProperty(name)) {
          continue;
        }
        this[name] = () => {
          const from = this.state;

          // Checks if the transition is valid in the current state.
          if (!TRANSITIONS[name][from]) {
            const error = `Transition "${name}" invalid for the current state "${from}"`;
            console.error(error);
            throw new Error(error);
          }

          const to = TRANSITIONS[name][from];

          if (from == to) {
            return;
          }

          // Transition to the next state.
          this.state = to;
          this.onStateChange(from);
        };
      }

      // Set initial state.
      this.state = this.media.paused ? PAUSED : PLAYING;
      this.onStateChange(null);
    }

    // State change handler
    onStateChange(from) {
      this.render(from);
    }

    render(from = this.state) {
      const isAudioOnly = this.media.localName == "audio";
      if (!isAudioOnly) {
        // XXX This should ideally use clientHeight/clientWidth,
        //     but for some reason I couldn't figure out yet,
        //     using it breaks layout.
        this.root.style.height = this.media.videoHeight;
        this.root.style.width = this.media.videoWidth;
      }

      // Error
      if (this.state == ERRORED) {
        //XXX render errored state
        return;
      }

      if (this.state != from) {
        // Play/Pause button.
        const playPauseButton = this.elements.playPauseButton;
        playPauseButton.classList.remove(from);
        playPauseButton.classList.add(this.state);
      }

      // Progress.
      const positionPercent = this.media.currentTime / this.media.duration * 100;
      if (!isNaN(positionPercent) && positionPercent != Infinity) {
        this.elements.progress.value = positionPercent;
      } else {
        this.elements.progress.value = 0;
      }

      // Current time and duration.
      let currentTime = "0:00";
      let duration = "0:00";
      if (!isNaN(this.media.currentTime) && !isNaN(this.media.duration)) {
        currentTime = formatTime(Math.round(this.media.currentTime * 1000));
        duration = formatTime(Math.round(this.media.duration * 1000));
      }
      this.elements.positionDurationBox.show(currentTime, duration);

      // Volume.
      const volumeSwitchClass = this.media.muted || this.media.volume == 0 ? "muted" : "volumeup";
      if (!this.elements.volumeSwitch.classList.contains(volumeSwitchClass)) {
        this.elements.volumeSwitch.classList = "";
        this.elements.volumeSwitch.classList.add(volumeSwitchClass);
      }
      const volumeLevelValue = Math.round((this.media.muted ? 0 : this.media.volume) * 100);
      if (this.elements.volumeLevel.value != volumeLevelValue) {
        this.elements.volumeLevel.value = volumeLevelValue;
      }
    }

    handleEvent(event) {
      if (!event.isTrusted) {
        console.warn(`Drop untrusted event ${event.type}`);
        return;
      }

      if (this.mediaEvents.includes(event.type)) {
        this.onMediaEvent(event);
      } else {
        this.onControlEvent(event);
      }
    }

    onControlEvent(event) {
      switch (event.type) {
        case "click":
          switch (event.currentTarget) {
            case this.elements.playPauseButton:
              this.playOrPause();
              break;
            case this.elements.volumeSwitch:
              this.muteUnmute();
              break;
          }
          break;
        case "input":
          switch (event.currentTarget) {
            case this.elements.volumeLevel:
              this.changeVolume();
              break;
          }
          break;
        break;
          throw new Error(`Unknown event ${event.type}`);
      }
    }

    // HTMLMediaElement event handler
    onMediaEvent(event) {
      switch (event.type) {
        case "ended":
          this.end();
          break;
        case "play":
        case "pause":
          // Transition to PLAYING or PAUSED state.
          this[event.type]();
          break;
        case "volumechange":
        case "timeupdate":
        case "resize":
          this.render();
          break;
        case "loadedmetadata":
          break;
      }
    }

    /* Media actions */

    playOrPause() {
      switch(this.state) {
        case PLAYING:
          this.media.pause();
          break;
        case BUFFERING:
        case ENDED:
        case PAUSED:
          this.media.play();
          break;
        default:
          throw new Error(`Invalid state ${this.state}`);
      }
    }

    muteUnmute() {
      this.media.muted = !this.media.muted;
    }

    changeVolume() {
      const volume = parseInt(this.elements.volumeLevel.value);
      if (!isNaN(volume)) {
        this.media.volume = volume / 100;
      }
    }
  }

  new MediaControls();
})();
<|endoftext|>


<commit_before>var Gaffa = require('gaffa');

function executeBehaviour(behaviour, value){
    behaviour.gaffa.actions.trigger(behaviour.actions.change, behaviour);
}

function ModelChangeBehaviour(){}
ModelChangeBehaviour = Gaffa.createSpec(ModelChangeBehaviour, Gaffa.Behaviour);
ModelChangeBehaviour.prototype._type = 'modelChange';
ModelChangeBehaviour.prototype.condition = new Gaffa.Property({value: true});
ModelChangeBehaviour.prototype.watch = new Gaffa.Property({
    update: function(behaviour, value){
        var gaffa = behaviour.gaffa;

        if(!behaviour.condition.value){
            return;
        }

        var throttleTime = behaviour.throttle;
        if(!isNaN(throttleTime)){
            var now = new Date();
            if(!behaviour.lastTrigger || now - behaviour.lastTrigger > throttleTime){
                behaviour.lastTrigger = now;
                executeBehaviour(behaviour, value);
            }else{
                clearTimeout(behaviour.timeout);
                behaviour.timeout = setTimeout(function(){
                        behaviour.lastTrigger = now;
                        executeBehaviour(behaviour, value);
                    },
                    throttleTime - (now - behaviour.lastTrigger)
                );
            }
        }else{
            executeBehaviour(behaviour, value);
        }
    }
});

module.exports = ModelChangeBehaviour;<commit_msg>Change is checked when either condition or watch changes<commit_after>var Gaffa = require('gaffa');

function change(behaviour){
        var gaffa = behaviour.gaffa;

        if(!behaviour.condition.value){
            return;
        }

        var throttleTime = behaviour.throttle;
        if(!isNaN(throttleTime)){
            var now = new Date();
            if(!behaviour.lastTrigger || now - behaviour.lastTrigger > throttleTime){
                behaviour.lastTrigger = now;
                behaviour.triggerActions('change');
            }else{
                clearTimeout(behaviour.timeout);
                behaviour.timeout = setTimeout(function(){
                        behaviour.lastTrigger = now;
                        behaviour.triggerActions('change');
                    },
                    throttleTime - (now - behaviour.lastTrigger)
                );
            }
        }else{
            behaviour.triggerActions('change');
        }
    }
}

function ModelChangeBehaviour(){}
ModelChangeBehaviour = Gaffa.createSpec(ModelChangeBehaviour, Gaffa.Behaviour);
ModelChangeBehaviour.prototype._type = 'modelChange';
ModelChangeBehaviour.prototype.condition = new Gaffa.Property({
    update: change,
    value: true
});
ModelChangeBehaviour.prototype.watch = new Gaffa.Property(change);

module.exports = ModelChangeBehaviour;<|endoftext|>


<commit_before>var mongoose = require('mongoose')

var schemaOptions = {
  timestamps: true,
  toJSON: {
    virtuals: true
  }
}

var getDateOffset = function (milliseconds = 0) {
  var timeObject = new Date()
  timeObject.setTime(timeObject.getTime() + milliseconds)
  return timeObject
}

var pillSchema = new mongoose.Schema({
  userId: { type: mongoose.Schema.Types.ObjectId, required: true },
  title: { type: String, required: true },
  description: String,
  icon: String,
  rule: {
    startDate: { type: Date, required: true, default: getDateOffset() },
    endDate: { type: Date, required: true, default: getDateOffset(365 * 24 * 60 * 60 * 1000) },
    currentDate: Date,
    step: { type: Number, required: true, default: 1 * 60 * 60 * 1000 }
  },
  history: { type: Array, default: [] }
}, schemaOptions)

pillSchema.virtual('rule.nextDate').get(function () {
  let nextDate = new Date()
  if (!this.rule.currentDate) { this.rule.currentDate = this.rule.startDate }
  nextDate.setTime(this.rule.currentDate.getTime() + this.rule.step)
  return nextDate
})

pillSchema.methods.updateHistory = function (cb) {
  this.history.push(getDateOffset())
  return this.save(cb)
}

pillSchema.methods.tookOne = function (cb) {
  this.rule.currentDate = this.rule.nextDate
  return this.save(cb)
}

pillSchema.pre('save', function (next) {
  if (!this.rule.currentDate) { this.rule.currentDate = this.rule.startDate }
  next()
})

var Pill = mongoose.model('Pill', pillSchema)

module.exports = Pill
<commit_msg>add methods array to Pill model<commit_after>var mongoose = require('mongoose')

var schemaOptions = {
  timestamps: true,
  toJSON: {
    virtuals: true
  }
}

var getDateOffset = function (milliseconds = 0) {
  var timeObject = new Date()
  timeObject.setTime(timeObject.getTime() + milliseconds)
  return timeObject
}

var pillSchema = new mongoose.Schema({
  userId: { type: mongoose.Schema.Types.ObjectId, required: true },
  title: { type: String, required: true },
  description: String,
  icon: String,
  rule: {
    startDate: { type: Date, required: true, default: getDateOffset() },
    endDate: { type: Date, required: true, default: getDateOffset(365 * 24 * 60 * 60 * 1000) },
    currentDate: Date,
    step: { type: Number, required: true, default: 1 * 60 * 60 * 1000 }
  },
  methods: { type: Array, default: [] },
  history: { type: Array, default: [] }
}, schemaOptions)

pillSchema.virtual('rule.nextDate').get(function () {
  let nextDate = new Date()
  if (!this.rule.currentDate) { this.rule.currentDate = this.rule.startDate }
  nextDate.setTime(this.rule.currentDate.getTime() + this.rule.step)
  return nextDate
})

pillSchema.methods.updateHistory = function (cb) {
  this.history.push(getDateOffset())
  return this.save(cb)
}

pillSchema.methods.tookOne = function (cb) {
  this.rule.currentDate = this.rule.nextDate
  return this.save(cb)
}

pillSchema.pre('save', function (next) {
  if (!this.rule.currentDate) { this.rule.currentDate = this.rule.startDate }
  next()
})

var Pill = mongoose.model('Pill', pillSchema)

module.exports = Pill
<|endoftext|>


<commit_before>var keystone	= require( 'keystone' ),
	Types		= keystone.Field.Types;

// Create model
var User = new keystone.List( 'User', {
	autokey: { path: 'key', from: 'email', unique: true },
	map: { name: 'email' },
	hidden: true
});

// Create fields
User.add( 'Login Information', {

	email: { type: Types.Email, label: 'email address', unique: true, required: true, initial: true },
	password: { type: Types.Password, label: 'password', required: true, initial: true },
	resetPasswordToken: { type: String, hidden: true, noedit: true }

}, {

	userType: { type: Types.Text, hidden: true }

});

// Define default columns in the admin interface and register the model
User.defaultColumns = 'email';
User.register();

// Export to make it available using require.  The keystone.list import throws a ReferenceError when importing a list
// that comes later when sorting alphabetically
exports = module.exports = User;
<commit_msg>make username and password non-required fields<commit_after>var keystone	= require( 'keystone' ),
	Types		= keystone.Field.Types;

// Create model
var User = new keystone.List( 'User', {
	autokey: { path: 'key', from: 'email', unique: true },
	map: { name: 'email' },
	hidden: true
});

// Create fields
User.add( 'Login Information', {

	email: { type: Types.Email, label: 'email address', unique: true, initial: true },
	password: { type: Types.Password, label: 'password', initial: true },
	resetPasswordToken: { type: String, hidden: true, noedit: true }

}, {

	userType: { type: Types.Text, hidden: true }

});

// Define default columns in the admin interface and register the model
User.defaultColumns = 'email';
User.register();

// Export to make it available using require.  The keystone.list import throws a ReferenceError when importing a list
// that comes later when sorting alphabetically
exports = module.exports = User;
<|endoftext|>


<commit_before>// This script removes demo app files
import path from 'path';
import rimraf from 'rimraf';
import fs from 'fs';
import {chalkSuccess} from './chalkConfig';

/* eslint-disable no-console */

const fileTemplates = [
  {path: './src/index.ejs', content: path.resolve(__dirname, 'template/index.default.html')},
  {path: './src/empty.spec.js', content:path.resolve(__dirname, 'template/empty.spec.js')},
  {path: './src/styles/_site.theme.scss', content:path.resolve(__dirname, 'template/_site.theme.scss')},
  {path: './src/styles/site.common.scss', content:path.resolve(__dirname, 'template/site.common.scss')}
];

const pathsToRemove = [
  './src/about/*',
  './src/app',
  './src/components',
  './src/static/*',
  './src/styles/*',
  './src/favicon.ico',
  './src/index.js',
  './src/index.style.scss',
  './src/webpack-entries.js',
  './tools/templates',
  './tools/remove.demo.js',
];

const filesToCreate = [
  {
    path: './src/index.ejs',
    content:defaultIndex,
  },
  {
    path: './src/index.js',
    content: '// Set up your application entry point here...'
  },
  {
    path: './src/styles/_site.theme.scss',
    content: '//Override any of the bootstrap variables here to customize your site theme https://github.com/twbs/bootstrap/blob/v4.0.0-alpha.6/scss/_variables.scss'
  },
  {
    path: './src/webpack-entries.js',
    content: '//setup your entry points here...\n import path from \'path\';\n export default [\n];'
  },
  {
    path: './src/default.test.js',
    content: defaultTest
  }
];

function loadTemplates(fileTemplates){
  let tasks = [];
  return new Promise(resolve=>{
    fileTemplates.forEach((fileInfo)=>tasks.push(readFile(fileInfo)));
    Promise.all(tasks).then((fileArray)=>resolve(fileArray))
      .catch((error)=> {throw new Error(error);});
  });

}

function readFile({path, file}){
  return new Promise((resolve, reject)=>{
    fs.readFile(file, 'utf8', (error, content)=>{
      if(error) reject(error);
      return {
        path,
        content
      };
    });
  });
}

function removeFile(path){
  return new Promise((resolve, reject)=>{
    rimraf(path, error => {
      if(error) reject(error);
      resolve();
    });
  });
}

function removeDemoFiles(fileList){
  let tasks = [];
  return new Promise(resolve=>{
    fileList.forEach(path => tasks.push(removeFile(path)));
    Promise.all(tasks).then(()=>resolve())
      .catch(error=> {throw new Error(error);});
  });

}

function createFile(file) {
  fs.writeFile(file.path, file.content, error => {
    if (error) throw new Error(error);
  });
}

function removePackageJsonScriptEntry(scriptName) {
  const packageJsonPath = './package.json';
  let fileData = fs.readFileSync(packageJsonPath);
  let content = JSON.parse(fileData);
  delete content.scripts[scriptName];
  fs.writeFileSync(packageJsonPath,
    JSON.stringify(content, null, 2) + '\n');
}

async function removeDemo(){
  await removeDemoFiles(pathsToRemove);
  let templates = await loadTemplates(fileTemplates);
  (filesToCreate.concat(templates)).map(file=>createFile(file));
}

removeDemo();
removePackageJsonScriptEntry('remove-demo');

console.log(chalkSuccess('Demo app removed.'));
<commit_msg>moved removePackageJsonEntry to removeDemo function<commit_after>// This script removes demo app files
import path from 'path';
import rimraf from 'rimraf';
import fs from 'fs';
import {chalkSuccess} from './chalkConfig';

/* eslint-disable no-console */

const fileTemplates = [
  {path: './src/index.ejs', content: path.resolve(__dirname, 'template/index.default.html')},
  {path: './src/empty.spec.js', content:path.resolve(__dirname, 'template/empty.spec.js')},
  {path: './src/styles/_site.theme.scss', content:path.resolve(__dirname, 'template/_site.theme.scss')},
  {path: './src/styles/site.common.scss', content:path.resolve(__dirname, 'template/site.common.scss')}
];

const pathsToRemove = [
  './src/about/*',
  './src/app',
  './src/components',
  './src/static/*',
  './src/styles/*',
  './src/favicon.ico',
  './src/index.js',
  './src/index.style.scss',
  './src/webpack-entries.js',
  './tools/templates',
  './tools/remove.demo.js',
];

const filesToCreate = [
  {
    path: './src/index.ejs',
    content:defaultIndex,
  },
  {
    path: './src/index.js',
    content: '// Set up your application entry point here...'
  },
  {
    path: './src/styles/_site.theme.scss',
    content: '//Override any of the bootstrap variables here to customize your site theme https://github.com/twbs/bootstrap/blob/v4.0.0-alpha.6/scss/_variables.scss'
  },
  {
    path: './src/webpack-entries.js',
    content: '//setup your entry points here...\n import path from \'path\';\n export default [\n];'
  },
  {
    path: './src/default.test.js',
    content: defaultTest
  }
];

function loadTemplates(fileTemplates){
  let tasks = [];
  return new Promise(resolve=>{
    fileTemplates.forEach((fileInfo)=>tasks.push(readFile(fileInfo)));
    Promise.all(tasks).then((fileArray)=>resolve(fileArray))
      .catch((error)=> {throw new Error(error);});
  });

}

function readFile({path, file}){
  return new Promise((resolve, reject)=>{
    fs.readFile(file, 'utf8', (error, content)=>{
      if(error) reject(error);
      return {
        path,
        content
      };
    });
  });
}

function removeFile(path){
  return new Promise((resolve, reject)=>{
    rimraf(path, error => {
      if(error) reject(error);
      resolve();
    });
  });
}

function removeDemoFiles(fileList){
  let tasks = [];
  return new Promise(resolve=>{
    fileList.forEach(path => tasks.push(removeFile(path)));
    Promise.all(tasks).then(()=>resolve())
      .catch(error=> {throw new Error(error);});
  });

}

function createFile(file) {
  fs.writeFile(file.path, file.content, error => {
    if (error) throw new Error(error);
  });
}

function removePackageJsonScriptEntry(scriptName) {
  const packageJsonPath = './package.json';
  let fileData = fs.readFileSync(packageJsonPath);
  let content = JSON.parse(fileData);
  delete content.scripts[scriptName];
  fs.writeFileSync(packageJsonPath,
    JSON.stringify(content, null, 2) + '\n');
}

async function removeDemo(){
  await removeDemoFiles(pathsToRemove);
  let templates = await loadTemplates(fileTemplates);
  (filesToCreate.concat(templates)).map(file=>createFile(file));
  removePackageJsonScriptEntry('remove-demo');
}

removeDemo();

console.log(chalkSuccess('Demo app removed.'));
<|endoftext|>


<commit_before>import isString from 'lodash/isString'
import last from 'lodash/last'
import extend from 'lodash/extend'
import clone from 'lodash/clone'
import map from 'lodash/map'
import $ from 'substance-cheerio'
import EventEmitter from '../util/EventEmitter'
import DOMElement from './DOMElement'

class CheerioDOMElement extends DOMElement {

  constructor(el) {
    super()
    EventEmitter.call(this)

    this.el = el
    this.$el = $(el)
    el._wrapper = this
    this.htmlProps = {}
  }

  get _isCheerioDOMElement() {
    return true
  }

  getNativeElement() {
    return this.el
  }

  _wrapNativeElement(el) {
    if (el._wrapper) {
      return el._wrapper
    } else {
      return new CheerioDOMElement(el)
    }
  }

  hasClass(className) {
    return this.$el.hasClass(className)
  }

  addClass(className) {
    this.$el.addClass(className)
    return this
  }

  removeClass(className) {
    this.$el.removeClass(className)
    return this
  }

  getClasses() {
    return this.$el.attr('class')
  }

  setClasses(classString) {
    this.$el.attr('class', classString)
    return this
  }

  getAttribute(name) {
    return this.$el.attr(name)
  }

  setAttribute(name, value) {
    this.$el.attr(name, value)
    return this
  }

  removeAttribute(name) {
    this.$el.removeAttr(name)
    return this
  }

  getAttributes() {
    let attributes = clone(this.el.attribs)
    return attributes
  }

  getProperty(name) {
    return this.$el.prop(name)
  }

  setProperty(name, value) {
    this.htmlProps[name] = value
    this.$el.prop(name, value)
    return this
  }

  // TODO: verify that this.el[name] is correct
  removeProperty(name) {
    delete this.htmlProps[name]
    delete this.el[name]
    return this
  }

  getTagName() {
    if (this.el.type !== 'tag') {
      return ""
    } else {
      return this.el.name.toLowerCase()
    }
  }

  setTagName(tagName) {
    let newEl = $._createElement(tagName, this.el.root)
    let $newEl = $(newEl)
    $newEl.html(this.$el.html())
    newEl.attribs = extend({}, this.el.attribs)
    this._replaceNativeEl(newEl)
    return this
  }

  getId() {
    return this.$el.attr('id')
  }

  setId(id) {
    this.$el.attr('id', id)
    return this
  }

  getTextContent() {
    return this.$el.text()
  }

  setTextContent(text) {
    this.$el.text(text)
    return this
  }

  getInnerHTML() {
    return this.$el.html()
  }

  setInnerHTML(html) {
    this.$el.html(html)
    return this
  }

  getOuterHTML() {
    // TODO: this is not really jquery
    return $._serialize(this.el)
  }

  getValue() {
    return this.$el.val()
  }

  setValue(value) {
    this.$el.val(value)
    return this
  }

  getStyle(name) {
    return this.$el.css(name)
  }

  setStyle(name, value) {
    this.$el.css(name, value)
    return this
  }

  addEventListener() {
    return this
  }

  removeEventListener() {
    return this
  }

  removeAllEventListeners() {
    return this
  }

  getEventListeners() {
    return []
  }

  getChildCount() {
    return this.el.children.length
  }

  getChildNodes() {
    let childNodes = this.el.children
    childNodes = childNodes.map(function(node) {
      return this._wrapNativeElement(node)
    }.bind(this))
    return childNodes
  }

  getChildren() {
    let children = this.el.children
    children = children.filter(function(node) {
      return node.type === "tag"
    })
    children = children.map(function(node) {
      return this._wrapNativeElement(node)
    }.bind(this))
    return children
  }

  getChildAt(pos) {
    return this._wrapNativeElement(this.el.children[pos])
  }

  getChildIndex(child) {
    if (!child._isCheerioDOMElement) {
      throw new Error('Expecting a CheerioDOMElement instance.')
    }
    return this.el.children.indexOf(child.el)
  }

  getFirstChild() {
    let firstChild = this.el.children[0]
    if (firstChild) {
      return CheerioDOMElement.wrapNativeElement(firstChild)
    } else {
      return null
    }
  }

  getLastChild() {
    let lastChild = last(this.el.children)
    if (lastChild) {
      return CheerioDOMElement.wrapNativeElement(lastChild)
    } else {
      return null
    }
  }

  getNextSibling() {
    var next = this.el.next;
    if (next) {
      return CheerioDOMElement.wrapNativeElement(next)
    } else {
      return null
    }
  }

  getPreviousSibling() {
    let previous = this.el.previous
    if (previous) {
      return CheerioDOMElement.wrapNativeElement(previous)
    } else {
      return null
    }
  }

  isTextNode() {
    // cheerio specific
    return this.el.type === "text"
  }

  isElementNode() {
    // cheerio specific
    return this.el.type === "tag" || this.el.type === "script"
  }

  isCommentNode() {
    // cheerio specific
    return this.el.type === "comment"
  }

  isDocumentNode() {
    return this.el === this.el.root
  }

  clone() {
    let clone = this.$el.clone()[0]
    return this._wrapNativeElement(clone)
  }

  createElement(tagName) {
    let el = $._createElement(tagName, this.el.root)
    return this._wrapNativeElement(el)
  }

  createTextNode(text) {
    let el = $._createTextNode(text)
    return this._wrapNativeElement(el)
  }

  is(cssSelector) {
    // Note: unfortunately there is no cross-browser supported selectr matcher
    // Element.matches is not supported by all (mobile) browsers
    return this.$el.is(cssSelector)
  }

  getParent() {
    let parent = this.el.parent
    if (parent) {
      return this._wrapNativeElement(parent)
    } else {
      return null
    }
  }

  getRoot() {
    let el = this.el
    let parent = el
    while (parent) {
      el = parent
      parent = el.parent
    }
    return this._wrapNativeElement(el)
  }

  find(cssSelector) {
    let result = this.$el.find(cssSelector)
    if (result.length > 0) {
      return this._wrapNativeElement(result[0])
    } else {
      return null
    }
  }

  findAll(cssSelector) {
    let result = this.$el.find(cssSelector)
    if (result.length > 0) {
      return map(result, function(el) {
        return this._wrapNativeElement(el)
      }.bind(this))
    } else {
      return []
    }
  }

  _normalizeChild(child) {
    if (isString(child)) {
      child = this.createTextNode(child)
    }
    if (child._wrapper) {
      child = child._wrapper
    }
    if (!child || !child._isCheerioDOMElement) {
      throw new Error('Illegal argument: only String and CheerioDOMElement instances are valid.')
    }
    console.assert(child.el._wrapper === child, "Expecting a backlink between native element and CheerioDOMElement")
    return child.getNativeElement()
  }

  appendChild(child) {
    child = this._normalizeChild(child)
    this.el.children.push(child)
    child.parent = this.el
    return this
  }

  insertAt(pos, child) {
    child = this._normalizeChild(child)
    let children = this.el.children
    // NOTE: manipulating cheerio's internal children array
    // as otherwise cheerio clones the element loosing our custom data
    if (pos >= children.length) {
      children.push(child)
    } else {
      children.splice(pos, 0, child)
    }
    child.parent = this.el
    return this
  }

  insertBefore(child, before) {
    let pos = this.el.children.indexOf(before.el)
    if (pos > -1) {
      return this.insertAt(pos, child)
    } else {
      throw new Error('insertBefore(): reference node is not a child of this element.')
    }
  }

  removeAt(pos) {
    if (pos < 0 || pos >= this.el.children.length) {
      throw new Error('removeAt(): Index out of bounds.')
    }
    // NOTE: again manipulating cheerio's internal children array --
    // it works.
    let child = this.el.children[pos]
    child.parent = null
    this.el.children.splice(pos, 1)
    return this
  }

  removeChild(child) {
    if (!child || !child._isCheerioDOMElement) {
      throw new Error('removeChild(): Illegal arguments. Expecting a CheerioDOMElement instance.')
    }
    let idx = this.el.children.indexOf(child.el)
    if (idx < 0) {
      throw new Error('removeChild(): element is not a child.')
    }
    this.removeAt(idx)
    return this
  }

  replaceChild(oldChild, newChild) {
    if (!newChild || !oldChild ||
        !newChild._isCheerioDOMElement || !oldChild._isCheerioDOMElement) {
      throw new Error('replaceChild(): Illegal arguments. Expecting BrowserDOMElement instances.')
    }
    let idx = this.el.children.indexOf(oldChild.el)
    if (idx > -1) {
      this.removeAt(idx)
      this.insertAt(idx, newChild.el)
    }
    return this
  }

  empty() {
    this.$el.empty()
    return this
  }

  remove() {
    this.$el.remove()
    return this
  }

  _replaceNativeEl(newEl) {
    let $newEl = $(newEl)
    this.$el.replaceWith($newEl)
    this.el = newEl
    this.$el = $newEl
    // HACK: we need the correct backlink
    this.el._wrapper = this
  }

  isInDocument() {
    let el = this.el
    while (el) {
      if (el === el.root) {
        return true
      }
      el = el.parent
    }
    return false
  }

  click() {
    this.emit('click')
  }

}

EventEmitter.mixin(CheerioDOMElement)

DOMElement._defineProperties(CheerioDOMElement, DOMElement._propertyNames);

CheerioDOMElement.createTextNode = function(text) {
  return CheerioDOMElement.wrapNativeElement(
    $._createTextNode(text)
  )
}

CheerioDOMElement.createElement = function(tagName) {
  return CheerioDOMElement.wrapNativeElement(
    $('<' + tagName + '>')[0]
  )
}

CheerioDOMElement.parseMarkup = function(str, format) {
  let nativeEls = []
  let doc;

  if (!str) {
    // Create an empty XML document
    if (format === 'xml') {
      doc = $.parseXML('')
    } else {
      doc = $.parseHTML('')
    }
    return new CheerioDOMElement(doc)
  } else {
    if (format === 'xml') {
      nativeEls = $.parseXML(str)
    } else {
      nativeEls = $.parseHTML(str)
    }
  }
  let elements = nativeEls.map(function(el) {
    return new CheerioDOMElement(el)
  });
  if (elements.length === 1) {
    return elements[0]
  } else {
    return elements
  }
}

CheerioDOMElement.wrapNativeElement = function(el) {
  if (el._wrapper) {
    return el._wrapper
  } else {
    return new CheerioDOMElement(el)
  }
}

export default CheerioDOMElement
<commit_msg>Removed incorecct to EventEmitter ctor<commit_after>import isString from 'lodash/isString'
import last from 'lodash/last'
import extend from 'lodash/extend'
import clone from 'lodash/clone'
import map from 'lodash/map'
import $ from 'substance-cheerio'
import EventEmitter from '../util/EventEmitter'
import DOMElement from './DOMElement'

class CheerioDOMElement extends DOMElement {

  constructor(el) {
    super()

    this.el = el
    this.$el = $(el)
    el._wrapper = this
    this.htmlProps = {}
  }

  get _isCheerioDOMElement() {
    return true
  }

  getNativeElement() {
    return this.el
  }

  _wrapNativeElement(el) {
    if (el._wrapper) {
      return el._wrapper
    } else {
      return new CheerioDOMElement(el)
    }
  }

  hasClass(className) {
    return this.$el.hasClass(className)
  }

  addClass(className) {
    this.$el.addClass(className)
    return this
  }

  removeClass(className) {
    this.$el.removeClass(className)
    return this
  }

  getClasses() {
    return this.$el.attr('class')
  }

  setClasses(classString) {
    this.$el.attr('class', classString)
    return this
  }

  getAttribute(name) {
    return this.$el.attr(name)
  }

  setAttribute(name, value) {
    this.$el.attr(name, value)
    return this
  }

  removeAttribute(name) {
    this.$el.removeAttr(name)
    return this
  }

  getAttributes() {
    let attributes = clone(this.el.attribs)
    return attributes
  }

  getProperty(name) {
    return this.$el.prop(name)
  }

  setProperty(name, value) {
    this.htmlProps[name] = value
    this.$el.prop(name, value)
    return this
  }

  // TODO: verify that this.el[name] is correct
  removeProperty(name) {
    delete this.htmlProps[name]
    delete this.el[name]
    return this
  }

  getTagName() {
    if (this.el.type !== 'tag') {
      return ""
    } else {
      return this.el.name.toLowerCase()
    }
  }

  setTagName(tagName) {
    let newEl = $._createElement(tagName, this.el.root)
    let $newEl = $(newEl)
    $newEl.html(this.$el.html())
    newEl.attribs = extend({}, this.el.attribs)
    this._replaceNativeEl(newEl)
    return this
  }

  getId() {
    return this.$el.attr('id')
  }

  setId(id) {
    this.$el.attr('id', id)
    return this
  }

  getTextContent() {
    return this.$el.text()
  }

  setTextContent(text) {
    this.$el.text(text)
    return this
  }

  getInnerHTML() {
    return this.$el.html()
  }

  setInnerHTML(html) {
    this.$el.html(html)
    return this
  }

  getOuterHTML() {
    // TODO: this is not really jquery
    return $._serialize(this.el)
  }

  getValue() {
    return this.$el.val()
  }

  setValue(value) {
    this.$el.val(value)
    return this
  }

  getStyle(name) {
    return this.$el.css(name)
  }

  setStyle(name, value) {
    this.$el.css(name, value)
    return this
  }

  addEventListener() {
    return this
  }

  removeEventListener() {
    return this
  }

  removeAllEventListeners() {
    return this
  }

  getEventListeners() {
    return []
  }

  getChildCount() {
    return this.el.children.length
  }

  getChildNodes() {
    let childNodes = this.el.children
    childNodes = childNodes.map(function(node) {
      return this._wrapNativeElement(node)
    }.bind(this))
    return childNodes
  }

  getChildren() {
    let children = this.el.children
    children = children.filter(function(node) {
      return node.type === "tag"
    })
    children = children.map(function(node) {
      return this._wrapNativeElement(node)
    }.bind(this))
    return children
  }

  getChildAt(pos) {
    return this._wrapNativeElement(this.el.children[pos])
  }

  getChildIndex(child) {
    if (!child._isCheerioDOMElement) {
      throw new Error('Expecting a CheerioDOMElement instance.')
    }
    return this.el.children.indexOf(child.el)
  }

  getFirstChild() {
    let firstChild = this.el.children[0]
    if (firstChild) {
      return CheerioDOMElement.wrapNativeElement(firstChild)
    } else {
      return null
    }
  }

  getLastChild() {
    let lastChild = last(this.el.children)
    if (lastChild) {
      return CheerioDOMElement.wrapNativeElement(lastChild)
    } else {
      return null
    }
  }

  getNextSibling() {
    var next = this.el.next;
    if (next) {
      return CheerioDOMElement.wrapNativeElement(next)
    } else {
      return null
    }
  }

  getPreviousSibling() {
    let previous = this.el.previous
    if (previous) {
      return CheerioDOMElement.wrapNativeElement(previous)
    } else {
      return null
    }
  }

  isTextNode() {
    // cheerio specific
    return this.el.type === "text"
  }

  isElementNode() {
    // cheerio specific
    return this.el.type === "tag" || this.el.type === "script"
  }

  isCommentNode() {
    // cheerio specific
    return this.el.type === "comment"
  }

  isDocumentNode() {
    return this.el === this.el.root
  }

  clone() {
    let clone = this.$el.clone()[0]
    return this._wrapNativeElement(clone)
  }

  createElement(tagName) {
    let el = $._createElement(tagName, this.el.root)
    return this._wrapNativeElement(el)
  }

  createTextNode(text) {
    let el = $._createTextNode(text)
    return this._wrapNativeElement(el)
  }

  is(cssSelector) {
    // Note: unfortunately there is no cross-browser supported selectr matcher
    // Element.matches is not supported by all (mobile) browsers
    return this.$el.is(cssSelector)
  }

  getParent() {
    let parent = this.el.parent
    if (parent) {
      return this._wrapNativeElement(parent)
    } else {
      return null
    }
  }

  getRoot() {
    let el = this.el
    let parent = el
    while (parent) {
      el = parent
      parent = el.parent
    }
    return this._wrapNativeElement(el)
  }

  find(cssSelector) {
    let result = this.$el.find(cssSelector)
    if (result.length > 0) {
      return this._wrapNativeElement(result[0])
    } else {
      return null
    }
  }

  findAll(cssSelector) {
    let result = this.$el.find(cssSelector)
    if (result.length > 0) {
      return map(result, function(el) {
        return this._wrapNativeElement(el)
      }.bind(this))
    } else {
      return []
    }
  }

  _normalizeChild(child) {
    if (isString(child)) {
      child = this.createTextNode(child)
    }
    if (child._wrapper) {
      child = child._wrapper
    }
    if (!child || !child._isCheerioDOMElement) {
      throw new Error('Illegal argument: only String and CheerioDOMElement instances are valid.')
    }
    console.assert(child.el._wrapper === child, "Expecting a backlink between native element and CheerioDOMElement")
    return child.getNativeElement()
  }

  appendChild(child) {
    child = this._normalizeChild(child)
    this.el.children.push(child)
    child.parent = this.el
    return this
  }

  insertAt(pos, child) {
    child = this._normalizeChild(child)
    let children = this.el.children
    // NOTE: manipulating cheerio's internal children array
    // as otherwise cheerio clones the element loosing our custom data
    if (pos >= children.length) {
      children.push(child)
    } else {
      children.splice(pos, 0, child)
    }
    child.parent = this.el
    return this
  }

  insertBefore(child, before) {
    let pos = this.el.children.indexOf(before.el)
    if (pos > -1) {
      return this.insertAt(pos, child)
    } else {
      throw new Error('insertBefore(): reference node is not a child of this element.')
    }
  }

  removeAt(pos) {
    if (pos < 0 || pos >= this.el.children.length) {
      throw new Error('removeAt(): Index out of bounds.')
    }
    // NOTE: again manipulating cheerio's internal children array --
    // it works.
    let child = this.el.children[pos]
    child.parent = null
    this.el.children.splice(pos, 1)
    return this
  }

  removeChild(child) {
    if (!child || !child._isCheerioDOMElement) {
      throw new Error('removeChild(): Illegal arguments. Expecting a CheerioDOMElement instance.')
    }
    let idx = this.el.children.indexOf(child.el)
    if (idx < 0) {
      throw new Error('removeChild(): element is not a child.')
    }
    this.removeAt(idx)
    return this
  }

  replaceChild(oldChild, newChild) {
    if (!newChild || !oldChild ||
        !newChild._isCheerioDOMElement || !oldChild._isCheerioDOMElement) {
      throw new Error('replaceChild(): Illegal arguments. Expecting BrowserDOMElement instances.')
    }
    let idx = this.el.children.indexOf(oldChild.el)
    if (idx > -1) {
      this.removeAt(idx)
      this.insertAt(idx, newChild.el)
    }
    return this
  }

  empty() {
    this.$el.empty()
    return this
  }

  remove() {
    this.$el.remove()
    return this
  }

  _replaceNativeEl(newEl) {
    let $newEl = $(newEl)
    this.$el.replaceWith($newEl)
    this.el = newEl
    this.$el = $newEl
    // HACK: we need the correct backlink
    this.el._wrapper = this
  }

  isInDocument() {
    let el = this.el
    while (el) {
      if (el === el.root) {
        return true
      }
      el = el.parent
    }
    return false
  }

  click() {
    this.emit('click')
  }

}

EventEmitter.mixin(CheerioDOMElement)

DOMElement._defineProperties(CheerioDOMElement, DOMElement._propertyNames);

CheerioDOMElement.createTextNode = function(text) {
  return CheerioDOMElement.wrapNativeElement(
    $._createTextNode(text)
  )
}

CheerioDOMElement.createElement = function(tagName) {
  return CheerioDOMElement.wrapNativeElement(
    $('<' + tagName + '>')[0]
  )
}

CheerioDOMElement.parseMarkup = function(str, format) {
  let nativeEls = []
  let doc;

  if (!str) {
    // Create an empty XML document
    if (format === 'xml') {
      doc = $.parseXML('')
    } else {
      doc = $.parseHTML('')
    }
    return new CheerioDOMElement(doc)
  } else {
    if (format === 'xml') {
      nativeEls = $.parseXML(str)
    } else {
      nativeEls = $.parseHTML(str)
    }
  }
  let elements = nativeEls.map(function(el) {
    return new CheerioDOMElement(el)
  });
  if (elements.length === 1) {
    return elements[0]
  } else {
    return elements
  }
}

CheerioDOMElement.wrapNativeElement = function(el) {
  if (el._wrapper) {
    return el._wrapper
  } else {
    return new CheerioDOMElement(el)
  }
}

export default CheerioDOMElement
<|endoftext|>


<commit_before>var TILESIZE = 40,
    PRESSED_KEYS = [],
    FPS = 0,
    lastFrameTime = 0,
    playersCollection = new PlayersCollection(),
    minesCollection = new MinesCollection(),
    camera = new Camera(),
    currentPlayer,
    canvas,
    context,
    board;

// main game loop
function main() {
  var currentTime = new Date().getTime();
  var diff = (currentTime - lastFrameTime) / 1000; // divide by msecs
  lastFrameTime = currentTime;
  FPS = 1.0 / diff;

  draw();
  update();
  window.requestAnimationFrame(main);
}

function setup() {
  canvas.width = 800;
  canvas.height = 600;
  board = new Board(40, 40);

  // Create a new Player and add to the middle of the board
  var playerPos = new Vector(board.w, board.h).mul(0.5);
  currentPlayer = playersCollection.newPlayer('liam', playerPos);
}

// does the screen drawing
function draw() {
  Utils.clearCanvas(canvas);

  var player = currentPlayer;
  var newX = player.position.x * TILESIZE - (canvas.width / 2);
  var newY = player.position.y * TILESIZE - (canvas.height / 2);
  context.translate(-newX, -newY);

  board.draw();
  playersCollection.draw();
  minesCollection.draw();
  camera.draw();

  context.translate(newX, newY);
  document.getElementById('debug').innerHTML = Math.floor(FPS) + 'fps';
}

// updates the current objects
function update() {
  camera.update(currentPlayer.position);
  board.update({keys: PRESSED_KEYS});
  minesCollection.update();
  playersCollection.update({keys: PRESSED_KEYS});
  PRESSED_KEYS = []; // clear all pressed keys for this frame
}

// set up the game and run it
window.onload = function herewego() {
  canvas = document.getElementById('canvas');
  context = canvas.getContext('2d');
  setup();
  main();
};

window.addEventListener('keydown', function (event) {
  switch (event.keyCode) {
    case 37: PRESSED_KEYS.push('left'); break;
    case 38: PRESSED_KEYS.push('up'); break;
    case 39: PRESSED_KEYS.push('right'); break;
    case 40: PRESSED_KEYS.push('down'); break;
    case 65: PRESSED_KEYS.push('zoomin'); break; // a
    case 83: PRESSED_KEYS.push('zoomout'); break; // s
    case 32: PRESSED_KEYS.push('leavemine'); break; // space
  }
  // event.preventDefault();
});

<commit_msg>setup camera in game.setup, board does not take keyboard input anymore<commit_after>var TILESIZE = 40,
    PRESSED_KEYS = [],
    FPS = 0,
    lastFrameTime = 0,
    playersCollection = new PlayersCollection(),
    minesCollection = new MinesCollection(),
    camera = new Camera(),
    currentPlayer,
    canvas,
    context,
    board;

// main game loop
function main() {
  var currentTime = new Date().getTime();
  var diff = (currentTime - lastFrameTime) / 1000; // divide by msecs
  lastFrameTime = currentTime;
  FPS = 1.0 / diff;

  draw();
  update();
  window.requestAnimationFrame(main);
}

function setup() {
  canvas.width = 800;
  canvas.height = 600;
  board = new Board(70, 70);
  camera.setup();

  // Create a new Player and add to the middle of the board
  var playerPos = new Vector(board.w, board.h).mul(0.5);
  currentPlayer = playersCollection.newPlayer('liam', playerPos);
}

// does the screen drawing
function draw() {
  Utils.clearCanvas(canvas);

  var player = currentPlayer;
  var newX = player.position.x * TILESIZE - (canvas.width / 2);
  var newY = player.position.y * TILESIZE - (canvas.height / 2);
  context.translate(-newX, -newY);

  board.draw();
  playersCollection.draw();
  minesCollection.draw();
  camera.draw();

  context.translate(newX, newY);
  document.getElementById('debug').innerHTML = Math.floor(FPS) + 'fps';
}

// updates the current objects
function update() {
  camera.update(currentPlayer.position);
  board.update();
  minesCollection.update();
  playersCollection.update({keys: PRESSED_KEYS});
  PRESSED_KEYS = []; // clear all pressed keys for this frame
}

// set up the game and run it
window.onload = function herewego() {
  canvas = document.getElementById('canvas');
  context = canvas.getContext('2d');
  setup();
  main();
};

window.addEventListener('keydown', function (event) {
  switch (event.keyCode) {
    case 37: PRESSED_KEYS.push('left'); break;
    case 38: PRESSED_KEYS.push('up'); break;
    case 39: PRESSED_KEYS.push('right'); break;
    case 40: PRESSED_KEYS.push('down'); break;
    case 65: PRESSED_KEYS.push('zoomin'); break; // a
    case 83: PRESSED_KEYS.push('zoomout'); break; // s
    case 32: PRESSED_KEYS.push('leavemine'); break; // space
  }
  // event.preventDefault();
});

<|endoftext|>


<commit_before>'use strict'

const {bookshelf} = require('../db/database')
// require('./gameWord')
// require('./word')
// require('./user')
// require('./userGame')

const Animal = bookshelf.Model.extend({
  tableName: 'games',
  // sets relationship with words
  // words: function () { return this.belongsToMany('Word').through('gameWord')},
}, {
  // gets all games
  getAllGames: function () {
    return this.forge().orderBy('id', 'ASC')
  }
  // gets all games with a specified user
  // getAllWithRelated: function() {
  //   return this.forge().orderBy('id', 'ASC').fetchAll({withRelated: ['users']})
  // }
  // adds a game
  // addGame: function(game) {
  //   return this.forge(game).save({},{require: true})
  // },
  // use by cascade delete to delete games records from pivot table
  // dependents: ['users', 'words'],

  // edits game
  // updateGame: function(id,{number_correct, number_asked, won}) {
  //   // console.log("bodyFromModel",{age:10});
  //   return this.forge({id}).save({number_correct, number_asked, won})
  //   .then( (edit) =>{
  //     return{"msg" : "edited successfully"}
  //   })
  //   .catch( (err) =>{ return err})
  // }
})

module.exports = bookshelf.model('Game', Game)
<commit_msg>added .fetchAll() to method to make test pass<commit_after>'use strict'

const {bookshelf} = require('../db/database')
// require('./gameWord')
// require('./word')
// require('./user')
// require('./userGame')

const Game = bookshelf.Model.extend({
  tableName: 'games'
  // sets relationship with words
  // words: function () { return this.belongsToMany('Word').through('gameWord')},
}, {
  // gets all games
  getAllGames: function() {
    return this.forge().orderBy('id', 'ASC').fetchAll()
  }
  // gets all games with a specified user
  // getAllWithRelated: function() {
  //   return this.forge().orderBy('id', 'ASC').fetchAll({withRelated: ['users']})
  // }
  // adds a game
  // addGame: function(game) {
  //   return this.forge(game).save({},{require: true})
  // },
  // use by cascade delete to delete games records from pivot table
  // dependents: ['users', 'words'],

  // edits game
  // updateGame: function(id,{number_correct, number_asked, won}) {
  //   // console.log("bodyFromModel",{age:10});
  //   return this.forge({id}).save({number_correct, number_asked, won})
  //   .then( (edit) =>{
  //     return{"msg" : "edited successfully"}
  //   })
  //   .catch( (err) =>{ return err})
  // }
})

module.exports = bookshelf.model('Game', Game)
<|endoftext|>