<commit_before>/**
 * Copyright 2014-2016 Nicholas Humfrey
 * Copyright 2013 IBM Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

module.exports = function(RED) {
    "use strict";
    var owfs = require("owfs");
    var Promise = require("bluebird");

    var dirallslash = Promise.promisify(
        owfs.Client.prototype.dirallslash
    );

    function recursiveDirall(client, path, blacklist) {
        return dirallslash.call(client, path).then(function(entries) {
            return Promise.filter(entries, function(entry) {
                // Filter out any paths that match the blacklist
                return !blacklist || !entry.match(blacklist);
            }).mapSeries(function(entry) {
                // We use mapSeries, to prevent lots of concurrent connections to owfs
                if (entry.slice(-1) == '/') {
                    return recursiveDirall(client, entry, blacklist);
                } else {
                    return entry;
                }
            });
        });
    }

    function flattenArrayOfArrays(a, r) {
        if (!r) r = [];
        a.forEach(function(item) {
            if (Array.isArray(item)) {
                flattenArrayOfArrays(item, r);
            } else {
                r.push(item);
            }
        });
        return r;
    }

    function OwfsNode(n) {
        RED.nodes.createNode(this, n);
        this.host = n.host;
        this.port = n.port;
        this.paths = n.paths;
        this.uncached = n.uncached;

        var node = this;
        node.on("input", function(msg) {
            var host = msg.host || node.host;
            var port = msg.port || node.port || 4304;
            var uncached = msg.hasOwnProperty('uncached') ? msg.uncached : node.uncached;
            if (!host || host.length < 1) {
                node.warn("missing host configuration and not provided by msg.host");
                node.status({fill:"red", shape:"ring", text:"No host"});
                return;
            }

            var paths = msg.topic || node.paths;
            if (!Array.isArray(paths)) {
                paths = [paths];
            }
            if (!paths || paths.length < 1) {
                node.warn("no owfs paths configured and msg.topic is empty");
                node.status({fill:"red", shape:"ring", text:"No path"});
                return;
            }

            var client = new owfs.Client(host, port);
            var clientRead = Promise.promisify(client.read, {context: client});

            var performRequest = function(path) {
                if (uncached) {
                    return clientRead('uncached/' + path);
                } else {
                    return clientRead(path);
                }
            }

            var sendResult = function(result, index) {
                if (result.match(/^\-?\d+\.\d+$/)) {
                    msg.payload = parseFloat(result);
                } else if (result.match(/^\-?\d+$/)) {
                    msg.payload = parseInt(result);
                } else {
                    msg.payload = result;
                }
                msg.topic = paths[index];
                msg.timestamp = Date.now();
                node.send(msg);
            };

            node.status({fill:"blue", shape:"dot", text:"Reading"});

            Promise
                .mapSeries(paths, performRequest)
                .each(sendResult)
                .then(function() {
                    node.status({});
                })
                .catch(function(error) {
                    node.status({fill:"red", shape:"ring", text:"Error"});
                    if ('msg' in error) {
                        node.error(error.msg, msg);
                    } else {
                        node.error(error, msg);
                    }
                });
        });
    }
    RED.nodes.registerType("owfs", OwfsNode);

    RED.httpAdmin.get("/owfs/dirall", function(req, res) {
        if (!req.query.host) {
            return res.status(400).send({
                'error': "Missing 'host' parameter in query string"
            });
        } else if (!req.query.port) {
            return res.status(400).send({
                'error': "Missing 'port' parameter in query string"
            });
        }

        var blacklist = new RegExp("/(?:address|crc8|errata/|family|id|locator|pages/|r_[a-z]+)$");
        var client = new owfs.Client(req.query.host, req.query.port);

        recursiveDirall(client, "/", blacklist)
            .then(function(paths) {
                res.send({
                    'deviceCount': paths.length,
                    'paths': flattenArrayOfArrays(paths).map(function(path) {
                        // Strip off the first slash - MQTT style
                        return path.substr(1)
                    })
                });
            })
            .catch(function(error) {
                res.send({
                    'error': error.message
                });
            });
    });
}
<commit_msg>Moved result parsing code to separate parseResult() function<commit_after>/**
 * Copyright 2014-2016 Nicholas Humfrey
 * Copyright 2013 IBM Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

module.exports = function(RED) {
    "use strict";
    var owfs = require("owfs");
    var Promise = require("bluebird");

    var dirallslash = Promise.promisify(
        owfs.Client.prototype.dirallslash
    );

    function recursiveDirall(client, path, blacklist) {
        return dirallslash.call(client, path).then(function(entries) {
            return Promise.filter(entries, function(entry) {
                // Filter out any paths that match the blacklist
                return !blacklist || !entry.match(blacklist);
            }).mapSeries(function(entry) {
                // We use mapSeries, to prevent lots of concurrent connections to owfs
                if (entry.slice(-1) == '/') {
                    return recursiveDirall(client, entry, blacklist);
                } else {
                    return entry;
                }
            });
        });
    }

    function flattenArrayOfArrays(a, r) {
        if (!r) r = [];
        a.forEach(function(item) {
            if (Array.isArray(item)) {
                flattenArrayOfArrays(item, r);
            } else {
                r.push(item);
            }
        });
        return r;
    }

    function parseResult(result) {
        if (typeof result.match === 'function') {
            if (result.match(/^\-?\d+\.\d+$/)) {
                return parseFloat(result);
            } else if (result.match(/^\-?\d+$/)) {
                return parseInt(result);
            }
        }
        return result;
    }

    function OwfsNode(n) {
        RED.nodes.createNode(this, n);
        this.host = n.host;
        this.port = n.port;
        this.paths = n.paths;
        this.uncached = n.uncached;

        var node = this;
        node.on("input", function(msg) {
            var host = msg.host || node.host;
            var port = msg.port || node.port || 4304;
            var uncached = msg.hasOwnProperty('uncached') ? msg.uncached : node.uncached;
            if (!host || host.length < 1) {
                node.warn("missing host configuration and not provided by msg.host");
                node.status({fill:"red", shape:"ring", text:"No host"});
                return;
            }

            var paths = msg.topic || node.paths;
            if (!Array.isArray(paths)) {
                paths = [paths];
            }
            if (!paths || paths.length < 1) {
                node.warn("no owfs paths configured and msg.topic is empty");
                node.status({fill:"red", shape:"ring", text:"No path"});
                return;
            }

            var client = new owfs.Client(host, port);
            var clientRead = Promise.promisify(client.read, {context: client});

            var performRequest = function(path) {
                if (uncached) {
                    return clientRead('uncached/' + path);
                } else {
                    return clientRead(path);
                }
            }

            var sendResult = function(result, index) {
                msg.payload = parseResult(result);
                msg.topic = paths[index];
                msg.timestamp = Date.now();
                node.send(msg);
            };

            node.status({fill:"blue", shape:"dot", text:"Reading"});

            Promise
                .mapSeries(paths, performRequest)
                .each(sendResult)
                .then(function() {
                    node.status({});
                })
                .catch(function(error) {
                    node.status({fill:"red", shape:"ring", text:"Error"});
                    if ('msg' in error) {
                        node.error(error.msg, msg);
                    } else {
                        node.error(error, msg);
                    }
                });
        });
    }
    RED.nodes.registerType("owfs", OwfsNode);

    RED.httpAdmin.get("/owfs/dirall", function(req, res) {
        if (!req.query.host) {
            return res.status(400).send({
                'error': "Missing 'host' parameter in query string"
            });
        } else if (!req.query.port) {
            return res.status(400).send({
                'error': "Missing 'port' parameter in query string"
            });
        }

        var blacklist = new RegExp("/(?:address|crc8|errata/|family|id|locator|pages/|r_[a-z]+)$");
        var client = new owfs.Client(req.query.host, req.query.port);

        recursiveDirall(client, "/", blacklist)
            .then(function(paths) {
                res.send({
                    'deviceCount': paths.length,
                    'paths': flattenArrayOfArrays(paths).map(function(path) {
                        // Strip off the first slash - MQTT style
                        return path.substr(1)
                    })
                });
            })
            .catch(function(error) {
                res.send({
                    'error': error.message
                });
            });
    });
}
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs'),
    os = require('os');

var FileSystem = require('../../lib/file-system');

var BASE64_ENCODED =
      'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby' +
      'blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC';

var TEST_FILE_PATH = os.tmpdir() + '/camunda-modeler.fs.test';

describe('FileSystem', function() {

  var fileSystem;

  beforeEach(function() {
    fileSystem = new FileSystem({
      dialog: {}
    });
  });

  after(function() {
    try {
      fs.unlinkSync(TEST_FILE_PATH);
    } catch (e) { /** YEA */ }
  });

  it('should write BASE64 encoded file', function() {

    var file = {
      contents: BASE64_ENCODED
    };

    // when
    fileSystem.writeFile(TEST_FILE_PATH, file);

    var readFile = fileSystem.readFile(TEST_FILE_PATH, 'base64');

    // then
    expect(readFile.contents).to.match(/iVBOR/);
  });

  it('should write UTF8 encoded file', function() {

    var file = {
      contents: 'FOO BAR'
    };

    // when
    fileSystem.writeFile(TEST_FILE_PATH, file);

    var readFile = fileSystem.readFile(TEST_FILE_PATH);

    // then
    expect(readFile.contents).to.eql('FOO BAR');
  });

  it('should strip whitespace in read file', function() {

    var file = {
      contents: '  FOO BAR  \r\n\n'
    };

    // when
    fileSystem.writeFile(TEST_FILE_PATH, file);

    var readFile = fileSystem.readFile(TEST_FILE_PATH);

    // then
    expect(readFile.contents).to.eql('FOO BAR');
  });

  describe('should set last modified property', function() {

    it('on read', function() {
      // given
      var file = {
        contents: 'FOO BAR'
      };

      file = fileSystem.writeFile(TEST_FILE_PATH, file);
      // HFS+ tracks seconds only
      file.lastModified -= 1000;

      // when
      var updatedFile = fileSystem.readFile(TEST_FILE_PATH);

      // then
      expect(updatedFile.lastModified).to.be.above(file.lastModified);
    });

    it('on write', function() {
      // given
      var file = {
        contents: 'FOO BAR',
        // HFS+ tracks seconds only
        lastModified: new Date().getTime() - 1000
      };

      // when
      var newFile = fileSystem.writeFile(TEST_FILE_PATH, file);

      // then
      expect(newFile.lastModified).to.be.above(file.lastModified);
    });

  });

  describe('readFileStats', function() {

    it('should set last modified property on existing file', function() {
      // given
      var file = {
        path: TEST_FILE_PATH
      };

      // when
      var statsFile = fileSystem.readFileStats(file);

      // then
      expect(statsFile).to.have.property('lastModified').above(0);
    });

    it('should set last modified property to "0" if file is not accesible', function() {
      // given
      var file = {
        path: TEST_FILE_PATH + '.does-not-exist.xml'
      };

      // when
      var statsFile = fileSystem.readFileStats(file);

      // then
      expect(statsFile).to.have.property('lastModified').eql(0);
    });

  });

});
<commit_msg>test(file-system): make read file stats test independent<commit_after>'use strict';

var fs = require('fs'),
    os = require('os');

var FileSystem = require('../../lib/file-system');

var BASE64_ENCODED =
      'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby' +
      'blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC';

var TEST_FILE_PATH = os.tmpdir() + '/camunda-modeler.fs.test';

describe('FileSystem', function() {

  var fileSystem;

  beforeEach(function() {
    fileSystem = new FileSystem({
      dialog: {}
    });
  });

  afterEach(function() {
    try {
      fs.unlinkSync(TEST_FILE_PATH);
    } catch (e) { /** YEA */ }
  });

  it('should write BASE64 encoded file', function() {

    var file = {
      contents: BASE64_ENCODED
    };

    // when
    fileSystem.writeFile(TEST_FILE_PATH, file);

    var readFile = fileSystem.readFile(TEST_FILE_PATH, 'base64');

    // then
    expect(readFile.contents).to.match(/iVBOR/);
  });

  it('should write UTF8 encoded file', function() {

    var file = {
      contents: 'FOO BAR'
    };

    // when
    fileSystem.writeFile(TEST_FILE_PATH, file);

    var readFile = fileSystem.readFile(TEST_FILE_PATH);

    // then
    expect(readFile.contents).to.eql('FOO BAR');
  });

  it('should strip whitespace in read file', function() {

    var file = {
      contents: '  FOO BAR  \r\n\n'
    };

    // when
    fileSystem.writeFile(TEST_FILE_PATH, file);

    var readFile = fileSystem.readFile(TEST_FILE_PATH);

    // then
    expect(readFile.contents).to.eql('FOO BAR');
  });

  describe('should set last modified property', function() {

    it('on read', function() {
      // given
      var file = {
        contents: 'FOO BAR'
      };

      file = fileSystem.writeFile(TEST_FILE_PATH, file);
      // HFS+ tracks seconds only
      file.lastModified -= 1000;

      // when
      var updatedFile = fileSystem.readFile(TEST_FILE_PATH);

      // then
      expect(updatedFile.lastModified).to.be.above(file.lastModified);
    });

    it('on write', function() {
      // given
      var file = {
        contents: 'FOO BAR',
        // HFS+ tracks seconds only
        lastModified: new Date().getTime() - 1000
      };

      // when
      var newFile = fileSystem.writeFile(TEST_FILE_PATH, file);

      // then
      expect(newFile.lastModified).to.be.above(file.lastModified);
    });

  });

  describe('readFileStats', function() {

    beforeEach(function(done) {
      fs.writeFile(TEST_FILE_PATH, '', function(error) {
        done(error);
      });
    });

    it('should set last modified property on existing file', function() {
      // given
      var file = {
        path: TEST_FILE_PATH
      };

      // when
      var statsFile = fileSystem.readFileStats(file);

      // then
      expect(statsFile).to.have.property('lastModified').above(0);
    });

    it('should set last modified property to "0" if file is not accesible', function() {
      // given
      var file = {
        path: TEST_FILE_PATH + '.does-not-exist.xml'
      };

      // when
      var statsFile = fileSystem.readFileStats(file);

      // then
      expect(statsFile).to.have.property('lastModified').eql(0);
    });

  });

});
<|endoftext|>


<commit_before>

var DiscoverView = function() {

    this.initialize = function() {
        // 'div' wrapper to attach html and events to
        this.el = $('<div/>');
    };

    this.render = function() {
	if (!this.homeView) {
	    this.homeView = { enteredName:  "" }
	}

	var discover_view = DiscoverView.template(this.homeView);
        this.el.html(discover);

	this.scan();

        return this;
    };

    this.scan = function() {
        var self = this;

        console.log('scan(): init');
        // documentation said the syntax was this:
        // var scanner = window.PhoneGap.require("cordova/plugin/BarcodeScanner");
        // but playing with options, seems like it should be this:
        //var scanner = window.cordova.require("cordova/plugin/BarcodeScanner");

	if (!window.cordova) {
            app.showAlert("Barcode Scanner not supported", "Error");
            return;
        }

	cordova.plugins.barcodeScanner.scan(
                function (result) {

		    var inner_template = Handlebars.compile($("#"+result.text+"-tpl").html());
		    var inner_html     = inner_template(self.homeView);

		    $('#info-page').html(inner_html);

                    app.showAlert("Result: " + result.text + "\n"
				  + "Format: " + result.format + "\n"
				  + "Cancelled: " + result.cancelled,
				  "We got a barcode");
                },
                function (error) {
                    app.showAlert(err,"Scanning failed: ");
                }
        );
    };

    this.initialize();

}

DiscoverView.template = Handlebars.compile($("#discover-tpl").html());

<commit_msg>Typo fix<commit_after>

var DiscoverView = function() {

    this.initialize = function() {
        // 'div' wrapper to attach html and events to
        this.el = $('<div/>');
    };

    this.render = function() {
	if (!this.homeView) {
	    this.homeView = { enteredName:  "" }
	}

	var discover_view = DiscoverView.template(this.homeView);
        this.el.html(discover);

	this.scan();

        return this;
    };

    this.scan = function() {
        var self = this;

        console.log('scan(): init');
        // documentation said the syntax was this:
        // var scanner = window.PhoneGap.require("cordova/plugin/BarcodeScanner");
        // but playing with options, seems like it should be this:
        //var scanner = window.cordova.require("cordova/plugin/BarcodeScanner");

	if (!window.cordova) {
            app.showAlert("Barcode Scanner not supported", "Error");
            return;
        }

	cordova.plugins.barcodeScanner.scan(
                function (result) {

		    var inner_template = Handlebars.compile($("#"+result.text+"-tpl").html());
		    var inner_html     = inner_template.template(self.homeView);

		    $('#info-page').html(inner_html);

                    app.showAlert("Result: " + result.text + "\n"
				  + "Format: " + result.format + "\n"
				  + "Cancelled: " + result.cancelled,
				  "We got a barcode");
                },
                function (error) {
                    app.showAlert(err,"Scanning failed: ");
                }
        );
    };

    this.initialize();

}

DiscoverView.template = Handlebars.compile($("#discover-tpl").html());

<|endoftext|>


<commit_before>// See: https://gist.github.com/xiaodaigh/6445698
var swichTab = function(tabId, i) {
    tabs = $(tabId).find('li');
    tabs.each(function() {
        $(this).removeClass('active')
    });
    $(tabs[i]).addClass('active');
    tabsContents = $(tabId).next('.tab-content').children('.tab-pane');
    tabsContents.each(function() {
        $(this).removeClass('active')
    });
    $(tabsContents[i]).addClass('active');
}

function initTour() {

    var steps = [{
            content: '
Welcome...
',
            target: [50, 120],
            nextButton: true,
            my: 'bottom left'
    }, {
        content: [
            '
Choose expression dataset to upload.
',
            '
It should contain a sinlge column with gene names ',
            'followed by the  expression profiles.
',
            '
If you want to test this app you can use ',
            '',
            'expression_example.csv.
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#datain_container'),
        my: 'top left',
        at: 'bottom center',
    }, {
        content: [
            '
Select input file separator
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#sep'),
        my: 'bottom center',
        at: 'top center'
    }, {
        content: [
            '
Check if file has been loaded as expected.
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#datain_preview'),
        my: 'bottom center',
        at: 'top center'
    }, {
        content: [
            '
Choose control samples
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#control_samples'),
        my: 'bottom center',
        at: 'top center'
    }, {
        content: [
            '
If you prefer you can use disease signature dataset ',
            'obtained from the Gene Expression Omnibus
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#datain_type'),
        my: 'top left',
        at: 'bottom right',
        teardown: function(tour, options) {
            $('input:radio[name=datain_type]').filter('[value=disease]').trigger('click');
        }
    }, {
        content: [
            '
Add preprocessing steps
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#datain_preprocessing'),
        my: 'bottom center',
        at: 'top center'
    }, {
        content: [
            '
Switch to the Characteristic Direction Analysis
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#workflow_panel'),
        my: 'top center',
        at: 'bottom center',
        teardown: function(tour, options) {
            swichTab('#workflow_panel', 1);
        }
    }, {
        content: [
            '
Check input data summary
'
        ].join(''),
        nextButton: true,
        closeButton: true,
        target: $('#chdir_input_summary'),
        my: 'bottom center',
        at: 'bottom center'
    }, {
        content: [
            '
Set parameters...
'
        ].join(''),
        nextButton: true,
        closeButton: true,
        target: $('#chdir_parameters'),
        my: 'bottom center',
        at: 'bottom center'
    }, {
        content: [
            '
...and run chdir
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#run_chdir_container'),
        my: 'bottom center',
        at: 'top center'
    }, {
        content: [
            '
When chdir analysis is finished ',
            'you can download the results...
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#chdir_downloads'),
        my: 'bottom center',
        at: 'bottom center'
    }, {
        content: [
            '
... and start PAE analysis
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#workflow_panel'),
        my: 'bottom center',
        at: 'bottom center',
        teardown: function(tour, options) {
            swichTab('#workflow_panel', 2);
        }
    }, {
        content: [
            '
To run PAEA click Run Principle Angle Enrichment
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#run_paea_container'),
        my: 'bottom center',
        at: 'top center'
    }, {
        content: [
            '
When PAEA is ready results will be shown below
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#pae_results'),
        my: 'top left',
        at: 'top left'
    },  {
        content: [
            '
... and will be available for download
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#paea_downloads'),
        my: 'top left',
        at: 'top left'
    }];

    var tour = new Tourist.Tour({
        steps: steps,
        tipClass: 'Bootstrap',
        tipOptions:{ showEffect: 'slidein' }
    });
    tour.start();
}

$(document).ready(function() {
    $('#start_tour').click(initTour);
})<commit_msg>Add enrichr step<commit_after>// See: https://gist.github.com/xiaodaigh/6445698
var swichTab = function(tabId, i) {
    tabs = $(tabId).find('li');
    tabs.each(function() {
        $(this).removeClass('active')
    });
    $(tabs[i]).addClass('active');
    tabsContents = $(tabId).next('.tab-content').children('.tab-pane');
    tabsContents.each(function() {
        $(this).removeClass('active')
    });
    $(tabsContents[i]).addClass('active');
}

function initTour() {

    var steps = [{
            content: '
Welcome...
',
            target: [50, 120],
            nextButton: true,
            my: 'bottom left'
    }, {
        content: [
            '
Choose expression dataset to upload.
',
            '
It should contain a sinlge column with gene names ',
            'followed by the  expression profiles.
',
            '
If you want to test this app you can use ',
            '',
            'expression_example.csv.
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#datain_container'),
        my: 'top left',
        at: 'bottom center',
    }, {
        content: [
            '
Select input file separator
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#sep'),
        my: 'bottom center',
        at: 'top center'
    }, {
        content: [
            '
Check if file has been loaded as expected.
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#datain_preview'),
        my: 'bottom center',
        at: 'top center'
    }, {
        content: [
            '
Choose control samples
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#control_samples'),
        my: 'bottom center',
        at: 'top center'
    }, {
        content: [
            '
If you prefer you can use disease signature dataset ',
            'obtained from the Gene Expression Omnibus
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#datain_type'),
        my: 'top left',
        at: 'bottom right',
        teardown: function(tour, options) {
            $('input:radio[name=datain_type]').filter('[value=disease]').trigger('click');
        }
    }, {
        content: [
            '
Add preprocessing steps
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#datain_preprocessing'),
        my: 'bottom center',
        at: 'top center'
    }, {
        content: [
            '
Switch to the Characteristic Direction Analysis
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#workflow_panel'),
        my: 'top center',
        at: 'bottom center',
        teardown: function(tour, options) {
            swichTab('#workflow_panel', 1);
        }
    }, {
        content: [
            '
Check input data summary
'
        ].join(''),
        nextButton: true,
        closeButton: true,
        target: $('#chdir_input_summary'),
        my: 'bottom center',
        at: 'bottom center'
    }, {
        content: [
            '
Set parameters...
'
        ].join(''),
        nextButton: true,
        closeButton: true,
        target: $('#chdir_parameters'),
        my: 'bottom center',
        at: 'bottom center'
    }, {
        content: [
            '
...and run chdir
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#run_chdir_container'),
        my: 'bottom center',
        at: 'top center'
    }, {
        content: [
            '
When chdir analysis is finished ',
            'you can download the results...
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#chdir_downloads'),
        my: 'bottom center',
        at: 'bottom center'
    }, {
        content: [
            '
...send results to the Enrichr...
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#enrichr_form'),
        my: 'top center',
        at: 'bottom center'
    }, {
        content: [
            '
or start PAE analysis
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#workflow_panel'),
        my: 'bottom center',
        at: 'bottom center',
        teardown: function(tour, options) {
            swichTab('#workflow_panel', 2);
        }
    }, {
        content: [
            '
To run PAEA click Run Principle Angle Enrichment
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#run_paea_container'),
        my: 'bottom center',
        at: 'top center'
    }, {
        content: [
            '
When PAEA is ready results will be shown below
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#pae_results'),
        my: 'top left',
        at: 'top left'
    },  {
        content: [
            '
... and will be available for download
'
        ].join(''),
        highlightTarget: true,
        nextButton: true,
        closeButton: true,
        target: $('#paea_downloads'),
        my: 'top left',
        at: 'top left'
    }];

    var tour = new Tourist.Tour({
        steps: steps,
        tipClass: 'Bootstrap',
        tipOptions:{ showEffect: 'slidein' }
    });
    tour.start();
}

$(document).ready(function() {
    $('#start_tour').click(initTour);
})<|endoftext|>


<commit_before>/* eslint strict: 0, no-shadow: 0, no-unused-vars: 0, no-console: 0 */
'use strict';

const os = require('os');
const webpack = require('webpack');
const cfg = require('./webpack-config/production.js');
const packager = require('electron-packager');
const del = require('del');
const exec = require('child_process').exec;
const argv = require('minimist')(process.argv.slice(2));
const pkg = require('./package.json');
const devDeps = Object.keys(pkg.devDependencies);

const appName = pkg.productName;
const shouldUseAsar = argv.asar || argv.a || false;
const shouldBuildAll = argv.all || false;

const DEFAULT_OPTS = {
  dir: './',
  name: appName,
  asar: shouldUseAsar,
  ignore: [
    '/test($|/)',
    '/tools($|/)',
    '/release($|/)',
    '/config($|/)',
    '/webpack-config($|/)',
    '/node_modules($|/)',
  ]
};

const version = argv.version || argv.v;

if (version) {
  DEFAULT_OPTS.version = version;
  startPack();
} else {
  // use the same version as the currently-installed electron-prebuilt
  exec('npm list electron-prebuilt', (err, stdout) => {
    if (err) {
      DEFAULT_OPTS.version = '0.36.7';
    } else {
      DEFAULT_OPTS.version = stdout.split('electron-prebuilt@')[1].replace(/\s/g, '');
    }

    startPack();
  });
}

function startPack() {
  console.log('start pack...');
  webpack(cfg, (err, stats) => {
    if (err) return console.error(err);
    del('release')
    .then(paths => {
      if (shouldBuildAll) {
        // build for all platforms
        const archs = ['ia32', 'x64'];
        const platforms = ['linux', 'win32', 'darwin'];

        platforms.forEach(plat => {
          archs.forEach(arch => {
            pack(plat, arch, log(plat, arch));
          });
        });
      } else {
        // build for current platform only
        pack(os.platform(), os.arch(), log(os.platform(), os.arch()));
      }
    })
    .catch(err => {
      console.error(err);
    });
  });
}

function pack(plat, arch, cb) {
  // there is no darwin ia32 electron
  if (plat === 'darwin' && arch === 'ia32') return;

  let icon;
  if (plat === 'darwin') {
    icon = 'resources/osx/icon.icns';
  } else if (plat === 'win32') {
    icon = 'resources/windows/icon.ico'
  } else if (plat === 'linux') {
    icon = 'resources/linux/icon.png';
  }

  const iconObj = {icon};

  const opts = Object.assign({}, DEFAULT_OPTS, iconObj, {
    platform: plat,
    arch,
    prune: true,
    out: `release/${pkg.name}-${plat}-${arch}-${pkg.version}`,
    "app-version": pkg.version
  });

  packager(opts, cb);
}

function log(plat, arch) {
  return (err, filepath) => {
    if (err) return console.error(err);
    console.log(`${plat}-${arch} finished!`);
  };
}
<commit_msg>update electron version<commit_after>/* eslint strict: 0, no-shadow: 0, no-unused-vars: 0, no-console: 0 */
'use strict';

const os = require('os');
const webpack = require('webpack');
const cfg = require('./webpack-config/production.js');
const packager = require('electron-packager');
const del = require('del');
const exec = require('child_process').exec;
const argv = require('minimist')(process.argv.slice(2));
const pkg = require('./package.json');
const devDeps = Object.keys(pkg.devDependencies);

const appName = pkg.productName;
const shouldUseAsar = argv.asar || argv.a || false;
const shouldBuildAll = argv.all || false;

const DEFAULT_OPTS = {
  dir: './',
  name: appName,
  asar: shouldUseAsar,
  ignore: [
    '/test($|/)',
    '/tools($|/)',
    '/release($|/)',
    '/config($|/)',
    '/webpack-config($|/)',
    '/node_modules($|/)',
  ]
};

const version = argv.version || argv.v;

if (version) {
  DEFAULT_OPTS.version = version;
  startPack();
} else {
  // use the same version as the currently-installed electron-prebuilt
  exec('npm list electron-prebuilt', (err, stdout) => {
    if (err) {
      DEFAULT_OPTS.version = '0.37.2';
    } else {
      DEFAULT_OPTS.version = stdout.split('electron-prebuilt@')[1].replace(/\s/g, '');
    }

    startPack();
  });
}

function startPack() {
  console.log('start pack...');
  webpack(cfg, (err, stats) => {
    if (err) return console.error(err);
    del('release')
    .then(paths => {
      if (shouldBuildAll) {
        // build for all platforms
        const archs = ['ia32', 'x64'];
        const platforms = ['linux', 'win32', 'darwin'];

        platforms.forEach(plat => {
          archs.forEach(arch => {
            pack(plat, arch, log(plat, arch));
          });
        });
      } else {
        // build for current platform only
        pack(os.platform(), os.arch(), log(os.platform(), os.arch()));
      }
    })
    .catch(err => {
      console.error(err);
    });
  });
}

function pack(plat, arch, cb) {
  // there is no darwin ia32 electron
  if (plat === 'darwin' && arch === 'ia32') return;

  let icon;
  if (plat === 'darwin') {
    icon = 'resources/osx/icon.icns';
  } else if (plat === 'win32') {
    icon = 'resources/windows/icon.ico'
  } else if (plat === 'linux') {
    icon = 'resources/linux/icon.png';
  }

  const iconObj = {icon};

  const opts = Object.assign({}, DEFAULT_OPTS, iconObj, {
    platform: plat,
    arch,
    prune: true,
    out: `release/${pkg.name}-${plat}-${arch}-${pkg.version}`,
    "app-version": pkg.version
  });

  packager(opts, cb);
}

function log(plat, arch) {
  return (err, filepath) => {
    if (err) return console.error(err);
    console.log(`${plat}-${arch} finished!`);
  };
}
<|endoftext|>


<commit_before>/**
 * SetupFormUA component stories.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import { STORE_NAME } from '../../datastore/constants';
import { MODULES_ANALYTICS_4 } from '../../../analytics-4/datastore/constants';
import { provideModules, provideModuleRegistrations, provideSiteInfo } from '../../../../../../tests/js/utils';
import ModuleSetup from '../../../../components/setup/ModuleSetup';
import WithRegistrySetup from '../../../../../../tests/js/WithRegistrySetup';
import * as fixtures from '../../datastore/__fixtures__';

export const Ready = () => <ModuleSetup moduleSlug="analytics" />;
Ready.storyName = 'SetupFormUA';
Ready.decorators = [
	( Story ) => {
		const setupRegistry = ( registry ) => {
			const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
			const accountID = accounts[ 0 ].id;
			const propertyID = properties[ 0 ].id;

			registry.dispatch( STORE_NAME ).receiveGetSettings( { adsConversionID: '' } );
			registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts.slice( 0, 1 ) );
			registry.dispatch( STORE_NAME ).receiveGetProperties(
				// eslint-disable-next-line sitekit/acronym-case
				properties.slice( 0, 1 ).map( ( property ) => ( { ...property, websiteUrl: 'http://example.com' } ) ),
				{ accountID },
			);
			registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, { accountID, propertyID } );
			registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );
			registry.dispatch( MODULES_ANALYTICS_4 ).receiveGetProperties( [], { accountID } );
			registry.dispatch( STORE_NAME ).selectAccount( accountID );
		};

		return (
			<WithRegistrySetup func={ setupRegistry }>
				<Story />
			</WithRegistrySetup>
		);
	},
];
Ready.parameters = {
	features: [
		'ga4setup',
	],
};

export default {
	title: 'Modules/Analytics/Setup/SetupFormUA',
	decorators: [
		( Story ) => {
			const setupRegistry = ( registry ) => {
				provideModules( registry, [
					{
						slug: 'analytics',
						active: true,
						connected: true,
					},
					{
						slug: 'analytics-4',
						active: true,
						connected: true,
					},
				] );

				provideSiteInfo( registry );
				provideModuleRegistrations( registry );
			};

			return (
				<WithRegistrySetup func={ setupRegistry }>
					<Story />
				</WithRegistrySetup>
			);
		},
	],
};
<commit_msg>Update stories for the SetupFormUA component.<commit_after>/**
 * SetupFormUA component stories.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import { STORE_NAME } from '../../datastore/constants';
import { MODULES_ANALYTICS_4 } from '../../../analytics-4/datastore/constants';
import { provideModules, provideModuleRegistrations, provideSiteInfo } from '../../../../../../tests/js/utils';
import ModuleSetup from '../../../../components/setup/ModuleSetup';
import WithRegistrySetup from '../../../../../../tests/js/WithRegistrySetup';
import * as fixtures from '../../datastore/__fixtures__';

const features = [ 'ga4setup' ];

function Template() {
	return <ModuleSetup moduleSlug="analytics" />;
}

export const WithoutExistingTag = Template.bind( null );
WithoutExistingTag.storyName = 'Without Existing Tag';
WithoutExistingTag.parameters = { features };

export const WithExistingTag = Template.bind( null );
WithExistingTag.storyName = 'With Existing Tag';
WithExistingTag.parameters = { features };
WithExistingTag.decorators = [
	( Story ) => {
		const setupRegistry = ( registry ) => {
			registry.dispatch( STORE_NAME ).receiveGetExistingTag( fixtures.accountsPropertiesProfiles.properties[ 0 ].id );
		};

		return (
			<WithRegistrySetup func={ setupRegistry }>
				<Story />
			</WithRegistrySetup>
		);
	},
];

export default {
	title: 'Modules/Analytics/Setup/SetupFormUA',
	decorators: [
		( Story ) => {
			const setupRegistry = ( registry ) => {
				const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles;
				const accountID = accounts[ 0 ].id;
				const propertyID = properties[ 0 ].id;

				provideModules( registry, [
					{
						slug: 'analytics',
						active: true,
						connected: true,
					},
					{
						slug: 'analytics-4',
						active: true,
						connected: true,
					},
				] );

				provideSiteInfo( registry );
				provideModuleRegistrations( registry );

				registry.dispatch( STORE_NAME ).receiveGetSettings( { adsConversionID: '' } );
				registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts.slice( 0, 1 ) );
				registry.dispatch( STORE_NAME ).receiveGetProperties(
					// eslint-disable-next-line sitekit/acronym-case
					properties.slice( 0, 1 ).map( ( property ) => ( { ...property, websiteUrl: 'http://example.com' } ) ),
					{ accountID },
				);
				registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, { accountID, propertyID } );
				registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );
				registry.dispatch( MODULES_ANALYTICS_4 ).receiveGetProperties( [], { accountID } );
				registry.dispatch( STORE_NAME ).selectAccount( accountID );
			};

			return (
				<WithRegistrySetup func={ setupRegistry }>
					<Story />
				</WithRegistrySetup>
			);
		},
	],
};
<|endoftext|>


<commit_before>/* eslint-disable quote-props */
'use strict';
const pify = require('pify');
const packager = require('electron-packager');
const hardRejection = require('hard-rejection');
const pkg = require('./package.json');
const electronCfg = require('./webpack.config.electron');

hardRejection();

const deps = Object.keys(pkg.dependencies);
const devDeps = Object.keys(pkg.devDependencies);

const ignoredDeps = deps
	.filter(name => !electronCfg.externals.includes(name))
	.map(name => `/node_modules/${name}($|/)`);
const ignoredDevDeps = devDeps.map(name => `/node_modules/${name}($|/)`);

const ignore = [
	'^/test($|/)',
	'^/release($|/)',
	'^/media($|/)',
	'^/static($|/)',
	'^/webpack+?',
	'^/pack.js$',
	'^/interface($|/)',
	'^/CSSFlowStub.js.flow',
	'^/main.development.js',
	...ignoredDevDeps,
	...ignoredDeps
];

function pack(target) {
	const buildOpts = {
		macos: {
			platform: 'darwin',
			arch: 'x64',
			icon: 'static/Icon.icns',
			'app-bundle-id': 'io.github.akameco.pixivdeck',
			'osx-sign': true
		},
		windows: {
			platform: 'win32',
			arch: 'ia32',
			icon: 'static/Icon.ico',
			'app-bundle-id': 'io.github.akameco.pixivdeck'
		},
		linux: {
			platform: 'linux',
			arch: 'x64',
			icon: 'static/Icon.png',
			'version-string.ProductName': pkg.productName
		}
	};

	const pkgOpt = Object.assign({
		dir: './',
		name: pkg.productName,
		asar: true,
		'app-version': pkg.version,
		overwrite: true,
		prune: true,
		out: 'release',
		ignore
	}, buildOpts[target]);

	return pify(packager)(pkgOpt);
}

const input = process.argv.slice(2)[0];

if (!input || !['macos', 'windows', 'linux'].includes(input)) {
	console.error('input required');
	process.exit(1); // eslint-disable-line xo/no-process-exit
}

pack(input);
<commit_msg>Add metadata for Windows<commit_after>/* eslint-disable quote-props */
'use strict';
const pify = require('pify');
const packager = require('electron-packager');
const hardRejection = require('hard-rejection');
const pkg = require('./package.json');
const electronCfg = require('./webpack.config.electron');

hardRejection();

const deps = Object.keys(pkg.dependencies);
const devDeps = Object.keys(pkg.devDependencies);

const ignoredDeps = deps
	.filter(name => !electronCfg.externals.includes(name))
	.map(name => `/node_modules/${name}($|/)`);
const ignoredDevDeps = devDeps.map(name => `/node_modules/${name}($|/)`);

const ignore = [
	'^/test($|/)',
	'^/release($|/)',
	'^/media($|/)',
	'^/static($|/)',
	'^/webpack+?',
	'^/pack.js$',
	'^/interface($|/)',
	'^/CSSFlowStub.js.flow',
	'^/main.development.js',
	...ignoredDevDeps,
	...ignoredDeps
];

function pack(target) {
	const buildOpts = {
		macos: {
			platform: 'darwin',
			arch: 'x64',
			icon: 'static/Icon.icns',
			'app-bundle-id': 'io.github.akameco.pixivdeck',
			'osx-sign': true
		},
		windows: {
			platform: 'win32',
			arch: 'ia32',
			icon: 'static/Icon.ico',
			'app-bundle-id': 'io.github.akameco.pixivdeck',
			win32metadata: {
				FileDescription: pkg.productName
			}
		},
		linux: {
			platform: 'linux',
			arch: 'x64',
			icon: 'static/Icon.png',
			'version-string.ProductName': pkg.productName
		}
	};

	const pkgOpt = Object.assign({
		dir: './',
		name: pkg.productName,
		asar: true,
		'app-version': pkg.version,
		overwrite: true,
		prune: true,
		out: 'release',
		ignore
	}, buildOpts[target]);

	return pify(packager)(pkgOpt);
}

const input = process.argv.slice(2)[0];

if (!input || !['macos', 'windows', 'linux'].includes(input)) {
	console.error('input required');
	process.exit(1); // eslint-disable-line xo/no-process-exit
}

pack(input);
<|endoftext|>


<commit_before>export default (config) => {
};<commit_msg>examples: update<commit_after>export default (config) => {
  config.set('views', {
    root: config.viewsPath
  });
};<|endoftext|>


<commit_before>'use strict';

class TimelineEngine {
    /**
     * @param  {Renderer} renderer
     * @param  {Legend} legend
     * @param  {Element} threshold
     * @param  {Object} request
     * @param  {Number} eventHeight
     * @param  {Number} horizontalMargin
     */
    constructor(renderer, legend, threshold, request, eventHeight = 36, horizontalMargin = 10) {
        this.renderer = renderer;
        this.legend = legend;
        this.threshold = threshold;
        this.request = request;
        this.scale = renderer.width / request.end;
        this.eventHeight = eventHeight;
        this.horizontalMargin = horizontalMargin;
        this.labelY = Math.round(this.eventHeight * 0.48);
        this.periodY = Math.round(this.eventHeight * 0.66);
        this.FqcnMatcher = /\\([^\\]+)$/i;
        this.origin = null;

        this.createEventElements = this.createEventElements.bind(this);
        this.createBackground = this.createBackground.bind(this);
        this.createPeriod = this.createPeriod.bind(this);
        this.render = this.render.bind(this);
        this.renderEvent = this.renderEvent.bind(this);
        this.renderPeriod = this.renderPeriod.bind(this);
        this.onResize = this.onResize.bind(this);
        this.isActive = this.isActive.bind(this);

        this.threshold.addEventListener('change', this.render);
        this.legend.addEventListener('change', this.render);

        window.addEventListener('resize', this.onResize);

        this.createElements();
        this.render();
    }

    onResize() {
        this.renderer.measure();
        this.setScale(this.renderer.width / this.request.end);
    }

    setScale(scale) {
        if (scale !== this.scale) {
            this.scale = scale;
            this.render();
        }
    }

    createElements() {
        this.origin = this.renderer.setFullVerticalLine(this.createBorder(), 0);
        this.renderer.add(this.origin);

        this.request.events
            .filter(event => event.category === 'section')
            .map(this.createBackground)
            .forEach(this.renderer.add);

        this.request.events
            .map(this.createEventElements)
            .forEach(this.renderer.add);
    }

    createBackground(event) {
        const subrequest = event.name === '__section__.child';
        const background = this.renderer.create('rect', subrequest ? 'timeline-subrequest' : 'timeline-border');

        event.elements = Object.assign(event.elements || {}, { background });

        return background;
    }

    createEventElements(event) {
        const { name, category, duration, memory, periods } = event;
        const border = this.renderer.setFullHorizontalLine(this.createBorder(), 0);
        const lines = periods.map(period => this.createPeriod(period, category));
        const label = this.createLabel(this.getShortName(name), duration, memory, periods[0]);
        const title = this.renderer.createTitle(name);
        const group = this.renderer.group([title, border, label].concat(lines), this.legend.getClassname(event.category));

        event.elements = Object.assign(event.elements || {}, { group, label, border });

        this.legend.add(event.category)

        return group;
    }

    createLabel(name, duration, memory, period) {
        const label = this.renderer.createText(name, period.start * this.scale, this.labelY, 'timeline-label');
        const sublabel = this.renderer.createTspan(`  ${duration} ms / ${memory} Mb`, 'timeline-sublabel');

        label.appendChild(sublabel);

        return label;
    }

    createPeriod(period, category) {
        const timeline = this.renderer.createPath(null, 'timeline-period');

        period.draw = category === 'section' ? this.renderer.setSectionLine : this.renderer.setPeriodLine;
        period.elements = Object.assign(period.elements || {}, { timeline });

        return timeline;
    }

    createBorder() {
        return this.renderer.createPath(null, 'timeline-border');
    }

    isActive(event) {
        const { duration, category } = event;

        return duration >= this.threshold.value && this.legend.isActive(category);
    }

    render() {
        const events = this.request.events.filter(this.isActive);
        const width = this.renderer.width + this.horizontalMargin * 2;
        const height = this.eventHeight * events.length;

        // Set view box
        this.renderer.setViewBox(-this.horizontalMargin, 0, width, height);

        // Show 0ms origin
        this.renderer.setFullVerticalLine(this.origin, 0);

        // Render all events
        this.request.events.forEach(event => this.renderEvent(event, events.indexOf(event)));
    }

    renderEvent(event, index) {
        const { name, category, duration, memory, periods, elements } = event;
        const { group, label, border, background } = elements;
        const visible = index >= 0;

        group.setAttribute('visibility', visible ? 'visible' : 'hidden');

        if (background) {
            background.setAttribute('visibility', visible ? 'visible' : 'hidden');

            if (visible) {
                const [min, max] = this.getEventLimits(event);

                this.renderer.setFullRectangle(background, min * this.scale, max * this.scale);
            }
        }

        if (visible) {
            // Position the group
            group.setAttribute('transform', `translate(0, ${index * this.eventHeight})`);

            // Update top border
            this.renderer.setFullHorizontalLine(border, 0);

            // render label and ensure it doesn't escape the viewport
            this.renderLabel(label, event);

            // Update periods
            periods.forEach(this.renderPeriod);
        }
    }

    renderLabel(label, event) {
        const width = this.getLabelWidth(label);
        const [min, max] = this.getEventLimits(event);
        const alignLeft = (min * this.scale) + width <= this.renderer.width;

        label.setAttribute('x', (alignLeft ? min : max) * this.scale);
        label.setAttribute('text-anchor', alignLeft ? 'start' : 'end');
    }

    renderPeriod(period) {
        const { elements, start, duration } = period;

        period.draw(elements.timeline, start * this.scale, this.periodY, Math.max(duration * this.scale, 1));
    }

    getLabelWidth(label) {
        if (typeof label.width === 'undefined') {
            label.width = label.getBBox().width;
        }

        return label.width;
    }

    getEventLimits(event) {
        if (typeof event.limits === 'undefined') {
            const { periods } = event;

            event.limits = [
                periods[0].start,
                periods[periods.length - 1].end
            ];
        }

        return event.limits;
    }

    getShortName(name) {
        const matches = this.FqcnMatcher.exec(name);

        if (matches) {
            return matches[1];
        }

        return name;
    }
}

class Legend {
    constructor(element, classnames) {
        this.element = element;
        this.classnames = classnames;

        this.toggle = this.toggle.bind(this);
        this.createCategory = this.createCategory.bind(this);

        this.categories = Array.from(Object.keys(classnames)).map(this.createCategory);
    }

    add(category) {
        this.get(category).classList.add('present');
    }

    createCategory(category) {
        const element = document.createElement('button');

        element.className = `timeline-category ${this.getClassname(category)} active`;
        element.innerText = category;
        element.value = category;
        element.type = 'button';
        element.addEventListener('click', this.toggle);

        this.element.appendChild(element);

        return element;
    }

    toggle(event) {
        event.target.classList.toggle('active');

        this.emit('change');
    }

    isActive(category) {
        return this.get(category).classList.contains('active');
    }

    get(category) {
        return this.categories.find(element => element.value === category);
    }

    getClassname(category) {
        return this.classnames[category];
    }

    getSectionClassname() {
        return this.classnames.section;
    }

    getDefaultClassname() {
        return this.classnames.default;
    }

    getStandardClassenames() {
        return Array.from(Object.values(this.classnames))
            .filter(className => className !== this.getSectionClassname());
    }

    emit(name) {
        this.element.dispatchEvent(new Event(name));
    }

    addEventListener(name, callback) {
        this.element.addEventListener(name, callback);
    }

    removeEventListener(name, callback) {
        this.element.removeEventListener(name, callback);
    }
}

class SvgRenderer {
    /**
     * @param  {SVGElement} element
     */
    constructor(element) {
        this.ns = 'http://www.w3.org/2000/svg';
        this.width = null;
        this.viewBox = {};
        this.element = element;

        this.add = this.add.bind(this);

        this.setViewBox(0, 0, 0, 0);
        this.measure();
    }

    setViewBox(x, y, width, height) {
        this.viewBox = { x, y, width, height };
        this.element.setAttribute('viewBox', `${x} ${y} ${width} ${height}`);
    }

    measure() {
        this.width = this.element.getBoundingClientRect().width;
    }

    add(element) {
        this.element.appendChild(element);
    }

    group(elements, className) {
        const group = this.create('g', className);

        elements.forEach(element => group.appendChild(element));

        return group;
    }

    setHorizontalLine(element, x, y, width) {
        element.setAttribute('d', `M${x},${y} h${width}`);

        return element;
    }

    setVerticalLine(element, x, y, height) {
        element.setAttribute('d', `M${x},${y} v${height}`);

        return element;
    }

    setFullHorizontalLine(element, y) {
        return this.setHorizontalLine(element, this.viewBox.x, y, this.viewBox.width);
    }

    setFullVerticalLine(element, x) {
        return this.setVerticalLine(element, x, this.viewBox.y, this.viewBox.height);
    }

    setFullRectangle(element, min, max) {
        element.setAttribute('x', min);
        element.setAttribute('y', this.viewBox.y);
        element.setAttribute('width', max - min);
        element.setAttribute('height', this.viewBox.height);
    }

    setSectionLine(element, x, y, width, height = 4, markerSize = 6) {
        const totalHeight = height + markerSize;
        const maxMarkerWidth = Math.min(markerSize, width / 2);
        const widthWithoutMarker = Math.max(0, width - (maxMarkerWidth * 2));

        element.setAttribute('d', `M${x},${y + totalHeight} v${-totalHeight} h${width} v${totalHeight} l${-maxMarkerWidth} ${-markerSize} h${-widthWithoutMarker} Z`);
    }

    setPeriodLine(element, x, y, width, height = 4, markerWidth = 2, markerHeight = 4) {
        const totalHeight = height + markerHeight;
        const maxMarkerWidth = Math.min(markerWidth, width);

        element.setAttribute('d', `M${x + maxMarkerWidth},${y + totalHeight} h${-maxMarkerWidth} v${-totalHeight} h${width} v${height} h${maxMarkerWidth-width}Z`);
    }

    createText(content, x, y, className) {
        const element = this.create('text', className);

        element.setAttribute('x', x);
        element.setAttribute('y', y);
        element.textContent = content;

        return element;
    }

    createTspan(content, className) {
        const element = this.create('tspan', className);

        element.textContent = content;

        return element;
    }

    createTitle(content) {
        const element = this.create('title');

        element.textContent = content;

        return element;
    }

    createPath(path = null, className = null) {
        const element = this.create('path', className);

        if (path) {
            element.setAttribute('d', path);
        }

        return element;
    }

    create(name, className = null) {
        const element = document.createElementNS(this.ns, name);

        if (className) {
            element.setAttribute('class', className);
        }

        return element;
    }
}
<commit_msg>[WebProfiler] Fix Javascript error when using custom stopwatch categories<commit_after>'use strict';

class TimelineEngine {
    /**
     * @param  {Renderer} renderer
     * @param  {Legend} legend
     * @param  {Element} threshold
     * @param  {Object} request
     * @param  {Number} eventHeight
     * @param  {Number} horizontalMargin
     */
    constructor(renderer, legend, threshold, request, eventHeight = 36, horizontalMargin = 10) {
        this.renderer = renderer;
        this.legend = legend;
        this.threshold = threshold;
        this.request = request;
        this.scale = renderer.width / request.end;
        this.eventHeight = eventHeight;
        this.horizontalMargin = horizontalMargin;
        this.labelY = Math.round(this.eventHeight * 0.48);
        this.periodY = Math.round(this.eventHeight * 0.66);
        this.FqcnMatcher = /\\([^\\]+)$/i;
        this.origin = null;

        this.createEventElements = this.createEventElements.bind(this);
        this.createBackground = this.createBackground.bind(this);
        this.createPeriod = this.createPeriod.bind(this);
        this.render = this.render.bind(this);
        this.renderEvent = this.renderEvent.bind(this);
        this.renderPeriod = this.renderPeriod.bind(this);
        this.onResize = this.onResize.bind(this);
        this.isActive = this.isActive.bind(this);

        this.threshold.addEventListener('change', this.render);
        this.legend.addEventListener('change', this.render);

        window.addEventListener('resize', this.onResize);

        this.createElements();
        this.render();
    }

    onResize() {
        this.renderer.measure();
        this.setScale(this.renderer.width / this.request.end);
    }

    setScale(scale) {
        if (scale !== this.scale) {
            this.scale = scale;
            this.render();
        }
    }

    createElements() {
        this.origin = this.renderer.setFullVerticalLine(this.createBorder(), 0);
        this.renderer.add(this.origin);

        this.request.events
            .filter(event => event.category === 'section')
            .map(this.createBackground)
            .forEach(this.renderer.add);

        this.request.events
            .map(this.createEventElements)
            .forEach(this.renderer.add);
    }

    createBackground(event) {
        const subrequest = event.name === '__section__.child';
        const background = this.renderer.create('rect', subrequest ? 'timeline-subrequest' : 'timeline-border');

        event.elements = Object.assign(event.elements || {}, { background });

        return background;
    }

    createEventElements(event) {
        const { name, category, duration, memory, periods } = event;
        const border = this.renderer.setFullHorizontalLine(this.createBorder(), 0);
        const lines = periods.map(period => this.createPeriod(period, category));
        const label = this.createLabel(this.getShortName(name), duration, memory, periods[0]);
        const title = this.renderer.createTitle(name);
        const group = this.renderer.group([title, border, label].concat(lines), this.legend.getClassname(event.category));

        event.elements = Object.assign(event.elements || {}, { group, label, border });

        this.legend.add(event.category)

        return group;
    }

    createLabel(name, duration, memory, period) {
        const label = this.renderer.createText(name, period.start * this.scale, this.labelY, 'timeline-label');
        const sublabel = this.renderer.createTspan(`  ${duration} ms / ${memory} Mb`, 'timeline-sublabel');

        label.appendChild(sublabel);

        return label;
    }

    createPeriod(period, category) {
        const timeline = this.renderer.createPath(null, 'timeline-period');

        period.draw = category === 'section' ? this.renderer.setSectionLine : this.renderer.setPeriodLine;
        period.elements = Object.assign(period.elements || {}, { timeline });

        return timeline;
    }

    createBorder() {
        return this.renderer.createPath(null, 'timeline-border');
    }

    isActive(event) {
        const { duration, category } = event;

        return duration >= this.threshold.value && this.legend.isActive(category);
    }

    render() {
        const events = this.request.events.filter(this.isActive);
        const width = this.renderer.width + this.horizontalMargin * 2;
        const height = this.eventHeight * events.length;

        // Set view box
        this.renderer.setViewBox(-this.horizontalMargin, 0, width, height);

        // Show 0ms origin
        this.renderer.setFullVerticalLine(this.origin, 0);

        // Render all events
        this.request.events.forEach(event => this.renderEvent(event, events.indexOf(event)));
    }

    renderEvent(event, index) {
        const { name, category, duration, memory, periods, elements } = event;
        const { group, label, border, background } = elements;
        const visible = index >= 0;

        group.setAttribute('visibility', visible ? 'visible' : 'hidden');

        if (background) {
            background.setAttribute('visibility', visible ? 'visible' : 'hidden');

            if (visible) {
                const [min, max] = this.getEventLimits(event);

                this.renderer.setFullRectangle(background, min * this.scale, max * this.scale);
            }
        }

        if (visible) {
            // Position the group
            group.setAttribute('transform', `translate(0, ${index * this.eventHeight})`);

            // Update top border
            this.renderer.setFullHorizontalLine(border, 0);

            // render label and ensure it doesn't escape the viewport
            this.renderLabel(label, event);

            // Update periods
            periods.forEach(this.renderPeriod);
        }
    }

    renderLabel(label, event) {
        const width = this.getLabelWidth(label);
        const [min, max] = this.getEventLimits(event);
        const alignLeft = (min * this.scale) + width <= this.renderer.width;

        label.setAttribute('x', (alignLeft ? min : max) * this.scale);
        label.setAttribute('text-anchor', alignLeft ? 'start' : 'end');
    }

    renderPeriod(period) {
        const { elements, start, duration } = period;

        period.draw(elements.timeline, start * this.scale, this.periodY, Math.max(duration * this.scale, 1));
    }

    getLabelWidth(label) {
        if (typeof label.width === 'undefined') {
            label.width = label.getBBox().width;
        }

        return label.width;
    }

    getEventLimits(event) {
        if (typeof event.limits === 'undefined') {
            const { periods } = event;

            event.limits = [
                periods[0].start,
                periods[periods.length - 1].end
            ];
        }

        return event.limits;
    }

    getShortName(name) {
        const matches = this.FqcnMatcher.exec(name);

        if (matches) {
            return matches[1];
        }

        return name;
    }
}

class Legend {
    constructor(element, classnames) {
        this.element = element;
        this.classnames = classnames;

        this.toggle = this.toggle.bind(this);
        this.createCategory = this.createCategory.bind(this);

        this.categories = Array.from(Object.keys(classnames)).map(this.createCategory);
    }

    add(category) {
        this.get(category).classList.add('present');
    }

    createCategory(category) {
        const element = document.createElement('button');

        element.className = `timeline-category ${this.getClassname(category)} active`;
        element.innerText = category;
        element.value = category;
        element.type = 'button';
        element.addEventListener('click', this.toggle);

        this.element.appendChild(element);

        return element;
    }

    toggle(event) {
        event.target.classList.toggle('active');

        this.emit('change');
    }

    isActive(category) {
        return this.get(category).classList.contains('active');
    }

    get(category) {
        return this.categories.find(element => element.value === category) || this.createCategory(category);
    }

    getClassname(category) {
        return this.classnames[category] || '';
    }

    getSectionClassname() {
        return this.classnames.section;
    }

    getDefaultClassname() {
        return this.classnames.default;
    }

    getStandardClassenames() {
        return Array.from(Object.values(this.classnames))
            .filter(className => className !== this.getSectionClassname());
    }

    emit(name) {
        this.element.dispatchEvent(new Event(name));
    }

    addEventListener(name, callback) {
        this.element.addEventListener(name, callback);
    }

    removeEventListener(name, callback) {
        this.element.removeEventListener(name, callback);
    }
}

class SvgRenderer {
    /**
     * @param  {SVGElement} element
     */
    constructor(element) {
        this.ns = 'http://www.w3.org/2000/svg';
        this.width = null;
        this.viewBox = {};
        this.element = element;

        this.add = this.add.bind(this);

        this.setViewBox(0, 0, 0, 0);
        this.measure();
    }

    setViewBox(x, y, width, height) {
        this.viewBox = { x, y, width, height };
        this.element.setAttribute('viewBox', `${x} ${y} ${width} ${height}`);
    }

    measure() {
        this.width = this.element.getBoundingClientRect().width;
    }

    add(element) {
        this.element.appendChild(element);
    }

    group(elements, className) {
        const group = this.create('g', className);

        elements.forEach(element => group.appendChild(element));

        return group;
    }

    setHorizontalLine(element, x, y, width) {
        element.setAttribute('d', `M${x},${y} h${width}`);

        return element;
    }

    setVerticalLine(element, x, y, height) {
        element.setAttribute('d', `M${x},${y} v${height}`);

        return element;
    }

    setFullHorizontalLine(element, y) {
        return this.setHorizontalLine(element, this.viewBox.x, y, this.viewBox.width);
    }

    setFullVerticalLine(element, x) {
        return this.setVerticalLine(element, x, this.viewBox.y, this.viewBox.height);
    }

    setFullRectangle(element, min, max) {
        element.setAttribute('x', min);
        element.setAttribute('y', this.viewBox.y);
        element.setAttribute('width', max - min);
        element.setAttribute('height', this.viewBox.height);
    }

    setSectionLine(element, x, y, width, height = 4, markerSize = 6) {
        const totalHeight = height + markerSize;
        const maxMarkerWidth = Math.min(markerSize, width / 2);
        const widthWithoutMarker = Math.max(0, width - (maxMarkerWidth * 2));

        element.setAttribute('d', `M${x},${y + totalHeight} v${-totalHeight} h${width} v${totalHeight} l${-maxMarkerWidth} ${-markerSize} h${-widthWithoutMarker} Z`);
    }

    setPeriodLine(element, x, y, width, height = 4, markerWidth = 2, markerHeight = 4) {
        const totalHeight = height + markerHeight;
        const maxMarkerWidth = Math.min(markerWidth, width);

        element.setAttribute('d', `M${x + maxMarkerWidth},${y + totalHeight} h${-maxMarkerWidth} v${-totalHeight} h${width} v${height} h${maxMarkerWidth-width}Z`);
    }

    createText(content, x, y, className) {
        const element = this.create('text', className);

        element.setAttribute('x', x);
        element.setAttribute('y', y);
        element.textContent = content;

        return element;
    }

    createTspan(content, className) {
        const element = this.create('tspan', className);

        element.textContent = content;

        return element;
    }

    createTitle(content) {
        const element = this.create('title');

        element.textContent = content;

        return element;
    }

    createPath(path = null, className = null) {
        const element = this.create('path', className);

        if (path) {
            element.setAttribute('d', path);
        }

        return element;
    }

    create(name, className = null) {
        const element = document.createElementNS(this.ns, name);

        if (className) {
            element.setAttribute('class', className);
        }

        return element;
    }
}
<|endoftext|>


<commit_before>document.addEventListener("online",  function(){
    document.getElementById('onlineTest').innerHTML = "

Online";
}, false);

document.addEventListener("offline",  function(){
    document.getElementById('onlineTest').innerHTML = "

Offline";
}, false);

document.addEventListener("deviceready", function(){
    document.getElementById('readyTest').innerHTML = "

deviceready";

}, false);

var pWatchId;

var element = document.getElementById('permaCheck');

function getPCurGeoData() {

    var options = {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge:120000
    };

    pWatchId = navigator.geolocation.watchPosition(onPermGeoDataSuccess, getPCurGeoError, options);

}

function getPCurGeoError(error) {

    var d;

    d = new Date();

    var span_date = 'Zeit: ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + ' ';

    element.innerHTML = 'Permanent Error '+ span_date + '

'+ element.innerHTML;

}

function onPermGeoDataSuccess(position) {

    var d = new Date();
    //console.log(getTime() + " setGeoData r_key => " + r_key);

    var span_date = 'Zeit: ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() +'';

    element.innerHTML = 'Success | '+ span_date      + '
' +
        'Lat: '          + position.coords.latitude          + ' | ' +
        'Long: '         + position.coords.longitude         + '
' +
        'Acc: '          + position.coords.accuracy          + ' | ' +
        'Alt: '          + position.coords.altitude          + ' | ' +
        'Alt Acc: '      + position.coords.altitudeAccuracy  + '
' +
        'Heading: '      + position.coords.heading           + '|' +
        'Speed: '        + position.coords.speed             + '

'+ element.innerHTML;

}<commit_msg>Commit<commit_after>var pWatchId;
var element = document.getElementById('permaCheck');

function getPCurGeoData() {
    var options = {
        enableHighAccuracy: false,
        timeout: 10000,
        maximumAge:120000
    };

    pWatchId = navigator.geolocation.watchPosition(onPermGeoDataSuccess, getPCurGeoError, options);
}

function getPCurGeoError(error) {
    var d = new Date();
    var span_date = 'Zeit: ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + ' ';

    element.innerHTML = 'Permanent Error '+ span_date + '

'+ element.innerHTML;
}

function onPermGeoDataSuccess(position) {
    var d = new Date();
    var span_date = 'Zeit: ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() +'';

    element.innerHTML = 'Success | '+ span_date      + '
' +
        'Lat: '          + position.coords.latitude          + ' | ' +
        'Long: '         + position.coords.longitude         + '
' +
        'Acc: '          + position.coords.accuracy          + ' | ' +
        'Alt: '          + position.coords.altitude          + ' | ' +
        'Alt Acc: '      + position.coords.altitudeAccuracy  + '
' +
        'Heading: '      + position.coords.heading           + '|' +
        'Speed: '        + position.coords.speed             + '

'+ element.innerHTML;
}<|endoftext|>


<commit_before>'use strict';

define(['dust/core', 'lib/utils'], function(dust, utils) {

    var bypassExtensions = ['.ico'];
    dust.filters.amp = function(string) {
        if (utils.isServer) {

            string = string.replace(/<img([^>]*)>/g, function(all, attr) {
                var bypass = false;
                attr = attr.replace(/src\w*=\w*("|')([^\"\']+)("|')/g, function(at, qt, src) {
                    var chunks = [],
                        size = {height: -1, width: -1},
                        found = false;

                    for(var i=0, count = bypassExtensions.length; i < count; i++) {
                        if(src.substr(src.length-4) === bypassExtensions[i]) {
                            bypass = true;
                        }
                    }
                    if(bypass) {
                        return at;
                    }
                    try {
                        if (src.substr(0, 4).toLowerCase() !== 'http') {
                            src = 'http:' + src;
                        }

                        var imageSize = require('image-size'),
                            request = require('request');

                        var r = request.get({uri: src})
                            .on('data', function (chunk) {
                                chunks.push(chunk);
                                if (chunks.length > 2) {
                                    r.abort();
                                }
                            }).on('end', function() {
                                var buffer = Buffer.concat(chunks);
                                size = imageSize(buffer);
                                found = true;
                            });
                        setTimeout(function() { found = true; }, 150);
                        while (!found) {
                            require('deasync').runLoopOnce();
                        }
                    } catch (err) {
                        if (GLOBAL && GLOBAL.liveblogLogger) {
                            liveblogLogger.info('ERROR amp request: %s', err);
                        }
                    }
                    return 'src="' + src + '" height="' + size.height + '" width="' + size.width + '"';
                });
                if(bypass) {
                    return all;
                }
                return '<amp-img layout="responsive"' + attr + '/>';
            });

            return string;
        }
        return string;
    };
    return dust;
});
<commit_msg>chore: jscs style issues fixed.<commit_after>'use strict';

define(['dust/core', 'lib/utils'], function(dust, utils) {

    var bypassExtensions = ['.ico'];
    dust.filters.amp = function(string) {
        if (utils.isServer) {

            string = string.replace(/<img([^>]*)>/g, function(all, attr) {
                var bypass = false;
                attr = attr.replace(/src\w*=\w*("|')([^\"\']+)("|')/g, function(at, qt, src) {
                    var chunks = [],
                        size = {height: -1, width: -1},
                        found = false;

                    for (var i = 0, count = bypassExtensions.length; i < count; i++) {
                        if (src.substr(src.length - 4) === bypassExtensions[i]) {
                            bypass = true;
                        }
                    }
                    if (bypass) {
                        return at;
                    }
                    try {
                        if (src.substr(0, 4).toLowerCase() !== 'http') {
                            src = 'http:' + src;
                        }

                        var imageSize = require('image-size'),
                            request = require('request');

                        var r = request.get({uri: src})
                            .on('data', function (chunk) {
                                chunks.push(chunk);
                                if (chunks.length > 2) {
                                    r.abort();
                                }
                            }).on('end', function() {
                                var buffer = Buffer.concat(chunks);
                                size = imageSize(buffer);
                                found = true;
                            });
                        setTimeout(function() { found = true; }, 150);
                        while (!found) {
                            require('deasync').runLoopOnce();
                        }
                    } catch (err) {
                        if (GLOBAL && GLOBAL.liveblogLogger) {
                            liveblogLogger.info('ERROR amp request: %s', err);
                        }
                    }
                    return 'src="' + src + '" height="' + size.height + '" width="' + size.width + '"';
                });
                if (bypass) {
                    return all;
                }
                return '<amp-img layout="responsive"' + attr + '/>';
            });

            return string;
        }
        return string;
    };
    return dust;
});
<|endoftext|>