<commit_before>import React from 'react';
import { act } from 'react-dom/test-utils';
import Highcharts from 'highcharts';

import addHighchartsMore from 'highcharts/highcharts-more';
//import addHighcharts3DModule from 'highcharts/highcharts-3d';
import addBulletModule from 'highcharts/modules/bullet';
import addFunnelModule from 'highcharts/modules/funnel';
//import addCylinderModule from 'highcharts/modules/cylinder';
import addHeatmapModule from 'highcharts/modules/heatmap';
//import addHistogramBellCurveModule from 'highcharts/modules/histogram-bellcurve';
import addNetworkGraphModule from 'highcharts/modules/networkgraph';
//import addParetoModule from 'highcharts/modules/pareto';
import addSankeyModule from 'highcharts/modules/sankey';
import addSolidGaugeModule from 'highcharts/modules/solid-gauge';
import addStreamGraphModule from 'highcharts/modules/streamgraph';
import addSunburstModule from 'highcharts/modules/sunburst';
import addTilemapModule from 'highcharts/modules/tilemap';
import addTreemapModule from 'highcharts/modules/treemap';
import addVariablePieModule from 'highcharts/modules/variable-pie';
import addVariwideModule from 'highcharts/modules/variwide';
import addVectorModule from 'highcharts/modules/vector';
import addVennModule from 'highcharts/modules/venn';
import addWindBarbModule from 'highcharts/modules/windbarb';
import addXRangeModule from 'highcharts/modules/xrange';

import {
  HighchartsChart,
  Chart,
  YAxis,
  XAxis,
  withHighcharts
} from '../../../src';

import * as all from '../../../src';

addHighchartsMore(Highcharts);
//addHighcharts3DModule(Highcharts);
addBulletModule(Highcharts);
//addCylinderModule(Highcharts);
addFunnelModule(Highcharts);
addHeatmapModule(Highcharts);
//addHistogramBellCurveModule(Highcharts);
addNetworkGraphModule(Highcharts);
//addParetoModule(Highcharts);
addSankeyModule(Highcharts);
addSolidGaugeModule(Highcharts);
addStreamGraphModule(Highcharts);
addSunburstModule(Highcharts);
addTilemapModule(Highcharts);
addTreemapModule(Highcharts);
addVariablePieModule(Highcharts);
addVariwideModule(Highcharts);
addVectorModule(Highcharts);
addVennModule(Highcharts);
addWindBarbModule(Highcharts);
addXRangeModule(Highcharts);

const skippedSeries = ['BarSeries'];
const noAxisSeries = [
  'PieSeries',
  'VariablePieSeries',
  'PyramidSeries',
  'FunnelSeries',
  'VennSeries',
  'PackedBubbleSeries'
];
const needParentSeries = ['BellCurveSeries', 'HistogramSeries', 'ParetoSeries'];

Object.keys(all)
  .filter(name => /^[A-Z].*Series$/.test(name))
  .forEach(seriesName => {
    if (skippedSeries.includes(seriesName)) return;
    const seriesType = seriesName
      .substring(0, seriesName.indexOf('Series'))
      .toLowerCase();
    const SeriesComponent = all[seriesName]; // eslint-disable-line import/namespace

    describe(`<${seriesName} /> integration`, () => {
      beforeEach(() => {
        jest.spyOn(window, 'requestAnimationFrame').mockImplementation(cb =>
          window.setTimeout(
            () =>
              act(() => {
                cb();
              }),
            0
          )
        );
      });

      afterEach(() => {
        window.requestAnimationFrame.mockRestore();
      });

      if (seriesType in Highcharts.seriesTypes) {
        it('renders with real highcharts', done => {
          const afterAddSeries = event => {
            expect(event.target.series.length).toBe(1);
            expect(event.target.series[0].type).toBe(seriesType);
            if (!noAxisSeries.includes(seriesName)) {
              expect(event.target.series[0].yAxis.userOptions.id).toBe(
                'myYAxis'
              );
            }
            done();
          };
          const Component = props => {
            return (
              <HighchartsChart>
                <Chart zoomType="x" onAfterAddSeries={afterAddSeries} />
                <XAxis></XAxis>
                <YAxis id="myYAxis"></YAxis>
                <SeriesComponent axisId="myYAxis" data={[1, 2, 3, 4]} />
              </HighchartsChart>
            );
          };
          const WithComponent = withHighcharts(Component, Highcharts);
          mount(<WithComponent />);
        });
        it('binds hide event correctly', done => {
          const afterAddSeries = event => {
            expect(event.target.series[0].visible).toBe(true);
            event.target.series[0].hide();
          };
          const onHide = event => {
            expect(event.target.visible).toBe(false);
            done();
          };
          const Component = props => {
            return (
              <HighchartsChart>
                <Chart zoomType="x" onAfterAddSeries={afterAddSeries} />
                <XAxis></XAxis>
                <YAxis>
                  <SeriesComponent data={[1, 2, 3, 4]} onHide={onHide} />
                </YAxis>
              </HighchartsChart>
            );
          };
          const WithComponent = withHighcharts(Component, Highcharts);
          mount(<WithComponent />);
        });
      }
    });
  });
<commit_msg>Simplify SeriesTypes test<commit_after>import React from 'react';
import Highcharts from 'highcharts';

import addHighchartsMore from 'highcharts/highcharts-more';
//import addHighcharts3DModule from 'highcharts/highcharts-3d';
import addBulletModule from 'highcharts/modules/bullet';
import addFunnelModule from 'highcharts/modules/funnel';
//import addCylinderModule from 'highcharts/modules/cylinder';
import addHeatmapModule from 'highcharts/modules/heatmap';
//import addHistogramBellCurveModule from 'highcharts/modules/histogram-bellcurve';
import addNetworkGraphModule from 'highcharts/modules/networkgraph';
//import addParetoModule from 'highcharts/modules/pareto';
import addSankeyModule from 'highcharts/modules/sankey';
import addSolidGaugeModule from 'highcharts/modules/solid-gauge';
import addStreamGraphModule from 'highcharts/modules/streamgraph';
import addSunburstModule from 'highcharts/modules/sunburst';
import addTilemapModule from 'highcharts/modules/tilemap';
import addTreemapModule from 'highcharts/modules/treemap';
import addVariablePieModule from 'highcharts/modules/variable-pie';
import addVariwideModule from 'highcharts/modules/variwide';
import addVectorModule from 'highcharts/modules/vector';
import addVennModule from 'highcharts/modules/venn';
import addWindBarbModule from 'highcharts/modules/windbarb';
import addXRangeModule from 'highcharts/modules/xrange';

import {
  HighchartsChart,
  Chart,
  YAxis,
  XAxis,
  HighchartsProvider
} from '../../../src';

import * as all from '../../../src';

addHighchartsMore(Highcharts);
//addHighcharts3DModule(Highcharts);
addBulletModule(Highcharts);
//addCylinderModule(Highcharts);
addFunnelModule(Highcharts);
addHeatmapModule(Highcharts);
//addHistogramBellCurveModule(Highcharts);
addNetworkGraphModule(Highcharts);
//addParetoModule(Highcharts);
addSankeyModule(Highcharts);
addSolidGaugeModule(Highcharts);
addStreamGraphModule(Highcharts);
addSunburstModule(Highcharts);
addTilemapModule(Highcharts);
addTreemapModule(Highcharts);
addVariablePieModule(Highcharts);
addVariwideModule(Highcharts);
addVectorModule(Highcharts);
addVennModule(Highcharts);
addWindBarbModule(Highcharts);
addXRangeModule(Highcharts);

const skippedSeries = ['BarSeries'];
const noAxisSeries = [
  'PieSeries',
  'VariablePieSeries',
  'PyramidSeries',
  'FunnelSeries',
  'VennSeries',
  'PackedBubbleSeries'
];
const needParentSeries = ['BellCurveSeries', 'HistogramSeries', 'ParetoSeries'];

Object.keys(all)
  .filter(name => /^[A-Z].*Series$/.test(name))
  .forEach(seriesName => {
    if (skippedSeries.includes(seriesName)) return;
    const seriesType = seriesName
      .substring(0, seriesName.indexOf('Series'))
      .toLowerCase();
    const SeriesComponent = all[seriesName]; // eslint-disable-line import/namespace

    describe(`<${seriesName} /> integration`, () => {
      if (seriesType in Highcharts.seriesTypes) {
        it('renders with real highcharts', done => {
          const afterAddSeries = event => {
            expect(event.target.series.length).toBe(1);
            const series = event.target.series[0];

            expect(series.type).toBe(seriesType);
            if (!noAxisSeries.includes(seriesName)) {
              expect(series.yAxis.userOptions.id).toBe('myYAxis');
            }
            done();
          };
          const Component = props => {
            return (
              <HighchartsProvider Highcharts={Highcharts}>
                <HighchartsChart>
                  <Chart zoomType="x" onAfterAddSeries={afterAddSeries} />
                  <XAxis></XAxis>
                  <YAxis id="myYAxis"></YAxis>
                  <SeriesComponent axisId="myYAxis" data={[1, 2, 3, 4]} />
                </HighchartsChart>
              </HighchartsProvider>
            );
          };
          mount(<Component />);
        });
        it('binds hide event correctly', done => {
          const afterAddSeries = event => {
            const series = event.target.series[0];
            expect(series.visible).toBe(true);
            series.hide();
          };
          const onHide = event => {
            expect(event.target.visible).toBe(false);
            done();
          };
          const Component = props => {
            return (
              <HighchartsProvider Highcharts={Highcharts}>
                <HighchartsChart>
                  <Chart zoomType="x" onAfterAddSeries={afterAddSeries} />
                  <XAxis></XAxis>
                  <YAxis>
                    <SeriesComponent data={[1, 2, 3, 4]} onHide={onHide} />
                  </YAxis>
                </HighchartsChart>
              </HighchartsProvider>
            );
          };
          mount(<Component />);
        });
      }
    });
  });
<|endoftext|>


<commit_before>ace.define("ace/snippets/coffee",["require","exports","module"], function(require, exports, module) {
"use strict";

exports.snippetText = "# Closure loop\n\
snippet forindo\n\
	for ${1:name} in ${2:array}\n\
		do ($1) ->\n\
			${3:// body}\n\
# Array comprehension\n\
snippet fora\n\
	for ${1:name} in ${2:array}\n\
		${3:// body...}\n\
# Object comprehension\n\
snippet foro\n\
	for ${1:key}, ${2:value} of ${3:object}\n\
		${4:// body...}\n\
# Range comprehension (inclusive)\n\
snippet forr\n\
	for ${1:name} in [${2:start}..${3:finish}]\n\
		${4:// body...}\n\
snippet forrb\n\
	for ${1:name} in [${2:start}..${3:finish}] by ${4:step}\n\
		${5:// body...}\n\
# Range comprehension (exclusive)\n\
snippet forrex\n\
	for ${1:name} in [${2:start}...${3:finish}]\n\
		${4:// body...}\n\
snippet forrexb\n\
	for ${1:name} in [${2:start}...${3:finish}] by ${4:step}\n\
		${5:// body...}\n\
# Function\n\
snippet fun\n\
	(${1:args}) ->\n\
		${2:// body...}\n\
# Function (bound)\n\
snippet bfun\n\
	(${1:args}) =>\n\
		${2:// body...}\n\
# Class\n\
snippet cla class ..\n\
	class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`}\n\
		${2}\n\
snippet cla class .. constructor: ..\n\
	class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`}\n\
		constructor: (${2:args}) ->\n\
			${3}\n\
\n\
		${4}\n\
snippet cla class .. extends ..\n\
	class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`} extends ${2:ParentClass}\n\
		${3}\n\
snippet cla class .. extends .. constructor: ..\n\
	class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`} extends ${2:ParentClass}\n\
		constructor: (${3:args}) ->\n\
			${4}\n\
\n\
		${5}\n\
# If\n\
snippet if\n\
	if ${1:condition}\n\
		${2:// body...}\n\
# If __ Else\n\
snippet ife\n\
	if ${1:condition}\n\
		${2:// body...}\n\
	else\n\
		${3:// body...}\n\
# Else if\n\
snippet elif\n\
	else if ${1:condition}\n\
		${2:// body...}\n\
# Ternary If\n\
snippet ifte\n\
	if ${1:condition} then ${2:value} else ${3:other}\n\
# Unless\n\
snippet unl\n\
	${1:action} unless ${2:condition}\n\
# Switch\n\
snippet swi\n\
	switch ${1:object}\n\
		when ${2:value}\n\
			${3:// body...}\n\
\n\
# Log\n\
snippet log\n\
	console.log ${1}\n\
# Try __ Catch\n\
snippet try\n\
	try\n\
		${1}\n\
	catch ${2:error}\n\
		${3}\n\
# Require\n\
snippet req\n\
	${2:$1} = require '${1:sys}'${3}\n\
# Export\n\
snippet exp\n\
	${1:root} = exports ? this\n\
";
exports.scope = "coffee";

});
<commit_msg>Update tmp/bower_components/ace-builds/src-noconflict/snippets/coffee.js<commit_after><|endoftext|>


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

module.exports = function(grunt, data) {
    var dist    = Object.keys(data.app.config.build.js)[0],
        source  = data.app.config.build.js[dist];
    return {
        "core-js": {
            options: {
                baseUrl: path.dirname(source),
                paths: '<%= app.config.paths %>',
                shim: '<%= app.config.shim %>',
                optimize: "uglify2",

                wrap: {
                    start: "(function() {",
                    end: "}());"
                },
                include: ['../lib/almond/almond', path.basename(source)],
                out: dist
            }
        }
    };
};
<commit_msg>add: refactor requirejs grunt task<commit_after>const path = require('path');

module.exports = function(grunt, factory) {
    var dist = Object.keys(factory.app.config.build.js)[0],
        source = factory.app.config.build.js[dist];
    return {
        options: {
            baseUrl: path.dirname(source),
            paths: '<%= app.config.paths %>',
            shim: '<%= app.config.shim %>',
            wrap: {
                start: "(function() {",
                end: "}());"
            },
            include: ['../lib/almond/almond', path.basename(source)],
            out: dist
        },
        "build": {
            options: {
                optimize: "uglify2",
            }
        },
        "live": {
            options: {
                optimize: 'none'
            }
        }
    };
};
<|endoftext|>


<commit_before>/* Dieses Skript wird ausgeführt, wenn der Browser index.html lädt. */

// Befehle werden sequenziell abgearbeitet ...

/**
 * "console.log" schreibt auf die Konsole des Browsers
 * Das Konsolenfenster muss im Browser explizit geöffnet werden.
 */
console.log("The script is going to start...");

// Es folgen einige Deklarationen, die aber noch nicht ausgeführt werden ...

/**
 * GeoTagApp Locator Modul
 */
var gtaLocator = (function GtaLocator() {

    // Private Member

    /**
     * Funktion spricht Geolocation API an.
     * Bei Erfolg Callback 'onsuccess' mit Position.
     * Bei Fehler Callback 'onerror' mit Meldung.
     * Callback Funktionen als Parameter übergeben.
     */
    var tryLocate = function (onsuccess, onerror) {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(onsuccess, function (error) {
                var msg;
                switch (error.code) {
                    case error.PERMISSION_DENIED:
                        msg = "User denied the request for Geolocation.";
                        break;
                    case error.POSITION_UNAVAILABLE:
                        msg = "Location information is unavailable.";
                        break;
                    case error.TIMEOUT:
                        msg = "The request to get user location timed out.";
                        break;
                    case error.UNKNOWN_ERROR:
                        msg = "An unknown error occurred.";
                        break;
                }
                onerror(msg);
            });
        } else {
            onerror("Geolocation is not supported by this browser.");
        }
    };

    // Auslesen Breitengrad aus der Position
    var getLatitude = function (position) {
        return position.coords.latitude;
    };

    // Auslesen Längengrad aus Position
    var getLongitude = function (position) {
        return position.coords.longitude;
    };

    // Hier Google Maps API Key eintragen
    var apiKey = "YOUR API KEY HERE";

    /**
     * Funktion erzeugt eine URL, die auf die Karte verweist.
     * Falls die Karte geladen werden soll, muss oben ein API Key angegeben
     * sein.
     *
     * lat, lon : aktuelle Koordinaten (hier zentriert die Karte)
     * tags : Array mit Geotag Objekten, das auch leer bleiben kann
     * zoom: Zoomfaktor der Karte
     */
    var getLocationMapSrc = function (lat, lon, tags, zoom) {
        zoom = typeof zoom !== 'undefined' ? zoom : 10;

        if (apiKey === "YOUR API KEY HERE") {
            console.log("No API key provided.");
            return "images/mapview.jpg";
        }

        var tagList = "";
        if (typeof tags !== 'undefined') tags.forEach(function (tag) {
            tagList += "&markers=%7Clabel:" + tag.name
                + "%7C" + tag.latitude + "," + tag.longitude;
        });

        var urlString = "http://maps.googleapis.com/maps/api/staticmap?center="
            + lat + "," + lon + "&markers=%7Clabel:you%7C" + lat + "," + lon
            + tagList + "&zoom=" + zoom + "&size=640x480&sensor=false&key=" + apiKey;

        console.log("Generated Maps Url: " + urlString);
        return urlString;
    };

    return { // Start öffentlicher Teil des Moduls ...

        // Public Member

        readme: "Dieses Objekt enthält 'öffentliche' Teile des Moduls.",

        updateLocation: function () {
            // TODO Hier Inhalt der Funktion "update" ergänzen
        }

    }; // ... Ende öffentlicher Teil
})();

/**
 * $(document).ready wartet, bis die Seite komplett geladen wurde. Dann wird die
 * angegebene Funktion aufgerufen. An dieser Stelle beginnt die eigentliche Arbeit
 * des Skripts.
 */
$(document).ready(function () {
    alert("Hello World")
    // TODO Hier den Aufruf für updateLocation einfügen
});
<commit_msg>geolocation mock +  mapquest service instead of google maps<commit_after>/* Dieses Skript wird ausgeführt, wenn der Browser index.html lädt. */

// Befehle werden sequenziell abgearbeitet ...

/**
 * "console.log" schreibt auf die Konsole des Browsers
 * Das Konsolenfenster muss im Browser explizit geöffnet werden.
 */
console.log("The script is going to start...");

// Es folgen einige Deklarationen, die aber noch nicht ausgeführt werden ...

// Hier wird die verwendete API für Geolocations gewählt
// Die folgende Deklaration ist ein 'Mockup', das immer funktioniert und eine fixe Position liefert.
GEOLOCATIONAPI = {
    getCurrentPosition: function(onsuccess) {
        onsuccess({
            "coords": {
                "latitude": 49.013790,
                "longitude": 8.390071,
                "altitude": null,
                "accuracy": 39,
                "altitudeAccuracy": null,
                "heading": null,
                "speed": null
            },
            "timestamp": 1540282332239
        });
    }
};

// Die echte API ist diese.
// Falls es damit Probleme gibt, kommentieren Sie die Zeile aus.
GEOLOCATIONAPI = navigator.geolocation;

/**
 * GeoTagApp Locator Modul
 */
var gtaLocator = (function GtaLocator(geoLocationApi) {

    // Private Member

    /**
     * Funktion spricht Geolocation API an.
     * Bei Erfolg Callback 'onsuccess' mit Position.
     * Bei Fehler Callback 'onerror' mit Meldung.
     * Callback Funktionen als Parameter übergeben.
     */
    var tryLocate = function(onsuccess, onerror) {
        if (geoLocationApi) {
            geoLocationApi.getCurrentPosition(onsuccess, function(error) {
                var msg;
                switch (error.code) {
                    case error.PERMISSION_DENIED:
                        msg = "User denied the request for Geolocation.";
                        break;
                    case error.POSITION_UNAVAILABLE:
                        msg = "Location information is unavailable.";
                        break;
                    case error.TIMEOUT:
                        msg = "The request to get user location timed out.";
                        break;
                    case error.UNKNOWN_ERROR:
                        msg = "An unknown error occurred.";
                        break;
                }
                onerror(msg);
            });
        } else {
            onerror("Geolocation is not supported by this browser.");
        }
    };

    // Auslesen Breitengrad aus der Position
    var getLatitude = function(position) {
        return position.coords.latitude;
    };

    // Auslesen Längengrad aus Position
    var getLongitude = function(position) {
        return position.coords.longitude;
    };

    // Hier Google Maps API Key eintragen
    var apiKey = "YOUR_API_KEY_HERE";

    /**
     * Funktion erzeugt eine URL, die auf die Karte verweist.
     * Falls die Karte geladen werden soll, muss oben ein API Key angegeben
     * sein.
     *
     * lat, lon : aktuelle Koordinaten (hier zentriert die Karte)
     * tags : Array mit Geotag Objekten, das auch leer bleiben kann
     * zoom: Zoomfaktor der Karte
     */
    var getLocationMapSrc = function(lat, lon, tags, zoom) {
        zoom = typeof zoom !== 'undefined' ? zoom : 10;

        if (apiKey === "YOUR_API_KEY_HERE") {
            console.log("No API key provided.");
            return "images/mapview.jpg";
        }

        var tagList = "&pois=You," + lat + "," + lon;
        if (tags !== undefined) tags.forEach(function(tag) {
            tagList += "|" + tag.name + "," + tag.latitude + "," + tag.longitude;
        });

        var urlString = "https://www.mapquestapi.com/staticmap/v4/getmap?key=" +
            apiKey + "&size=600,400&zoom=" + zoom + "&center=" + lat + "," + lon + "&" + tagList;

        console.log("Generated Maps Url: " + urlString);
        return urlString;
    };

    return { // Start öffentlicher Teil des Moduls ...

        // Public Member

        readme: "Dieses Objekt enthält 'öffentliche' Teile des Moduls.",

        updateLocation: function() {
            // TODO Hier Inhalt der Funktion "update" ergänzen
        }

    }; // ... Ende öffentlicher Teil
})(GEOLOCATIONAPI);

/**
 * $(document).ready wartet, bis die Seite komplett geladen wurde. Dann wird die
 * angegebene Funktion aufgerufen. An dieser Stelle beginnt die eigentliche Arbeit
 * des Skripts.
 */
$(document).ready(function() {
    alert("Please change the script 'geotagging.js'");
    // TODO Hier den Aufruf für updateLocation einfügen
});<|endoftext|>


<commit_before>describe("NMBS Liveboards", function() {

  var scope, $compile;
  var element;

  beforeEach(module('ui-nmbs-liveboards'));

  beforeEach(inject(function ($rootScope, _$compile_) {
    scope = $rootScope;
    $compile = _$compile_;
  }));

  describe('Uninitialized Liveboard', function() {
      var createLiveboard = function (tpl) {
      if (!tpl) tpl = '<div nmbs-liveboards>';
        element = angular.element(tpl);
        element = $compile(element)(scope);
        scope.$digest();
      }

    beforeEach(function () {
      inject(function ($httpBackend) {
        $httpBackend.whenGET('https://data.irail.be/NMBS/Stations.json').respond({
          "Stations":[{
            "id":"BE.NMBS.00101",
            "name":"Simonis",
            "longitude":
            "4.330556",
            "latitude":
            "50.863056","departures":"https:\/\/data.iRail.be\/NMBS\/Liveboard\/Simonis\/2014\/03\/30\/19\/20"
          }]
        });
        createLiveboard();
        $httpBackend.flush();
      });
    });

    it('should render a select element with stations', function() {
      expect(element.find('select').hasClass('ng-pristine ng-valid')).toBeTruthy();
      expect(element.find('option')).toBeTruthy();
    });

    it('should not render a loader upon initialization', function() {
      expect(element.find('div.nmbsLiveboards div.loader')).not.toBeDefined();
    });
  });

  describe('Initialized Liveboard', function() {

    var createLiveboard = function (tpl) {
      if (!tpl) tpl = '<div nmbs-liveboards>';
      element = angular.element(tpl);
      element = $compile(element)(scope);
      scope.$digest();
    }

    beforeEach(function () {
      inject(function ($httpBackend) {
        $httpBackend.whenGET('https://data.irail.be/NMBS/Stations.json').respond({
          "Stations":[{
            "id":"BE.NMBS.00101",
            "name":"Simonis",
            "longitude":"4.330556",
            "latitude":"50.863056",
            "departures":"https:\/\/data.iRail.be\/NMBS\/Liveboard\/Simonis\/2014\/03\/30\/19\/20"
          }]
        });

        $httpBackend.whenGET('https://data.iRail.be/NMBS/Liveboard/Simonis/2014/03/30/19/20.json').respond({
          "Liveboard":{
            "location":{
              "name":"Simonis",
              "longitude":4.32898,
              "latitude":50.863645},
              "departures":[{
                "time":1396237380,
                "iso8601":"2014-03-31T05:43:00+0200",
                "delay":300,
                "direction":"Brussel-Zuid",
                "vehicle":"BE.NMBS.L5325",
                "platform":{"name":"2"}
              }]
            }
        });

        var board = '<div nmbs-liveboards station=\"\'Simonis\'\">';
        createLiveboard(board);
        $httpBackend.flush();
      });
    });

    it('should show a liveboard if one is found', function() {
      expect(element.find('div.stationData h1').text()).toMatch('Simonis');
      expect(element.find('div.stationData tr.departure')).toBeDefined();
    });

    it('should show a valid departure record if one is found', function() {
      // expect valid time
      expect(element.find('tr.departure td.direction').text()).toMatch('Brussel-Zuid');
      expect(element.find('tr.departure td.type').text()).toMatch('L');
      expect(element.find('tr.departure td.platform').text()).toMatch('2');
      expect(element.find('tr.departure td.delay').text()).toMatch(/\+00h05/);
    });

    it('should show a human readable error message if no liveboard could be loaded', function() {
    });
  });
});

describe('NMBS Liveboards iRail API test', function() {

});
<commit_msg>added: various fixes and tests<commit_after>describe("NMBS Liveboards", function() {

  var scope, $compile;
  var element;

  beforeEach(module('ui-nmbs-liveboards'));

  beforeEach(inject(function ($rootScope, _$compile_) {
    scope = $rootScope;
    $compile = _$compile_;
  }));

  describe('Uninitialized Liveboard', function() {
    var createLiveboard = function (tpl) {
      if (!tpl) { tpl = '<div nmbs-liveboards>'; }
      element = angular.element(tpl);
      element = $compile(element)(scope);
      scope.$digest();
    };

    beforeEach(function () {
      inject(function ($httpBackend) {
        $httpBackend.whenGET('https://data.irail.be/NMBS/Stations.json').respond({
          "Stations":[{
            "id": "BE.NMBS.00101",
            "name": "Simonis",
            "longitude": "4.330556",
            "latitude": "50.863056",
            "departures": "https:\/\/data.iRail.be\/NMBS\/Liveboard\/Simonis\/2014\/03\/30\/19\/20"
          }]
        });
        createLiveboard();
        $httpBackend.flush();
      });
    });

    it('should render a select element with stations', function() {
      expect(element.find('select').hasClass('ng-pristine ng-valid')).toBeTruthy();
      expect(element.find('option')).toBeTruthy();
    });

    it('should not render a loader upon initialization', function() {
      expect(element.find('div.nmbsLiveboards div.loader').length).toBe(0);
    });
  });

  describe('Initialized Liveboard', function() {

    var createLiveboard = function (tpl) {
      if (!tpl) { tpl = '<div nmbs-liveboards station="\'Simonis\'">'; }
      element = angular.element(tpl);
      element = $compile(element)(scope);
      scope.$digest();
    };

    beforeEach(function () {
      inject(function ($httpBackend) {
        $httpBackend.whenGET('https://data.irail.be/NMBS/Stations.json').respond({
          "Stations":[{
            "id":"BE.NMBS.00101",
            "name":"Simonis",
            "longitude":"4.330556",
            "latitude":"50.863056",
            "departures":"https:\/\/data.iRail.be\/NMBS\/Liveboard\/Simonis\/2014\/03\/30\/19\/20"
          }]
        });

        $httpBackend.whenGET('https://data.iRail.be/NMBS/Liveboard/Simonis/2014/03/30/19/20.json').respond({
          "Liveboard":{
            "location":{
              "name":"Simonis",
              "longitude":4.32898,
              "latitude":50.863645
            },
            "departures":[{
                "time":1396237380,
                "iso8601":"2014-03-31T05:43:00+0200",
                "delay":300,
                "direction":"Brussel-Zuid",
                "vehicle":"BE.NMBS.L5325",
                "platform":{"name":"2"}
              }]
            }
          });

        var board = '<div nmbs-liveboards station=\"\'Simonis\'\">';
        createLiveboard(board);
        $httpBackend.flush();
      });
    });

    it('should show a liveboard if one is found', function() {
      expect(element.find('div.stationData h1').text()).toMatch('Simonis');
      expect(element.find('div.stationData tr.departure')).toBeDefined();
    });

    it('should show a valid departure record if one is found', function() {
      // expect valid time
      expect(element.find('tr.departure td.direction').text()).toMatch(/^Brussel-Zuid$/);
      expect(element.find('tr.departure td.type').text()).toMatch(/^L$/);
      expect(element.find('tr.departure td.platform').text()).toMatch(/^2$/);
      expect(element.find('tr.departure td.delay').text()).toMatch(/^\+00h05$/);
    });

    it('should not render a loader upon initialization', function() {
      expect(element.find('div.nmbsLiveboards div.loader').length).toBe(0);
    });

    it('should show a human readable error message if no liveboard could be loaded', function() {
    });
  });
});

describe('NMBS Liveboards iRail API test', function() {

});
<|endoftext|>


<commit_before>'use strict'

const Note = require('../models/note');

module.exports.index = (req, res) => {
    Note.find({}, (err, notes) => {
        res.render('notes-index', {notes: notes});
    });
};

module.exports.newNote = (req, res) => {
    res.render('new-note');
};

module.exports.create = (req,res) => {
    Note.create(req.body, (err, note) => {
        if (err) throw (err);

        res.redirect(`/notes/${note._id}`);
    });
};

module.exports.show = (req, res) => {
    Note.findById(req.params.id, (err, note) => {
        if (err) throw (err);
        res.render('show-note', {note: note});
    });
};

module.exports.edit = (req, res) => {
    Note.findById(req.params.id, (err, note) => {
        if (err) throw (err);
        res.render('new-note', {note: note});
    });
};

module.exports.update = (req, res) => {
    Note.findByIdAndUpdate(req.params.id, req.body, (err, note) => {
        if (err) throw (err);

        res.redirect(`/notes/${note._id}`);
    });
};

module.exports.destroy = (req, res) => {
    Note.findByIdAndRemove(req.params.id, (err) => {
        if (err) throw (err);
        res.redirect('/notes');
    });
};

<commit_msg>Added es6 syntax to note controller page<commit_after>'use strict'

const Note = require('../models/note');

module.exports = {

    index (req, res) {
        Note.find({}, (err, notes) => {
            res.render('notes-index', {notes: notes});
        });
    },

    newNote (req, res) {
        res.render('new-note');
    },

    create (req,res) {
        Note.create(req.body, (err, note) => {
            if (err) throw (err);

            res.redirect(`/notes/${note._id}`);
        });
    },

    show (req, res) {
        Note.findById(req.params.id, (err, note) => {
            if (err) throw (err);
            res.render('show-note', {note: note});
        });
    },

    edit (req, res) {
        Note.findById(req.params.id, (err, note) => {
            if (err) throw (err);
            res.render('new-note', {note: note});
        });
    },

    update (req, res) {
        Note.findByIdAndUpdate(req.params.id, req.body, (err, note) => {
            if (err) throw (err);

            res.redirect(`/notes/${note._id}`);
        });
    },

    destroy (req, res) {
        Note.findByIdAndRemove(req.params.id, (err) => {
            if (err) throw (err);
            res.redirect('/notes');
        });
    },

}

<|endoftext|>


<commit_before>/**
 * Подменяем и расширяем Backbone.View, добавляя в него милые методы для работы с селекторами, выбором элементов и
 * дата атрибутами
 * @class Backbone.ElementsView
 * @extends Backbone.View
 */
Backbone.ElementsView = Backbone.View.redefine(function (origin) {
    return /**@lends Backbone.View*/{
        initialize: function () {
            origin.initialize.apply(this, arguments);

            /**
             * @type {jQuery}
             * @protected
             */
            this._$window = $(window);

            /**
             * @type {jQuery}
             * @protected
             */
            this._$document = $(document);

            /**
             * @type {jQuery}
             * @protected
             */
            this._$body = $(document.body);
        },

        setElement: function () {
            origin.setElement.apply(this, arguments);

            /**
             * Дата атрибуты {@link Backbone.View.$el} в camelCase
             * @type {Object.<string, string>}
             * @protected
             */
            this._data = this.$el.data() || {};
            this._resetCaches();
            return this;
        },

        /**
         * Сбрасывает кэши клаасов, селекторов и элементов
         * @private
         */
        _resetCaches: function () {

            /**
             * Здесь сохраняются закешированные классы, полученные из
             * {@link Backbone.ElementsView._classes}
             * @type {Object.<string, string>}
             * @private
             */
            this._cachedClasses = this._classes();

            /**
             * Здесь сохраняются закешированные селекторы, в том числе полученные из
             * {@link Backbone.ElementsView._classes}
             * @type {Object.<string, string>}
             * @private
             */
            this._cachedSelectors = this._selectors();

            /**
             * Кеш для {@link Backbone.ElementsView._elem}
             * @type {Object.<string, jQuery>}
             * @private
             */
            this._cachedElements = {};
        },

        /**
         * CSS классы используемые во вьюшке складываются сюда. Ключи - имена элементов, значение - названия классов.
         * Свойство можно переопределять в наследуемых классах
         * @returns {Object.<string, string>}
         * @protected
         * @example
         *     _classes: function(){
         *         return {
         *             table: 'js-table'
         *         };
         *     }
         *
         */
        _classes: function () {
            return {};
        },

        /**
         * Возвращает css класс элемента по его имени, классы берутся из {@link Backbone.ElementsView._classes}
         * @param {String} name название элемента
         * @returns {String} css класс
         * @throws {Error} если название елемента нигде не найдено
         * @protected
         */
        _class: function (name) {
            var cl = this._cachedClasses[name];
            if (cl == null) {
                throw new Error('Selector for ' + name + ' does not found');
            }

            return cl;
        },

        /**
         * Селекторы используемые во вьюшке описываются здесь. Метод надо переопределять в наследуемых классах
         * @returns {Object.<string, string>} Ключи - названия элементов, значения - селекторы
         * @protected
         * @example
         *      _selectors: function(){
         *          return {
         *              map: '.google-map:first'
         *          };
         *      }
         *
         */
        _selectors: function () {
            return {};
        },

        /**
         * Возвращает селектор элемента по его имени, селекторы берутся из {@link Backbone.ElementsView._selectors} или
         * {@link Backbone.ElementsView._classes}
         * @param {String} name название элемента
         * @returns {String} селектор
         * @protected
         * @example
         *      events: function(){
         *          var events = {};
         *          events['click ' + this._selector('map')] = this._clickOnMap;
         *          events['click ' + this._selector('table')] = this._clickOnTable;
         *          return events;
         *      }
         *
         */
        _selector: function (name) {
            var args = null,
                cacheKey = this._getCacheKey.apply(this, arguments),
                selector = this._cachedSelectors[cacheKey];

            if (selector == null) {
                if (!this._cachedSelectors[name]) {
                    selector = '.' + this._class(name);
                    this._cachedSelectors[name] = selector;
                }

                args = Array.prototype.slice.call(arguments, 1);
                if (args.length) {
                    args.unshift(this._cachedSelectors[name]);
                    selector = _.sprintf.apply(_, args);
                    this._cachedSelectors[cacheKey] = selector;
                }
            }
            return selector;
        },

        /**
         * @param {String} name
         * @returns {Boolean}
         * @protected
         */
        _hasSelector: function (name) {
            return !!(this._cachedClasses[name] || this._cachedSelectors[name]);
        },

        /**
         * Возвращает jQuery коллекцию по имени из {@link Backbone.ElementsView._selectors} или
         * {@link Backbone.ElementsView._classes}. Кэширует результаты, для сброса кеша см.
         * {@link Backbone.ElementsView._dropElemCache}
         * @param {String} name название элемента
         * @returns {jQuery}
         * @protected
         * @example
         *     this._elem('table').hide();
         *
         */
        _elem: function (name) {
            var cacheKey = this._getCacheKey.apply(this, arguments),
                $elem = this._cachedElements[cacheKey];

            if ($elem != null) {
                return $elem;
            }

            $elem = this._findElem.apply(this, arguments);
            this._cachedElements[cacheKey] = $elem;

            return $elem;
        },

        /**
         * @param name
         * @returns {string}
         * @private
         */
        _getCacheKey: function (name) {
            return Array.prototype.join.call(arguments, '|');
        },

        /**
         * Finds element without using cache
         * @param {string} name
         * @returns {jQuery}
         * @protected
         */
        _findElem: function (name) {
            return this.$(this._selector.apply(this, arguments));
        },

        /**
         * Replaces element with passed content
         * @param {string} name
         * @param {HTMLElement|jQuery|string} content
         * @protected
         */
        _replaceElem: function (name, content) {
            var $el = this._elem(name),
                focusOnElem = $el[0] == document.activeElement || $el.has(document.activeElement).length;

            this._elem(name).replaceWith(content);
            this._dropElemCache(name);

            if (focusOnElem) {
                this._fixFocus(this._elem(name));
            }
        },

        /**
         * Sets element innerHTML
         * @param {string} name
         * @param {HTMLElement|jQuery|string} content
         * @protected
         */
        _setElemContent: function (name, content) {
            var $el = this._elem(name),
                focusInsideElem = $el.has(document.activeElement).length;

            $el.html(content);
            if (focusInsideElem) {
                this._fixFocus($el);
            }
        },

        /**
         * Emulate focus on passed element (focuses closest focusable element)
         * @param {jQuery} $el
         * @private
         */
        _fixFocus: function ($el) {
            var $focused = $el.closest('[tabindex],a,button:not(:disabled)');
            if ($focused.length) {
                $focused[0].focus();
            }
        },

        /**
         * Трет кеш для {@link Backbone.ElementsView._elem}
         * @param {String} [name] имя элемента для которого надо убрать кеш, если не задано - сотрется весь кеш
         * @protected
         */
        _dropElemCache: function (name) {
            if (name != null) {
                delete this._cachedElements[this._getCacheKey.apply(this, arguments)];
            }
            else {
                this._cachedElements = {};
            }
            return this;
        },

        /**
         * Возвращает дата атрибуты для элемента по его имени и имени атрибута
         * @param {String} name имя элемента
         * @param {String} [attr] имя атрибута, если не задано, то вернется объект со всеми дата атрибутами для элемента
         * @returns {*|Object}
         * @protected
         */
        _getElemData: function (name, attr) {
            var data = this._elem(name).data();
            if (attr == null) {
                return data;
            }

            return data[attr];
        },

        /**
         * Совместимость с Backbone.Decorate
         */
        beforeDecorate: function () {
            this._resetCaches();

            if (typeof origin.beforeDecorate == "function") {
                origin.beforeDecorate.apply(this, arguments);
            }
        }
    }
});<commit_msg>PSDJS-7571 Backbone.View.Elements _$document, _$window, _$body are in _initProperties now<commit_after>/**
 * Подменяем и расширяем Backbone.View, добавляя в него милые методы для работы с селекторами, выбором элементов и
 * дата атрибутами
 * @class Backbone.ElementsView
 * @extends Backbone.View
 */
Backbone.ElementsView = Backbone.View.redefine(function (origin) {
    return /**@lends Backbone.View*/{

        /**
         * @protected
         */
        _initProperties: function () {
            origin._initProperties.apply(this, arguments);

            /**
             * @type {jQuery}
             * @protected
             */
            this._$window = $(window);

            /**
             * @type {jQuery}
             * @protected
             */
            this._$document = $(document);

            /**
             * @type {jQuery}
             * @protected
             */
            this._$body = $(document.body);
        },

        setElement: function () {
            origin.setElement.apply(this, arguments);

            /**
             * Дата атрибуты {@link Backbone.View.$el} в camelCase
             * @type {Object.<string, string>}
             * @protected
             */
            this._data = this.$el.data() || {};
            this._resetCaches();
            return this;
        },

        /**
         * Сбрасывает кэши клаасов, селекторов и элементов
         * @private
         */
        _resetCaches: function () {

            /**
             * Здесь сохраняются закешированные классы, полученные из
             * {@link Backbone.ElementsView._classes}
             * @type {Object.<string, string>}
             * @private
             */
            this._cachedClasses = this._classes();

            /**
             * Здесь сохраняются закешированные селекторы, в том числе полученные из
             * {@link Backbone.ElementsView._classes}
             * @type {Object.<string, string>}
             * @private
             */
            this._cachedSelectors = this._selectors();

            /**
             * Кеш для {@link Backbone.ElementsView._elem}
             * @type {Object.<string, jQuery>}
             * @private
             */
            this._cachedElements = {};
        },

        /**
         * CSS классы используемые во вьюшке складываются сюда. Ключи - имена элементов, значение - названия классов.
         * Свойство можно переопределять в наследуемых классах
         * @returns {Object.<string, string>}
         * @protected
         * @example
         *     _classes: function(){
         *         return {
         *             table: 'js-table'
         *         };
         *     }
         *
         */
        _classes: function () {
            return {};
        },

        /**
         * Возвращает css класс элемента по его имени, классы берутся из {@link Backbone.ElementsView._classes}
         * @param {String} name название элемента
         * @returns {String} css класс
         * @throws {Error} если название елемента нигде не найдено
         * @protected
         */
        _class: function (name) {
            var cl = this._cachedClasses[name];
            if (cl == null) {
                throw new Error('Selector for ' + name + ' does not found');
            }

            return cl;
        },

        /**
         * Селекторы используемые во вьюшке описываются здесь. Метод надо переопределять в наследуемых классах
         * @returns {Object.<string, string>} Ключи - названия элементов, значения - селекторы
         * @protected
         * @example
         *      _selectors: function(){
         *          return {
         *              map: '.google-map:first'
         *          };
         *      }
         *
         */
        _selectors: function () {
            return {};
        },

        /**
         * Возвращает селектор элемента по его имени, селекторы берутся из {@link Backbone.ElementsView._selectors} или
         * {@link Backbone.ElementsView._classes}
         * @param {String} name название элемента
         * @returns {String} селектор
         * @protected
         * @example
         *      events: function(){
         *          var events = {};
         *          events['click ' + this._selector('map')] = this._clickOnMap;
         *          events['click ' + this._selector('table')] = this._clickOnTable;
         *          return events;
         *      }
         *
         */
        _selector: function (name) {
            var args = null,
                cacheKey = this._getCacheKey.apply(this, arguments),
                selector = this._cachedSelectors[cacheKey];

            if (selector == null) {
                if (!this._cachedSelectors[name]) {
                    selector = '.' + this._class(name);
                    this._cachedSelectors[name] = selector;
                }

                args = Array.prototype.slice.call(arguments, 1);
                if (args.length) {
                    args.unshift(this._cachedSelectors[name]);
                    selector = _.sprintf.apply(_, args);
                    this._cachedSelectors[cacheKey] = selector;
                }
            }
            return selector;
        },

        /**
         * @param {String} name
         * @returns {Boolean}
         * @protected
         */
        _hasSelector: function (name) {
            return !!(this._cachedClasses[name] || this._cachedSelectors[name]);
        },

        /**
         * Возвращает jQuery коллекцию по имени из {@link Backbone.ElementsView._selectors} или
         * {@link Backbone.ElementsView._classes}. Кэширует результаты, для сброса кеша см.
         * {@link Backbone.ElementsView._dropElemCache}
         * @param {String} name название элемента
         * @returns {jQuery}
         * @protected
         * @example
         *     this._elem('table').hide();
         *
         */
        _elem: function (name) {
            var cacheKey = this._getCacheKey.apply(this, arguments),
                $elem = this._cachedElements[cacheKey];

            if ($elem != null) {
                return $elem;
            }

            $elem = this._findElem.apply(this, arguments);
            this._cachedElements[cacheKey] = $elem;

            return $elem;
        },

        /**
         * @param name
         * @returns {string}
         * @private
         */
        _getCacheKey: function (name) {
            return Array.prototype.join.call(arguments, '|');
        },

        /**
         * Finds element without using cache
         * @param {string} name
         * @returns {jQuery}
         * @protected
         */
        _findElem: function (name) {
            return this.$(this._selector.apply(this, arguments));
        },

        /**
         * Replaces element with passed content
         * @param {string} name
         * @param {HTMLElement|jQuery|string} content
         * @protected
         */
        _replaceElem: function (name, content) {
            var $el = this._elem(name),
                focusOnElem = $el[0] == document.activeElement || $el.has(document.activeElement).length;

            this._elem(name).replaceWith(content);
            this._dropElemCache(name);

            if (focusOnElem) {
                this._fixFocus(this._elem(name));
            }
        },

        /**
         * Sets element innerHTML
         * @param {string} name
         * @param {HTMLElement|jQuery|string} content
         * @protected
         */
        _setElemContent: function (name, content) {
            var $el = this._elem(name),
                focusInsideElem = $el.has(document.activeElement).length;

            $el.html(content);
            if (focusInsideElem) {
                this._fixFocus($el);
            }
        },

        /**
         * Emulate focus on passed element (focuses closest focusable element)
         * @param {jQuery} $el
         * @private
         */
        _fixFocus: function ($el) {
            var $focused = $el.closest('[tabindex],a,button:not(:disabled)');
            if ($focused.length) {
                $focused[0].focus();
            }
        },

        /**
         * Трет кеш для {@link Backbone.ElementsView._elem}
         * @param {String} [name] имя элемента для которого надо убрать кеш, если не задано - сотрется весь кеш
         * @protected
         */
        _dropElemCache: function (name) {
            if (name != null) {
                delete this._cachedElements[this._getCacheKey.apply(this, arguments)];
            }
            else {
                this._cachedElements = {};
            }
            return this;
        },

        /**
         * Возвращает дата атрибуты для элемента по его имени и имени атрибута
         * @param {String} name имя элемента
         * @param {String} [attr] имя атрибута, если не задано, то вернется объект со всеми дата атрибутами для элемента
         * @returns {*|Object}
         * @protected
         */
        _getElemData: function (name, attr) {
            var data = this._elem(name).data();
            if (attr == null) {
                return data;
            }

            return data[attr];
        },

        /**
         * Совместимость с Backbone.Decorate
         */
        beforeDecorate: function () {
            this._resetCaches();

            if (typeof origin.beforeDecorate == "function") {
                origin.beforeDecorate.apply(this, arguments);
            }
        }
    }
});<|endoftext|>


<commit_before>#!/usr/bin/env node

/*	devProxy.js 0.2.1
 *	通过将数据请求转发到远程服务器, 来在本地开发环境中模拟服务器环境, 以实现完整的网站功能
 *	脚本执行时会从当前目录载入proxyConfig.js
 */

'use strict';
var http = require('http');
var https = require('https');
var util = require('util');
var path = require('path');
var fs = require('fs');
var dir = process.argv.length > 2 ? process.argv[2] : process.cwd();
var config = require(path.join(dir, 'proxyConfig.js'));

var mimes = {
	'': 'application/octet-stream',
	'html': 'text/html',
	'js': 'text/javascript',
	'css': 'text/css',
	'jpg': 'image/jpeg',
	'png': 'image/png',
	'gif': 'image/gif',
	'svg': 'image/svg+xml',
	'json': 'text/json'
};

if (config instanceof Array) {
	for (var i = 0; i < config.length; i++) {
		run(config[i]);
	}
} else {
	run(config);
}

function run(config) {
	var s;
	console.log(config);
	s = parseServer(config.remote);
	if (s) {
		config.remote = s;
		if (typeof config.local === 'string') {
			s = parseServer(config.local);
			if (s) {
				config.local = s;
			}
		} else {
			if (!config.local.prefix) {
				config.local.prefix = '/';
			}
		}
		if (config.local instanceof Object) {
			http.createServer(function(req, res) {
				if (req.method === 'POST' || (config.rule && config.rule.test(req.url))) {
					httpproxy(config.remote, req, res);
				} else {
					if (config.local instanceof Array) {
						httpproxy(config.local, req, res);
					} else {
						staticfile(config, req, res);
					}
				}
			}).listen(config.port, '0.0.0.0');
		} else {
			console.log('bad local server address: ' + config.local);
		}
	} else {
		console.log('bad remote server address: ' + config.remote);
	}
}

function staticfile(config, req, res) {
	var u = req.url.replace(/\?.*$/, '');
	if (u === '/') {
		u = config.local.prefix + config.local.index;
	} else if (u[u.length - 1] === '/') {
		u += config.local.index;
	}
	var p, v = config.local.prefix.length;
	if (u.substr(0, v) === config.local.prefix) {
		p = path.join(dir, config.local.root, u.substr(v));
		fs.stat(p, function(err, stat) {
			if (err) {
				httpproxy(config.remote, req, res);
			} else {
				if (stat.isDirectory()) {
					res.writeHeader(302, 'Found', {
						'Location': u + '/'
					});
					res.end();
				} else {
					var m = mimes[path.extname(p).substr(1)];
					if (!m) {
						m = mimes[''];
					}
					var f = fs.createReadStream(p);
					res.writeHeader(200, 'OK', {
						'Content-Type': m,
						'Content-Length': stat.size,
						'Last-Modified': new Date(stat.mtime).toUTCString()
					});
					f.pipe(res);
					console.log('static: ' + req.url);
				}
			}
		});
	} else {
		httpproxy(config.remote, req, res);
	}
}

function httpproxy(server, req, res) {
	var n;
	var info = {
		host: server[1],
		port: server[2],
		path: server[3] + req.url,
		method: req.method
	};
	var proxy = server[0].request(info, function(res2) {
		var cookie = res2.headers['set-cookie'];
		if (cookie instanceof Array) {
			for (var i = 0; i < cookie.length; i++) {
				cookie[i] = cookie[i].replace(/; domain=[^;]+/, '');
			}
		}
		delete res2.headers['access-control-allow-origin'];
		res.writeHeader(res2.statusCode, res2.headers);
		res2.pipe(res);
		console.log(buildServerStr(server) + req.url);
	});
	proxy.on('error', function(err) {
		console.log(err);
		res.end();
	});
	for (n in req.headers) {
		if (['host', 'origin', 'referer'].indexOf(n) < 0) {
			//console.log(n + ': ' + req.headers[n]);
			proxy.setHeader(n, req.headers[n]);
		}
		//console.log(n);
	}
	req.pipe(proxy);
}

function parseServer(str) {
	var r = str.match(/^http(s?):\/\/([^\/:]+)(?::(\d+))?(\/.*[^\/])?\/$/);
	if (r) {
		delete r.index;
		delete r.source;
		r.shift();
		r[2] = r[2] ? parseInt(r[2]) : r[0] ? 443 : 80;
		r[0] = r[0] ? https : http;
		!r[3] && (r[3] = '');
	}
	return r;
}

function buildServerStr(server) {
	var s = 'http';
	if (server[0] === https) {
		s += 's';
	}
	s += '://' + server[1];
	if ((server[0] === https && server[2] !== 443) || (server[0] === http && server[2] !== 80)) {
		s += ':' + server[2];
	}
	s += server[3];
	return s;
}<commit_msg>no message<commit_after>#!/usr/bin/env node

/*	devProxy.js 0.2.1
 *	通过将数据请求转发到远程服务器, 来在本地开发环境中模拟服务器环境, 以实现完整的网站功能
 *	脚本执行时会从当前目录载入proxyConfig.js
 */

'use strict';
var http = require('http');
var https = require('https');
var util = require('util');
var path = require('path');
var fs = require('fs');
var dir = process.argv.length > 2 ? process.argv[2] : process.cwd();
var config = require(path.join(dir, 'proxyConfig.js'));

var mimes = {
	'': 'application/octet-stream',
	'html': 'text/html',
	'js': 'text/javascript',
	'css': 'text/css',
	'jpg': 'image/jpeg',
	'png': 'image/png',
	'gif': 'image/gif',
	'svg': 'image/svg+xml',
	'json': 'text/json'
};

if (config instanceof Array) {
	for (var i = 0; i < config.length; i++) {
		run(config[i]);
	}
} else {
	run(config);
}

function run(config) {
	var s;
	console.log(config);
	s = parseServer(config.remote);
	if (s) {
		config.remote = s;
		if (typeof config.local === 'string') {
			s = parseServer(config.local);
			if (s) {
				config.local = s;
			}
		} else {
			if (!config.local.prefix) {
				config.local.prefix = '/';
			}
		}
		if (config.local instanceof Object) {
			http.createServer(function(req, res) {
				if (req.method === 'POST' || (config.rule && config.rule.test(req.url))) {
					httpproxy(config.remote, req, res);
				} else {
					if (config.local instanceof Array) {
						httpproxy(config.local, req, res);
					} else {
						staticfile(config, req, res);
					}
				}
			}).listen(config.port, '0.0.0.0');
		} else {
			console.log('bad local server address: ' + config.local);
		}
	} else {
		console.log('bad remote server address: ' + config.remote);
	}
}

function staticfile(config, req, res) {
	var u = req.url.replace(/\?.*$/, '');
	if (u === '/') {
		u = config.local.prefix + config.local.index;
	} else if (u[u.length - 1] === '/') {
		u += config.local.index;
	}
	var p, v = config.local.prefix.length;
	if (u.substr(0, v) === config.local.prefix) {
		p = path.join(dir, config.local.root, u.substr(v));
		fs.stat(p, function(err, stat) {
			if (err) {
				httpproxy(config.remote, req, res);
			} else {
				if (stat.isDirectory()) {
					res.writeHeader(302, 'Found', {
						'Location': u + '/'
					});
					res.end();
				} else {
					var m = mimes[path.extname(p).substr(1)];
					if (!m) {
						m = mimes[''];
					}
					var f = fs.createReadStream(p);
					res.writeHeader(200, 'OK', {
						'Content-Type': m,
						'Content-Length': stat.size,
						'Last-Modified': new Date(stat.mtime).toUTCString()
					});
					f.pipe(res);
					console.log('static: ' + req.url);
				}
			}
		});
	} else {
		httpproxy(config.remote, req, res);
	}
}

function httpproxy(server, req, res) {
	var n;
	var info = {
		host: server[1],
		port: server[2],
		path: server[3] + req.url,
		method: req.method
	};
	var proxy = server[0].request(info, function(res2) {
		var cookie = res2.headers['set-cookie'];
		if (cookie instanceof Array) {
			for (var i = 0; i < cookie.length; i++) {
				cookie[i] = cookie[i].replace(/; domain=[^;]+/, '');
			}
		}
		delete res2.headers['access-control-allow-origin'];
		res.writeHeader(res2.statusCode, res2.headers);
		res2.pipe(res);
		console.log(buildServerStr(server) + req.url);
	});
	proxy.on('error', function(err) {
		console.log(err);
		if (!res.headersSent) {
			res.writeHeader(502, 'Bad Gateway');
		}
		res.end();
	});
	for (n in req.headers) {
		if (['host', 'origin', 'referer'].indexOf(n) < 0) {
			//console.log(n + ': ' + req.headers[n]);
			proxy.setHeader(n, req.headers[n]);
		}
		//console.log(n);
	}
	req.pipe(proxy);
}

function parseServer(str) {
	var r = str.match(/^http(s?):\/\/([^\/:]+)(?::(\d+))?(\/.*[^\/])?\/$/);
	if (r) {
		delete r.index;
		delete r.source;
		r.shift();
		r[2] = r[2] ? parseInt(r[2]) : r[0] ? 443 : 80;
		r[0] = r[0] ? https : http;
		!r[3] && (r[3] = '');
	}
	return r;
}

function buildServerStr(server) {
	var s = 'http';
	if (server[0] === https) {
		s += 's';
	}
	s += '://' + server[1];
	if ((server[0] === https && server[2] !== 443) || (server[0] === http && server[2] !== 80)) {
		s += ':' + server[2];
	}
	s += server[3];
	return s;
}<|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 except paramsNumberArrayObject, inputFloat32Array, byteOffsetBegin.
 *
 */
class Base extends TestParams.Base {

  /**
   * 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
   *
   * @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.
   *
   * @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;
    let stepParamsMaker = Block.Base.create_Params_to_PointDepthPointParams( blockParams );

    let paramsNameOrderArray = Base.paramsNameOrderArray_Basic.slice(); // 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();
      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[ stepName ] = stepTestParams;
      this.in.paramsNumberArrayObject[ stepName ] = stepTestParams.weightsFloat32Array;

      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, this.in.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 );
  }

  /**
   * Responsible for generating testing paramters combinations.
   *
   * @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() {

    // Restrict some parameter's large kinds. Otherwise, too many combination will be generated.
    this.maxKindsRestrict = {
      sourceHeight: 5,
      sourceWidth:  5,
      sourceChannelCount: 4,
      stepCountRequested: 5,
      pointwise1ChannelCountRate: undefined,
      depthwiseFilterHeight: undefined,

      // Because the logic of activation function is simpler than other, it is just randomly tested once
      // (i.e. ( maxKinds == 0 )) for speeding up testing.
      nActivationId: 0,
      nActivationIdAtBlockEnd: 0,

      nWhetherShuffleChannel: undefined,
      bKeepInputTensor: undefined,
    };

    // 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.maxKindsRestrict.sourceHeight ),
      new TestParams.ParamDescConfig( Block.Params.sourceWidth,                this.maxKindsRestrict.sourceWidth ),
      new TestParams.ParamDescConfig( Block.Params.sourceChannelCount,         this.maxKindsRestrict.sourceChannelCount ),
      new TestParams.ParamDescConfig( Block.Params.stepCountRequested,          this.maxKindsRestrict.stepCountRequested ),
      new TestParams.ParamDescConfig( Block.Params.pointwise1ChannelCountRate, this.maxKindsRestrict.pointwise1ChannelCountRate ),
      new TestParams.ParamDescConfig( Block.Params.depthwiseFilterHeight,      this.maxKindsRestrict.depthwiseFilterHeight ),
      new TestParams.ParamDescConfig( Block.Params.nActivationId,              this.maxKindsRestrict.nActivationId ),
      new TestParams.ParamDescConfig( Block.Params.nActivationIdAtBlockEnd,    this.maxKindsRestrict.nActivationIdAtBlockEnd ),
      new TestParams.ParamDescConfig( Block.Params.nWhetherShuffleChannel,     this.maxKindsRestrict.nWhetherShuffleChannel ),
      new TestParams.ParamDescConfig( Block.Params.bKeepInputTensor,           this.maxKindsRestrict.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 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 {

  /**
   * 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
   *
   * @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.
   *
   * @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;
    let stepParamsMaker = Block.Base.create_Params_to_PointDepthPointParams( blockParams );

    this.stepsArray = new Array( stepParamsMaker.stepCount );
    let paramsNameOrderArray = Base.paramsNameOrderArray_Basic.slice(); // 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();
      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;
      this.in.paramsNumberArrayObject[ stepName ] = stepTestParams.weightsFloat32Array;

      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, this.in.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 );
  }

  /**
   * Responsible for generating testing paramters combinations.
   *
   * @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() {

    // Restrict some parameter's large kinds. Otherwise, too many combination will be generated.
    this.maxKindsRestrict = {
      sourceHeight: 5,
      sourceWidth:  5,
      sourceChannelCount: 4,
      stepCountRequested: 5,
      pointwise1ChannelCountRate: undefined,
      depthwiseFilterHeight: undefined,

      // Because the logic of activation function is simpler than other, it is just randomly tested once
      // (i.e. ( maxKinds == 0 )) for speeding up testing.
      nActivationId: 0,
      nActivationIdAtBlockEnd: 0,

      nWhetherShuffleChannel: undefined,
      bKeepInputTensor: undefined,
    };

    // 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.maxKindsRestrict.sourceHeight ),
      new TestParams.ParamDescConfig( Block.Params.sourceWidth,                this.maxKindsRestrict.sourceWidth ),
      new TestParams.ParamDescConfig( Block.Params.sourceChannelCount,         this.maxKindsRestrict.sourceChannelCount ),
      new TestParams.ParamDescConfig( Block.Params.stepCountRequested,          this.maxKindsRestrict.stepCountRequested ),
      new TestParams.ParamDescConfig( Block.Params.pointwise1ChannelCountRate, this.maxKindsRestrict.pointwise1ChannelCountRate ),
      new TestParams.ParamDescConfig( Block.Params.depthwiseFilterHeight,      this.maxKindsRestrict.depthwiseFilterHeight ),
      new TestParams.ParamDescConfig( Block.Params.nActivationId,              this.maxKindsRestrict.nActivationId ),
      new TestParams.ParamDescConfig( Block.Params.nActivationIdAtBlockEnd,    this.maxKindsRestrict.nActivationIdAtBlockEnd ),
      new TestParams.ParamDescConfig( Block.Params.nWhetherShuffleChannel,     this.maxKindsRestrict.nWhetherShuffleChannel ),
      new TestParams.ParamDescConfig( Block.Params.bKeepInputTensor,           this.maxKindsRestrict.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|>


<commit_before>'use strict';

App.factory('iframeHelpers', function() {
  var iframeHelpers = {
    resizeIframe: function() {
      setTimeout(function() {
        if (window.postMessage) {
          var minPageHeight = 250; // px
          var docElement = document.documentElement;
          var height = Math.max(docElement.scrollHeight, docElement.offsetHeight, docElement.clientHeight);
          window.parent.postMessage('MASRESIZE-' + height, '*');
        }
      });
    }
  };

  return iframeHelpers;
});

<commit_msg>refactor to be inline with style guide<commit_after>'use strict';

App.factory('iframeHelpers', function() {
  var iframeHelpers = {
    resizeIframe: function() {
      setTimeout(function() {
        if (window.postMessage) {
          var minPageHeight = 250,
              docElement = document.documentElement,
              height = Math.max(docElement.scrollHeight, docElement.offsetHeight, docElement.clientHeight);

          window.parent.postMessage('MASRESIZE-' + height, '*');
        }
      });
    }
  };

  return iframeHelpers;
});

<|endoftext|>


<commit_before>const {
    createConfig,
    defineConstants,
    env,
    entryPoint,
    setOutput,
    sourceMaps,
    addPlugins,
    devServer,
    postcss,
    sass,
    css,
    typescript,
    extractText,
    customConfig,
    uglify,
    match,
    file,
    url
} = require('webpack-blocks');
const tslint = require('@webpack-blocks/tslint');
const autoprefixer = require('autoprefixer');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

const path = require('path');
const fs = require('fs');

const appPath = (...names) => path.join(process.cwd(), ...names);
const userConfig = require(appPath('webpack.config.js'));

const preprocessor = production => ({
    PRODUCTION: production,
    DEVELOPMENT: !production
});

const ifdef = (opts, block) => (context, utils) => prevConfig => {
    let conf = block(context, utils)(prevConfig);
    const index = conf.module.rules
        .map(
            (r, i) =>
                !Array.isArray(r.test) &&
                r.test.test('name.ts') &&
                r.enforce !== 'pre'
                    ? i
                    : -1
        )
        .reduce((acc, curr) => (acc === -1 && curr !== -1 ? curr : acc), -1);
    conf.module.rules[index].use.push({
        loader: 'ifdef-loader',
        options: opts
    });
    return conf;
};

const tsIfDef = production =>
    ifdef(
        preprocessor(production),
        typescript({
            useCache: true,
            cacheDirectory: 'node_modules/.cache/at-loader'
        })
    );

module.exports = createConfig([
    customConfig(userConfig),
    tslint(),
    match(
        ['*.scss', '*.sass'],
        [
            sass({
                includePaths: [appPath('node_modules')],
                sourceMap: true
            }),
            postcss({
                plugins: [autoprefixer({ browsers: ['last 2 versions'] })]
            }),
            env('production', [extractText('[name].[contenthash:8].css')])
        ]
    ),
    match(['*.eot', '*.ttf', '*.woff', '*.woff2'], [file()]),
    match(
        ['*.gif', '*.jpg', '*.jpeg', '*.png', '*.svg', '*.webp'],
        [url({ limit: 10000 })]
    ),
    defineConstants({
        'process.env.NODE_ENV': process.env.NODE_ENV
    }),
    addPlugins([
        new HtmlWebpackPlugin({
            template: './index.ejs',
            inject: true,
            favicon: 'public/favicon.png',
            hash: true
        }),
        new webpack.ProvidePlugin({
            Snabbdom: 'snabbdom-pragma'
        })
    ]),
    env('development', [
        tsIfDef(false),
        devServer(),
        sourceMaps(),
        addPlugins([new webpack.NamedModulesPlugin()])
    ]),
    env('production', [
        tsIfDef(true),
        uglify({
            parallel: true,
            cache: true,
            uglifyOptions: {
                compress: {
                    warnings: false
                }
            }
        }),
        addPlugins([
            new CleanWebpackPlugin([appPath('build')], {
                root: process.cwd()
            }),
            new CopyWebpackPlugin([{ from: 'public', to: '' }])
        ])
    ]),
    env('test', [tsIfDef(true)])
]);
<commit_msg>Fix `userConfig` not overwriting flavor config<commit_after>const {
    createConfig,
    defineConstants,
    env,
    entryPoint,
    setOutput,
    sourceMaps,
    addPlugins,
    devServer,
    postcss,
    sass,
    css,
    typescript,
    extractText,
    customConfig,
    uglify,
    match,
    file,
    url
} = require('webpack-blocks');
const webpackMerge = require('webpack-merge');
const tslint = require('@webpack-blocks/tslint');
const autoprefixer = require('autoprefixer');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

const path = require('path');
const fs = require('fs');

const appPath = (...names) => path.join(process.cwd(), ...names);
const userConfig = require(appPath('webpack.config.js'));

const preprocessor = production => ({
    PRODUCTION: production,
    DEVELOPMENT: !production
});

const ifdef = (opts, block) => (context, utils) => prevConfig => {
    let conf = block(context, utils)(prevConfig);
    const index = conf.module.rules
        .map(
            (r, i) =>
                !Array.isArray(r.test) &&
                r.test.test('name.ts') &&
                r.enforce !== 'pre'
                    ? i
                    : -1
        )
        .reduce((acc, curr) => (acc === -1 && curr !== -1 ? curr : acc), -1);
    conf.module.rules[index].use.push({
        loader: 'ifdef-loader',
        options: opts
    });
    return conf;
};

const tsIfDef = production =>
    ifdef(
        preprocessor(production),
        typescript({
            useCache: true,
            cacheDirectory: 'node_modules/.cache/at-loader'
        })
    );

module.exports = webpackMerge(createConfig([
    tslint(),
    match(
        ['*.scss', '*.sass'],
        [
            sass({
                includePaths: [appPath('node_modules')],
                sourceMap: true
            }),
            postcss({
                plugins: [autoprefixer({ browsers: ['last 2 versions'] })]
            }),
            env('production', [extractText('[name].[contenthash:8].css')])
        ]
    ),
    match(['*.eot', '*.ttf', '*.woff', '*.woff2'], [file()]),
    match(
        ['*.gif', '*.jpg', '*.jpeg', '*.png', '*.svg', '*.webp'],
        [url({ limit: 10000 })]
    ),
    defineConstants({
        'process.env.NODE_ENV': process.env.NODE_ENV
    }),
    addPlugins([
        new HtmlWebpackPlugin({
            template: './index.ejs',
            inject: true,
            favicon: 'public/favicon.png',
            hash: true
        }),
        new webpack.ProvidePlugin({
            Snabbdom: 'snabbdom-pragma'
        })
    ]),
    env('development', [
        tsIfDef(false),
        devServer(),
        sourceMaps(),
        addPlugins([new webpack.NamedModulesPlugin()])
    ]),
    env('production', [
        tsIfDef(true),
        uglify({
            parallel: true,
            cache: true,
            uglifyOptions: {
                compress: {
                    warnings: false
                }
            }
        }),
        addPlugins([
            new CleanWebpackPlugin([appPath('build')], {
                root: process.cwd()
            }),
            new CopyWebpackPlugin([{ from: 'public', to: '' }])
        ])
    ]),
    env('test', [tsIfDef(true)])
]), userConfig);
<|endoftext|>