<commit_before>;
(function() {

  /* Sparkline AddIn, based on jquery.sparkline.js sparklines.
   *
   */
  var sparkline = {
    name: "sparkline",
    label: "Sparkline",
    defaults: {
      type: 'line'
    },
    implementation: function (tgt, st, opt) {
      var t = $(tgt);
      t.sparkline(st.value.split(/,/),opt);
      t.removeClass("sparkline");
    }
  };
  Dashboards.registerAddIn("Table", "colType", new AddIn(sparkline));

  var pvSparkline = {
    name: "pvSparkline",
    label: "Protovis Sparkline",
    defaults: {
      height: 10,
      strokeStyle: "#000",
      lineWidth: 1,
      width: undefined,
      canvasMargin: 2
    },
    implementation: function(tgt, st, opt) {
      var ph = $(tgt),
      sparklineData = st.value,
      data = sparklineData.split(",");
      n = data.length,
      w = opt.width || ph.width(),
      h = opt.height,
      min = pv.min.index(data),
      max = pv.max.index(data);
      ph.empty();

      var container = $("

").appendTo(ph);

      //console.log("count "+count);

      var vis = new pv.Panel()
      .canvas(container.get(0))
      .width(w)
      .height(h)
      .margin(opt.canvasMargin);

      vis.add(pv.Line)
      .data(data)
      .left(pv.Scale.linear(0, n - 1).range(0, w).by(pv.index))
      .bottom(pv.Scale.linear(data).range(0, h))
      .strokeStyle(opt.strokeStyle)
      .lineWidth(opt.lineWidth);

      vis.render();

    }
  };
  Dashboards.registerAddIn("Table", "colType", new AddIn(pvSparkline));

 dataBar = {
    name: "dataBar",
    label: "Data Bar",
    defaults: {
      widthRatio:1,
      height: 10,
      startColor: "#55A4D6",
      endColor: "#448FC8",
      stroke: null,
      max: undefined,
      includeValue: false,
      valueFormat: function(v, format, st) {
        return "" + sprintf(format,v) + "";
      }
    },
    implementation: function(tgt, st, opt) {
      var max = opt.max || Math.max.apply(Math,st.tableData.map(function(e){return Math.abs(e[st.colIdx]);}));
      var cell = $(tgt);
      cell.empty();

      var ph =$("

").addClass('dataBarContainer').appendTo(cell);
      var wtmp = opt.widthRatio * ph.width();
      var htmp = opt.height;

      var value = st.value;
      var leftVal=0, rightVal=parseFloat(value);
      if(leftVal>rightVal){
      	leftVal = value;
      	rightVal = 0;
      }
      var delta = rightVal - leftVal;
      var xx = pv.Scale.linear(0,max).range(0,wtmp);

      var paper = Raphael(ph.get(0), xx(delta), htmp);
      var c = paper.rect(xx(leftVal), 0, xx(delta), htmp);

      c.attr({
      	fill: "90-"+opt.startColor + "-" + opt.endColor,
      	stroke: opt.stroke,
      	title: "Value: "+ value
      });

      if(opt.includeValue) {
        ph.append(opt.valueFormat(st.value, st.colFormat, st));
      }
    }
  };
  Dashboards.registerAddIn("Table", "colType", new AddIn(dataBar));

  var trendArrow = {
    name: "trendArrow",
    label: "Trend Arrows",
    defaults: {
      includeValue: false,
      valueFormat: function(v,format,st) {
        return sprintf(format,v);
      }
    },
    implementation: function(tgt, st, opt) {
      var ph = $(tgt),
      trendClass =  st.value < 0 ? "down" : "up";
      var trend = $("

");
      trend.addClass('trend');
      trend.addClass(trendClass);
      ph.empty();
      if(opt.includeValue) {
        ph.append(opt.valueFormat(st.value, st.colFormat, st));
      }
      ph.append(trend);
    }
  };
  Dashboards.registerAddIn("Table", "colType", new AddIn(trendArrow));

  var link = {
    name: "hyperlink",
    label: "Hyperlink",
    defaults:{
      openInNewTab: true,
      prependHttpIfNeeded: true,
      regexp: null
    },

    implementation: function(tgt, st, opt){

      var ph = $(tgt);
      var link = st.value;
      if (opt.prependHttpIfNeeded && !/^https?:\/\//.test(link)){
        link = "http://" + link;
      }
      // is this text an hyperlink?
      if(opt.regexp == null || (new RegExp(opt.regexp).test(st.value))){
        var a = $("").attr("href",link).addClass("hyperlinkAddIn");
        a.text(st.value);
        if(opt.openInNewTab){
          a.attr("target","_blank");
        }
        ph.empty().append(a);
      }
    }

  };
  Dashboards.registerAddIn("Table", "colType", new AddIn(link));

})();

<commit_msg>Added var declaration to dataBar in coltypes.js<commit_after>;
(function() {

  /* Sparkline AddIn, based on jquery.sparkline.js sparklines.
   *
   */
  var sparkline = {
    name: "sparkline",
    label: "Sparkline",
    defaults: {
      type: 'line'
    },
    implementation: function (tgt, st, opt) {
      var t = $(tgt);
      t.sparkline(st.value.split(/,/),opt);
      t.removeClass("sparkline");
    }
  };
  Dashboards.registerAddIn("Table", "colType", new AddIn(sparkline));

  var pvSparkline = {
    name: "pvSparkline",
    label: "Protovis Sparkline",
    defaults: {
      height: 10,
      strokeStyle: "#000",
      lineWidth: 1,
      width: undefined,
      canvasMargin: 2
    },
    implementation: function(tgt, st, opt) {
      var ph = $(tgt),
      sparklineData = st.value,
      data = sparklineData.split(",");
      n = data.length,
      w = opt.width || ph.width(),
      h = opt.height,
      min = pv.min.index(data),
      max = pv.max.index(data);
      ph.empty();

      var container = $("

").appendTo(ph);

      //console.log("count "+count);

      var vis = new pv.Panel()
      .canvas(container.get(0))
      .width(w)
      .height(h)
      .margin(opt.canvasMargin);

      vis.add(pv.Line)
      .data(data)
      .left(pv.Scale.linear(0, n - 1).range(0, w).by(pv.index))
      .bottom(pv.Scale.linear(data).range(0, h))
      .strokeStyle(opt.strokeStyle)
      .lineWidth(opt.lineWidth);

      vis.render();

    }
  };
  Dashboards.registerAddIn("Table", "colType", new AddIn(pvSparkline));

  var dataBar = {
    name: "dataBar",
    label: "Data Bar",
    defaults: {
      widthRatio:1,
      height: 10,
      startColor: "#55A4D6",
      endColor: "#448FC8",
      stroke: null,
      max: undefined,
      includeValue: false,
      valueFormat: function(v, format, st) {
        return "" + sprintf(format,v) + "";
      }
    },
    implementation: function(tgt, st, opt) {
      var max = opt.max || Math.max.apply(Math,st.tableData.map(function(e){return Math.abs(e[st.colIdx]);}));
      var cell = $(tgt);
      cell.empty();

      var ph =$("

").addClass('dataBarContainer').appendTo(cell);
      var wtmp = opt.widthRatio * ph.width();
      var htmp = opt.height;

      var value = st.value;
      var leftVal=0, rightVal=parseFloat(value);
      if(leftVal>rightVal){
      	leftVal = value;
      	rightVal = 0;
      }
      var delta = rightVal - leftVal;
      var xx = pv.Scale.linear(0,max).range(0,wtmp);

      var paper = Raphael(ph.get(0), xx(delta), htmp);
      var c = paper.rect(xx(leftVal), 0, xx(delta), htmp);

      c.attr({
      	fill: "90-"+opt.startColor + "-" + opt.endColor,
      	stroke: opt.stroke,
      	title: "Value: "+ value
      });

      if(opt.includeValue) {
        ph.append(opt.valueFormat(st.value, st.colFormat, st));
      }
    }
  };
  Dashboards.registerAddIn("Table", "colType", new AddIn(dataBar));

  var trendArrow = {
    name: "trendArrow",
    label: "Trend Arrows",
    defaults: {
      includeValue: false,
      valueFormat: function(v,format,st) {
        return sprintf(format,v);
      }
    },
    implementation: function(tgt, st, opt) {
      var ph = $(tgt),
      trendClass =  st.value < 0 ? "down" : "up";
      var trend = $("

");
      trend.addClass('trend');
      trend.addClass(trendClass);
      ph.empty();
      if(opt.includeValue) {
        ph.append(opt.valueFormat(st.value, st.colFormat, st));
      }
      ph.append(trend);
    }
  };
  Dashboards.registerAddIn("Table", "colType", new AddIn(trendArrow));

  var link = {
    name: "hyperlink",
    label: "Hyperlink",
    defaults:{
      openInNewTab: true,
      prependHttpIfNeeded: true,
      regexp: null
    },

    implementation: function(tgt, st, opt){

      var ph = $(tgt);
      var link = st.value;
      if (opt.prependHttpIfNeeded && !/^https?:\/\//.test(link)){
        link = "http://" + link;
      }
      // is this text an hyperlink?
      if(opt.regexp == null || (new RegExp(opt.regexp).test(st.value))){
        var a = $("").attr("href",link).addClass("hyperlinkAddIn");
        a.text(st.value);
        if(opt.openInNewTab){
          a.attr("target","_blank");
        }
        ph.empty().append(a);
      }
    }

  };
  Dashboards.registerAddIn("Table", "colType", new AddIn(link));

})();

<|endoftext|>


<commit_before>import { subscribe, unsubscribe, isSubscribed } from '@vue-storefront/core/modules/mailchimp/features'

export default {
  name: 'MyNewsletter',
  data () {
    return {
      user: {
        isSubscribed: false
      }
    }
  },
  methods: {
    unsubscribe () {
      this.$store.dispatch('mailchimp/unsubscribe', this.email).then(res => {
        this.user.isSubscribed = false
      }).catch(err =>
        this.$emit('unsubscription-error', err)
      )
    },
    subscribe () {
      this.$store.dispatch('mailchimp/subscribe', this.email).then(res => {
        this.user.isSubscribed = true
      }).catch(err =>
        this.$emit('subscription-error', err)
      )
    },
    updateNewsletter () {
      if (this.user.isSubscribed) {
        this.subscribe(this.$store.state.user.current.email)
      } else {
        this.unsubscribe(this.$store.state.user.current.email)
      }
      this.$store.dispatch('user/updatePreferences', { isSubscribed: this.user.isSubscribed })
      this.exitSection()
    }
  },
  mixins: [subscribe, unsubscribe, isSubscribed]
}
<commit_msg>removed old import features<commit_after>export default {
  name: 'MyNewsletter',
  data () {
    return {
      user: {
        isSubscribed: false
      }
    }
  },
  methods: {
    unsubscribe () {
      this.$store.dispatch('mailchimp/unsubscribe', this.email).then(res => {
        this.user.isSubscribed = false
      }).catch(err =>
        this.$emit('unsubscription-error', err)
      )
    },
    subscribe () {
      this.$store.dispatch('mailchimp/subscribe', this.email).then(res => {
        this.user.isSubscribed = true
      }).catch(err =>
        this.$emit('subscription-error', err)
      )
    },
    updateNewsletter () {
      if (this.user.isSubscribed) {
        this.subscribe(this.$store.state.user.current.email)
      } else {
        this.unsubscribe(this.$store.state.user.current.email)
      }
      this.$store.dispatch('user/updatePreferences', { isSubscribed: this.user.isSubscribed })
      this.exitSection()
    }
  },
  mixins: [subscribe, unsubscribe, isSubscribed]
}
<|endoftext|>


<commit_before>var common       = require('../../common');
var assert       = require('assert');
var test         = require('utest');
var parseNavdata = require(common.lib + '/navdata/parseNavdata');
var fs           = require('fs');
var fixture      = fs.readFileSync(common.fixtures + '/navdata.bin');

test('parseNavdata', {
  'parses main payload': function() {
    var navdata = parseNavdata(fixture);

    assert.equal(navdata.header, parseNavdata.NAVDATA_HEADER);

    var droneState = navdata.droneState;
    assert.equal(droneState.flying, 0);
    assert.equal(droneState.videoEnabled, 0);
    assert.equal(droneState.visionEnabled, 0);
    assert.equal(droneState.controlAlgorithm, 0);
    assert.equal(droneState.altitudeControlAlgorithm, 1);
    assert.equal(droneState.startButtonState, 0);
    assert.equal(droneState.controlCommandAck, 1);
    assert.equal(droneState.cameraReady, 1);
    assert.equal(droneState.travellingEnabled, 0);
    assert.equal(droneState.usbReady, 0);
    assert.equal(droneState.navdataDemo, 0);
    assert.equal(droneState.navdataBootstrap, 0);
    assert.equal(droneState.motorProblem, 0);
    assert.equal(droneState.communicationLost, 0);
    assert.equal(droneState.softwareFault, 0);
    assert.equal(droneState.lowBattery, 0);
    assert.equal(droneState.userEmergencyLanding, 0);
    assert.equal(droneState.timerElapsed, 0);
    assert.equal(droneState.MagnometerNeedsCalibration, 0);
    assert.equal(droneState.anglesOutOfRange, 0);
    assert.equal(droneState.tooMuchWind, 0);
    assert.equal(droneState.ultrasonicSensorDeaf, 0);
    assert.equal(droneState.cutoutDetected, 0);
    assert.equal(droneState.picVersionNumberOk, 1);
    assert.equal(droneState.atCodecThreadOn, 1);
    assert.equal(droneState.navdataThreadOn, 1);
    assert.equal(droneState.videoThreadOn, 1);
    assert.equal(droneState.acquisitionThreadOn, 1);
    assert.equal(droneState.controlWatchdogDelay, 0);
    assert.equal(droneState.adcWatchdogDelay, 0);
    assert.equal(droneState.comWatchdogProblem, 1);
    assert.equal(droneState.emergencyLanding, 0);

    assert.equal(navdata.sequenceNumber, 300711);
    assert.equal(navdata.visionFlag, 1);
  },

  'parses demo option': function() {
    var demo = parseNavdata(fixture).demo;
    assert.equal(demo.flyState, 'FLYING_OK');
    assert.equal(demo.controlState, 'CTRL_LANDED');
    assert.equal(demo.batteryPercentage, 50);

    assert.equal(demo.frontBackDegrees, 2.974);
    assert.equal(demo.leftRightDegrees, 0.55);
    assert.equal(demo.clockwiseDegrees, 1.933);

    assert.equal(demo.rotation.frontBack, 2.974);
    assert.equal(demo.rotation.leftRight, 0.55);
    assert.equal(demo.rotation.clockwise, 1.933);

    assert.equal(demo.rotation.pitch, 2.974);
    assert.equal(demo.rotation.roll, 0.55);
    assert.equal(demo.rotation.yaw, 1.933);

    assert.equal(demo.rotation.theta, 2.974);
    assert.equal(demo.rotation.phi, 0.55);
    assert.equal(demo.rotation.psi, 1.933);

    assert.equal(demo.rotation.y, 2.974);
    assert.equal(demo.rotation.x, 0.55);
    assert.equal(demo.rotation.z, 1.933);

    assert.equal(demo.altitudeMeters, 0);
    assert.equal(demo.altitude, 0);

    assert.equal(demo.xVelocity, 0.0585307739675045);
    assert.equal(demo.yVelocity, -0.8817979097366333);
    assert.equal(demo.zVelocity, 0);
    assert.equal(demo.velocity.x, 0.0585307739675045);
    assert.equal(demo.velocity.y, -0.8817979097366333);
    assert.equal(demo.velocity.z, 0);
  },

  'parses wifi option': function() {
    var wifi = parseNavdata(fixture).wifi;
    assert.equal(wifi.linkQuality, 1);
  },

  'parses time option': function() {
    var time = parseNavdata(fixture).time;
    assert.equal(time, 362979.125);
  },

  'parses rawMeasures option': function() {
    var rawMeasures = parseNavdata(fixture).rawMeasures;

    assert.equal(rawMeasures.accelerometers.x, 2040);
    assert.equal(rawMeasures.accelerometers.y, 2036);
    assert.equal(rawMeasures.accelerometers.z, 2528);

    assert.equal(rawMeasures.gyrometers.x, -23);
    assert.equal(rawMeasures.gyrometers.y, 15);
    assert.equal(rawMeasures.gyrometers.z, 0);
    assert.equal(rawMeasures.gyroscopes.x, -23);
    assert.equal(rawMeasures.gyroscopes.y, 15);
    assert.equal(rawMeasures.gyroscopes.z, 0);

    assert.equal(rawMeasures.gyrometers110[0], 0);
    assert.equal(rawMeasures.gyrometers110[1], 0);
    assert.equal(rawMeasures.gyrometers110.length, 2);
    assert.equal(rawMeasures.gyroscopes110.x, 0);
    assert.equal(rawMeasures.gyroscopes110.y, 0);

    assert.equal(rawMeasures.batteryMilliVolt, 11686);

    assert.equal(rawMeasures.usDebutEcho, 0);
    assert.equal(rawMeasures.usFinEcho, 0);
    assert.equal(rawMeasures.usAssociationEcho, 3758);
    assert.equal(rawMeasures.usDistanceEcho, 0);
    assert.equal(rawMeasures.us.echo.start, 0);
    assert.equal(rawMeasures.us.echo.end, 0);
    assert.equal(rawMeasures.us.echo.association, 3758);
    assert.equal(rawMeasures.us.echo.distance, 0);

    assert.equal(rawMeasures.usCourbeTemps, 21423);
    assert.equal(rawMeasures.usCourbeValeur, 0);
    assert.equal(rawMeasures.usCourbeRef, 120);
    assert.equal(rawMeasures.us.curve.time, 21423);
    assert.equal(rawMeasures.us.curve.value, 0);
    assert.equal(rawMeasures.us.curve.ref, 120);

    assert.equal(rawMeasures.flagEchoIni, 1);
    assert.equal(rawMeasures.nbEcho, 1);
    assert.equal(rawMeasures.sumEcho, 3539193);
    assert.equal(rawMeasures.echo.flagIni, 1);
    assert.equal(rawMeasures.echo.num, 1);
    assert.equal(rawMeasures.echo.sum, 3539193);

    assert.equal(rawMeasures.altTempRaw, 243);
    assert.equal(rawMeasures.altTemp, 243);
  },

  'parses pwm option': function() {
    var pwm = parseNavdata(fixture).pwm;

    assert.deepEqual(pwm.motors, [0, 0, 0, 0]);
    assert.deepEqual(pwm.satMotors, [255, 255, 255, 255]);
    assert.equal(pwm.gazFeedForward, 0);
    assert.equal(pwm.gazAltitude, 0);
    assert.equal(pwm.altitudeIntegral, 0);
    assert.equal(pwm.vzRef, 0);
    assert.equal(pwm.uPitch, 0);
    assert.equal(pwm.uRoll, 0);
    assert.equal(pwm.uYaw, 0);
    assert.equal(pwm.yawUI, 0);
    assert.equal(pwm.uPitchPlanif, 0);
    assert.equal(pwm.uRollPlanif, 0);
    assert.equal(pwm.uYawPlanif, 0);
    assert.equal(pwm.uGazPlanif, 0);
    assert.deepEqual(pwm.motorCurrents, [0, 0, 0, 0]);
    assert.equal(pwm.altitudeProp, 0);
    assert.equal(pwm.altitudeDer, 0);
  },

  'parses watchdog option': function() {
    var watchdog = parseNavdata(fixture).watchdog;
    assert.equal(watchdog, 4822);
  },

  'throws exception on invalid header': function() {
    assert.throws(function() {
      parseNavdata(new Buffer([1, 2, 3, 4]));
    }, /header/i);
  },

  'detects bad checksum': function() {
    // hacky way to get a copy of our fixture
    var fixtureCopy = Buffer.concat([new Buffer(0), fixture]);

    // corrupt a byte inside our fixture
    fixtureCopy[23] = fixtureCopy[23] + 1;

    assert.throws(function() {
      parseNavdata(fixtureCopy)
    }, /checksum/i);
  },

  'no infinite loop when checksum is cut off': function() {
    var incompleteFixture = Buffer.concat([
      new Buffer(0),
      fixture.slice(0, fixture.length - 8) // strip checksum from end
    ]);

    assert.throws(function() {
      parseNavdata(incompleteFixture)
    }, /beyond/i);
  },
});
<commit_msg>WIP commit. Adding tests for 9(?) of the 22(?) new `navdata` objects.<commit_after>var common       = require('../../common');
var assert       = require('assert');
var test         = require('utest');
var parseNavdata = require(common.lib + '/navdata/parseNavdata');
var fs           = require('fs');
var fixture      = fs.readFileSync(common.fixtures + '/navdata.bin');

test('parseNavdata', {
  'parses main payload': function() {
    var navdata = parseNavdata(fixture);

    assert.equal(navdata.header, parseNavdata.NAVDATA_HEADER);

    var droneState = navdata.droneState;
    assert.equal(droneState.flying, 0);
    assert.equal(droneState.videoEnabled, 0);
    assert.equal(droneState.visionEnabled, 0);
    assert.equal(droneState.controlAlgorithm, 0);
    assert.equal(droneState.altitudeControlAlgorithm, 1);
    assert.equal(droneState.startButtonState, 0);
    assert.equal(droneState.controlCommandAck, 1);
    assert.equal(droneState.cameraReady, 1);
    assert.equal(droneState.travellingEnabled, 0);
    assert.equal(droneState.usbReady, 0);
    assert.equal(droneState.navdataDemo, 0);
    assert.equal(droneState.navdataBootstrap, 0);
    assert.equal(droneState.motorProblem, 0);
    assert.equal(droneState.communicationLost, 0);
    assert.equal(droneState.softwareFault, 0);
    assert.equal(droneState.lowBattery, 0);
    assert.equal(droneState.userEmergencyLanding, 0);
    assert.equal(droneState.timerElapsed, 0);
    assert.equal(droneState.MagnometerNeedsCalibration, 0);
    assert.equal(droneState.anglesOutOfRange, 0);
    assert.equal(droneState.tooMuchWind, 0);
    assert.equal(droneState.ultrasonicSensorDeaf, 0);
    assert.equal(droneState.cutoutDetected, 0);
    assert.equal(droneState.picVersionNumberOk, 1);
    assert.equal(droneState.atCodecThreadOn, 1);
    assert.equal(droneState.navdataThreadOn, 1);
    assert.equal(droneState.videoThreadOn, 1);
    assert.equal(droneState.acquisitionThreadOn, 1);
    assert.equal(droneState.controlWatchdogDelay, 0);
    assert.equal(droneState.adcWatchdogDelay, 0);
    assert.equal(droneState.comWatchdogProblem, 1);
    assert.equal(droneState.emergencyLanding, 0);

    assert.equal(navdata.sequenceNumber, 300711);
    assert.equal(navdata.visionFlag, 1);
  },

  'parses demo option': function() {
    var demo = parseNavdata(fixture).demo;
    assert.equal(demo.flyState, 'FLYING_OK');
    assert.equal(demo.controlState, 'CTRL_LANDED');
    assert.equal(demo.batteryPercentage, 50);

    assert.equal(demo.frontBackDegrees, 2.974);
    assert.equal(demo.leftRightDegrees, 0.55);
    assert.equal(demo.clockwiseDegrees, 1.933);

    assert.equal(demo.rotation.frontBack, 2.974);
    assert.equal(demo.rotation.leftRight, 0.55);
    assert.equal(demo.rotation.clockwise, 1.933);

    assert.equal(demo.rotation.pitch, 2.974);
    assert.equal(demo.rotation.roll, 0.55);
    assert.equal(demo.rotation.yaw, 1.933);

    assert.equal(demo.rotation.theta, 2.974);
    assert.equal(demo.rotation.phi, 0.55);
    assert.equal(demo.rotation.psi, 1.933);

    assert.equal(demo.rotation.y, 2.974);
    assert.equal(demo.rotation.x, 0.55);
    assert.equal(demo.rotation.z, 1.933);

    assert.equal(demo.altitudeMeters, 0);
    assert.equal(demo.altitude, 0);

    assert.equal(demo.xVelocity, 0.0585307739675045);
    assert.equal(demo.yVelocity, -0.8817979097366333);
    assert.equal(demo.zVelocity, 0);
    assert.equal(demo.velocity.x, 0.0585307739675045);
    assert.equal(demo.velocity.y, -0.8817979097366333);
    assert.equal(demo.velocity.z, 0);
  },

  'parses time option': function() {
    var time = parseNavdata(fixture).time;
    assert.equal(time, 362979.125);
  },

  'parses rawMeasures option': function() {
    var rawMeasures = parseNavdata(fixture).rawMeasures;

    assert.equal(rawMeasures.accelerometers.x, 2040);
    assert.equal(rawMeasures.accelerometers.y, 2036);
    assert.equal(rawMeasures.accelerometers.z, 2528);

    assert.equal(rawMeasures.gyrometers.x, -23);
    assert.equal(rawMeasures.gyrometers.y, 15);
    assert.equal(rawMeasures.gyrometers.z, 0);
    assert.equal(rawMeasures.gyroscopes.x, -23);
    assert.equal(rawMeasures.gyroscopes.y, 15);
    assert.equal(rawMeasures.gyroscopes.z, 0);

    assert.equal(rawMeasures.gyrometers110[0], 0);
    assert.equal(rawMeasures.gyrometers110[1], 0);
    assert.equal(rawMeasures.gyrometers110.length, 2);
    assert.equal(rawMeasures.gyroscopes110.x, 0);
    assert.equal(rawMeasures.gyroscopes110.y, 0);

    assert.equal(rawMeasures.batteryMilliVolt, 11686);

    assert.equal(rawMeasures.usDebutEcho, 0);
    assert.equal(rawMeasures.usFinEcho, 0);
    assert.equal(rawMeasures.usAssociationEcho, 3758);
    assert.equal(rawMeasures.usDistanceEcho, 0);
    assert.equal(rawMeasures.us.echo.start, 0);
    assert.equal(rawMeasures.us.echo.end, 0);
    assert.equal(rawMeasures.us.echo.association, 3758);
    assert.equal(rawMeasures.us.echo.distance, 0);

    assert.equal(rawMeasures.usCourbeTemps, 21423);
    assert.equal(rawMeasures.usCourbeValeur, 0);
    assert.equal(rawMeasures.usCourbeRef, 120);
    assert.equal(rawMeasures.us.curve.time, 21423);
    assert.equal(rawMeasures.us.curve.value, 0);
    assert.equal(rawMeasures.us.curve.ref, 120);

    assert.equal(rawMeasures.flagEchoIni, 1);
    assert.equal(rawMeasures.nbEcho, 1);
    assert.equal(rawMeasures.sumEcho, 3539193);
    assert.equal(rawMeasures.echo.flagIni, 1);
    assert.equal(rawMeasures.echo.num, 1);
    assert.equal(rawMeasures.echo.sum, 3539193);

    assert.equal(rawMeasures.altTempRaw, 243);
    assert.equal(rawMeasures.altTemp, 243);
  },

  'parses physMeasures option': function() {
    var actual   = parseNavdata(fixture).physMeasures;
    var expected = {
        temperature : {
            accelerometer : 45.309303283691406,
            gyroscope     : 55738
        },
        accelerometers : {
            x : 80.2970962524414,
            y : -33.318603515625,
            z : -942.5283203125
        },
        gyroscopes : {
            x : -0.11236488074064255,
            y : 0.06872134655714035,
            z : 0.06200997903943062
        },
        alim3V3   : 0,
        vrefEpson : 0,
        vrefIDG   : 0
    };
    assert.equal(actual.temperature.accelerometer, expected.temperature.accelerometer);
    assert.equal(actual.temperature.gyroscope, expected.temperature.gyroscope);
    assert.equal(actual.accelerometers.x, expected.accelerometers.x);
    assert.equal(actual.accelerometers.y, expected.accelerometers.y);
    assert.equal(actual.accelerometers.z, expected.accelerometers.z);
    assert.equal(actual.gyroscopes.x, expected.gyroscopes.x);
    assert.equal(actual.gyroscopes.y, expected.gyroscopes.y);
    assert.equal(actual.gyroscopes.z, expected.gyroscopes.z);
    assert.equal(actual.alim3V3, expected.alim3V3);
    assert.equal(actual.vrefEpson, expected.vrefEpson);
    assert.equal(actual.vrefIDG, expected.vrefIDG);
  },

  'parses gyrosOffsets option': function() {
    var actual   = parseNavdata(fixture).gyrosOffsets;
    var expected = {
        x : -0.5329172611236572,
        y : 0.1788240224123001,
        z : 0
    };

    assert.equal(actual.x, expected.x);
    assert.equal(actual.y, expected.y);
    assert.equal(actual.z, expected.z);
  },

  'parses eulerAngles option': function() {
    var actual   = parseNavdata(fixture).eulerAngles;
    var expected = {
        theta : 4866,
        phi   : 2024
    };

    assert.equal(actual.theta, expected.theta);
    assert.equal(actual.phi, expected.phi);
  },

  'parses references option': function() {
    var actual   = parseNavdata(fixture).references;
    var expected = {
        theta    : 0,
        phi      : 0,
        thetaI   : 0,
        phiI     : 0,
        pitch    : 0,
        roll     : 0,
        yaw      : 0,
        psi      : 0,
        vx       : 0,
        vy       : 0,
        thetaMod : 0,
        phiMod   : 0,
        kVX      : 0,
        kVY      : 0,
        kMode    : 0,
        ui       : {
            time        : 0,
            theta       : 0,
            phi         : 0,
            psi         : 0,
            psiAccuracy : 0,
            seq         : 0
        }
    };

    assert.equal(actual.theta, expected.theta);
    assert.equal(actual.phi, expected.phi);
    assert.equal(actual.thetaI, expected.thetaI);
    assert.equal(actual.phiI, expected.phiI);
    assert.equal(actual.pitch, expected.pitch);
    assert.equal(actual.roll, expected.roll);
    assert.equal(actual.yaw, expected.yaw);
    assert.equal(actual.psi, expected.psi);
    assert.equal(actual.vx, expected.vx);
    assert.equal(actual.vy, expected.vy);
    assert.equal(actual.thetaMod, expected.thetaMod);
    assert.equal(actual.phiMod, expected.phiMod);
    assert.equal(actual.kVX, expected.kVX);
    assert.equal(actual.kVY, expected.kVY);
    assert.equal(actual.kMode, expected.kMode);
    assert.equal(actual.ui.time, expected.ui.time);
    assert.equal(actual.ui.theta, expected.ui.theta);
    assert.equal(actual.ui.phi, expected.ui.phi);
    assert.equal(actual.ui.psi, expected.ui.psi);
    assert.equal(actual.ui.psiAccuracy, expected.ui.psiAccuracy);
    assert.equal(actual.ui.seq, expected.ui.seq);
  },

  'parses trims option': function() {
    var actual   = parseNavdata(fixture).trims;
    var expected = {
        angularRates : {
            r : 0
        },
        eulerAngles : {
            theta : 3028.916015625,
            phi   : 1544.318359375
        }
    };

    assert.equal(actual.angularRates.r, expected.angularRates.r);
    assert.equal(actual.eulerAngles.theta, expected.eulerAngles.theta);
    assert.equal(actual.eulerAngles.phi, expected.eulerAngles.phi);
  },

  'parses rcReferences option': function() {
    var actual   = parseNavdata(fixture).rcReferences;
    var expected = {
        pitch : 0,
        roll  : 0,
        yaw   : 0,
        gaz   : 0,
        ag    : 0
    };

    assert.equal(actual.pitch, expected.pitch);
    assert.equal(actual.roll, expected.roll);
    assert.equal(actual.yaw, expected.yaw);
    assert.equal(actual.gaz, expected.gaz);
    assert.equal(actual.ag, expected.ag);
  },

  'parses pwm option': function() {
    var pwm = parseNavdata(fixture).pwm;

    assert.deepEqual(pwm.motors, [0, 0, 0, 0]);
    assert.deepEqual(pwm.satMotors, [255, 255, 255, 255]);
    assert.equal(pwm.gazFeedForward, 0);
    assert.equal(pwm.gazAltitude, 0);
    assert.equal(pwm.altitudeIntegral, 0);
    assert.equal(pwm.vzRef, 0);
    assert.equal(pwm.uPitch, 0);
    assert.equal(pwm.uRoll, 0);
    assert.equal(pwm.uYaw, 0);
    assert.equal(pwm.yawUI, 0);
    assert.equal(pwm.uPitchPlanif, 0);
    assert.equal(pwm.uRollPlanif, 0);
    assert.equal(pwm.uYawPlanif, 0);
    assert.equal(pwm.uGazPlanif, 0);
    assert.deepEqual(pwm.motorCurrents, [0, 0, 0, 0]);
    assert.equal(pwm.altitudeProp, 0);
    assert.equal(pwm.altitudeDer, 0);
  },

  'parses altitude option': function() {
    var actual   = parseNavdata(fixture).altitude;
    var expected = {
        vision   : 243,
        velocity : 0,
        ref      : 0,
        raw      : 243,
        observer : {
            acceleration: 0,
            altitude: 0,
            x: {
                x: 0,
                y: 0,
                z: 0
            },
            state: 0
        },
        estimated: {
            vb: {
                x: 0,
                y: 0
            },
            state: 0
        }
    };

    assert.equal(actual.vision, expected.vision);
    assert.equal(actual.velocity, expected.velocity);
    assert.equal(actual.ref, expected.ref);
    assert.equal(actual.raw, expected.raw);
    assert.equal(actual.observer.acceleration, expected.observer.acceleration);
    assert.equal(actual.observer.altitude, expected.observer.altitude);
    assert.equal(actual.observer.x.x, expected.observer.x.x);
    assert.equal(actual.observer.x.y, expected.observer.x.y);
    assert.equal(actual.observer.x.z, expected.observer.x.z);
    assert.equal(actual.observer.state, expected.observer.state);
    assert.equal(actual.estimated.vb.x, expected.estimated.vb.x);
    assert.equal(actual.estimated.vb.y, expected.estimated.vb.y);
    assert.equal(actual.estimated.state, expected.estimated.state);
  },

  'parses visionRaw option': function() {
    var actual   = parseNavdata(fixture).visionRaw;
    var expected = {
        tx: 1.3266397714614868,
        ty: -0.7230937480926514,
        tz: 0
    };

    assert.equal(actual.tx, expected.tx);
    assert.equal(actual.ty, expected.ty);
    assert.equal(actual.tz, expected.tz);
  },

  'parses visionOf option': function() {
    var actual   = parseNavdata(fixture).visionOf;
    var expected = {
        dx: [0, 0, 0, 0, 0],
        dy: [0, 0, 0, 0, 0]
    };

    assert.deepEqual(actual.dx, expected.dx);
    assert.deepEqual(actual.dy, expected.dy);
  },

  // 'parses option': function() {
  //   var actual   = parseNavdata(fixture).;
  //   var expected = ;
  //
  //   assert.equal(actual)
  // },

  // 'parses option': function() {
  //   var actual   = parseNavdata(fixture).;
  //   var expected = ;
  //
  //   assert.equal(actual)
  // },

  // 'parses option': function() {
  //   var actual   = parseNavdata(fixture).;
  //   var expected = ;
  //
  //   assert.equal(actual)
  // },

  // 'parses option': function() {
  //   var actual   = parseNavdata(fixture).;
  //   var expected = ;
  //
  //   assert.equal(actual)
  // },

  'parses watchdog option': function() {
    var watchdog = parseNavdata(fixture).watchdog;
    assert.equal(watchdog, 4822);
  },

  // 'parses option': function() {
  //   var actual   = parseNavdata(fixture).;
  //   var expected = ;
  //
  //   assert.equal(actual)
  // },

  // 'parses option': function() {
  //   var actual   = parseNavdata(fixture).;
  //   var expected = ;
  //
  //   assert.equal(actual)
  // },

  // 'parses option': function() {
  //   var actual   = parseNavdata(fixture).;
  //   var expected = ;
  //
  //   assert.equal(actual)
  // },

  // 'parses option': function() {
  //   var actual   = parseNavdata(fixture).;
  //   var expected = ;
  //
  //   assert.equal(actual)
  // },

  // 'parses option': function() {
  //   var actual   = parseNavdata(fixture).;
  //   var expected = ;
  //
  //   assert.equal(actual)
  // },

  // 'parses option': function() {
  //   var actual   = parseNavdata(fixture).;
  //   var expected = ;
  //
  //   assert.equal(actual)
  // },

  // 'parses option': function() {
  //   var actual   = parseNavdata(fixture).;
  //   var expected = ;
  //
  //   assert.equal(actual)
  // },

  // 'parses option': function() {
  //   var actual   = parseNavdata(fixture).;
  //   var expected = ;
  //
  //   assert.equal(actual)
  // },

  'parses wifi option': function() {
    var wifi = parseNavdata(fixture).wifi;
    assert.equal(wifi.linkQuality, 1);
  },

  // 'parses option': function() {
  //   var actual   = parseNavdata(fixture).;
  //   var expected = ;
  //
  //   assert.equal(actual)
  // },

  'throws exception on invalid header': function() {
    assert.throws(function() {
      parseNavdata(new Buffer([1, 2, 3, 4]));
    }, /header/i);
  },

  'detects bad checksum': function() {
    // hacky way to get a copy of our fixture
    var fixtureCopy = Buffer.concat([new Buffer(0), fixture]);

    // corrupt a byte inside our fixture
    fixtureCopy[23] = fixtureCopy[23] + 1;

    assert.throws(function() {
      parseNavdata(fixtureCopy)
    }, /checksum/i);
  },

  'no infinite loop when checksum is cut off': function() {
    var incompleteFixture = Buffer.concat([
      new Buffer(0),
      fixture.slice(0, fixture.length - 8) // strip checksum from end
    ]);

    assert.throws(function() {
      parseNavdata(incompleteFixture)
    }, /beyond/i);
  },
});
<|endoftext|>


<commit_before>var Waterline = require('../../../lib/waterline'),
    assert = require('assert');

describe('Collection Query', function() {

  describe('.update()', function() {

    describe('with nested model values', function() {
      var query;

      before(function(done) {

        var waterline = new Waterline();
        var Model = Waterline.Collection.extend({
          identity: 'user',
          connection: 'foo',
          attributes: {
            name: {
              type: 'string',
              defaultsTo: 'Foo Bar'
            },
            nestedModel: {
              model: 'nested'
            }
          }
        });
        var Nested = Waterline.Collection.extend({
          identity: 'nested',
          connection: 'foo',
          attributes: {
            name: 'string'
          }
        });

        waterline.loadCollection(Model);
        waterline.loadCollection(Nested);

        // Fixture Adapter Def
        var _id = 1;
        var findValues = [];

        var adapterDef = {
          update: function(con, col, criteria, values, cb) {
            values.id = _id;
            findValues.push(values);
            _id++;
            return cb(null, values);
          },
          find: function(con, col, criteria, cb) {
            cb(null, findValues[_id - 1]);
          }
        };

        var connections = {
          'foo': {
            adapter: 'foobar'
          }
        };

        waterline.initialize({ adapters: { foobar: adapterDef }, connections: connections }, function(err, colls) {
          if(err) return done(err);
          query = colls.collections.user;
          done();
        });
      });

      it('should reduce the nested object down to a foreign key', function(done) {
        query.update({}, { name: 'foo', nestedModel: { id: 1337, name: 'joe' }}, function(err, status) {
          assert(!err, err);
          assert(status[0].nestedModel);
          assert(status[0].nestedModel === 1337);
          done();
        });
      });
    });

    describe('with nested model values (create)', function() {
      var query;

      before(function(done) {

        var waterline = new Waterline();
        var Model = Waterline.Collection.extend({
          identity: 'user',
          connection: 'foo',
          attributes: {
            name: {
              type: 'string',
              defaultsTo: 'Foo Bar'
            },
            nestedModel: {
              model: 'nested'
            }
          }
        });
        var Nested = Waterline.Collection.extend({
          identity: 'nested',
          connection: 'foo',
          attributes: {
            name: 'string'
          }
        });

        waterline.loadCollection(Model);
        waterline.loadCollection(Nested);

        // Fixture Adapter Def
        var _id = 1;
        var findValues = [];

        var adapterDef = {
          create: function(con, col, values, cb) {
            values.id = _id;
            findValues.push(values);
            _id++;
            return cb(null, values);
          },
          update: function(con, col, criteria, values, cb) {
            values.id = _id;
            findValues.push(values);
            _id++;
            return cb(null, values);
          },
          find: function(con, col, criteria, cb) {
            cb(null, findValues[_id - 1]);
          }
        };

        var connections = {
          'foo': {
            adapter: 'foobar'
          }
        };

        waterline.initialize({ adapters: { foobar: adapterDef }, connections: connections }, function(err, colls) {
          if(err) return done(err);
          query = colls.collections.user;
          done();
        });
      });

      it('should reduce the newly created nested object down to a foreign key', function(done) {
        query.update({}, { name: 'foo', nestedModel: { name: 'joe' }}, function(err, status) {
          assert(!err, err);
          assert(status[0].nestedModel);
          assert(status[0].nestedModel === 1);
          done();
        });
      });
    });

    describe('with nested collection values', function() {
      var query, updatedModels = [];

      before(function(done) {

        var waterline = new Waterline();
        var Model = Waterline.Collection.extend({
          identity: 'user',
          connection: 'foo',
          attributes: {
            name: {
              type: 'string',
              defaultsTo: 'Foo Bar'
            },
            nestedModels: {
              collection: 'nested',
              via: 'model'
            }
          }
        });
        var Nested = Waterline.Collection.extend({
          identity: 'nested',
          connection: 'foo',
          attributes: {
            name: 'string',
            model: {
              model: 'user'
            }
          }
        });

        waterline.loadCollection(Model);
        waterline.loadCollection(Nested);

        // Fixture Adapter Def
        var _id = 1;
        var findValues = [];

        var adapterDef = {
          update: function(con, col, criteria, values, cb) {
            updatedModels.push(criteria.where);
            values.id = _id;
            findValues.push(values);
            _id++;
            return cb(null, [values]);
          },

          find: function(con, col, criteria, cb) {
            cb(null, findValues[_id - 1]);
          }
        };

        var connections = {
          'foo': {
            adapter: 'foobar'
          }
        };

        waterline.initialize({ adapters: { foobar: adapterDef }, connections: connections }, function(err, colls) {
          if(err) return done(err);
          query = colls.collections.user;
          done();
        });
      });

      //
      // TO-DO:
      // Make this not use a shit load of queries. (currently 10)!
      //

      it('should attempt to update each nested model', function(done) {

        var nestedModels = [
          { id: 1337, name: 'joe', model: 2 },
          { id: 1338, name: 'moe', model: 3 },
          { id: 1339, name: 'flow', model: 4 }
        ];

        query.update({}, { id: 5, name: 'foo', nestedModels: nestedModels }, function(err, status) {
          assert(!err, err);
          assert(status[0].nestedModels.length === 0);
          assert(updatedModels.length === 10);
          done();
        });
      });
    });

  });
});
<commit_msg>Update unit test for nested update to test for multiple nested attributes<commit_after>var Waterline = require('../../../lib/waterline'),
    assert = require('assert');

describe('Collection Query', function() {

  describe('.update()', function() {

    describe('with nested model values', function() {
      var query;

      before(function(done) {

        var waterline = new Waterline();
        var Model = Waterline.Collection.extend({
          identity: 'user',
          connection: 'foo',
          attributes: {
            name: {
              type: 'string',
              defaultsTo: 'Foo Bar'
            },
            nestedModel: {
              model: 'nested'
            }
          }
        });
        var Nested = Waterline.Collection.extend({
          identity: 'nested',
          connection: 'foo',
          attributes: {
            name: 'string'
          }
        });

        waterline.loadCollection(Model);
        waterline.loadCollection(Nested);

        // Fixture Adapter Def
        var _id = 1;
        var findValues = [];

        var adapterDef = {
          update: function(con, col, criteria, values, cb) {
            values.id = _id;
            findValues.push(values);
            _id++;
            return cb(null, values);
          },
          find: function(con, col, criteria, cb) {
            cb(null, findValues[_id - 1]);
          }
        };

        var connections = {
          'foo': {
            adapter: 'foobar'
          }
        };

        waterline.initialize({ adapters: { foobar: adapterDef }, connections: connections }, function(err, colls) {
          if(err) return done(err);
          query = colls.collections.user;
          done();
        });
      });

      it('should reduce the nested object down to a foreign key', function(done) {
        query.update({}, { name: 'foo', nestedModel: { id: 1337, name: 'joe' }}, function(err, status) {
          assert(!err, err);
          assert(status[0].nestedModel);
          assert(status[0].nestedModel === 1337);
          done();
        });
      });
    });

    describe('with nested model values (create)', function() {
      var query;

      before(function(done) {

        var waterline = new Waterline();
        var Model = Waterline.Collection.extend({
          identity: 'user',
          connection: 'foo',
          attributes: {
            name: {
              type: 'string',
              defaultsTo: 'Foo Bar'
            },
            nestedModel: {
              model: 'nested'
            },
            nestedModel2: {
              model: 'nested'
            }
          }
        });
        var Nested = Waterline.Collection.extend({
          identity: 'nested',
          connection: 'foo',
          attributes: {
            name: 'string'
          }
        });

        waterline.loadCollection(Model);
        waterline.loadCollection(Nested);

        // Fixture Adapter Def
        var _id = 1;
        var findValues = [];

        var adapterDef = {
          create: function(con, col, values, cb) {
            values.id = _id;
            findValues.push(values);
            _id++;
            return cb(null, values);
          },
          update: function(con, col, criteria, values, cb) {
            values.id = _id;
            findValues.push(values);
            _id++;
            return cb(null, values);
          },
          find: function(con, col, criteria, cb) {
            cb(null, findValues[_id - 1]);
          }
        };

        var connections = {
          'foo': {
            adapter: 'foobar'
          }
        };

        waterline.initialize({ adapters: { foobar: adapterDef }, connections: connections }, function(err, colls) {
          if(err) return done(err);
          query = colls.collections.user;
          done();
        });
      });

      it('should reduce the newly created nested object down to two foreign keys', function(done) {
        query.update({}, { name: 'foo', nestedModel: { name: 'joe' }, nestedModel2: { name: 'jane' } }, function(err, status) {
          assert(!err, err);
          assert(status[0].nestedModel);
          assert(status[0].nestedModel === 1);
          assert(status[0].nestedModel2);
          assert(status[0].nestedModel2 === 2);
          done();
        });
      });
    });

    describe('with nested model values (create, asynchronous adapter)', function() {
      var query;

      before(function(done) {

        var waterline = new Waterline();
        var Model = Waterline.Collection.extend({
          identity: 'user',
          connection: 'foo',
          attributes: {
            name: {
              type: 'string',
              defaultsTo: 'Foo Bar'
            },
            nestedModel: {
              model: 'nested'
            },
            nestedModel2: {
              model: 'nested'
            }
          }
        });
        var Nested = Waterline.Collection.extend({
          identity: 'nested',
          connection: 'foo',
          attributes: {
            name: 'string'
          }
        });

        waterline.loadCollection(Model);
        waterline.loadCollection(Nested);

        // Fixture Adapter Def
        var _id = 1;
        var findValues = [];

        var adapterDef = {
          create: function(con, col, values, cb) {
            process.nextTick(function() {
              values.id = _id;
              findValues.push(values);
              _id++;
              return cb(null, values);
            });
          },
          update: function(con, col, criteria, values, cb) {
            process.nextTick(function() {
              values.id = _id;
              findValues.push(values);
              _id++;
              return cb(null, values);
            });
          },
          find: function(con, col, criteria, cb) {
            process.nextTick(function() {
              cb(null, findValues[_id - 1]);
            });
          }
        };

        var connections = {
          'foo': {
            adapter: 'foobar'
          }
        };

        waterline.initialize({ adapters: { foobar: adapterDef }, connections: connections }, function(err, colls) {
          if(err) return done(err);
          query = colls.collections.user;
          done();
        });
      });

      it('should call back only once and reduce the newly created nested object down to two foreign keys', function(done) {
        var count = 0;
        query.update({}, { name: 'foo', nestedModel: { name: 'joe' }, nestedModel2: { name: 'jane' } }, function(err, status) {
          assert(++count === 1);
          assert(!err, err);
          assert(status[0].nestedModel);
          assert(status[0].nestedModel2);
          assert.deepEqual([status[0].nestedModel, status[0].nestedModel2].sort(), [1, 2]);
          done();
        });
      });
    });

    describe('with nested collection values', function() {
      var query, updatedModels = [];

      before(function(done) {

        var waterline = new Waterline();
        var Model = Waterline.Collection.extend({
          identity: 'user',
          connection: 'foo',
          attributes: {
            name: {
              type: 'string',
              defaultsTo: 'Foo Bar'
            },
            nestedModels: {
              collection: 'nested',
              via: 'model'
            }
          }
        });
        var Nested = Waterline.Collection.extend({
          identity: 'nested',
          connection: 'foo',
          attributes: {
            name: 'string',
            model: {
              model: 'user'
            }
          }
        });

        waterline.loadCollection(Model);
        waterline.loadCollection(Nested);

        // Fixture Adapter Def
        var _id = 1;
        var findValues = [];

        var adapterDef = {
          update: function(con, col, criteria, values, cb) {
            updatedModels.push(criteria.where);
            values.id = _id;
            findValues.push(values);
            _id++;
            return cb(null, [values]);
          },

          find: function(con, col, criteria, cb) {
            cb(null, findValues[_id - 1]);
          }
        };

        var connections = {
          'foo': {
            adapter: 'foobar'
          }
        };

        waterline.initialize({ adapters: { foobar: adapterDef }, connections: connections }, function(err, colls) {
          if(err) return done(err);
          query = colls.collections.user;
          done();
        });
      });

      //
      // TO-DO:
      // Make this not use a shit load of queries. (currently 10)!
      //

      it('should attempt to update each nested model', function(done) {

        var nestedModels = [
          { id: 1337, name: 'joe', model: 2 },
          { id: 1338, name: 'moe', model: 3 },
          { id: 1339, name: 'flow', model: 4 }
        ];

        query.update({}, { id: 5, name: 'foo', nestedModels: nestedModels }, function(err, status) {
          assert(!err, err);
          assert(status[0].nestedModels.length === 0);
          assert(updatedModels.length === 10);
          done();
        });
      });
    });

  });
});
<|endoftext|>


<commit_before>require(require('root-path')('test/setup'));
var PlaySession = requireFromRoot('api/services/PlaySession');

var request = {
  headers: {
    cookie: 'lol=lol; PLAY_SESSION="6cb3b755aebf3bec7d792aa23e2d7651b55d0cba-pa.u.exp=1415742115467&pa.p.id=password&pa.u.id=l%40lw.io"; other=morelols'
  }
};

var validSession = function() {
  return new PlaySession(request, {secret: 'iamasecret'});
};

describe('PlaySession', function() {
  describe('#isValid', function() {

    it('is false when there is no cookie', function() {
      expect(new PlaySession({}).isValid()).to.be.false;
    });

    it('is false when the cookie signature does not match', function() {
      expect(new PlaySession(request, {secret: 'iamabadsecret'}).isValid()).to.be.false;
    });

    it('is true when the cookie signature matches', function() {
      expect(validSession().isValid()).to.be.true;
    });
  });

    describe('.data', function() {
      it('is a hash created from the query string in the session', function() {
        expect(validSession().data).to.eql({
          'pa.u.exp': '1415742115467',
          'pa.p.id': 'password',
          'pa.u.id': 'l@lw.io'
        });
      });
    });

})<commit_msg>fix indentation<commit_after>require(require('root-path')('test/setup'));
var PlaySession = requireFromRoot('api/services/PlaySession');

var request = {
  headers: {
    cookie: 'lol=lol; PLAY_SESSION="6cb3b755aebf3bec7d792aa23e2d7651b55d0cba-pa.u.exp=1415742115467&pa.p.id=password&pa.u.id=l%40lw.io"; other=morelols'
  }
};

var validSession = function() {
  return new PlaySession(request, {secret: 'iamasecret'});
};

describe('PlaySession', function() {
  describe('#isValid', function() {

    it('is false when there is no cookie', function() {
      expect(new PlaySession({}).isValid()).to.be.false;
    });

    it('is false when the cookie signature does not match', function() {
      expect(new PlaySession(request, {secret: 'iamabadsecret'}).isValid()).to.be.false;
    });

    it('is true when the cookie signature matches', function() {
      expect(validSession().isValid()).to.be.true;
    });
  });

  describe('.data', function() {
    it('is a hash created from the query string in the session', function() {
      expect(validSession().data).to.eql({
        'pa.u.exp': '1415742115467',
        'pa.p.id': 'password',
        'pa.u.id': 'l@lw.io'
      });
    });
  });

})<|endoftext|>


<commit_before>// jscs:disable requireMultipleVarDecl

'use strict';

// # Local File System Image Storage module
// The (default) module for storing images, using the local file system

var serveStatic = require('express').static,
    fs = require('fs-extra'),
    path = require('path'),
    Promise = require('bluebird'),
    config = require('../../config'),
    errors = require('../../errors'),
    i18n = require('../../i18n'),
    utils = require('../../utils'),
    StorageBase = require('ghost-storage-base');

class LocalFileStore extends StorageBase {

    constructor() {
        super();

        this.storagePath = config.getContentPath('images');
    }

    /**
     * Saves the image to storage (the file system)
     * - image is the express image object
     * - returns a promise which ultimately returns the full url to the uploaded image
     *
     * @param image
     * @param targetDir
     * @returns {*}
     */
    save(image, targetDir) {
        var targetFilename,
            self = this;

        // NOTE: the base implementation of `getTargetDir` returns the format this.storagePath/YYYY/MM
        targetDir = targetDir || this.getTargetDir(this.storagePath);

        return this.getUniqueFileName(image, targetDir).then(function (filename) {
            targetFilename = filename;
            return Promise.promisify(fs.mkdirs)(targetDir);
        }).then(function () {
            return Promise.promisify(fs.copy)(image.path, targetFilename);
        }).then(function () {
            // The src for the image must be in URI format, not a file system path, which in Windows uses \
            // For local file system storage can use relative path so add a slash
            var fullUrl = (
                utils.url.urlJoin('/', utils.url.getSubdir(),
                    utils.url.STATIC_IMAGE_URL_PREFIX,
                    path.relative(self.storagePath, targetFilename))
            ).replace(new RegExp('\\' + path.sep, 'g'), '/');

            return fullUrl;
        }).catch(function (e) {
            return Promise.reject(e);
        });
    }

    exists(fileName, targetDir) {
        var filePath = path.join(targetDir || this.storagePath, fileName);

        return new Promise(function (resolve) {
            fs.stat(filePath, function (err) {
                var exists = !err;
                resolve(exists);
            });
        });
    }

    /**
     * For some reason send divides the max age number by 1000
     * Fallthrough: false ensures that if an image isn't found, it automatically 404s
     * Wrap server static errors
     *
     * @returns {serveStaticContent}
     */
    serve() {
        var self = this;

        return function serveStaticContent(req, res, next) {
            return serveStatic(self.storagePath, {maxAge: utils.ONE_YEAR_MS, fallthrough: false})(req, res, function (err) {
                if (err) {
                    if (err.statusCode === 404) {
                        return next(new errors.NotFoundError({
                            message: i18n.t('errors.errors.imageNotFound'),
                            code: 'STATIC_FILE_NOT_FOUND',
                            property: err.path
                        }));
                    }

                    return next(new errors.GhostError({err: err}));
                }

                next();
            });
        };
    }

    /**
     * Not implemented.
     * @returns {Promise.<*>}
     */
    delete() {
        return Promise.reject('not implemented');
    }

    /**
     * Reads bytes from disk for a target image
     * - path of target image (without content path!)
     *
     * @param options
     */
    read(options) {
        options = options || {};

        // remove trailing slashes
        options.path = (options.path || '').replace(/\/$|\\$/, '');

        var targetPath = path.join(this.storagePath, options.path);

        return new Promise(function (resolve, reject) {
            fs.readFile(targetPath, function (err, bytes) {
                if (err) {
                    return reject(new errors.GhostError({
                        err: err,
                        message: 'Could not read image: ' + targetPath
                    }));
                }

                resolve(bytes);
            });
        });
    }
}

module.exports = LocalFileStore;
<commit_msg>Debug: LocalStorage response time<commit_after>// jscs:disable requireMultipleVarDecl

'use strict';

// # Local File System Image Storage module
// The (default) module for storing images, using the local file system

var serveStatic = require('express').static,
    fs = require('fs-extra'),
    path = require('path'),
    Promise = require('bluebird'),
    moment = require('moment'),
    config = require('../../config'),
    errors = require('../../errors'),
    i18n = require('../../i18n'),
    utils = require('../../utils'),
    logging = require('../../logging'),
    StorageBase = require('ghost-storage-base');

class LocalFileStore extends StorageBase {

    constructor() {
        super();

        this.storagePath = config.getContentPath('images');
    }

    /**
     * Saves the image to storage (the file system)
     * - image is the express image object
     * - returns a promise which ultimately returns the full url to the uploaded image
     *
     * @param image
     * @param targetDir
     * @returns {*}
     */
    save(image, targetDir) {
        var targetFilename,
            self = this;

        // NOTE: the base implementation of `getTargetDir` returns the format this.storagePath/YYYY/MM
        targetDir = targetDir || this.getTargetDir(this.storagePath);

        return this.getUniqueFileName(image, targetDir).then(function (filename) {
            targetFilename = filename;
            return Promise.promisify(fs.mkdirs)(targetDir);
        }).then(function () {
            return Promise.promisify(fs.copy)(image.path, targetFilename);
        }).then(function () {
            // The src for the image must be in URI format, not a file system path, which in Windows uses \
            // For local file system storage can use relative path so add a slash
            var fullUrl = (
                utils.url.urlJoin('/', utils.url.getSubdir(),
                    utils.url.STATIC_IMAGE_URL_PREFIX,
                    path.relative(self.storagePath, targetFilename))
            ).replace(new RegExp('\\' + path.sep, 'g'), '/');

            return fullUrl;
        }).catch(function (e) {
            return Promise.reject(e);
        });
    }

    exists(fileName, targetDir) {
        var filePath = path.join(targetDir || this.storagePath, fileName);

        return new Promise(function (resolve) {
            fs.stat(filePath, function (err) {
                var exists = !err;
                resolve(exists);
            });
        });
    }

    /**
     * For some reason send divides the max age number by 1000
     * Fallthrough: false ensures that if an image isn't found, it automatically 404s
     * Wrap server static errors
     *
     * @returns {serveStaticContent}
     */
    serve() {
        var self = this;

        return function serveStaticContent(req, res, next) {
            var startedAtMoment = moment();

            return serveStatic(
                self.storagePath,
                {
                    maxAge: utils.ONE_YEAR_MS,
                    fallthrough: false,
                    onEnd: function onEnd() {
                        logging.info('LocalFileStorage.serve', req.path, moment().diff(startedAtMoment, 'ms') + 'ms');
                    }
                }
            )(req, res, function (err) {
                if (err) {
                    if (err.statusCode === 404) {
                        return next(new errors.NotFoundError({
                            message: i18n.t('errors.errors.imageNotFound'),
                            code: 'STATIC_FILE_NOT_FOUND',
                            property: err.path
                        }));
                    }

                    return next(new errors.GhostError({err: err}));
                }

                next();
            });
        };
    }

    /**
     * Not implemented.
     * @returns {Promise.<*>}
     */
    delete() {
        return Promise.reject('not implemented');
    }

    /**
     * Reads bytes from disk for a target image
     * - path of target image (without content path!)
     *
     * @param options
     */
    read(options) {
        options = options || {};

        // remove trailing slashes
        options.path = (options.path || '').replace(/\/$|\\$/, '');

        var targetPath = path.join(this.storagePath, options.path);

        return new Promise(function (resolve, reject) {
            fs.readFile(targetPath, function (err, bytes) {
                if (err) {
                    return reject(new errors.GhostError({
                        err: err,
                        message: 'Could not read image: ' + targetPath
                    }));
                }

                resolve(bytes);
            });
        });
    }
}

module.exports = LocalFileStore;
<|endoftext|>


<commit_before>//var canvasWidth = 700;
//var canvasHeight = 700;

var spriteWidth = 512;
var spriteHeight = 768;

var rows = 4;
var cols = 4;

var trackRight = 2;
var trackLeft = 1;
var trackUp = 3;
var trackDown = 0;

var width = spriteWidth/cols;
var height = spriteHeight/rows;

var curFrame = 0;
var frameCount = 4;

var centreX = canvas.height/4;
var centreY = canvas.width/4;

var srcX;
var srcY;

var left = false;
var right = true;
var up = false;
var down = false;

//var canvas = document.getElementById('canvas');
//canvas.width = canvasWidth;
//canvas.height = canvasHeight;

//var ctx = canvas.getContext("2d");

var character = new Image();
character.src = "images/farmerSprite.png";

function updateFrame(){
    curFrame = ++curFrame % frameCount;
    srcX = curFrame * width;
    // canvasContext.clearRect(centreX,centreY,width,height);

    if(left){
        srcY = trackLeft * height;
    }
    if(right){
        srcY = trackRight * height;
    }
    if(up){
        srcY = trackUp * height;
    }
    if(down ){
        srcY = trackDown * height;
    }

}

function draw(){
    updateFrame();

    var centreX = camPanX + canvas.height/4;
    var centreY = camPanY + canvas.width/4;
    canvasContext.drawImage(character,srcX,srcY,width*1,height*1,centreX,centreY,TILE_W*0.7,TILE_H);

}

function moveLeft(){
    left = true;
    right = up = down = false;
    animate()
}

function moveRight(){
    right = true;
    left = up = down = false;
    animate()
}

function moveUp(){
    up = true;
    right = left = down = false;
    animate()
}

function moveDown(){
    down = true;
    right = up = left = false;
    animate()
}

function start() {
    var refreshIntervalId = setInterval(draw, 150);
    setTimeout(clearInterval(refreshIntervalId), 3000);
}

function interval(func, wait, times){
    var interv = function(w, t){
        return function(){
            if(typeof t === "undefined" || t-- > 0){
                setTimeout(interv, w);
                try{
                    func.call(null);
                }
                catch(e){
                    t = 0;
                    throw e.toString();
                }
            }
        };
    }(wait, times);

    setTimeout(interv, wait);
}

function animate() {
    interval(function(){
        draw()
    }, 150, 6);
}
<commit_msg>Delete Sprite.js<commit_after><|endoftext|>


<commit_before>'use strict';
const util = require('./util');

function Status() {
	this.map = new Map();
}
module.exports = Status;

Status.prototype.clone = function() {
	const obj = Object.create(Status.prototype);
	obj.map = new Map(this.map);
	return obj;
};
Status.prototype.get = function(key) {
	return this.map.get(key) || 0;
};
Status.prototype.set = function(key, val) {
	this.map.set(key, val|0);
};
Status.prototype.incr = function(key, val) {
	this.map.set(key, (this.map.get(key)|0)+val);
};
Status.prototype.maybeDecr = function(key) {
	const val = this.map.get(key);
	if (val > 0) this.map.set(key, val-1);
};
Status.prototype.clear = function() {
	this.map.clear();
};
Status.prototype.hash = function() {
	let ret = 0xdeadbeef;
	for (const [k, v] of this.map) {
		if (v) ret ^= util.hashString(k) ^ (v * 0x04004004);
	}
	return ret;
};
<commit_msg>Fix Status maybeDecr regression<commit_after>'use strict';
const util = require('./util');

function Status() {
	this.map = new Map();
}
module.exports = Status;

Status.prototype.clone = function() {
	const obj = Object.create(Status.prototype);
	obj.map = new Map(this.map);
	return obj;
};
Status.prototype.get = function(key) {
	return this.map.get(key) || 0;
};
Status.prototype.set = function(key, val) {
	this.map.set(key, val|0);
};
Status.prototype.incr = function(key, val) {
	this.map.set(key, (this.map.get(key)|0)+val);
};
Status.prototype.maybeDecr = function(key) {
	const val = this.get(key);
	if (val > 0) this.map.set(key, val-1);
	return val;
};
Status.prototype.clear = function() {
	this.map.clear();
};
Status.prototype.hash = function() {
	let ret = 0xdeadbeef;
	for (const [k, v] of this.map) {
		if (v) ret ^= util.hashString(k) ^ (v * 0x04004004);
	}
	return ret;
};
<|endoftext|>


<commit_before>import { deepEqual } from 'assert'

import updateSyncErrors from '../../src/updaters/updateSyncErrors'
import { UPDATE_FIELD, UPDATE_ALL, VALIDATE_FIELD, VALIDATE_ALL } from '../../src/constants'

const rules = {
  name: [[x => x.length > 3, 'Minimum length is four.']],
  random: [[x => x.length > 6, 'Minimum length is seven.']]
}

describe('updaters/updateSyncErrors', () => {

  it('should return an empty array when field value is valid and validateSingle is set to true', () => {
    const expected = [{form: {name: 'foobar'}, errors: {name: []}}, []]
    const result = updateSyncErrors([{form: {name: 'foobar'}, errors: {}}, []], UPDATE_FIELD, {rules, validateSingle: true, name: 'name'})
    deepEqual(expected, result)
  })

  it('should return an array containing the error messages when field value is invalid', () => {
    const expected = [{form: {name: 'bar'}, errors: {name: ['Minimum length is four.']}}, []]
    const result = updateSyncErrors([{form: {name: 'bar'}, errors: {}}, []], UPDATE_FIELD, {rules, validateSingle: true, name: 'name'})
    deepEqual(expected, result)
  })

  it('should skip validating when validateSingle is set to false and a field has been updated', () => {
    const expected = [{form: {name: 'foo'}, errors: {}}, []]
    const result = updateSyncErrors([{form: {name: 'foo'}, errors: {}}, []], UPDATE_FIELD, {rules, validateSingle: false, name: 'name'})
    deepEqual(expected, result)
  })

  it('should return an empty array when field value is valid and validateSingle is set to true and a validate field has been triggered', () => {
    const expected = [{form: {name: 'foobar'}, errors: {name: []}}, []]
    const result = updateSyncErrors([{form: {name: 'foobar'}, errors: {}}, []], VALIDATE_FIELD, {rules, validateSingle: true, name: 'name'})
    deepEqual(expected, result)
  })

  it('should validate all fields when the complete form state has been updated', () => {
    const expected = [{form: {name: 'foo', random: 'random'}, errors: {name: ['Minimum length is four.'], random: ['Minimum length is seven.']}}, []]
    const result = updateSyncErrors([{form: {name: 'foo', random: 'random'}, errors: {}}, []], UPDATE_ALL, {rules})
    deepEqual(expected, result)
  })

  it('should validate all fields a validate all actions has been triggered', () => {
    const expected = [{form: {name: 'foo', random: 'random'}, errors: {name: ['Minimum length is four.'], random: ['Minimum length is seven.']}}, []]
    const result = updateSyncErrors([{form: {name: 'foo', random: 'random'}, errors: {}}, []], VALIDATE_ALL, {rules})
    deepEqual(expected, result)
  })

})
<commit_msg>Fix failing tests<commit_after>import { deepEqual } from 'assert'

import updateSyncErrors from '../../src/updaters/updateSyncErrors'
import { UPDATE_FIELD, UPDATE_ALL, VALIDATE_FIELD, VALIDATE_ALL } from '../../src/constants'

const rules = {
  name: [[x => x.length > 3, 'Minimum length is four.']],
  random: [[x => x.length > 6, 'Minimum length is seven.']]
}

describe('updaters/updateSyncErrors', () => {

  it('should return an empty array when field value is valid and validateSingle is set to true', () => {
    const expected = [{form: {name: 'foobar'}, errors: {name: []}}, []]
    const result = updateSyncErrors([{form: {name: 'foobar'}, errors: {}}, []], UPDATE_FIELD, {
      rules,
      validateSingle: true,
      instantValidation: true,
      name: 'name'
    })
    deepEqual(expected, result)
  })

  it('should return an array containing the error messages when field value is invalid', () => {
    const expected = [{form: {name: 'bar'}, errors: {name: ['Minimum length is four.']}}, []]
    const result = updateSyncErrors([{form: {name: 'bar'}, errors: {}}, []], UPDATE_FIELD, {
      rules,
      validateSingle: true,
      instantValidation: true,
      name: 'name'
    })
    deepEqual(expected, result)
  })

  it('should skip validating when validateSingle is set to false and a field has been updated', () => {
    const expected = [{form: {name: 'foo'}, errors: {}}, []]
    const result = updateSyncErrors([{form: {name: 'foo'}, errors: {}}, []], UPDATE_FIELD, {
      rules,
      validateSingle: false,
      instantValidation: true,
      name: 'name'
    })
    deepEqual(expected, result)
  })

  it('should return an empty array when field value is valid and validateSingle is set to true and a validate field has been triggered', () => {
    const expected = [{form: {name: 'foobar'}, errors: {name: []}}, []]
    const result = updateSyncErrors([{form: {name: 'foobar'}, errors: {}}, []], VALIDATE_FIELD, {
      rules,
      validateSingle: true,
      instantValidation: true,
      name: 'name'
    })
    deepEqual(expected, result)
  })

  it('should validate all fields when the complete form state has been updated', () => {
    const expected = [{
      form: {name: 'foo', random: 'random'},
      errors: {name: ['Minimum length is four.'], random: ['Minimum length is seven.']}
    }, []]
    const result = updateSyncErrors([{form: {name: 'foo', random: 'random'}, errors: {}}, []], UPDATE_ALL, {
      rules,
      instantValidation: true
    })
    deepEqual(expected, result)
  })

  it('should validate all fields a validate all actions has been triggered', () => {
    const expected = [{
      form: {name: 'foo', random: 'random'},
      errors: {name: ['Minimum length is four.'], random: ['Minimum length is seven.']}
    }, []]
    const result = updateSyncErrors([{form: {name: 'foo', random: 'random'}, errors: {}}, []], VALIDATE_ALL, {
      rules,
      instantValidation: true
    })
    deepEqual(expected, result)
  })

  it('should skip validation when instantValidation is false and the action is not validate all', () => {
    const expected = [{
      form: {name: 'foo', random: 'random'},
      errors: {}
    }, []]
    const result = updateSyncErrors([{form: {name: 'foo', random: 'random'}, errors: {}}, []], UPDATE_ALL, {
      rules,
      instantValidation: false
    })
    deepEqual(expected, result)
  })

})
<|endoftext|>


<commit_before>describe("VglDodecahedronGeometry component", function() {
    const {VglDodecahedronGeometry, VglNamespace} = VueGL;
    const assert = chai.assert;
    describe("Parameters of a instance should be same as the component properties.", function() {
        it("When properties are number.", function() {
            const vm = new Vue({
                template: `<vgl-namespace><vgl-dodecahedron-geometry ref="geo" :radius="11.1" :detail="2" /></vgl-namespace>`,
                components: {VglDodecahedronGeometry, VglNamespace}
            }).$mount();
            assert.strictEqual(vm.$refs.geo.inst.parameters.radius, 11.1);
            assert.strictEqual(vm.$refs.geo.inst.parameters.detail, 2);
        });
        it("When properties are string.", function() {
            const vm = new Vue({
                template: `<vgl-namespace><vgl-dodecahedron-geometry ref="geo" radius="1.11" detail="3" /></vgl-namespace>`,
                components: {VglDodecahedronGeometry, VglNamespace}
            }).$mount();
            assert.strictEqual(vm.$refs.geo.inst.parameters.radius, 1.11);
            assert.strictEqual(vm.$refs.geo.inst.parameters.detail, 3);
        });
        it("When properties are undefined.", function() {
            const vm = new Vue({
                template: `<vgl-namespace><vgl-dodecahedron-geometry ref="geo" /></vgl-namespace>`,
                components: {VglDodecahedronGeometry, VglNamespace}
            }).$mount();
            assert.isUndefined(vm.$refs.geo.inst.parameters.radius);
            assert.isUndefined(vm.$refs.geo.inst.parameters.detail);
        });
    });
    describe("Instance should be recreated when a property changed.", function() {
        it("When the radius property changes.", function(done) {
            const vm = new Vue({
                template: `<vgl-namespace><vgl-dodecahedron-geometry ref="geo" :radius="radius" /></vgl-namespace>`,
                components: {VglDodecahedronGeometry, VglNamespace},
                data: {radius: 25}
            }).$mount();
            const before = vm.$refs.geo.inst;
            vm.radius = 11;
            vm.$nextTick(() => {
                try {
                    assert.notEqual(before, vm.$refs.geo.inst);
                    done();
                } catch(e) {
                    done(e);
                }
            });
        });
    });
});
<commit_msg>Reduce detail of the dodecahedron to avoid timeouts.<commit_after>describe("VglDodecahedronGeometry component", function() {
    const {VglDodecahedronGeometry, VglNamespace} = VueGL;
    const assert = chai.assert;
    describe("Parameters of a instance should be same as the component properties.", function() {
        it("When properties are number.", function() {
            const vm = new Vue({
                template: `<vgl-namespace><vgl-dodecahedron-geometry ref="geo" :radius="11.1" :detail="2" /></vgl-namespace>`,
                components: {VglDodecahedronGeometry, VglNamespace}
            }).$mount();
            assert.strictEqual(vm.$refs.geo.inst.parameters.radius, 11.1);
            assert.strictEqual(vm.$refs.geo.inst.parameters.detail, 2);
        });
        it("When properties are string.", function() {
            const vm = new Vue({
                template: `<vgl-namespace><vgl-dodecahedron-geometry ref="geo" radius="1.11" detail="2" /></vgl-namespace>`,
                components: {VglDodecahedronGeometry, VglNamespace}
            }).$mount();
            assert.strictEqual(vm.$refs.geo.inst.parameters.radius, 1.11);
            assert.strictEqual(vm.$refs.geo.inst.parameters.detail, 2);
        });
        it("When properties are undefined.", function() {
            const vm = new Vue({
                template: `<vgl-namespace><vgl-dodecahedron-geometry ref="geo" /></vgl-namespace>`,
                components: {VglDodecahedronGeometry, VglNamespace}
            }).$mount();
            assert.isUndefined(vm.$refs.geo.inst.parameters.radius);
            assert.isUndefined(vm.$refs.geo.inst.parameters.detail);
        });
    });
    describe("Instance should be recreated when a property changed.", function() {
        it("When the radius property changes.", function(done) {
            const vm = new Vue({
                template: `<vgl-namespace><vgl-dodecahedron-geometry ref="geo" :radius="radius" /></vgl-namespace>`,
                components: {VglDodecahedronGeometry, VglNamespace},
                data: {radius: 25}
            }).$mount();
            const before = vm.$refs.geo.inst;
            vm.radius = 11;
            vm.$nextTick(() => {
                try {
                    assert.notEqual(before, vm.$refs.geo.inst);
                    done();
                } catch(e) {
                    done(e);
                }
            });
        });
    });
});
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import * as d3 from 'd3'

class SelectionAndData extends Component {
  componentDidMount() {
    const rectWidth = 50
    const height = 200
    var data = [100, 250, 175, 200, 120]
    d3.selectAll('rect')
      .data(data)
      .attr('x', (d, i) => i * rectWidth)
      .attr('y', d => height - d)
      .attr('width', rectWidth)
      .attr('height', d => d)
      .attr('fill', 'blue')
      .attr('stroke', '#fff')
  }

  render() {
    return (
      <svg>
        <rect />
        <rect />
        <rect />
        <rect />
        <rect />
      </svg>
    )
  }
}

export default SelectionAndData;
<commit_msg>[refactor] Make selector more specific To avoid conflicts with future examples.<commit_after>import React, { Component } from 'react'
import * as d3 from 'd3'

class SelectionAndData extends Component {
  componentDidMount() {
    const rectWidth = 50
    const height = 200
    var data = [100, 250, 175, 200, 120]
    d3.selectAll('.rect-1')
      .data(data)
      .attr('x', (d, i) => i * rectWidth)
      .attr('y', d => height - d)
      .attr('width', rectWidth)
      .attr('height', d => d)
      .attr('fill', 'blue')
      .attr('stroke', '#fff')
  }

  render() {
    return (
      <svg>
        <rect class='rect-1' />
        <rect class='rect-1' />
        <rect class='rect-1' />
        <rect class='rect-1' />
        <rect class='rect-1' />
      </svg>
    )
  }
}

export default SelectionAndData;
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import {
  View,
  AsyncStorage
} from 'react-native';
import styles from './StyleSheet';
import _ from 'lodash';
import ScrollableTabView from 'react-native-scrollable-tab-view';
import NewTabBar from './replay_scroll_tab_view';
import Content from './content';
import Schedule, {Types} from './ReplayFX_Axios';

//This is a class that has all the info for our swipeable nav bar
export default class Scroll_Tab_View extends Component {

  constructor(props) {
    super(props);
    this.state = {
      //this array gets filled when people start "starring" their schedule
      favorites: [],
      //Array of types of events that will become the names of the tabs
      baseTabs: [
        //hard-coded
        {DisplayName: 'Experience', Name: 'all'},
        {DisplayName: 'My Schedule', Name: 'favorites'}
      ],
      tabs: [],

      baseSchedule: []
    };

    //binding so we know what 'this' is in reference to the class
    this.addFavorite = this.addFavorite.bind(this);
    this.removeFavorite = this.removeFavorite.bind(this);
    this.loadSchedule = this.loadSchedule.bind(this);
    this.loadFavorites = this.loadFavorites.bind(this);
    this.loadTypes = this.loadTypes.bind(this);
    this.loadLocalSchedule = this.loadLocalSchedule.bind(this);
    this.loadLocalTypes = this.loadLocalTypes.bind(this);

    //callbacks
    setTimeout(this.loadTypes, 2000);
    setTimeout(this.loadLocalTypes, 1000);
    this.loadLocalSchedule();
    this.loadSchedule();
    this.loadFavorites();
  }

  //function that loads favorites from local storage
  loadFavorites() {
    AsyncStorage.getItem('favorites', (err, value) => {
      if (value !== null) {
        this.setState({favorites: JSON.parse(value)});
      }
    });
  }
  //Axios call that gives baseSchedule its state and stores the data
  loadSchedule() {
    Schedule().then((results) => {
      this.setState({baseSchedule: results.data});
      AsyncStorage.setItem('all', JSON.stringify(results.data));
    });
  }
  loadLocalSchedule() {
    AsyncStorage.getItem('all', (err, value) => {
      if (value !== null) {
        this.setState({baseSchedule: JSON.parse(value)});
      }
    });
  }

  //Axios call that receives category types and stores the data
  loadTypes() {
    Types().then((results) => {
      this.setState({tabs: [...this.state.baseTabs, ...results.data]});
      AsyncStorage.setItem('types', JSON.stringify(results.data));
    });
  }

  loadLocalTypes() {
   //AsyncStorage.removeItem('types');
    AsyncStorage.getItem('types', (err, value) => {
      if (value !== null) {
        this.setState({tabs: [...this.state.baseTabs, ...JSON.parse(value)]});

      }
    });
  }

  //changes the state of favorites to add a new event id
  addFavorite(id)
  {
    let favorites = [...this.state.favorites, id];
    this.setState({favorites});

    AsyncStorage.setItem('favorites', JSON.stringify(favorites));
  }
  //changes the state of favorite to remove event id
  removeFavorite(id)
{
    let favorites = _.pull(this.state.favorites, id);
    this.setState({favorites});
    AsyncStorage.setItem('favorites', JSON.stringify(favorites));
  }

  render() {

    return (
      // This returns the tabs from the array so we can see them on the screen!
        <ScrollableTabView renderTabBar = {() => <NewTabBar favoritesCount= {this.state.favorites.length}/>} >
          {this.state.tabs.map((item, index) =>
          {return (<View style={styles.slide} tabLabel= {item.DisplayName} key = {index} >
            {/* passing the state of the length of the favorites so it's displayed in the
            'my schedule' section on the swipeable nav bar */}
            <Content
              //rendering the state based on whether an item is in the favorites array or not
              typeIs={item.Name}
              favorites={this.state.favorites}
              removeFavorite={this.removeFavorite}
              addFavorite={this.addFavorite}
              baseSchedule={this.state.baseSchedule}/>
          </View>);})}
        </ScrollableTabView>
    );
  }
}
<commit_msg>Fixed Local Types?<commit_after>import React, {Component} from 'react';
import {
  View,
  AsyncStorage
} from 'react-native';
import styles from './StyleSheet';
import _ from 'lodash';
import ScrollableTabView from 'react-native-scrollable-tab-view';
import NewTabBar from './replay_scroll_tab_view';
import Content from './content';
import Schedule, {Types} from './ReplayFX_Axios';

//This is a class that has all the info for our swipeable nav bar
export default class Scroll_Tab_View extends Component {

  constructor(props) {
    super(props);
    this.state = {
      //this array gets filled when people start "starring" their schedule
      favorites: [],
      //Array of types of events that will become the names of the tabs
      baseTabs: [
        //hard-coded
        {DisplayName: 'Experience', Name: 'all'},
        {DisplayName: 'My Schedule', Name: 'favorites'}
      ],
      baseSchedule: []
    };

    //binding so we know what 'this' is in reference to the class
    this.addFavorite = this.addFavorite.bind(this);
    this.removeFavorite = this.removeFavorite.bind(this);
    this.loadSchedule = this.loadSchedule.bind(this);
    this.loadFavorites = this.loadFavorites.bind(this);
    this.loadTypes = this.loadTypes.bind(this);
    this.loadLocalSchedule = this.loadLocalSchedule.bind(this);
    this.loadLocalTypes = this.loadLocalTypes.bind(this);

    //callbacks
    setTimeout(this.loadLocalTypes, 1000);
    setTimeout(this.loadTypes, 2000);
    this.loadLocalSchedule();
    this.loadSchedule();
    this.loadFavorites();
  }

  //function that loads favorites from local storage
  loadFavorites() {
    AsyncStorage.getItem('favorites', (err, value) => {
      if (value !== null) {
        this.setState({favorites: JSON.parse(value)});
      }
    });
  }
  //Axios call that gives baseSchedule its state and stores the data
  loadSchedule() {
    Schedule().then((results) => {
      this.setState({baseSchedule: results.data});
      AsyncStorage.setItem('all', JSON.stringify(results.data));
    });
  }
  loadLocalSchedule() {
    AsyncStorage.getItem('all', (err, value) => {
      if (value !== null) {
        this.setState({baseSchedule: JSON.parse(value)});
      }
    });
  }

  //Axios call that receives category types and stores the data
  loadTypes() {
    Types().then((results) => {
      this.setState({tabs: [...this.state.baseTabs, ...results.data]});
      AsyncStorage.setItem('types', JSON.stringify(results.data));
    });
  }

  loadLocalTypes() {
   //AsyncStorage.removeItem('types');
    AsyncStorage.getItem('types', (err, value) => {
      if (value !== null) {
        this.setState({baseTabs: [...this.state.baseTabs, ...JSON.parse(value)]});

      }
    });
  }

  //changes the state of favorites to add a new event id
  addFavorite(id)
  {
    let favorites = [...this.state.favorites, id];
    this.setState({favorites});

    AsyncStorage.setItem('favorites', JSON.stringify(favorites));
  }
  //changes the state of favorite to remove event id
  removeFavorite(id)
{
    let favorites = _.pull(this.state.favorites, id);
    this.setState({favorites});
    AsyncStorage.setItem('favorites', JSON.stringify(favorites));
  }

  render() {

    return (
      // This returns the tabs from the array so we can see them on the screen!
        <ScrollableTabView renderTabBar = {() => <NewTabBar favoritesCount= {this.state.favorites.length}/>} >
          {this.state.baseTabs.map((item, index) =>
          {return (<View style={styles.slide} tabLabel= {item.DisplayName} key = {index} >
            {/* passing the state of the length of the favorites so it's displayed in the
            'my schedule' section on the swipeable nav bar */}
            <Content
              //rendering the state based on whether an item is in the favorites array or not
              typeIs={item.Name}
              favorites={this.state.favorites}
              removeFavorite={this.removeFavorite}
              addFavorite={this.addFavorite}
              baseSchedule={this.state.baseSchedule}/>
          </View>);})}
        </ScrollableTabView>
    );
  }
}
<|endoftext|>