<commit_before>import {extent} from "d3-array";
import {nest} from "d3-collection";
import {interpolatePath} from "d3-interpolate-path";
import {select} from "d3-selection";
import * as paths from "d3-shape";
import {transition} from "d3-transition";

import {accessor, constant} from "d3plus-common";
import {strip} from "d3plus-text";

import {default as Shape} from "./Shape";

/**
    @class Area
    @extends Shape
    @desc Creates SVG areas based on an array of data.
*/
export default class Area extends Shape {

  /**
      @memberof Area
      @desc Invoked when creating a new class instance, and overrides any default parameters inherited from Shape.
      @private
  */
  constructor() {

    super();

    this._curve = "linear";
    this._x = accessor("x");
    this._x0 = accessor("x");
    this._x1 = null;
    this._y = constant(0);
    this._y0 = constant(0);
    this._y1 = accessor("y");

  }

  /**
      Draws the lines.
      @param {Function} [*callback* = undefined]
      @private
  */
  render(callback) {

    super.render(callback);

    const path = this._path = paths.area()
      .defined(d => d)
      .curve(paths[`curve${this._curve.charAt(0).toUpperCase()}${this._curve.slice(1)}`])
      .x(this._x)
      .x0(this._x0)
      .x1(this._x1)
      .y(this._y)
      .y0(this._y0)
      .y1(this._y1);

    const exitPath = paths.area()
      .defined(d => d)
      .curve(paths[`curve${this._curve.charAt(0).toUpperCase()}${this._curve.slice(1)}`])
      .x(this._x)
      .x0(this._x0)
      .x1(this._x1)
      .y(this._y)
      .y0(this._y0)
      .y1(this._y1);

    const areas = nest().key(this._id).entries(this._data).map(d => {
      const x = extent(d.values.map(this._x)
        .concat(d.values.map(this._x0))
        .concat(this._x1 ? d.values.map(this._x1) : [])
      );
      d.xR = x;
      d.width = x[1] - x[0];
      d.x = x[0] + d.width / 2;
      const y = extent(d.values.map(this._y)
        .concat(d.values.map(this._y0))
        .concat(this._y1 ? d.values.map(this._y1) : [])
      );
      d.yR = y;
      d.height = y[1] - y[0];
      d.y = y[0] + d.height / 2;
      d.nested = true;
      return d;
    });

    const groups = this._select.selectAll(".d3plus-Area").data(areas, d => d.key);

    groups.transition(this._transition)
      .attr("transform", d => `translate(${d.x}, ${d.y})`);

    groups.select("path").transition(this._transition)
      .attr("transform", d => `translate(${-d.xR[0] - d.width / 2}, ${-d.yR[0] - d.height / 2})`)
      .attrTween("d", function(d) {
        return interpolatePath(select(this).attr("d"), path(d.values));
      })
      .call(this._applyStyle.bind(this));

    groups.exit().select("path").transition(this._transition)
      .attrTween("d", function(d) {
        return interpolatePath(select(this).attr("d"), exitPath(d.values));
      });

    groups.exit().transition().delay(this._duration).remove();

    groups.exit().call(this._applyLabels.bind(this), false);

    const enter = groups.enter().append("g")
        .attr("class", d => `d3plus-Shape d3plus-Area d3plus-id-${strip(d.key)}`)
        .attr("transform", d => `translate(${d.x}, ${d.y})`)
        .attr("opacity", 0);

    enter.append("path")
      .attr("transform", d => `translate(${-d.xR[0] - d.width / 2}, ${-d.yR[0] - d.height / 2})`)
      .attr("d", d => path(d.values))
      .call(this._applyStyle.bind(this));

    const update = enter.merge(groups);

    update.call(this._applyLabels.bind(this))
        .attr("pointer-events", "none")
      .transition(this._transition)
        .attr("opacity", this._opacity)
      .transition()
        .attr("pointer-events", "all");

    this._applyEvents(update);

    return this;

  }

  /**
      @memberof Area
      @desc Given a specific data point and index, returns the aesthetic properties of the shape.
      @param {Object} *data point*
      @param {Number} *index*
      @private
  */
  _aes(d, i) {
    return {points: d.values.map(p => [this._x(p, i), this._y(p, i)])};
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the line curve to the specified string and returns the current class instance. If *value* is not specified, returns the current line curve. The number returned should correspond to the horizontal center of the rectangle.
      @param {String} [*value* = "linear"]
  */
  curve(_) {
    return arguments.length ? (this._curve = _, this) : this._curve;
  }

  /**
      @memberof Area
      @desc Updates the style and positioning of the elements matching *selector* and returns the current class instance. This is helpful when not wanting to loop through all shapes just to change the style of a few.
      @param {String|HTMLElement} *selector*
  */
  update(_) {

    const groups = this._select.selectAll(_),
          t = transition().duration(this._duration);

    groups
        .call(this._applyLabels.bind(this))
      .transition(t)
        .attr("opacity", this._opacity);

    groups.select("path").transition(t)
      .attr("d", d => this._path(d.values));

    return this;

  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the x accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current x accessor.
      @param {Function|Number} [*value*]
      @example
function(d) {
  return d.x;
}
  */
  x(_) {
    return arguments.length ? (this._x = _, this) : this._x;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the x0 accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current x0 accessor.
      @param {Function|Number} [*value*]
  */
  x0(_) {
    return arguments.length ? (this._x0 = _, this) : this._x0;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the x1 accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current x1 accessor.
      @param {Function|Number} [*value*]
  */
  x1(_) {
    return arguments.length ? (this._x1 = _, this) : this._x1;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the y accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current y accessor.
      @param {Function|Number} [*value*]
      @example
function(d) {
  return d.y;
}
  */
  y(_) {
    return arguments.length ? (this._y = _, this) : this._y;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the y0 accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current y0 accessor.
      @param {Function|Number} [*value*]
  */
  y0(_) {
    return arguments.length ? (this._y0 = _, this) : this._y0;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the y1 accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current y1 accessor.
      @param {Function|Number} [*value*]
  */
  y1(_) {
    return arguments.length ? (this._y1 = _, this) : this._y1;
  }

}
<commit_msg>allows passing constants to Area x/y methods<commit_after>import {extent} from "d3-array";
import {nest} from "d3-collection";
import {interpolatePath} from "d3-interpolate-path";
import {select} from "d3-selection";
import * as paths from "d3-shape";
import {transition} from "d3-transition";

import {accessor, constant} from "d3plus-common";
import {strip} from "d3plus-text";

import {default as Shape} from "./Shape";

/**
    @class Area
    @extends Shape
    @desc Creates SVG areas based on an array of data.
*/
export default class Area extends Shape {

  /**
      @memberof Area
      @desc Invoked when creating a new class instance, and overrides any default parameters inherited from Shape.
      @private
  */
  constructor() {

    super();

    this._curve = "linear";
    this._x = accessor("x");
    this._x0 = accessor("x");
    this._x1 = null;
    this._y = constant(0);
    this._y0 = constant(0);
    this._y1 = accessor("y");

  }

  /**
      Draws the lines.
      @param {Function} [*callback* = undefined]
      @private
  */
  render(callback) {

    super.render(callback);

    const path = this._path = paths.area()
      .defined(d => d)
      .curve(paths[`curve${this._curve.charAt(0).toUpperCase()}${this._curve.slice(1)}`])
      .x(this._x)
      .x0(this._x0)
      .x1(this._x1)
      .y(this._y)
      .y0(this._y0)
      .y1(this._y1);

    const exitPath = paths.area()
      .defined(d => d)
      .curve(paths[`curve${this._curve.charAt(0).toUpperCase()}${this._curve.slice(1)}`])
      .x(this._x)
      .x0(this._x0)
      .x1(this._x1)
      .y(this._y)
      .y0(this._y0)
      .y1(this._y1);

    const areas = nest().key(this._id).entries(this._data).map(d => {
      const x = extent(d.values.map(this._x)
        .concat(d.values.map(this._x0))
        .concat(this._x1 ? d.values.map(this._x1) : [])
      );
      d.xR = x;
      d.width = x[1] - x[0];
      d.x = x[0] + d.width / 2;
      const y = extent(d.values.map(this._y)
        .concat(d.values.map(this._y0))
        .concat(this._y1 ? d.values.map(this._y1) : [])
      );
      d.yR = y;
      d.height = y[1] - y[0];
      d.y = y[0] + d.height / 2;
      d.nested = true;
      return d;
    });

    const groups = this._select.selectAll(".d3plus-Area").data(areas, d => d.key);

    groups.transition(this._transition)
      .attr("transform", d => `translate(${d.x}, ${d.y})`);

    groups.select("path").transition(this._transition)
      .attr("transform", d => `translate(${-d.xR[0] - d.width / 2}, ${-d.yR[0] - d.height / 2})`)
      .attrTween("d", function(d) {
        return interpolatePath(select(this).attr("d"), path(d.values));
      })
      .call(this._applyStyle.bind(this));

    groups.exit().select("path").transition(this._transition)
      .attrTween("d", function(d) {
        return interpolatePath(select(this).attr("d"), exitPath(d.values));
      });

    groups.exit().transition().delay(this._duration).remove();

    groups.exit().call(this._applyLabels.bind(this), false);

    const enter = groups.enter().append("g")
        .attr("class", d => `d3plus-Shape d3plus-Area d3plus-id-${strip(d.key)}`)
        .attr("transform", d => `translate(${d.x}, ${d.y})`)
        .attr("opacity", 0);

    enter.append("path")
      .attr("transform", d => `translate(${-d.xR[0] - d.width / 2}, ${-d.yR[0] - d.height / 2})`)
      .attr("d", d => path(d.values))
      .call(this._applyStyle.bind(this));

    const update = enter.merge(groups);

    update.call(this._applyLabels.bind(this))
        .attr("pointer-events", "none")
      .transition(this._transition)
        .attr("opacity", this._opacity)
      .transition()
        .attr("pointer-events", "all");

    this._applyEvents(update);

    return this;

  }

  /**
      @memberof Area
      @desc Given a specific data point and index, returns the aesthetic properties of the shape.
      @param {Object} *data point*
      @param {Number} *index*
      @private
  */
  _aes(d, i) {
    return {points: d.values.map(p => [this._x(p, i), this._y(p, i)])};
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the line curve to the specified string and returns the current class instance. If *value* is not specified, returns the current line curve. The number returned should correspond to the horizontal center of the rectangle.
      @param {String} [*value* = "linear"]
  */
  curve(_) {
    return arguments.length ? (this._curve = _, this) : this._curve;
  }

  /**
      @memberof Area
      @desc Updates the style and positioning of the elements matching *selector* and returns the current class instance. This is helpful when not wanting to loop through all shapes just to change the style of a few.
      @param {String|HTMLElement} *selector*
  */
  update(_) {

    const groups = this._select.selectAll(_),
          t = transition().duration(this._duration);

    groups
        .call(this._applyLabels.bind(this))
      .transition(t)
        .attr("opacity", this._opacity);

    groups.select("path").transition(t)
      .attr("d", d => this._path(d.values));

    return this;

  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the x accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current x accessor.
      @param {Function|Number} [*value*]
      @example
function(d) {
  return d.x;
}
  */
  x(_) {
    return arguments.length ? (this._x = typeof _ === "function" ? _ : constant(_), this) : this._x;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the x0 accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current x0 accessor.
      @param {Function|Number} [*value*]
  */
  x0(_) {
    return arguments.length ? (this._x0 = typeof _ === "function" ? _ : constant(_), this) : this._x0;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the x1 accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current x1 accessor.
      @param {Function|Number|null} [*value*]
  */
  x1(_) {
    return arguments.length ? (this._x1 = typeof _ === "function" || _ === null ? _ : constant(_), this) : this._x1;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the y accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current y accessor.
      @param {Function|Number} [*value*]
      @example
function(d) {
  return d.y;
}
  */
  y(_) {
    return arguments.length ? (this._y = typeof _ === "function" ? _ : constant(_), this) : this._y;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the y0 accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current y0 accessor.
      @param {Function|Number} [*value*]
  */
  y0(_) {
    return arguments.length ? (this._y0 = typeof _ === "function" ? _ : constant(_), this) : this._y0;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the y1 accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current y1 accessor.
      @param {Function|Number|null} [*value*]
  */
  y1(_) {
    return arguments.length ? (this._y1 = typeof _ === "function" || _ === null ? _ : constant(_), this) : this._y1;
  }

}
<|endoftext|>


<commit_before>//gpsDialog();

function angleFromCoordinate(latLng1, latLng2) {
    var dLon = (latLng2.lng - latLng1.lng);

    var y = Math.sin(dLon) * Math.cos(latLng2.lat);
    var x = Math.cos(latLng1.lat) * Math.sin(latLng2.lat) - Math.sin(latLng1.lat) * Math.cos(latLng2.lat) * Math.cos(dLon);

    var brng = Math.atan2(y, x);

    brng = brng * (180 / Math.PI);
    brng = (brng + 360) % 360;
    brng = 360 - brng;
    return Math.floor(brng);
}

function MoveDegrees(degrees) {
    while (degrees < 0 || degrees >= 360) {
        if (degrees < 0)
            degrees = degrees + 360;
        if (degrees >= 360)
            degrees = degrees - 360;
    }
    return degrees;
}

function rotateMap() {
    if (bearingNow == bearingTarget || positionBefore == null)
        return;
    bearingNow = MoveDegrees(bearingNow);
    var dist = bearingTarget - bearingNow;
    if (dist < 0)
        dist += 360;
    if (dist > 180) {
        bearingNow -= 1;
        map.setBearing(bearingNow);
    } else {
        bearingNow += 1;
        map.setBearing(bearingNow);
    }
}

function rotateMap() {
    if (navigationSystem.bearingNow == navigationSystem.bearingTarget || navigationSystem.positionBefore == null)
        return;
    navigationSystem.bearingNow = MoveDegrees(navigationSystem.bearingNow);
    var dist = navigationSystem.bearingTarget - navigationSystem.bearingNow;
    if (dist < 0)
        dist += 360;
    if (dist > 180) {
        navigationSystem.bearingNow -= 1;
        map.setBearing(navigationSystem.bearingNow);
    } else {
        navigationSystem.bearingNow += 1;
        map.setBearing(navigationSystem.bearingNow);
    }
}

var NavigationSystem = function() {

    ////InitState - sprawdza czy gps jest włączony, jeśli jest ustawia przycisk na włączony i przechodzi do InitNavigationState, w drugim wypadku przechodzi na GpsOffState
    ////GpsOffState - wyłącza wszelkie watchPosition i nic nie robi, po kliknięciu przycisku przechodzi w InitState
    ////NavigationState - nawiguje, jeśli się nie uda przechodzi na GpsOffState

    this.state = "InitState";
    this.initAmount = 0;

    map.addControl(new label(id = "speedField", value = "Speed: 0"));
    map.addControl(new label(id = "accuracyField", value = "Accuracy: 0"));
    map.addControl(new returnButton());
    map.addControl(new navigationButton());

    this.naviMarker = L.Marker.movingMarker([
        [0, 0],
        [0, 0]
    ], [10000], { autostart: true, icon: navigationIcon }).addTo(map);

    this.position = new L.latLng(0, 0);
    this.positionBefore;
    this.bearingNow = 0.0;
    this.bearingTarget = 0.0;

    this.watchGeoLocation;
    this.initNavigation();
    var intervalRotateMap = window.setInterval(rotateMap, 30);
    var intervalPosMap = window.setInterval(this.setMapPos.bind(this), 50);

    this.loadRoute();
}

NavigationSystem.prototype = {
    initNavigation: function() {
        this.watchGeoLocation = navigator.geolocation.watchPosition(this.successGeoLocate.bind(this), this.errorGeoLocate.bind(this), { timeout: 2000, enableHighAccuracy: true });
    },
    setMapPos: function() {
        if (this.naviMarker.isRunning())
            map.panTo(this.naviMarker._latlng);
    },
    loadRoute: function() {
        var route = new Route();
        var routejson = localStorage.getItem(location.search.split('=')[1]);
        if (routejson != null) {
            route.dehydrate(routejson);
            route.loadOnMap();
        }
    },
    successGeoLocate: function(pos) {
        setNavigationButtonImage("url(img/navigationButtonOn.png)");
        document.getElementById("speedField").value = "Speed: " + (pos.coords.speed).toFixed(2);
        document.getElementById("accuracyField").value = "Accuracy: " + pos.coords.accuracy;

        if ((pos.coords.latitude == this.position.lat && pos.coords.longitude == this.position.lng))
            return;

        this.positionBefore = this.position;
        this.position = new L.latLng(pos.coords.latitude, pos.coords.longitude);

        this.naviMarker.moveTo([this.position.lat, this.position.lng], 2100);
        this.naviMarker.start();

        this.bearingTarget = 180 - angleFromCoordinate(this.position, this.positionBefore);
        this.bearingTarget = MoveDegrees(this.bearingTarget);
        this.bearingNow = MoveDegrees(this.bearingNow);
    },
    errorGeoLocate: function(error) {
        navigator.geolocation.clearWatch(this.watchGeoLocation);
        gpsDialog();
        setNavigationButtonImage("url(img/navigationButtonOff.png)");
    },
    gpsDialogYes: function(){
        map.closeModal();
        cordova.plugins.diagnostic.switchToLocationSettings();
        this.watchGeoLocation = navigator.geolocation.watchPosition(this.successGeoLocate.bind(this), this.errorGeoLocate, { timeout: 2000, enableHighAccuracy: true });
    },
    gpsDialogNo: function(){
        setNavigationButtonImage("url(img/navigationButtonOff.png)");
        map.closeModal();
    }
}

var navigationSystem = new NavigationSystem();

<commit_msg>refs #5<commit_after>//gpsDialog();

function angleFromCoordinate(latLng1, latLng2) {
    var dLon = (latLng2.lng - latLng1.lng);

    var y = Math.sin(dLon) * Math.cos(latLng2.lat);
    var x = Math.cos(latLng1.lat) * Math.sin(latLng2.lat) - Math.sin(latLng1.lat) * Math.cos(latLng2.lat) * Math.cos(dLon);

    var brng = Math.atan2(y, x);

    brng = brng * (180 / Math.PI);
    brng = (brng + 360) % 360;
    brng = 360 - brng;
    return Math.floor(brng);
}

function MoveDegrees(degrees) {
    while (degrees < 0 || degrees >= 360) {
        if (degrees < 0)
            degrees = degrees + 360;
        if (degrees >= 360)
            degrees = degrees - 360;
    }
    return degrees;
}

function rotateMap() {
    if (bearingNow == bearingTarget || positionBefore == null)
        return;
    bearingNow = MoveDegrees(bearingNow);
    var dist = bearingTarget - bearingNow;
    if (dist < 0)
        dist += 360;
    if (dist > 180) {
        bearingNow -= 1;
        map.setBearing(bearingNow);
    } else {
        bearingNow += 1;
        map.setBearing(bearingNow);
    }
}

function rotateMap() {
    if (navigationSystem.bearingNow == navigationSystem.bearingTarget || navigationSystem.positionBefore == null)
        return;
    navigationSystem.bearingNow = MoveDegrees(navigationSystem.bearingNow);
    var dist = navigationSystem.bearingTarget - navigationSystem.bearingNow;
    if (dist < 0)
        dist += 360;
    if (dist > 180) {
        navigationSystem.bearingNow -= 1;
        map.setBearing(navigationSystem.bearingNow);
    } else {
        navigationSystem.bearingNow += 1;
        map.setBearing(navigationSystem.bearingNow);
    }
}

var NavigationSystem = function() {

    ////InitState - sprawdza czy gps jest włączony, jeśli jest ustawia przycisk na włączony i przechodzi do InitNavigationState, w drugim wypadku przechodzi na GpsOffState
    ////GpsOffState - wyłącza wszelkie watchPosition i nic nie robi, po kliknięciu przycisku przechodzi w InitState
    ////NavigationState - nawiguje, jeśli się nie uda przechodzi na GpsOffState

    this.state = "InitState";
    this.initAmount = 0;

    map.addControl(new label(id = "speedField", value = "Speed: 0"));
    map.addControl(new label(id = "accuracyField", value = "Accuracy: 0"));
    map.addControl(new returnButton());
    map.addControl(new navigationButton());

    this.naviMarker = L.Marker.movingMarker([
        [0, 0],
        [0, 0]
    ], [10000], { autostart: true, icon: navigationIcon }).addTo(map);

    this.position = new L.latLng(0, 0);
    this.positionBefore;
    this.bearingNow = 0.0;
    this.bearingTarget = 0.0;

    this.watchGeoLocation;
    this.initNavigation();
    var intervalRotateMap = window.setInterval(rotateMap, 30);
    var intervalPosMap = window.setInterval(this.setMapPos.bind(this), 50);

    this.loadRoute();
}

NavigationSystem.prototype = {
    initNavigation: function() {
        this.watchGeoLocation = navigator.geolocation.watchPosition(this.successGeoLocate.bind(this), this.errorGeoLocate.bind(this), { timeout: 2000, enableHighAccuracy: true });
    },
    setMapPos: function() {
        if (this.naviMarker.isRunning())
            map.panTo(this.naviMarker._latlng);
    },
    loadRoute: function() {
        var route = new Route();
        var routejson = localStorage.getItem(location.search.split('=')[1]);
        if (routejson != null) {
            route.dehydrate(routejson);
            route.loadOnMap();
        }
    },
    successGeoLocate: function(pos) {
        setNavigationButtonImage("url(img/navigationButtonOn.png)");
        if (pos.coords.speed != undefined)
            document.getElementById("speedField").value = "Speed: " + (pos.coords.speed).toFixed(2);
        if (pos.coords.accuracy != undefined)
            document.getElementById("accuracyField").value = "Accuracy: " + pos.coords.accuracy;

        if ((pos.coords.latitude == this.position.lat && pos.coords.longitude == this.position.lng))
            return;

        this.positionBefore = this.position;
        this.position = new L.latLng(pos.coords.latitude, pos.coords.longitude);

        this.naviMarker.moveTo([this.position.lat, this.position.lng], 2100);
        this.naviMarker.start();

        this.bearingTarget = 180 - angleFromCoordinate(this.position, this.positionBefore);
        this.bearingTarget = MoveDegrees(this.bearingTarget);
        this.bearingNow = MoveDegrees(this.bearingNow);
    },
    errorGeoLocate: function(error) {
        navigator.geolocation.clearWatch(this.watchGeoLocation);
        gpsDialog();
        setNavigationButtonImage("url(img/navigationButtonOff.png)");
    },
    gpsDialogYes: function() {
        map.closeModal();
        cordova.plugins.diagnostic.switchToLocationSettings();
    },
    gpsDialogNo: function() {
        setNavigationButtonImage("url(img/navigationButtonOff.png)");
        map.closeModal();
    }
}

var navigationSystem = new NavigationSystem();

gpsDialog();
<|endoftext|>


<commit_before>define([
	"ember",
	"text!templates/components/formbutton.html.hbs"
], function( Ember, template ) {

	return Ember.Component.extend({
		layout: Ember.Handlebars.compile( template ),
		tagName: "button",
		attributeBindings: [ "type", "title" ],
		type: "button",
		title: "",
		classNameBindings: [
			":btn",
			"_iconAndNoText:btn-icon",
			"_iconAndText:btn-with-icon",
			"_iconanim:btn-with-anim",
			"class"
		],

		action: "",
		class: "",

		icon: false,
		_iconAndText: Ember.computed.and( "icon", "template" ),
		_iconAndNoText: function() {
			return this.get( "icon" ) && !this.get( "template" );
		}.property( "icon", "template" ),

		iconanim: false,
		_iconanim: false,

		click: function() {
			var self = this,
			    success;
			if ( this.get( "iconanim" ) ) {
				success = function( callback ) {
					self.set( "_iconanim", true );
					self.element.addEventListener( "webkitAnimationEnd", function( e ) {
						if ( e.animationName === "animIconScale" ) {
							self.set( "_iconanim", false );
							if ( callback ) { callback( e ); }
						}
					}, false );
				};
			}

			this.sendAction( "action", success );
		}
	});

});
<commit_msg>Added actionParam to FormButtonComponent<commit_after>define([
	"ember",
	"text!templates/components/formbutton.html.hbs"
], function( Ember, template ) {

	return Ember.Component.extend({
		layout: Ember.Handlebars.compile( template ),
		tagName: "button",
		attributeBindings: [ "type", "title" ],
		type: "button",
		title: null,
		classNameBindings: [
			":btn",
			"_iconAndNoText:btn-icon",
			"_iconAndText:btn-with-icon",
			"_iconanim:btn-with-anim",
			"class"
		],
		class: null,

		action: "",
		actionParam: null,

		icon: false,
		_iconAndText: Ember.computed.and( "icon", "template" ),
		_iconAndNoText: function() {
			return this.get( "icon" ) && !this.get( "template" );
		}.property( "icon", "template" ),

		iconanim: false,
		_iconanim: false,

		click: function() {
			var self  = this,
			    param = Ember.makeArray( this.get( "actionParam" ) ),
			    success;
			if ( this.get( "iconanim" ) ) {
				success = function( callback ) {
					self.set( "_iconanim", true );
					self.element.addEventListener( "webkitAnimationEnd", function( e ) {
						if ( e.animationName === "animIconScale" ) {
							self.set( "_iconanim", false );
							if ( callback ) { callback( e ); }
						}
					}, false );
				};
			}

			this.sendAction.apply( this, [ "action" ].concat( param ).concat( success ) );
		}
	});

});
<|endoftext|>


<commit_before>(function () {
  'use strict';
  /**
   *  @ngdoc object
   *  @name ui.grid.service:gridClassFactory
   *
   *  @description factory to return dom specific instances of a grid
   *
   */
  angular.module('ui.grid').service('gridClassFactory', ['gridUtil', '$q', '$compile', '$templateCache', 'uiGridConstants', 'Grid', 'GridColumn', 'GridRow',
    function (gridUtil, $q, $compile, $templateCache, uiGridConstants, Grid, GridColumn, GridRow) {

      var service = {
        /**
         * @ngdoc method
         * @name createGrid
         * @methodOf ui.grid.service:gridClassFactory
         * @description Creates a new grid instance. Each instance will have a unique id
         * @param {object} options An object map of options to pass into the created grid instance.
         * @returns {Grid} grid
         */
        createGrid : function(options) {
          options = (typeof(options) !== 'undefined') ? options : {};
          options.id = gridUtil.newId();
          var grid = new Grid(options);

          // NOTE/TODO: rowTemplate should always be defined...
          if (grid.options.rowTemplate) {
            var rowTemplateFnPromise = $q.defer();
            grid.getRowTemplateFn = rowTemplateFnPromise.promise;

            gridUtil.getTemplate(grid.options.rowTemplate)
              .then(
                function (template) {
                  var rowTemplateFn = $compile(template);
                  rowTemplateFnPromise.resolve(rowTemplateFn);
                },
                function (res) {
                  // Todo handle response error here?
                  throw new Error("Couldn't fetch/use row template '" + grid.options.rowTemplate + "'");
                }).catch(angular.noop);
          }

          grid.registerColumnBuilder(service.defaultColumnBuilder);

          // Row builder for custom row templates
          grid.registerRowBuilder(service.rowTemplateAssigner);

          // Reset all rows to visible initially
          grid.registerRowsProcessor(function allRowsVisible(rows) {
            rows.forEach(function (row) {
              row.evaluateRowVisibility( true );
            }, 50);

            return rows;
          });

          grid.registerColumnsProcessor(function applyColumnVisibility(columns) {
            columns.forEach(function (column) {
              column.visible = angular.isDefined(column.colDef.visible) ? column.colDef.visible : true;
            });

            return columns;
          }, 50);

          grid.registerRowsProcessor(grid.searchRows, 100);

          // Register the default row processor, it sorts rows by selected columns
          if (grid.options.externalSort && angular.isFunction(grid.options.externalSort)) {
            grid.registerRowsProcessor(grid.options.externalSort, 200);
          }
          else {
            grid.registerRowsProcessor(grid.sortByColumn, 200);
          }

          return grid;
        },

        /**
         * @ngdoc function
         * @name defaultColumnBuilder
         * @methodOf ui.grid.service:gridClassFactory
         * @description Processes designTime column definitions and applies them to col for the
         *              core grid features
         * @param {object} colDef reference to column definition
         * @param {GridColumn} col reference to gridCol
         * @param {object} gridOptions reference to grid options
         */
        defaultColumnBuilder: function (colDef, col, gridOptions) {

          var templateGetPromises = [];

          // Abstracts the standard template processing we do for every template type.
          var processTemplate = function( templateType, providedType, defaultTemplate, filterType, tooltipType ) {
            if ( !colDef[templateType] ){
              col[providedType] = defaultTemplate;
            } else {
              col[providedType] = colDef[templateType];
            }

            var templatePromise = gridUtil.getTemplate(col[providedType])
              .then(
                function (template) {
                  if ( angular.isFunction(template) ) { template = template(); }
                  var tooltipCall = ( tooltipType === 'cellTooltip' ) ? 'col.cellTooltip(row,col)' : 'col.headerTooltip(col)';
                  if ( tooltipType && col[tooltipType] === false ){
                    template = template.replace(uiGridConstants.TOOLTIP, '');
                  } else if ( tooltipType && col[tooltipType] ){
                    template = template.replace(uiGridConstants.TOOLTIP, 'title="{{' + tooltipCall + ' CUSTOM_FILTERS }}"');
                  }

                  if ( filterType ){
                    col[templateType] = template.replace(uiGridConstants.CUSTOM_FILTERS, function() {
                      return col[filterType] ? "|" + col[filterType] : "";
                    });
                  } else {
                    col[templateType] = template;
                  }
                },
                function (res) {
                  throw new Error("Couldn't fetch/use colDef." + templateType + " '" + colDef[templateType] + "'");
                }).catch(angular.noop);

            templateGetPromises.push(templatePromise);

            return templatePromise;
          };

          /**
           * @ngdoc property
           * @name cellTemplate
           * @propertyOf ui.grid.class:GridOptions.columnDef
           * @description a custom template for each cell in this column.  The default
           * is ui-grid/uiGridCell.  If you are using the cellNav feature, this template
           * must contain a div that can receive focus.
           *
           */
          col.cellTemplatePromise = processTemplate( 'cellTemplate', 'providedCellTemplate', 'ui-grid/uiGridCell', 'cellFilter', 'cellTooltip' );

          /**
           * @ngdoc property
           * @name headerCellTemplate
           * @propertyOf ui.grid.class:GridOptions.columnDef
           * @description a custom template for the header for this column.  The default
           * is ui-grid/uiGridHeaderCell
           *
           */
          col.headerCellTemplatePromise = processTemplate( 'headerCellTemplate', 'providedHeaderCellTemplate', 'ui-grid/uiGridHeaderCell', 'headerCellFilter', 'headerTooltip' );

          /**
           * @ngdoc property
           * @name footerCellTemplate
           * @propertyOf ui.grid.class:GridOptions.columnDef
           * @description a custom template for the footer for this column.  The default
           * is ui-grid/uiGridFooterCell
           *
           */
          col.footerCellTemplatePromise = processTemplate( 'footerCellTemplate', 'providedFooterCellTemplate', 'ui-grid/uiGridFooterCell', 'footerCellFilter' );

          /**
           * @ngdoc property
           * @name filterHeaderTemplate
           * @propertyOf ui.grid.class:GridOptions.columnDef
           * @description a custom template for the filter input.  The default is ui-grid/ui-grid-filter
           *
           */
          col.filterHeaderTemplatePromise = processTemplate( 'filterHeaderTemplate', 'providedFilterHeaderTemplate', 'ui-grid/ui-grid-filter' );

          // Create a promise for the compiled element function
          col.compiledElementFnDefer = $q.defer();

          return $q.all(templateGetPromises);
        },

        rowTemplateAssigner: function rowTemplateAssigner(row) {
          var grid = this;

          // Row has no template assigned to it
          if (!row.rowTemplate) {
            // Use the default row template from the grid
            row.rowTemplate = grid.options.rowTemplate;

            // Use the grid's function for fetching the compiled row template function
            row.getRowTemplateFn = grid.getRowTemplateFn;
          }
          // Row has its own template assigned
          else {
            // Create a promise for the compiled row template function
            var perRowTemplateFnPromise = $q.defer();
            row.getRowTemplateFn = perRowTemplateFnPromise.promise;

            // Get the row template
            gridUtil.getTemplate(row.rowTemplate)
              .then(function (template) {
                // Compile the template
                var rowTemplateFn = $compile(template);

                // Resolve the compiled template function promise
                perRowTemplateFnPromise.resolve(rowTemplateFn);
              },
              function (res) {
                // Todo handle response error here?
                throw new Error("Couldn't fetch/use row template '" + row.rowTemplate + "'");
              });
          }

          return row.getRowTemplateFn;
        }
      };

      //class definitions (moved to separate factories)

      return service;
    }]);

})();
<commit_msg>fix(gridClassFactory.js): Move priority to correct spot.<commit_after>(function () {
  'use strict';
  /**
   *  @ngdoc object
   *  @name ui.grid.service:gridClassFactory
   *
   *  @description factory to return dom specific instances of a grid
   *
   */
  angular.module('ui.grid').service('gridClassFactory', ['gridUtil', '$q', '$compile', '$templateCache', 'uiGridConstants', 'Grid', 'GridColumn', 'GridRow',
    function (gridUtil, $q, $compile, $templateCache, uiGridConstants, Grid, GridColumn, GridRow) {

      var service = {
        /**
         * @ngdoc method
         * @name createGrid
         * @methodOf ui.grid.service:gridClassFactory
         * @description Creates a new grid instance. Each instance will have a unique id
         * @param {object} options An object map of options to pass into the created grid instance.
         * @returns {Grid} grid
         */
        createGrid : function(options) {
          options = (typeof(options) !== 'undefined') ? options : {};
          options.id = gridUtil.newId();
          var grid = new Grid(options);

          // NOTE/TODO: rowTemplate should always be defined...
          if (grid.options.rowTemplate) {
            var rowTemplateFnPromise = $q.defer();
            grid.getRowTemplateFn = rowTemplateFnPromise.promise;

            gridUtil.getTemplate(grid.options.rowTemplate)
              .then(
                function (template) {
                  var rowTemplateFn = $compile(template);
                  rowTemplateFnPromise.resolve(rowTemplateFn);
                },
                function (res) {
                  // Todo handle response error here?
                  throw new Error("Couldn't fetch/use row template '" + grid.options.rowTemplate + "'");
                }).catch(angular.noop);
          }

          grid.registerColumnBuilder(service.defaultColumnBuilder);

          // Row builder for custom row templates
          grid.registerRowBuilder(service.rowTemplateAssigner);

          // Reset all rows to visible initially
          grid.registerRowsProcessor(function allRowsVisible(rows) {
            rows.forEach(function (row) {
              row.evaluateRowVisibility( true );
            });

            return rows;
          }, 50);

          grid.registerColumnsProcessor(function applyColumnVisibility(columns) {
            columns.forEach(function (column) {
              column.visible = angular.isDefined(column.colDef.visible) ? column.colDef.visible : true;
            });

            return columns;
          }, 50);

          grid.registerRowsProcessor(grid.searchRows, 100);

          // Register the default row processor, it sorts rows by selected columns
          if (grid.options.externalSort && angular.isFunction(grid.options.externalSort)) {
            grid.registerRowsProcessor(grid.options.externalSort, 200);
          }
          else {
            grid.registerRowsProcessor(grid.sortByColumn, 200);
          }

          return grid;
        },

        /**
         * @ngdoc function
         * @name defaultColumnBuilder
         * @methodOf ui.grid.service:gridClassFactory
         * @description Processes designTime column definitions and applies them to col for the
         *              core grid features
         * @param {object} colDef reference to column definition
         * @param {GridColumn} col reference to gridCol
         * @param {object} gridOptions reference to grid options
         */
        defaultColumnBuilder: function (colDef, col, gridOptions) {

          var templateGetPromises = [];

          // Abstracts the standard template processing we do for every template type.
          var processTemplate = function( templateType, providedType, defaultTemplate, filterType, tooltipType ) {
            if ( !colDef[templateType] ){
              col[providedType] = defaultTemplate;
            } else {
              col[providedType] = colDef[templateType];
            }

            var templatePromise = gridUtil.getTemplate(col[providedType])
              .then(
                function (template) {
                  if ( angular.isFunction(template) ) { template = template(); }
                  var tooltipCall = ( tooltipType === 'cellTooltip' ) ? 'col.cellTooltip(row,col)' : 'col.headerTooltip(col)';
                  if ( tooltipType && col[tooltipType] === false ){
                    template = template.replace(uiGridConstants.TOOLTIP, '');
                  } else if ( tooltipType && col[tooltipType] ){
                    template = template.replace(uiGridConstants.TOOLTIP, 'title="{{' + tooltipCall + ' CUSTOM_FILTERS }}"');
                  }

                  if ( filterType ){
                    col[templateType] = template.replace(uiGridConstants.CUSTOM_FILTERS, function() {
                      return col[filterType] ? "|" + col[filterType] : "";
                    });
                  } else {
                    col[templateType] = template;
                  }
                },
                function (res) {
                  throw new Error("Couldn't fetch/use colDef." + templateType + " '" + colDef[templateType] + "'");
                }).catch(angular.noop);

            templateGetPromises.push(templatePromise);

            return templatePromise;
          };

          /**
           * @ngdoc property
           * @name cellTemplate
           * @propertyOf ui.grid.class:GridOptions.columnDef
           * @description a custom template for each cell in this column.  The default
           * is ui-grid/uiGridCell.  If you are using the cellNav feature, this template
           * must contain a div that can receive focus.
           *
           */
          col.cellTemplatePromise = processTemplate( 'cellTemplate', 'providedCellTemplate', 'ui-grid/uiGridCell', 'cellFilter', 'cellTooltip' );

          /**
           * @ngdoc property
           * @name headerCellTemplate
           * @propertyOf ui.grid.class:GridOptions.columnDef
           * @description a custom template for the header for this column.  The default
           * is ui-grid/uiGridHeaderCell
           *
           */
          col.headerCellTemplatePromise = processTemplate( 'headerCellTemplate', 'providedHeaderCellTemplate', 'ui-grid/uiGridHeaderCell', 'headerCellFilter', 'headerTooltip' );

          /**
           * @ngdoc property
           * @name footerCellTemplate
           * @propertyOf ui.grid.class:GridOptions.columnDef
           * @description a custom template for the footer for this column.  The default
           * is ui-grid/uiGridFooterCell
           *
           */
          col.footerCellTemplatePromise = processTemplate( 'footerCellTemplate', 'providedFooterCellTemplate', 'ui-grid/uiGridFooterCell', 'footerCellFilter' );

          /**
           * @ngdoc property
           * @name filterHeaderTemplate
           * @propertyOf ui.grid.class:GridOptions.columnDef
           * @description a custom template for the filter input.  The default is ui-grid/ui-grid-filter
           *
           */
          col.filterHeaderTemplatePromise = processTemplate( 'filterHeaderTemplate', 'providedFilterHeaderTemplate', 'ui-grid/ui-grid-filter' );

          // Create a promise for the compiled element function
          col.compiledElementFnDefer = $q.defer();

          return $q.all(templateGetPromises);
        },

        rowTemplateAssigner: function rowTemplateAssigner(row) {
          var grid = this;

          // Row has no template assigned to it
          if (!row.rowTemplate) {
            // Use the default row template from the grid
            row.rowTemplate = grid.options.rowTemplate;

            // Use the grid's function for fetching the compiled row template function
            row.getRowTemplateFn = grid.getRowTemplateFn;
          }
          // Row has its own template assigned
          else {
            // Create a promise for the compiled row template function
            var perRowTemplateFnPromise = $q.defer();
            row.getRowTemplateFn = perRowTemplateFnPromise.promise;

            // Get the row template
            gridUtil.getTemplate(row.rowTemplate)
              .then(function (template) {
                // Compile the template
                var rowTemplateFn = $compile(template);

                // Resolve the compiled template function promise
                perRowTemplateFnPromise.resolve(rowTemplateFn);
              },
              function (res) {
                // Todo handle response error here?
                throw new Error("Couldn't fetch/use row template '" + row.rowTemplate + "'");
              });
          }

          return row.getRowTemplateFn;
        }
      };

      //class definitions (moved to separate factories)

      return service;
    }]);

})();
<|endoftext|>


<commit_before>// const path = require('path');
const request = require('supertest');
const assert = require('chai').assert;
const logger = require('../../lib/logger').test;
const gateway = require('../../lib/gateway');
const config = require('../../lib/config');
let policies = require('../../lib/policies');

module.exports = function () {
  let app, httpsApp, originalGatewayConfig, originalPolicies;
  function prepareScenario (testCase) {
    let testScenario = request(app);
    if (testCase.setup.putData) {
      testScenario = testScenario.put(testCase.setup.url, testCase.setup.putData);
    } else if (testCase.setup.postData) {
      testScenario = testScenario.post(testCase.setup.url, testCase.setup.postData);
    } else {
      testScenario = testScenario.get(testCase.setup.url);
    }

    testScenario.set('Content-Type', 'application/json');

    if (testCase.setup.host) {
      testScenario.set('Host', testCase.setup.host);
    }
    return testScenario;
  }
  return {
    addPolicy: (name, handler) => { // TODO: make it plugin
      policies.register({ policy: handler, name });
    },
    setup: ({ config, plugins } = {}) => {
      originalPolicies = policies;

      return gateway({ config, plugins })
        .then(apps => {
          app = apps.app;
          httpsApp = apps.httpsApp;
          return apps;
        });
    },
    setupApp: (preparedApp) => {
      app = preparedApp;
    },
    cleanup: () => {
      if (originalGatewayConfig) {
        config.gatewayConfig = originalGatewayConfig;
      }
      policies = originalPolicies;

      config.unwatch();

      app && app.close();
      httpsApp && httpsApp.close();
    },
    validate404: function (testCase) {
      testCase.test = testCase.test || {};
      testCase.test.errorCode = 404;
      return this.validateError(testCase);
    },
    validateError: (testCase) => {
      return (done) => {
        const testScenario = prepareScenario(testCase);
        testScenario
          .expect(testCase.test.errorCode)
          .expect('Content-Type', /text\/html/)
          .end((err, res) => {
            if (err) { logger.error(res.body); }
            err ? done(err) : done();
          });
      };
    },
    validateOptions: (testCase) => {
      return (done) => {
        const testScenario = request(app).options(testCase.setup.url);

        if (testCase.setup.host) {
          testScenario.set('Host', testCase.setup.host);
        }
        if (testCase.test.headers) {
          for (const el in testCase.test.headers) {
            const header = el;
            const value = testCase.test.headers[el];

            testScenario.expect(header, value);
          }
        }
        testScenario.expect(204)
          .end((err, res) => {
            err ? done(err) : done();
          });
      };
    },
    validateSuccess: (testCase) => {
      return (done) => {
        const testScenario = prepareScenario(testCase);
        testScenario
          .expect(200)
          .expect('Content-Type', /json/)
          .expect((res) => {
            if (testCase.test.result) {
              assert.equal(res.body.result, testCase.test.result);
            }
            assert.equal(res.body.url, testCase.test.url);
            if (testCase.test.host) {
              assert.equal(res.body.hostname, testCase.test.host);
            }
            if (testCase.test.scopes) {
              assert.deepEqual(res.body.apiEndpoint.scopes, testCase.test.scopes);
            }
          })
          .end((err, res) => {
            if (err) { logger.error(res.body); }
            err ? done(err) : done();
          });
      };
    },
    validateParams: (testCase) => {
      return (done) => {
        const testScenario = prepareScenario(testCase);
        testScenario
          .expect((res) => {
            assert.deepEqual(res.body.params, testCase.test.params);
          })
          .end((err, res) => {
            if (err) { logger.error(res.body); }
            err ? done(err) : done();
          });
      };
    }
  };
};
<commit_msg>Correctly wait for async resource close for apps<commit_after>// const path = require('path');
const request = require('supertest');
const assert = require('chai').assert;
const logger = require('../../lib/logger').test;
const gateway = require('../../lib/gateway');
const config = require('../../lib/config');
let policies = require('../../lib/policies');

module.exports = function () {
  let app, httpsApp, originalGatewayConfig, originalPolicies;
  function prepareScenario (testCase) {
    let testScenario = request(app);
    if (testCase.setup.putData) {
      testScenario = testScenario.put(testCase.setup.url, testCase.setup.putData);
    } else if (testCase.setup.postData) {
      testScenario = testScenario.post(testCase.setup.url, testCase.setup.postData);
    } else {
      testScenario = testScenario.get(testCase.setup.url);
    }

    testScenario.set('Content-Type', 'application/json');

    if (testCase.setup.host) {
      testScenario.set('Host', testCase.setup.host);
    }
    return testScenario;
  }
  return {
    addPolicy: (name, handler) => { // TODO: make it plugin
      policies.register({ policy: handler, name });
    },
    setup: ({ config, plugins } = {}) => {
      originalPolicies = policies;

      return gateway({ config, plugins })
        .then(apps => {
          app = apps.app;
          httpsApp = apps.httpsApp;
          return apps;
        });
    },
    setupApp: (preparedApp) => {
      app = preparedApp;
    },
    cleanup: () => {
      if (originalGatewayConfig) {
        config.gatewayConfig = originalGatewayConfig;
      }
      policies = originalPolicies;

      config.unwatch();

      return Promise.all([app, httpsApp].map((app) => {
        if (!app) {
          return Promise.resolve();
        }

        return new Promise((resolve, reject) => {
          app.close((err) => {
            if (err) {
              return reject(err);
            }
            return resolve();
          });
        });
      }));
    },
    validate404: function (testCase) {
      testCase.test = testCase.test || {};
      testCase.test.errorCode = 404;
      return this.validateError(testCase);
    },
    validateError: (testCase) => {
      return (done) => {
        const testScenario = prepareScenario(testCase);
        testScenario
          .expect(testCase.test.errorCode)
          .expect('Content-Type', /text\/html/)
          .end((err, res) => {
            if (err) { logger.error(res.body); }
            err ? done(err) : done();
          });
      };
    },
    validateOptions: (testCase) => {
      return (done) => {
        const testScenario = request(app).options(testCase.setup.url);

        if (testCase.setup.host) {
          testScenario.set('Host', testCase.setup.host);
        }
        if (testCase.test.headers) {
          for (const el in testCase.test.headers) {
            const header = el;
            const value = testCase.test.headers[el];

            testScenario.expect(header, value);
          }
        }
        testScenario.expect(204)
          .end((err, res) => {
            err ? done(err) : done();
          });
      };
    },
    validateSuccess: (testCase) => {
      return (done) => {
        const testScenario = prepareScenario(testCase);
        testScenario
          .expect(200)
          .expect('Content-Type', /json/)
          .expect((res) => {
            if (testCase.test.result) {
              assert.equal(res.body.result, testCase.test.result);
            }
            assert.equal(res.body.url, testCase.test.url);
            if (testCase.test.host) {
              assert.equal(res.body.hostname, testCase.test.host);
            }
            if (testCase.test.scopes) {
              assert.deepEqual(res.body.apiEndpoint.scopes, testCase.test.scopes);
            }
          })
          .end((err, res) => {
            if (err) { logger.error(res.body); }
            err ? done(err) : done();
          });
      };
    },
    validateParams: (testCase) => {
      return (done) => {
        const testScenario = prepareScenario(testCase);
        testScenario
          .expect((res) => {
            assert.deepEqual(res.body.params, testCase.test.params);
          })
          .end((err, res) => {
            if (err) { logger.error(res.body); }
            err ? done(err) : done();
          });
      };
    }
  };
};
<|endoftext|>


<commit_before>import React from 'react';
import {Link} from 'react-router';
import { Navbar, Nav, NavItem  } from 'react-bootstrap';
import SynchronizerContainer from '../containers/serverSynchronizer-container'

// Using "Stateless Functional Components"
export default function (props) {
    return (

            <SynchronizerContainer />

                <Navbar>
                    <Navbar.Header>
                        <Navbar.Brand>
                            <Link to="/" activeClassName="active">Moopy</Link>
                        </Navbar.Brand>
                    </Navbar.Header>
                  {/*
                        <NavItem eventKey={1} href="/">Link</NavItem>
                        <NavItem eventKey={2} href="/users">Users</NavItem>
                    */}

<Link to="/" activeClassName="active">Home</Link>

<Link to="/users" activeClassName="active">Users</Link>

<Link to="/widgets" activeClassName="active">Widgets</Link>

<Link to="/dashboards" activeClassName="active">Dashboards</Link>

                </Navbar>

                {/*

<Link to="/" activeClassName="active">Home</Link>

<Link to="/users" activeClassName="active">Users</Link>

<Link to="/widgets" activeClassName="active">Widgets</Link>

<Link to="/dashboards" activeClassName="active">Dashboards</Link>

*/}

           {/*

<Link to="/" activeClassName="active">Home</Link>

<Link to="/users" activeClassName="active">Users</Link>

<Link to="/widgets" activeClassName="active">Widgets</Link>

<Link to="/dashboards" activeClassName="active">Dashboards</Link>

            */}

                {props.children}

    );
}
<commit_msg>Clean up Header<commit_after>import React from 'react';
import {Link} from 'react-router';
import {Navbar, Nav, NavItem} from 'react-bootstrap';
import SynchronizerContainer from '../containers/serverSynchronizer-container'

// Using "Stateless Functional Components"
export default function (props) {
    return (

            <SynchronizerContainer />

                <Navbar>
                    <Navbar.Header>
                        <Navbar.Brand>
                            <Link to="/" activeClassName="active">Moopy</Link>
                        </Navbar.Brand>
                    </Navbar.Header>

<Link to="/" activeClassName="active">Home</Link>

<Link to="/users" activeClassName="active">Users</Link>

<Link to="/widgets" activeClassName="active">Widgets</Link>

<Link to="/dashboards" activeClassName="active">Dashboards</Link>

                </Navbar>

                {props.children}

    );
}
<|endoftext|>


<commit_before>export { Base };

import * as RandTools from "../../util/RandTools.js";
import * as NameNumberArrayObject_To_Float32Array from "../../util/NameNumberArrayObject_To_Float32Array.js";
//import * as ParamDesc from "../../Unpacker/ParamDesc.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
//import * as ValueRange from "../../Unpacker/ValueRange.js";
import * as TestParams from "./TestParams.js";
import * as PointDepthPoint_TestParams from "./PointDepthPoint_TestParams.js";
import * as Block from "../../Conv/Block.js";

/**
 *
 * This is an object { id, in, out } which has one number and two sub-objects.
 *
 * @member {number} id
 *   The numeric identifier of this testing parameter combination.
 *
 * @member {object} in
 *   The "in" sub-object's data members represent every parameters of the Block.Params's constructor. That is,
 * it has the following data members: sourceHeight, sourceWidth, sourceChannelCount, stepCountRequested,
 * pointwise1ChannelCountRate, depthwiseFilterHeight, nActivationId, nActivationIdAtBlockEnd, nWhetherShuffleChannel,
 * bKeepInputTensor. It also has the following properties:
 *   - paramsNumberArrayObject
 *   - inputFloat32Array
 *   - byteOffsetBegin
 *
 * @member {object} out
 *   The "out" sub-object's data members represent the "should-be" result of Block.Params's extract(). That is, it has
 * the above data members (with outputHeight, outputWidth) except paramsNumberArrayObject, inputFloat32Array, byteOffsetBegin.
 *
 * @member {object[]} stepsArray
 *   Every element is an PointDepthPoint_TestParams object for the parameters of the step.
 */
class Base extends TestParams.Base {

  /**
   *
   */
  constructor() {
    super();
    this.stepsArray = new Array();
  }

  /**
   * Use scattered parameters to fills the following proterties:
   *   - this.in.inputFloat32Array
   *   - this.in.byteOffsetBegin
   *   - this.out
   *
   * @return {Base}
   *   Return this object self.
   */
  set_By_ParamsScattered(
    sourceHeight, sourceWidth, sourceChannelCount, stepCountRequested, pointwise1ChannelCountRate,
    depthwiseFilterHeight, nActivationId, nActivationIdAtBlockEnd, nWhetherShuffleChannel, bKeepInputTensor
  ) {
    this.in.paramsNumberArrayObject = {};
    this.out = {
      sourceHeight, sourceWidth, sourceChannelCount, stepCountRequested, pointwise1ChannelCountRate,
      depthwiseFilterHeight, nActivationId, nActivationIdAtBlockEnd, nWhetherShuffleChannel, bKeepInputTensor
    };

    Object.assign( this.in, this.out ); // So that all parameters are by specified (none is by evolution).

    let weightsElementOffsetBegin = 0;
    return this.set_By_ParamsNumberArrayMap_ParamsOut( weightsElementOffsetBegin );
  }

  /**
   * Fills the following proterties:
   *   - this.in.inputFloat32Array
   *   - this.in.byteOffsetBegin
   *   - this.out.outputHeight
   *   - this.out.outputWidth
   *
   * @param {object} this.in.paramsNumberArrayObject
   *   Pass in an object. The result will be put into this object. It is a map from a string name (e.g. parameter name) to a number array.
   * The name should be one of Base.paramsNameOrderArray[] elements.
   *
   * @param {object} this.out
   *   An object which has the following data members: sourceHeight, sourceWidth, sourceChannelCount, stepCountRequested,
   * pointwise1ChannelCountRate, depthwiseFilterHeight, nActivationId, nActivationIdAtBlockEnd, nWhetherShuffleChannel,
   * bKeepInputTensor, outputHeight, outputWidth.
   *
   * @param {number} weightsElementOffsetBegin
   *   Offset how many elements (4 bytes per element) at the beginning of the result weightsFloat32Array.
   * The this.in.byteOffsetBegin will be ( 4 * weightsElementOffsetBegin ).
   *
   * @return {Base}
   *   Return this object self.
   */
  set_By_ParamsNumberArrayMap_ParamsOut( weightsElementOffsetBegin = 0 ) {
    let blockParams = this.out;

    // Fill in outputHeight, outputWidth.
    Block.Params.set_outputHeight_outputWidth_by_sourceHeight_sourceWidth.call( blockParams, blockParams.sourceHeight, blockParams.sourceWidth );

    let stepParamsMaker = Block.Base.create_Params_to_PointDepthPointParams( blockParams );
    stepParamsMaker.determine_stepCount_depthwiseFilterHeight_Default_Last();

    this.stepsArray.length = stepParamsMaker.stepCount;
    let paramsNameOrderArray = Base.paramsNameOrderArray_Basic.slice(); // Shallow copy.

    let paramsNumberArrayObject = {};
    Object.assign( paramsNumberArrayObject, this.in.paramsNumberArrayObject ); // Shallow copy.

    let channelShuffler;
    for ( let i = 0; i < stepParamsMaker.stepCount; ++i ) { // Step0, 1, 2, 3, ..., StepLast.

      if ( 0 == i ) { // Step0.
        stepParamsMaker.configTo_beforeStep0();
      }

      if ( ( this.stepsArray.length - 1 ) == i ) { // StepLast. (Note: Step0 may also be StepLast.)
        stepParamsMaker.configTo_beforeStepLast();
      }

      // If channelShuffler is not null, keep it so that its tensors could be released.
      if ( stepParamsMaker.channelShuffler ) {
        channelShuffler = stepParamsMaker.channelShuffler;
      }

      let stepName = `step${i}`;
      paramsNameOrderArray.push( stepName ); // Place every step's parameters in sequence.

      let stepTestParams = new PointDepthPoint_TestParams.Base( this.id );
      stepTestParams.set_By_ParamsScattered(
        stepParamsMaker.channelCount0_pointwise1Before,
        stepParamsMaker.channelCount1_pointwise1Before,
        stepParamsMaker.pointwise1ChannelCount, stepParamsMaker.bPointwise1Bias, stepParamsMaker.pointwise1ActivationId,
        stepParamsMaker.depthwise_AvgMax_Or_ChannelMultiplier, stepParamsMaker.depthwiseFilterHeight, stepParamsMaker.depthwiseStridesPad,
        stepParamsMaker.bDepthwiseBias, stepParamsMaker.depthwiseActivationId,
        stepParamsMaker.pointwise21ChannelCount, stepParamsMaker.bPointwise21Bias, stepParamsMaker.pointwise21ActivationId,
        stepParamsMaker.bOutput1Requested,
        stepParamsMaker.bKeepInputTensor
      );

      this.stepsArray[ i ] = stepTestParams;
      paramsNumberArrayObject[ stepName ] = stepTestParams.in.inputFloat32Array;

      if ( 0 == i ) { // After step0 (i.e. for step1, 2, 3, ...)
        stepParamsMaker.configTo_afterStep0();
      }
    }

    // Here (i.e. in Block_TestParams), the channelShuffler is not used. Just release it for avoiding memory leak.
    if ( channelShuffler ) {
      channelShuffler.disposeTensors();
      channelShuffler = null;
    }

    let Float32Array_ByteOffsetBegin = new NameNumberArrayObject_To_Float32Array.Base();
    Float32Array_ByteOffsetBegin.setByConcat( paramsNameOrderArray, paramsNumberArrayObject, weightsElementOffsetBegin );

    this.in.inputFloat32Array = Float32Array_ByteOffsetBegin.weightsFloat32Array;
    this.in.byteOffsetBegin = Float32Array_ByteOffsetBegin.weightsByteOffsetBegin;

    return this;
  }

  /**
   * @override
   */
  onBefore_Yield() {

    // For testing not start at the offset 0.
    let weightsElementOffsetBegin = RandTools.getRandomIntInclusive( 0, 3 ); // Skip a random un-used element count.

    this.set_By_ParamsNumberArrayMap_ParamsOut( weightsElementOffsetBegin );
  }

  /**
   * @override
   */
  onAfter_Yield() {
    this.stepsArray.length = 0; // Clear steps' parameters.
  }

  /**
   * Responsible for generating testing paramters combinations.
   *
   * @param {number} sourceHeight
   *   Only test the height of input image.
   *
   * @param {number} sourceWidth
   *   Only test the width of input image.
   *
   * @param {number} sourceChannelCount
   *   Only test the depth of input image.
   *
   * @yield {Base}
   *   Yield this object itself. The returned object (it is this object itself) should not be modified because it will be re-used.
   */
  * ParamsGenerator( sourceHeight, sourceWidth, sourceChannelCount ) {
    this.sourceHeight = sourceHeight;
    this.sourceWidth = sourceWidth;
    this.sourceChannelCount = sourceChannelCount;

    // Restrict some parameter's large kinds. Otherwise, too many combination will be generated.
    this.valueOutMinMax = {
      sourceHeight: [ this.sourceHeight, this.sourceHeight ], //5,
      sourceWidth:  [ this.sourceWidth,  this.sourceWidth  ], //5,
      sourceChannelCount: [ this.sourceChannelCount, this.sourceChannelCount ],

      stepCountRequested: [
        Block.Params.stepCountRequested.valueDesc.range.min,
        Block.Params.stepCountRequested.valueDesc.range.min + 5
      ],

//      pointwise1ChannelCountRate: undefined,
      pointwise1ChannelCountRate: [
        Block.Params.pointwise1ChannelCountRate.valueDesc.range.min,
        Block.Params.pointwise1ChannelCountRate.valueDesc.range.max
      ],

//      depthwiseFilterHeight: undefined,
      depthwiseFilterHeight: [
        2, //Block.Params.depthwiseFilterHeight.valueDesc.range.min, // WASM is fault when filterHeight = 1
        Block.Params.depthwiseFilterHeight.valueDesc.range.max
      ],

      // Because the logic of activation function is simpler than other, it is just randomly tested once
      // for speeding up testing.
      //
      // Beware of NONE and RELU. They easily result in infinity value because they do not have upper bound.
      //
//      nActivationId: undefined,
//!!! (2021/10/08 Remarked) Ignore NONE and RELU for avoiding infinity.
//       nActivationId: [
//         ValueDesc.ActivationFunction.Singleton.range.min,
//         ValueDesc.ActivationFunction.Singleton.range.max
//       ],
//       nActivationId: [
//         ValueDesc.ActivationFunction.Singleton.range.min + 1, // Exclude NONE for avoiding infinity.
//         ValueDesc.ActivationFunction.Singleton.range.max - 1  // Exclude RELU for avoiding infinity.
//       ],
      nActivationId: [
        ValueDesc.ActivationFunction.Singleton.Ids.RELU6,
        ValueDesc.ActivationFunction.Singleton.Ids.RELU6
      ],

//      nActivationIdAtBlockEnd: undefined,
//       nActivationIdAtBlockEnd: [
//         ValueDesc.ActivationFunction.Singleton.range.min,
//         ValueDesc.ActivationFunction.Singleton.range.max
//       ],
//       nActivationIdAtBlockEnd: [
//         ValueDesc.ActivationFunction.Singleton.range.min + 1, // Exclude NONE for avoiding infinity.
//         ValueDesc.ActivationFunction.Singleton.range.max - 1  // Exclude RELU for avoiding infinity.
//       ],
      nActivationIdAtBlockEnd: [
        ValueDesc.ActivationFunction.Singleton.Ids.RELU6,
        ValueDesc.ActivationFunction.Singleton.Ids.RELU6
      ],

//      nWhetherShuffleChannel: undefined,
      nWhetherShuffleChannel: [
        Block.Params.nWhetherShuffleChannel.valueDesc.range.min,
        Block.Params.nWhetherShuffleChannel.valueDesc.range.max
      ],

//      bKeepInputTensor: undefined,
      bKeepInputTensor: [
        Block.Params.bKeepInputTensor.valueDesc.range.min,
        Block.Params.bKeepInputTensor.valueDesc.range.max
      ],
    };

    // All the parameters to be tried.
    //
    // Note: The order of these element could be adjusted to change testing order. The last element will be tested (changed) first.
    let paramDescConfigArray = [
      new TestParams.ParamDescConfig( Block.Params.sourceHeight,               this.valueOutMinMax.sourceHeight ),
      new TestParams.ParamDescConfig( Block.Params.sourceWidth,                this.valueOutMinMax.sourceWidth ),
      new TestParams.ParamDescConfig( Block.Params.sourceChannelCount,         this.valueOutMinMax.sourceChannelCount ),
      new TestParams.ParamDescConfig( Block.Params.stepCountRequested,         this.valueOutMinMax.stepCountRequested ),
      new TestParams.ParamDescConfig( Block.Params.pointwise1ChannelCountRate, this.valueOutMinMax.pointwise1ChannelCountRate ),
      new TestParams.ParamDescConfig( Block.Params.depthwiseFilterHeight,      this.valueOutMinMax.depthwiseFilterHeight ),
      new TestParams.ParamDescConfig( Block.Params.nActivationId,              this.valueOutMinMax.nActivationId ),
      new TestParams.ParamDescConfig( Block.Params.nActivationIdAtBlockEnd,    this.valueOutMinMax.nActivationIdAtBlockEnd ),
      new TestParams.ParamDescConfig( Block.Params.nWhetherShuffleChannel,     this.valueOutMinMax.nWhetherShuffleChannel ),
      new TestParams.ParamDescConfig( Block.Params.bKeepInputTensor,           this.valueOutMinMax.bKeepInputTensor ),
    ];

    yield *Base.ParamsGenerator.call( this, paramDescConfigArray );
  }

}

/**
 * The order when generate weightsFloat32Array[].
 *
 * This order could not be changed arbitrarily. It must be the same as the parameter extracting order of Block.initer().
 */
Base.paramsNameOrderArray_Basic = [
  Block.Params.sourceHeight.paramName,
  Block.Params.sourceWidth.paramName,
  Block.Params.sourceChannelCount.paramName,
  Block.Params.stepCountRequested.paramName,
  Block.Params.pointwise1ChannelCountRate.paramName,
  Block.Params.depthwiseFilterHeight.paramName,
  Block.Params.nActivationId.paramName,
  Block.Params.nActivationIdAtBlockEnd.paramName,
  Block.Params.nWhetherShuffleChannel.paramName,
  Block.Params.bKeepInputTensor.paramName,
];
<commit_msg>Update Block_TestParams.js<commit_after>export { Base };

import * as RandTools from "../../util/RandTools.js";
import * as NameNumberArrayObject_To_Float32Array from "../../util/NameNumberArrayObject_To_Float32Array.js";
//import * as ParamDesc from "../../Unpacker/ParamDesc.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
//import * as ValueRange from "../../Unpacker/ValueRange.js";
import * as TestParams from "./TestParams.js";
import * as PointDepthPoint_TestParams from "./PointDepthPoint_TestParams.js";
import * as Block from "../../Conv/Block.js";

/**
 *
 * This is an object { id, in, out } which has one number and two sub-objects.
 *
 * @member {number} id
 *   The numeric identifier of this testing parameter combination.
 *
 * @member {object} in
 *   The "in" sub-object's data members represent every parameters of the Block.Params's constructor. That is,
 * it has the following data members: sourceHeight, sourceWidth, sourceChannelCount, stepCountRequested,
 * pointwise1ChannelCountRate, depthwiseFilterHeight, nActivationId, nActivationIdAtBlockEnd, nWhetherShuffleChannel,
 * bKeepInputTensor. It also has the following properties:
 *   - paramsNumberArrayObject
 *   - inputFloat32Array
 *   - byteOffsetBegin
 *
 * @member {object} out
 *   The "out" sub-object's data members represent the "should-be" result of Block.Params's extract(). That is, it has
 * the above data members (with outputHeight, outputWidth) except paramsNumberArrayObject, inputFloat32Array, byteOffsetBegin.
 *
 * @member {object[]} stepsArray
 *   Every element is an PointDepthPoint_TestParams object for the parameters of the step.
 */
class Base extends TestParams.Base {

  /**
   *
   */
  constructor() {
    super();
    this.stepsArray = new Array();
  }

  /**
   * Use scattered parameters to fills the following proterties:
   *   - this.in.inputFloat32Array
   *   - this.in.byteOffsetBegin
   *   - this.out
   *
   * @return {Base}
   *   Return this object self.
   */
  set_By_ParamsScattered(
    sourceHeight, sourceWidth, sourceChannelCount, stepCountRequested, pointwise1ChannelCountRate,
    depthwiseFilterHeight, nActivationId, nActivationIdAtBlockEnd, nWhetherShuffleChannel, bKeepInputTensor
  ) {
    this.in.paramsNumberArrayObject = {};
    this.out = {
      sourceHeight, sourceWidth, sourceChannelCount, stepCountRequested, pointwise1ChannelCountRate,
      depthwiseFilterHeight, nActivationId, nActivationIdAtBlockEnd, nWhetherShuffleChannel, bKeepInputTensor
    };

    Object.assign( this.in, this.out ); // So that all parameters are by specified (none is by evolution).

    let weightsElementOffsetBegin = 0;
    return this.set_By_ParamsNumberArrayMap_ParamsOut( weightsElementOffsetBegin );
  }

  /**
   * Fills the following proterties:
   *   - this.in.inputFloat32Array
   *   - this.in.byteOffsetBegin
   *   - this.out.outputHeight
   *   - this.out.outputWidth
   *
   * @param {object} this.in.paramsNumberArrayObject
   *   Pass in an object. The result will be put into this object. It is a map from a string name (e.g. parameter name) to a number array.
   * The name should be one of Base.paramsNameOrderArray[] elements.
   *
   * @param {object} this.out
   *   An object which has the following data members: sourceHeight, sourceWidth, sourceChannelCount, stepCountRequested,
   * pointwise1ChannelCountRate, depthwiseFilterHeight, nActivationId, nActivationIdAtBlockEnd, nWhetherShuffleChannel,
   * bKeepInputTensor, outputHeight, outputWidth.
   *
   * @param {number} weightsElementOffsetBegin
   *   Offset how many elements (4 bytes per element) at the beginning of the result weightsFloat32Array.
   * The this.in.byteOffsetBegin will be ( 4 * weightsElementOffsetBegin ).
   *
   * @return {Base}
   *   Return this object self.
   */
  set_By_ParamsNumberArrayMap_ParamsOut( weightsElementOffsetBegin = 0 ) {
    let blockParams = this.out;

    // Fill in outputHeight, outputWidth.
    Block.Params.set_outputHeight_outputWidth_by_sourceHeight_sourceWidth.call( blockParams, blockParams.sourceHeight, blockParams.sourceWidth );

    let stepParamsMaker = Block.Base.create_Params_to_PointDepthPointParams( blockParams );
    stepParamsMaker.determine_stepCount_depthwiseFilterHeight_Default_Last();

    this.stepsArray.length = stepParamsMaker.stepCount;
    let paramsNameOrderArray = Base.paramsNameOrderArray_Basic.slice(); // Shallow copy.

    let paramsNumberArrayObject = {};
    Object.assign( paramsNumberArrayObject, this.in.paramsNumberArrayObject ); // Shallow copy.

    let channelShuffler;
    for ( let i = 0; i < stepParamsMaker.stepCount; ++i ) { // Step0, 1, 2, 3, ..., StepLast.

      if ( 0 == i ) { // Step0.
        stepParamsMaker.configTo_beforeStep0();
      }

      if ( ( this.stepsArray.length - 1 ) == i ) { // StepLast. (Note: Step0 may also be StepLast.)
        stepParamsMaker.configTo_beforeStepLast();
      }

      // If channelShuffler is not null, keep it so that its tensors could be released.
      if ( stepParamsMaker.channelShuffler ) {
        channelShuffler = stepParamsMaker.channelShuffler;
      }

      let stepName = `step${i}`;
      paramsNameOrderArray.push( stepName ); // Place every step's parameters in sequence.

      let stepTestParams = new PointDepthPoint_TestParams.Base( this.id );
      stepTestParams.set_By_ParamsScattered(
        stepParamsMaker.channelCount0_pointwise1Before,
        stepParamsMaker.channelCount1_pointwise1Before,
        stepParamsMaker.pointwise1ChannelCount, stepParamsMaker.bPointwise1Bias, stepParamsMaker.pointwise1ActivationId,
        stepParamsMaker.depthwise_AvgMax_Or_ChannelMultiplier, stepParamsMaker.depthwiseFilterHeight, stepParamsMaker.depthwiseStridesPad,
        stepParamsMaker.bDepthwiseBias, stepParamsMaker.depthwiseActivationId,
        stepParamsMaker.pointwise21ChannelCount, stepParamsMaker.bPointwise21Bias, stepParamsMaker.pointwise21ActivationId,
        stepParamsMaker.bOutput1Requested,
        stepParamsMaker.bKeepInputTensor
      );

      this.stepsArray[ i ] = stepTestParams;
      paramsNumberArrayObject[ stepName ] = stepTestParams.in.inputFloat32Array;

      if ( 0 == i ) { // After step0 (i.e. for step1, 2, 3, ...)
        stepParamsMaker.configTo_afterStep0();
      }
    }

    // Here (i.e. in Block_TestParams), the channelShuffler is not used. Just release it for avoiding memory leak.
    if ( channelShuffler ) {
      channelShuffler.disposeTensors();
      channelShuffler = null;
    }

    let Float32Array_ByteOffsetBegin = new NameNumberArrayObject_To_Float32Array.Base();
    Float32Array_ByteOffsetBegin.setByConcat( paramsNameOrderArray, paramsNumberArrayObject, weightsElementOffsetBegin );

    this.in.inputFloat32Array = Float32Array_ByteOffsetBegin.weightsFloat32Array;
    this.in.byteOffsetBegin = Float32Array_ByteOffsetBegin.weightsByteOffsetBegin;

    return this;
  }

  /**
   * @override
   */
  onBefore_Yield() {

    // For testing not start at the offset 0.
    let weightsElementOffsetBegin = RandTools.getRandomIntInclusive( 0, 3 ); // Skip a random un-used element count.

    this.set_By_ParamsNumberArrayMap_ParamsOut( weightsElementOffsetBegin );
  }

  /**
   * @override
   */
  onAfter_Yield() {
    this.stepsArray.length = 0; // Clear steps' parameters.
  }

  /**
   * Responsible for generating testing paramters combinations.
   *
   * @param {number} sourceHeight
   *   Only test the height of input image.
   *
   * @param {number} sourceWidth
   *   Only test the width of input image.
   *
   * @param {number} sourceChannelCount
   *   Only test the depth of input image.
   *
   * @yield {Base}
   *   Yield this object itself. The returned object (it is this object itself) should not be modified because it will be re-used.
   */
  * ParamsGenerator( sourceHeight, sourceWidth, sourceChannelCount ) {
    this.sourceHeight = sourceHeight;
    this.sourceWidth = sourceWidth;
    this.sourceChannelCount = sourceChannelCount;

    // Restrict some parameter's large kinds. Otherwise, too many combination will be generated.
    this.valueOutMinMax = {
      sourceHeight: [ this.sourceHeight, this.sourceHeight ], //5,
      sourceWidth:  [ this.sourceWidth,  this.sourceWidth  ], //5,
      sourceChannelCount: [ this.sourceChannelCount, this.sourceChannelCount ],

      stepCountRequested: [
        Block.Params.stepCountRequested.valueDesc.range.min,
        Block.Params.stepCountRequested.valueDesc.range.min + 5
      ],

//      pointwise1ChannelCountRate: undefined,
      pointwise1ChannelCountRate: [
        Block.Params.pointwise1ChannelCountRate.valueDesc.range.min,
        Block.Params.pointwise1ChannelCountRate.valueDesc.range.max
      ],

//      depthwiseFilterHeight: undefined,
      depthwiseFilterHeight: [
        2, //Block.Params.depthwiseFilterHeight.valueDesc.range.min, // WASM is fault when filterHeight = 1
        Block.Params.depthwiseFilterHeight.valueDesc.range.max
      ],

      // Because the logic of activation function is simpler than other, it is just randomly tested once
      // for speeding up testing.
      //
      // Beware of NONE and RELU. They easily result in infinity value because they do not have upper bound.
      //
//      nActivationId: undefined,
//!!! (2021/10/08 Remarked) Ignore NONE and RELU for avoiding infinity.
//       nActivationId: [
//         ValueDesc.ActivationFunction.Singleton.range.min,
//         ValueDesc.ActivationFunction.Singleton.range.max
//       ],
//       nActivationId: [
//         ValueDesc.ActivationFunction.Singleton.range.min + 1, // Exclude NONE for avoiding infinity.
//         ValueDesc.ActivationFunction.Singleton.range.max - 1  // Exclude RELU for avoiding infinity.
//       ],
      nActivationId: [
        ValueDesc.ActivationFunction.Singleton.Ids.RELU6,
        ValueDesc.ActivationFunction.Singleton.Ids.RELU6
      ],

//      nActivationIdAtBlockEnd: undefined,
//       nActivationIdAtBlockEnd: [
//         ValueDesc.ActivationFunction.Singleton.range.min,
//         ValueDesc.ActivationFunction.Singleton.range.max
//       ],
//       nActivationIdAtBlockEnd: [
//         ValueDesc.ActivationFunction.Singleton.range.min + 1, // Exclude NONE for avoiding infinity.
//         ValueDesc.ActivationFunction.Singleton.range.max - 1  // Exclude RELU for avoiding infinity.
//       ],
//       nActivationIdAtBlockEnd: [
//         ValueDesc.ActivationFunction.Singleton.Ids.RELU6,
//         ValueDesc.ActivationFunction.Singleton.Ids.RELU6
//       ],
      nActivationIdAtBlockEnd: [
        ValueDesc.ActivationFunction.Singleton.Ids.NONE,
        ValueDesc.ActivationFunction.Singleton.Ids.RELU6
      ],

//      nWhetherShuffleChannel: undefined,
      nWhetherShuffleChannel: [
        Block.Params.nWhetherShuffleChannel.valueDesc.range.min,
        Block.Params.nWhetherShuffleChannel.valueDesc.range.max
      ],

//      bKeepInputTensor: undefined,
      bKeepInputTensor: [
        Block.Params.bKeepInputTensor.valueDesc.range.min,
        Block.Params.bKeepInputTensor.valueDesc.range.max
      ],
    };

    // All the parameters to be tried.
    //
    // Note: The order of these element could be adjusted to change testing order. The last element will be tested (changed) first.
    let paramDescConfigArray = [
      new TestParams.ParamDescConfig( Block.Params.sourceHeight,               this.valueOutMinMax.sourceHeight ),
      new TestParams.ParamDescConfig( Block.Params.sourceWidth,                this.valueOutMinMax.sourceWidth ),
      new TestParams.ParamDescConfig( Block.Params.sourceChannelCount,         this.valueOutMinMax.sourceChannelCount ),
      new TestParams.ParamDescConfig( Block.Params.stepCountRequested,         this.valueOutMinMax.stepCountRequested ),
      new TestParams.ParamDescConfig( Block.Params.pointwise1ChannelCountRate, this.valueOutMinMax.pointwise1ChannelCountRate ),
      new TestParams.ParamDescConfig( Block.Params.depthwiseFilterHeight,      this.valueOutMinMax.depthwiseFilterHeight ),
      new TestParams.ParamDescConfig( Block.Params.nActivationId,              this.valueOutMinMax.nActivationId ),
      new TestParams.ParamDescConfig( Block.Params.nActivationIdAtBlockEnd,    this.valueOutMinMax.nActivationIdAtBlockEnd ),
      new TestParams.ParamDescConfig( Block.Params.nWhetherShuffleChannel,     this.valueOutMinMax.nWhetherShuffleChannel ),
      new TestParams.ParamDescConfig( Block.Params.bKeepInputTensor,           this.valueOutMinMax.bKeepInputTensor ),
    ];

    yield *Base.ParamsGenerator.call( this, paramDescConfigArray );
  }

}

/**
 * The order when generate weightsFloat32Array[].
 *
 * This order could not be changed arbitrarily. It must be the same as the parameter extracting order of Block.initer().
 */
Base.paramsNameOrderArray_Basic = [
  Block.Params.sourceHeight.paramName,
  Block.Params.sourceWidth.paramName,
  Block.Params.sourceChannelCount.paramName,
  Block.Params.stepCountRequested.paramName,
  Block.Params.pointwise1ChannelCountRate.paramName,
  Block.Params.depthwiseFilterHeight.paramName,
  Block.Params.nActivationId.paramName,
  Block.Params.nActivationIdAtBlockEnd.paramName,
  Block.Params.nWhetherShuffleChannel.paramName,
  Block.Params.bKeepInputTensor.paramName,
];
<|endoftext|>