<commit_before>var oscviewer = (function() {

    function buildFidMap(features) {
        var map = {};
        for(var i=0, len=features.length; i < len; i++) {
            map[features[i].fid] = features[i];
        }
        return map;
    }

    function setActions(oscFeatures, osmFeatures) {
        var i;
        var oscFeature, osmFeature;
        var action;
        //var oscFeatures = oscLayer.features;
        var versionDiff;
        //var osmFeatures = [];

        var oscFeaturesFidMap = buildFidMap(oscFeatures);
        var osmFeaturesFidMap = buildFidMap(osmFeatures);

        var oscOnly = osmFeatures.length === 0;

        // Overpass diffs: distinguish deletes from old versions (before setting actions from osc!)
        for (i = 0; i < osmFeatures.length; i++) {
            osmFeature = osmFeatures[i];
            if (osmFeature.attributes['action'] === 'erase') {
                oscFeature = oscFeaturesFidMap[osmFeature.fid];
                if (oscFeature) {
                    // in 'insert' section = old version of modified object, remove 'erase'
                    delete osmFeature.attributes['action'];
                } else {
                    // replace action string 'erase' with 'delete'
                    osmFeature.attributes['action'] = 'delete';
                    setHasTags(osmFeature, null);
                }
            } else if (osmFeature.attributes['action'] === 'keep') {
			    // set common action for referenced objects (for styling)
				osmFeature.attributes['action'] = 'augment';
			}
        }

        for (i = 0; i < oscFeatures.length; i++) {
            oscFeature = oscFeatures[i];
            osmFeature = null;

            action = oscFeature.attributes['action'];

            if (!(oscOnly || action === 'create')) {
                osmFeature = osmFeaturesFidMap[oscFeature.fid];

                if (action === 'modify' || action === 'delete') {
                    if (osmFeature) {
                        // set action to old object
                        if (action === 'modify') {
                            setModifyAction(osmFeature, oscFeature);
                        } else {
                            osmFeature.attributes['action'] = action;
                        }
                    } else {
                        console.warn('Feature "' + oscFeature.fid + '" not found');
                    }
                } else if (action === 'insert') {
                    // Overpass diffs
                    if (osmFeature) {
                        // modify
                        setModifyAction(osmFeature, oscFeature);
                    } else {
                        // create
                        oscFeature.attributes['action'] = 'create';
                    }
                }
            }

            setHasTags(osmFeature, oscFeature);
        }
    }

    function setModifyAction(osmFeature, oscFeature) {
        var action = oscFeature.geometry.equals(osmFeature.geometry) ? 'modify' : 'modify:geometry';
        osmFeature.attributes['action'] = action;
        oscFeature.attributes['action'] = action;
    }

    function getHasTags(feature) {
        var result = false;
        for (var attr in feature.attributes) {
            if (!isMetaAttribute(attr)) {
                result = true;
                break;
            }
        }
        return result;
    }

    function setHasTags(osmFeature, oscFeature) {
        var osmHasTags = false;
        if (osmFeature) {
            osmHasTags = getHasTags(osmFeature);
            osmFeature.hasTags = osmHasTags;
        }
        if (oscFeature) {
            // also indicate that the old feature had tags, when the changed feature has none
            oscFeature.hasTags = osmHasTags || getHasTags(oscFeature);
        }
    }

    function isMetaAttribute(attr) {
        var metaAttrs = OpenLayers.Format.OSC.prototype.metaAttributes;
        return OpenLayers.Util.indexOf(metaAttrs, attr) !== -1;
    }

    function getInfoHtml(oldFeature, changeFeature) {
        var keys = [];
        var oldTags = undefined;
        var changeTags = undefined;
        var feature = changeFeature || oldFeature;
        var osm = {
            id : feature.osm_id,
            type : getOsmType(feature)
        };
        var action = feature.attributes['action'] || '';

        var infoHtml = '';
        infoHtml += '
';
        infoHtml += '
';
        infoHtml += '
';
        // modify:geometry -> modify_geometry for CSS
        infoHtml += '';
        infoHtml += action;
        infoHtml += '';
        infoHtml += ' ' + osm.type;
        infoHtml += ' ' + formatOsmLink(osm.id, osm.type);
        infoHtml += '
';

        if (!oldFeature && action != 'create') {
            infoHtml += '
Warning: Old feature not found,
probably not included in OSM file
';
        }

        infoHtml += '
';

        if (oldFeature) {
            oldTags = oldFeature.attributes;
            keys = _.keys(oldTags);
        }
        if (changeFeature) {
            changeTags = changeFeature.attributes;
            keys = keys.concat(_.keys(changeTags));
        }
        keys = _.filter(keys, function(key) {
            return !isMetaAttribute(key);
        });
        keys.sort();
        keys = _.unique(keys, true);

        infoHtml += printMeta('timestamp', oldTags, changeTags, formatIsoDateTime);
        infoHtml += printMeta('user', oldTags, changeTags, formatOsmLink);
        infoHtml += printMeta('version', oldTags, changeTags);
        infoHtml += printMeta('changeset', oldTags, changeTags, formatOsmLink);

        infoHtml += '

';
        infoHtml += printKeys(keys, oldTags, changeTags, action);

        infoHtml += '
';
        infoHtml += '
';
        infoHtml += '
';

        return infoHtml;
    }

    function getOsmType(feature) {
        return feature.fid.substring(0, feature.fid.indexOf('.'));
    }

    function formatIsoDateTime(dateTimeString) {
        return moment(dateTimeString).format('L LT');
    }

    function formatOsmLink(val, type) {
        var path = (type === 'user') ? '' : 'browse/';
        return '' + val + '';
    }

    function printMeta(key, oldTags, changeTags, format) {
        var infoHtml = '';
        if (!format) {
            // dummy
            format = function(val) {
                return val;
            };
        }
        infoHtml += '
' + key + '	';
        if (oldTags) {
            infoHtml += '' + format(oldTags[key], key) + '	';
        }
        if (changeTags) {
            infoHtml += '' + format(changeTags[key], key) + '	';
        }
        infoHtml += '
';
        return infoHtml;
    }

    function printKeys(keys, oldTags, changeTags, action) {
        var i;
        var oldVal, changeVal;
        var classes;
        var infoHtml = '';
        for (i = 0; i < keys.length; i++) {
            key = keys[i];
            oldVal = oldTags && oldTags[key];
            changeVal = changeTags && changeTags[key];
            classes = getClasses(oldVal, changeVal, action);
            infoHtml += '
' + key + '	';
            if (oldTags) {
                infoHtml += '' + val(oldVal) + '	';
            }
            if (changeTags) {
                infoHtml += '' + val(changeVal) + '	';
            }
            infoHtml += '
';
        }
        return infoHtml;
    }

    function getClasses(oldVal, changeVal, action) {
        var c = {
            key : 'keydefault',
            old : 'default',
            change : 'default'
        };
        if (_.isUndefined(oldVal)) {
            c.key = 'created';
            c.old = 'undefined';
            c.change = 'created';
        } else if (_.isUndefined(changeVal)) {
            // default on delete, because tags themselves are unchanged
            if (action !== 'delete') {
                c.key = 'deleted';
                c.old = 'deleted';
            }
            c.change = 'undefined';
        } else if (oldVal !== changeVal) {
            c.old = 'modified';
            c.change = 'modified';
        }

        return c;
    }

    function val(value) {
        return _.isUndefined(value) ? '' : value;
    }

    return {
        setActions : setActions,
        getInfoHtml: getInfoHtml,
        getOsmType: getOsmType
    };
})();<commit_msg>single column popup when same version<commit_after>var oscviewer = (function() {

    function buildFidMap(features) {
        var map = {};
        for(var i=0, len=features.length; i < len; i++) {
            map[features[i].fid] = features[i];
        }
        return map;
    }

    function setActions(oscFeatures, osmFeatures) {
        var i;
        var oscFeature, osmFeature;
        var action;
        //var oscFeatures = oscLayer.features;
        var versionDiff;
        //var osmFeatures = [];

        var oscFeaturesFidMap = buildFidMap(oscFeatures);
        var osmFeaturesFidMap = buildFidMap(osmFeatures);

        var oscOnly = osmFeatures.length === 0;

        // Overpass diffs: distinguish deletes from old versions (before setting actions from osc!)
        for (i = 0; i < osmFeatures.length; i++) {
            osmFeature = osmFeatures[i];
            if (osmFeature.attributes['action'] === 'erase') {
                oscFeature = oscFeaturesFidMap[osmFeature.fid];
                if (oscFeature) {
                    // in 'insert' section = old version of modified object, remove 'erase'
                    delete osmFeature.attributes['action'];
                } else {
                    // replace action string 'erase' with 'delete'
                    osmFeature.attributes['action'] = 'delete';
                    setHasTags(osmFeature, null);
                }
            } else if (osmFeature.attributes['action'] === 'keep') {
			    // set common action for referenced objects (for styling)
				osmFeature.attributes['action'] = 'augment';
			}
        }

        for (i = 0; i < oscFeatures.length; i++) {
            oscFeature = oscFeatures[i];
            osmFeature = null;

            action = oscFeature.attributes['action'];

            if (!(oscOnly || action === 'create')) {
                osmFeature = osmFeaturesFidMap[oscFeature.fid];

                if (action === 'modify' || action === 'delete') {
                    if (osmFeature) {
                        // set action to old object
                        if (action === 'modify') {
                            setModifyAction(osmFeature, oscFeature);
                        } else {
                            osmFeature.attributes['action'] = action;
                        }
                    } else {
                        console.warn('Feature "' + oscFeature.fid + '" not found');
                    }
                } else if (action === 'insert') {
                    // Overpass diffs
                    if (osmFeature) {
                        // modify
                        setModifyAction(osmFeature, oscFeature);
                    } else {
                        // create
                        oscFeature.attributes['action'] = 'create';
                    }
                }
            }

            setHasTags(osmFeature, oscFeature);
        }
    }

    function setModifyAction(osmFeature, oscFeature) {
        var action = oscFeature.geometry.equals(osmFeature.geometry) ? 'modify' : 'modify:geometry';
        osmFeature.attributes['action'] = action;
        oscFeature.attributes['action'] = action;
    }

    function getHasTags(feature) {
        var result = false;
        for (var attr in feature.attributes) {
            if (!isMetaAttribute(attr)) {
                result = true;
                break;
            }
        }
        return result;
    }

    function setHasTags(osmFeature, oscFeature) {
        var osmHasTags = false;
        if (osmFeature) {
            osmHasTags = getHasTags(osmFeature);
            osmFeature.hasTags = osmHasTags;
        }
        if (oscFeature) {
            // also indicate that the old feature had tags, when the changed feature has none
            oscFeature.hasTags = osmHasTags || getHasTags(oscFeature);
        }
    }

    function isMetaAttribute(attr) {
        var metaAttrs = OpenLayers.Format.OSC.prototype.metaAttributes;
        return OpenLayers.Util.indexOf(metaAttrs, attr) !== -1;
    }

    function getInfoHtml(oldFeature, changeFeature) {
        var keys = [];
        var oldTags = undefined;
        var changeTags = undefined;
        var feature = changeFeature || oldFeature;
        var osm = {
            id : feature.osm_id,
            type : getOsmType(feature)
        };
        var action = feature.attributes['action'] || '';

        var infoHtml = '';
        infoHtml += '
';
        infoHtml += '
';
        infoHtml += '
';
        // modify:geometry -> modify_geometry for CSS
        infoHtml += '';
        infoHtml += action;
        infoHtml += '';
        infoHtml += ' ' + osm.type;
        infoHtml += ' ' + formatOsmLink(osm.id, osm.type);
        infoHtml += '
';

        if (!oldFeature && action != 'create') {
            infoHtml += '
Warning: Old feature not found,
probably not included in OSM file
';
        }

        infoHtml += '
';

        if (oldFeature) {
            oldTags = oldFeature.attributes;
            keys = _.keys(oldTags);
        }
        if (changeFeature) {
            changeTags = changeFeature.attributes;
            keys = keys.concat(_.keys(changeTags));
        }
        keys = _.filter(keys, function(key) {
            return !isMetaAttribute(key);
        });
        keys.sort();
        keys = _.unique(keys, true);

        // single column display (no comparison) when same object version
        // e.g. for modify:geometry on way when only node changed or
        // duplicated delete when change version is not available (Osmosis diff)
        if (oldTags && changeTags && oldTags.version === changeTags.version) {
            changeTags = undefined;
        }

        infoHtml += printMeta('timestamp', oldTags, changeTags, formatIsoDateTime);
        infoHtml += printMeta('user', oldTags, changeTags, formatOsmLink);
        infoHtml += printMeta('version', oldTags, changeTags);
        infoHtml += printMeta('changeset', oldTags, changeTags, formatOsmLink);

        infoHtml += '

';
        infoHtml += printKeys(keys, oldTags, changeTags);

        infoHtml += '
';
        infoHtml += '
';
        infoHtml += '
';

        return infoHtml;
    }

    function getOsmType(feature) {
        return feature.fid.substring(0, feature.fid.indexOf('.'));
    }

    function formatIsoDateTime(dateTimeString) {
        return moment(dateTimeString).format('L LT');
    }

    function formatOsmLink(val, type) {
        var path = (type === 'user') ? '' : 'browse/';
        return '' + val + '';
    }

    function printMeta(key, oldTags, changeTags, format) {
        var infoHtml = '';
        if (!format) {
            // dummy
            format = function(val) {
                return val;
            };
        }
        infoHtml += '
' + key + '	';
        if (oldTags) {
            infoHtml += '' + format(oldTags[key], key) + '	';
        }
        if (changeTags) {
            infoHtml += '' + format(changeTags[key], key) + '	';
        }
        infoHtml += '
';
        return infoHtml;
    }

    function printKeys(keys, oldTags, changeTags) {
        var i;
        var oldVal, changeVal;
        var classes;
        var infoHtml = '';
        for (i = 0; i < keys.length; i++) {
            key = keys[i];
            oldVal = oldTags && oldTags[key];
            changeVal = changeTags && changeTags[key];
            classes = (oldTags && changeTags) ? getClasses(oldVal, changeVal) : getDefaultClasses();
            infoHtml += '
' + key + '	';
            if (oldTags) {
                infoHtml += '' + val(oldVal) + '	';
            }
            if (changeTags) {
                infoHtml += '' + val(changeVal) + '	';
            }
            infoHtml += '
';
        }
        return infoHtml;
    }

    function getDefaultClasses() {
        var c = {
            key : 'keydefault',
            old : 'default',
            change : 'default'
        };
        return c;
    }

    function getClasses(oldVal, changeVal) {
        var c = getDefaultClasses();

        if (_.isUndefined(oldVal)) {
            c.key = 'created';
            c.old = 'undefined';
            c.change = 'created';
        } else if (_.isUndefined(changeVal)) {
            c.key = 'deleted';
            c.old = 'deleted';
            c.change = 'undefined';
        } else if (oldVal !== changeVal) {
            c.old = 'modified';
            c.change = 'modified';
        }

        return c;
    }

    function val(value) {
        return _.isUndefined(value) ? '' : value;
    }

    return {
        setActions : setActions,
        getInfoHtml: getInfoHtml,
        getOsmType: getOsmType
    };
})();<|endoftext|>


<commit_before>$(function(){
	var demodata = [
		{
		    "urn" : "urn:public:snack",
		    "name" : "Snack",
		    "count" : 1709,
		    "csv" : "/ocpu/library/plotbuilder/demodata/snackdemo.csv",
		    "xml" : "/ocpu/library/plotbuilder/demodata/snackdemo.xml"
		},
		{
		    "urn" : "urn:public:media",
		    "name" : "Media",
		    "count" : 1025,
		    "csv" : "/ocpu/library/plotbuilder/demodata/mediademo.csv",
		    "xml" : "/ocpu/library/plotbuilder/demodata/mediademo.xml"
		},
		{
		    "urn" : "urn:public:nutrition",
		    "name" : "Nutrition",
		    "count" : 1443,
		    "csv" : "/ocpu/library/plotbuilder/demodata/nutritiondemo.csv",
		    "xml" : "/ocpu/library/plotbuilder/demodata/nutritiondemo.xml"
		},
		{
		    "urn" : "urn:public:trash",
		    "name" : "Trash",
		    "count" : 2667,
		    "csv" : "/ocpu/library/plotbuilder/demodata/trashdemo.csv",
		    "xml" : "/ocpu/library/plotbuilder/demodata/trashdemo.xml"
		}
	];

	$.each(demodata, function(i, val){
		var campaign = val.name;
		var urn = val.urn;
		var count = val.count;
		var csvlink = val.csv;
		var xmllink = val.xml;

		var tr = $("
").appendTo("tbody");
		$("").text(campaign).appendTo(tr);
		$("").text(urn).appendTo(tr);
		$("").text(count).appendTo(tr);
		$("").text(count).appendTo(tr);

		var td5 = $("").addClass("buttontd").appendTo(tr);
        var btn = $("
").addClass("dropdown").append('\
            <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown"> Demo </button>').appendTo(td5);

        var ul = $("
").addClass("dropdown-menu").appendTo(btn);

        var dashboardlink = $("").appendTo($("
").appendTo(ul)).append(' Dashboard').attr("href", 'navbar/dashboard/#' + urn)
        var plotapplink = $("").appendTo($("
").appendTo(ul)).append(' PlotApp').attr("href", 'navbar/plotapp/#' + urn)

        ul.append($("
").addClass('divider'))

        var csvlink = $("").appendTo($("
").appendTo(ul)).append(' Export Data').attr("href", csvlink);
        var xmllink = $("").appendTo($("
").appendTo(ul)).append(' Download XML').attr("href", xmllink);
	});

	var table = $('#demotable').DataTable( {
        "dom" : '<"pull-left"f>tip',
        "order": [[ 1, "desc" ]],
        "aoColumnDefs": [
           { 'bSortable': false, 'aTargets': [ 4 ] },
           { 'bSearchable': false, 'aTargets': [ 4 ] }
        ]
    })
})
<commit_msg>add demo page<commit_after>$(function(){
	var demodata = [
		{
		    "urn" : "urn:public:snack",
		    "name" : "Snack",
		    "count" : 1709,
		    "csv" : "/ocpu/library/plotbuilder/demodata/snackdemo.csv",
		    "xml" : "/ocpu/library/plotbuilder/demodata/snackdemo.xml"
		},
		{
		    "urn" : "urn:public:media",
		    "name" : "Media",
		    "count" : 1025,
		    "csv" : "/ocpu/library/plotbuilder/demodata/mediademo.csv",
		    "xml" : "/ocpu/library/plotbuilder/demodata/mediademo.xml"
		},
		{
		    "urn" : "urn:public:nutrition",
		    "name" : "Nutrition",
		    "count" : 1443,
		    "csv" : "/ocpu/library/plotbuilder/demodata/nutritiondemo.csv",
		    "xml" : "/ocpu/library/plotbuilder/demodata/nutritiondemo.xml"
		},
		{
		    "urn" : "urn:public:trash",
		    "name" : "Trash",
		    "count" : 2667,
		    "csv" : "/ocpu/library/plotbuilder/demodata/trashdemo.csv",
		    "xml" : "/ocpu/library/plotbuilder/demodata/trashdemo.xml"
		}
	];

	$.each(demodata, function(i, val){
		var campaign = val.name;
		var urn = val.urn;
		var count = val.count;
		var csvlink = val.csv;
		var xmllink = val.xml;

		var tr = $("
").appendTo("tbody");
		$("").text(campaign).appendTo(tr);
		$("").text(urn).appendTo(tr);
		$("").text(count).appendTo(tr);
		$("").text(count).appendTo(tr);

		var td5 = $("").addClass("buttontd").appendTo(tr);
        var btn = $("
").addClass("dropdown").append('\
            <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown"> Demo </button>').appendTo(td5);

        var ul = $("
").addClass("dropdown-menu").appendTo(btn);

        var dashboardlink = $("").appendTo($("
").appendTo(ul)).append(' Dashboard').attr("href", 'navbar/dashboard/#' + urn)
        var plotapplink = $("").appendTo($("
").appendTo(ul)).append(' PlotApp').attr("href", 'navbar/plotapp/#' + name.toLowerCase() + "demo")

        ul.append($("
").addClass('divider'))

        var csvlink = $("").appendTo($("
").appendTo(ul)).append(' Export Data').attr("href", csvlink);
        var xmllink = $("").appendTo($("
").appendTo(ul)).append(' Download XML').attr("href", xmllink);
	});

	var table = $('#demotable').DataTable( {
        "dom" : '<"pull-left"f>tip',
        "order": [[ 1, "desc" ]],
        "aoColumnDefs": [
           { 'bSortable': false, 'aTargets': [ 4 ] },
           { 'bSearchable': false, 'aTargets': [ 4 ] }
        ]
    })
})
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var EventEmitter = require('./lib/event_emitter');
var inherits = require('util').inherits;
var process = require('process');
var Buffer = require('buffer').Buffer;

var errors = require('./errors');
var States = require('./reqres_states');

var emptyBuffer = Buffer(0);

function TChannelInRequest(id, options) {
    /*eslint max-statements: [2, 40]*/
    var self = this;

    EventEmitter.call(self);
    self.errorEvent = self.defineEvent('error');
    self.timeoutEvent = self.defineEvent('timeout');
    self.finishEvent = self.defineEvent('finish');
    self.channel = options.channel;

    self.timeout = options.timeout || 0;
    self.tracing = options.tracing || null;
    self.serviceName = options.serviceName || '';
    self.callerName = options.headers && options.headers.cn || '';
    self.headers = options.headers || {};
    self.checksum = options.checksum || null;
    self.retryFlags = options.retryFlags || null;
    self.connection = options.connection || null;

    self.state = States.Initial;
    self.operations = null;
    self.timeHeapHandle = null;
    self.id = id || 0;
    self.remoteAddr = null;
    self.streamed = false;
    self.arg1 = emptyBuffer;
    self.endpoint = null;
    self.arg2 = emptyBuffer;
    self.arg3 = emptyBuffer;
    self.forwardTrace = false;
    self.span = null;
    self.start = self.channel.timers.now();
    self.res = null;
    self.err = null;
    self.circuit = null;
    self.flags = options.flags;

    if (options.tracer) {
        self.setupTracing(options);
    }
}

inherits(TChannelInRequest, EventEmitter);

TChannelInRequest.prototype.type = 'tchannel.incoming-request';

TChannelInRequest.prototype.extendLogInfo = function extendLogInfo(info) {
    var self = this;

    // TODO: add:
    // - request id?
    // - tracing id?
    // - other?

    info.inRequestId = self.id;
    info.inRequestType = self.type;
    info.inRequestState = States.describe(self.state);
    info.inRequestRemoteAddr = self.remoteAddr;
    info.serviceName = self.serviceName;
    info.callerName = self.callerName;
    info.inRequestErr = self.err;

    if (self.endpoint !== null) {
        info.inRequestArg1 = self.endpoint;
    } else {
        info.inRequestArg1 = String(self.arg1);
    }

    if (self.connection) {
        info = self.connection.extendLogInfo(info);
    }

    return info;
};

TChannelInRequest.prototype.setupTracing = function setupTracing(options) {
    var self = this;

    self.span = options.tracer.setupNewSpan({
        spanid: self.tracing.spanid,
        traceid: self.tracing.traceid,
        parentid: self.tracing.parentid,
        flags: self.tracing.flags,
        remoteName: options.hostPort,
        serviceName: self.serviceName,
        name: '' // fill this in later
    });

    self.span.annotateBinary('cn', self.callerName);
    self.span.annotateBinary('as', self.headers.as);
    if (self.connection) {
        self.span.annotateBinary('src', self.connection.remoteName);
    }

    self.span.annotate('sr');
};

TChannelInRequest.prototype.handleFrame = function handleFrame(parts, isLast) {
    var self = this;

    if (parts.length !== 3 || self.state !== States.Initial || !isLast) {
        return errors.ArgStreamUnimplementedError();
    }

    self.arg1 = parts[0] || emptyBuffer;
    self.endpoint = String(self.arg1);
    self.arg2 = parts[1] || emptyBuffer;
    self.arg3 = parts[2] || emptyBuffer;

    if (self.span) {
        self.span.name = self.endpoint;
    }

    self.emitFinish();

    return null;
};

TChannelInRequest.prototype.emitError = function emitError(err) {
    var self = this;

    if (self.circuit) {
        self.circuit.state.onRequestError(err);
    }

    self.err = err;
    self.errorEvent.emit(self, err);
};

TChannelInRequest.prototype.emitFinish = function emitFinish() {
    var self = this;

    self.state = States.Done;
    self.finishEvent.emit(self);
};

TChannelInRequest.prototype.onTimeout = function onTimeout(now) {
    var self = this;
    var timeoutError;

    if (!self.res || self.res.state === States.Initial) {
        // TODO: send an error frame response?
        // TODO: emit error on self.res instead / in addition to?
        // TODO: should cancel any pending handler
        timeoutError = errors.RequestTimeoutError({
            id: self.id,
            start: self.start,
            elapsed: now - self.start,
            timeout: self.timeout,
            remoteAddr: self.remoteAddr
        });
        process.nextTick(deferInReqTimeoutErrorEmit);
    }

    function deferInReqTimeoutErrorEmit() {
        if (!self.res || self.res.state === States.Initial) {
            self.timeoutEvent.emit(self, timeoutError);
            self.emitError(timeoutError);
        }

        if (self.operations) {
            self.operations.popInReq(self.id);
        }
    }
};

// TODO: deprecated, remove
TChannelInRequest.prototype.withArg1 = function withArg1(callback) {
    var self = this;
    callback(null, self.arg1);
};

TChannelInRequest.prototype.withArg2 = function withArg23(callback) {
    var self = this;
    callback(null, self.arg2);
};

TChannelInRequest.prototype.withArg23 = function withArg23(callback) {
    var self = this;
    callback(null, self.arg2, self.arg3);
};

module.exports = TChannelInRequest;
<commit_msg>TChannelInRequest: drop self. access pattern from constructor<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var EventEmitter = require('./lib/event_emitter');
var inherits = require('util').inherits;
var process = require('process');
var Buffer = require('buffer').Buffer;

var errors = require('./errors');
var States = require('./reqres_states');

var emptyBuffer = Buffer(0);

function TChannelInRequest(id, options) {
    /*eslint max-statements: [2, 40]*/

    EventEmitter.call(this);
    this.errorEvent = this.defineEvent('error');
    this.timeoutEvent = this.defineEvent('timeout');
    this.finishEvent = this.defineEvent('finish');
    this.channel = options.channel;

    this.timeout = options.timeout || 0;
    this.tracing = options.tracing || null;
    this.serviceName = options.serviceName || '';
    this.callerName = options.headers && options.headers.cn || '';
    this.headers = options.headers || {};
    this.checksum = options.checksum || null;
    this.retryFlags = options.retryFlags || null;
    this.connection = options.connection || null;

    this.state = States.Initial;
    this.operations = null;
    this.timeHeapHandle = null;
    this.id = id || 0;
    this.remoteAddr = null;
    this.streamed = false;
    this.arg1 = emptyBuffer;
    this.endpoint = null;
    this.arg2 = emptyBuffer;
    this.arg3 = emptyBuffer;
    this.forwardTrace = false;
    this.span = null;
    this.start = this.channel.timers.now();
    this.res = null;
    this.err = null;
    this.circuit = null;
    this.flags = options.flags;

    if (options.tracer) {
        this.setupTracing(options);
    }
}

inherits(TChannelInRequest, EventEmitter);

TChannelInRequest.prototype.type = 'tchannel.incoming-request';

TChannelInRequest.prototype.extendLogInfo = function extendLogInfo(info) {
    var self = this;

    // TODO: add:
    // - request id?
    // - tracing id?
    // - other?

    info.inRequestId = self.id;
    info.inRequestType = self.type;
    info.inRequestState = States.describe(self.state);
    info.inRequestRemoteAddr = self.remoteAddr;
    info.serviceName = self.serviceName;
    info.callerName = self.callerName;
    info.inRequestErr = self.err;

    if (self.endpoint !== null) {
        info.inRequestArg1 = self.endpoint;
    } else {
        info.inRequestArg1 = String(self.arg1);
    }

    if (self.connection) {
        info = self.connection.extendLogInfo(info);
    }

    return info;
};

TChannelInRequest.prototype.setupTracing = function setupTracing(options) {
    var self = this;

    self.span = options.tracer.setupNewSpan({
        spanid: self.tracing.spanid,
        traceid: self.tracing.traceid,
        parentid: self.tracing.parentid,
        flags: self.tracing.flags,
        remoteName: options.hostPort,
        serviceName: self.serviceName,
        name: '' // fill this in later
    });

    self.span.annotateBinary('cn', self.callerName);
    self.span.annotateBinary('as', self.headers.as);
    if (self.connection) {
        self.span.annotateBinary('src', self.connection.remoteName);
    }

    self.span.annotate('sr');
};

TChannelInRequest.prototype.handleFrame = function handleFrame(parts, isLast) {
    var self = this;

    if (parts.length !== 3 || self.state !== States.Initial || !isLast) {
        return errors.ArgStreamUnimplementedError();
    }

    self.arg1 = parts[0] || emptyBuffer;
    self.endpoint = String(self.arg1);
    self.arg2 = parts[1] || emptyBuffer;
    self.arg3 = parts[2] || emptyBuffer;

    if (self.span) {
        self.span.name = self.endpoint;
    }

    self.emitFinish();

    return null;
};

TChannelInRequest.prototype.emitError = function emitError(err) {
    var self = this;

    if (self.circuit) {
        self.circuit.state.onRequestError(err);
    }

    self.err = err;
    self.errorEvent.emit(self, err);
};

TChannelInRequest.prototype.emitFinish = function emitFinish() {
    var self = this;

    self.state = States.Done;
    self.finishEvent.emit(self);
};

TChannelInRequest.prototype.onTimeout = function onTimeout(now) {
    var self = this;
    var timeoutError;

    if (!self.res || self.res.state === States.Initial) {
        // TODO: send an error frame response?
        // TODO: emit error on self.res instead / in addition to?
        // TODO: should cancel any pending handler
        timeoutError = errors.RequestTimeoutError({
            id: self.id,
            start: self.start,
            elapsed: now - self.start,
            timeout: self.timeout,
            remoteAddr: self.remoteAddr
        });
        process.nextTick(deferInReqTimeoutErrorEmit);
    }

    function deferInReqTimeoutErrorEmit() {
        if (!self.res || self.res.state === States.Initial) {
            self.timeoutEvent.emit(self, timeoutError);
            self.emitError(timeoutError);
        }

        if (self.operations) {
            self.operations.popInReq(self.id);
        }
    }
};

// TODO: deprecated, remove
TChannelInRequest.prototype.withArg1 = function withArg1(callback) {
    var self = this;
    callback(null, self.arg1);
};

TChannelInRequest.prototype.withArg2 = function withArg23(callback) {
    var self = this;
    callback(null, self.arg2);
};

TChannelInRequest.prototype.withArg23 = function withArg23(callback) {
    var self = this;
    callback(null, self.arg2, self.arg3);
};

module.exports = TChannelInRequest;
<|endoftext|>


<commit_before>//
// We breken de make expensive hash op in stukken omdat
// anders IE8 gaat zeuren over scripts die te lang lopen.
//
// De utility functie komt van
//    http://www.picnet.com.au/blogs/Guido/post/2010/03/04/How-to-prevent-Stop-running-this-script-message-in-browsers.aspx
//
RepeatingOperation = function(op, yieldEveryIteration) {
	var count = 0;
	var runCount = 0;
	var instance = this;
	this.step = function(arg1,arg2) {
		// De step functie controleert feitelijk of we door
		// gaan in de huidige 'thread' (setTimeOut() zien we even als
		// thread), of dat we een nieuwe thread starten en de vorige stopzetten.
		//
		// Omdat IE aantal operaties per thread telt, kunnen we hier mee de
		// 'wow your script is slow'-waarschuwing omzeilen
		//
		runCount++;
		if (++count >= yieldEveryIteration) {
			count = 0;
			setTimeout(function() { op(arg1,arg2,runCount); }, 1, [])
			return;
		} // if

		op(arg1,arg2,runCount);
	}; // function
}; // RepeatingOperation

var ro = new RepeatingOperation(function(prefix, suffix, runCount) {
	var possibleChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
	var hash = prefix + suffix;

	uniquePart = '';
	for(i = 0; i < 15; i++) {
		var irand = Math.round(Math.random() * (possibleChars.length - 1));
		uniquePart += possibleChars[irand];
	} // for

	hash = $.sha1(prefix + '.' + uniquePart + suffix);

	if (hash.substr(0, 4) != '0000') {
		if (runCount > 400000) {
			alert("Unable to calculate SHA1 hash: " + runCount);
		} else {
			ro.step(prefix, suffix, runCount);
			return ;
		} // else
	} // if

	alert(prefix + '.' + uniquePart + suffix + ' ==> ' + runCount);
	alert($.sha1(prefix + '.' + uniquePart + suffix));
}, 500); // new RepeatingOperation met 10000 iteraties

// ro.step("<PqPs1LvROTU9PpfTQALQI.0.random", "@spot.net>", 0);
<commit_msg>Comment verbetering<commit_after>//
// We breken de make expensive hash op in stukken omdat
// anders IE8 gaat zeuren over scripts die te lang lopen.
//
// De utility functie komt van
//    http://www.picnet.com.au/blogs/Guido/post/2010/03/04/How-to-prevent-Stop-running-this-script-message-in-browsers.aspx
//
RepeatingOperation = function(op, yieldEveryIteration) {
	var count = 0;
	var runCount = 0;
	var instance = this;
	this.step = function(arg1,arg2) {
		// De step functie controleert feitelijk of we door
		// gaan in de huidige 'thread' (setTimeOut() zien we even als
		// thread), of dat we een nieuwe thread starten en de vorige stopzetten.
		//
		// Omdat IE aantal operaties per thread telt, kunnen we hier mee de
		// 'wow your script is slow'-waarschuwing omzeilen
		//
		runCount++;
		if (++count >= yieldEveryIteration) {
			count = 0;
			setTimeout(function() { op(arg1,arg2,runCount); }, 1, [])
			return;
		} // if

		op(arg1,arg2,runCount);
	}; // function
}; // RepeatingOperation

var ro = new RepeatingOperation(function(prefix, suffix, runCount) {
	var possibleChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
	var hash = prefix + suffix;

	uniquePart = '';
	for(i = 0; i < 15; i++) {
		var irand = Math.round(Math.random() * (possibleChars.length - 1));
		uniquePart += possibleChars[irand];
	} // for

	hash = $.sha1(prefix + '.' + uniquePart + suffix);

	if (hash.substr(0, 4) != '0000') {
		if (runCount > 400000) {
			alert("Unable to calculate SHA1 hash: " + runCount);
		} else {
			ro.step(prefix, suffix, runCount);
			return ;
		} // else
	} // if

	alert(prefix + '.' + uniquePart + suffix + ' ==> ' + runCount);
	alert($.sha1(prefix + '.' + uniquePart + suffix));
}, 500); // new RepeatingOperation met 500 iteraties

// ro.step("<PqPs1LvROTU9PpfTQALQI.0.random", "@spot.net>", 0);
<|endoftext|>


<commit_before>
var idbMock = require('../indexeddb.js');

describe('mock.open', function() {
	iit('should produce some kind of IDBDatabase mock', function(done) {
		idbMock.reset();
		idbMock.mock.open('somedb', 1).onsuccess = function(ev) {
			expect(ev.target).not.toBe(null);

			if (ev.target)
				expect(ev.target.result).not.toBe(null);
			done();
		};
	});
});

<commit_msg>Don't run just that one test which is the only one<commit_after>
var idbMock = require('../indexeddb.js');

describe('mock.open', function() {
	it('should produce some kind of IDBDatabase mock', function(done) {
		idbMock.reset();
		idbMock.mock.open('somedb', 1).onsuccess = function(ev) {
			expect(ev.target).not.toBe(null);

			if (ev.target)
				expect(ev.target.result).not.toBe(null);
			done();
		};
	});
});

<|endoftext|>


<commit_before>import { extend } from 'flarum/extend';
import app from 'flarum/app';
import PermissionGrid from 'flarum/components/PermissionGrid';

app.initializers.add('lock', () => {
  extend(PermissionGrid.prototype, 'moderateItems', items => {
    items.add('lock', {
      icon: 'fas fa-lock',
      label: app.translator.trans('flarum-lock.admin.permissions.lock_discussions_label'),
      permission: 'discussion.lock'
    }, 95);
  });
});
<commit_msg>Admin js changes for admin ux revamp<commit_after>import app from 'flarum/app';

app.initializers.add('lock', () => {
  app.extensionData.for('flarum-lock')
    .registerPermission({
      icon: 'fas fa-lock',
      label: app.translator.trans('flarum-lock.admin.permissions.lock_discussions_label'),
      permission: 'discussion.lock'
    }, 'moderate', 95);
});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2010, Duponchel David
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the GraouPack nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL DUPONCHEL DAVID BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

$.namespace("izpack.view");

izpack.view.Locale = function () {

	var available	= "#" + this.id + " #tab-locale-available";
	var selected	= "#" + this.id + " #tab-locale-selected";
	var lists	= "#" + this.id + " ul";

	this.initView = function () {
		$(lists).sortable({
			connectWith : lists,
			placeholder : 'ui-state-highlight'
		}).disableSelection();

	};

	this.validate = function () {
		if (!this.viewLoaded) {
			return false;
		}
		return $(" li", selected).length !== 0;
	};

	this.getLocales = function () {
		var locales = [];
		$(" li", selected).each(function () {
			locales.push($(this).attr("data-iso3"));
		});
		return locales;
	};
};
izpack.view.Locale.prototype = new izpack.view.GenericView("locale");
<commit_msg>Locales problem display an error border.<commit_after>/*
 * Copyright (c) 2010, Duponchel David
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the GraouPack nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL DUPONCHEL DAVID BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

$.namespace("izpack.view");

izpack.view.Locale = function () {

	var available	= "#" + this.id + " #tab-locale-available";
	var selected	= "#" + this.id + " #tab-locale-selected";
	var lists	= "#" + this.id + " ul";

	this.initView = function () {
		$(lists).sortable({
			connectWith : lists,
			placeholder : 'ui-state-highlight'
		}).disableSelection();

	};

	this.validate = function () {
		if (!this.viewLoaded) {
			return false;
		}
		var isValid = $(" li", selected).length !== 0;

		if (isValid) {
			$(selected).removeClass("validity-erroneous");
		}
		else {
			$(selected).addClass("validity-erroneous");
		}
		return isValid;
	};

	this.getLocales = function () {
		var locales = [];
		$(" li", selected).each(function () {
			locales.push($(this).attr("data-iso3"));
		});
		return locales;
	};
};
izpack.view.Locale.prototype = new izpack.view.GenericView("locale");
<|endoftext|>


<commit_before>'use strict';

var main = require('../main');

/** @class */
function TestSeries() {
    this.testCases = {};
    this.testCount = this.failedCount = this.errorCount = 0;
    this.warningCount = 0;
}
module.exports = TestSeries;

TestSeries.FAILED_ASSERTION_MSG = 'Failed assertion: ';

TestSeries.prototype.add = function (klass) {
    this.testCases[main.funcName(klass)] = klass;
    return klass;
};

TestSeries.prototype.testOneClass = function (Klass, methodPattern) {
    for (var method in Klass.prototype) {
        if (typeof Klass.prototype[method] !== 'function') continue;
        if (method.substr(0,4) !== 'test') continue;
        if (methodPattern && method.indexOf(methodPattern) === -1) continue;
        this.testCount++;
        var test = new Klass(main.funcName(Klass) + '#' + method);
        test.series = this;
        try {
            test[method].call(test);
            if (this.testCount === 1 && methodPattern) test.showInUi('First test matching "' + methodPattern + '"');
        } catch(e) {
            if (e.message.startsWith(TestSeries.FAILED_ASSERTION_MSG)) {
                this.failedCount++;
                e.message = e.message.substr(TestSeries.FAILED_ASSERTION_MSG.length);
                main.log.error('Test failed: ' + main.funcName(test) + ': ' + e.message + '\n');
            } else {
                this.errorCount++;
                main.log.error('Exception during test: ' + main.funcName(test) + ':\n' + e.stack + '\n');
            }
            test.showInUi(e.message);
        }
    }
};

/** Runs the registered test cases
 * @param {string} [specificClass] - name of single class to test. E.g. "TestSpeed"
 * @param {string} [methodPattern] - if given, only test names containing this pattern are run
 * @return {number} - number of issues detected (exceptions + errors + warnings); 0 if all fine
 */
TestSeries.prototype.run = function (specificClass, methodPattern) {
    var logLevel = main.log.level;
    var classCount = 0;
    this.testCount = this.checkCount = this.count = 0;
    this.failedCount = this.errorCount = this.warningCount = this.todoCount = 0;
    var startTime = Date.now();

    for (var t in this.testCases) {
        if (specificClass && t !== specificClass) continue;
        classCount++;
        var Klass = this.testCases[t];
        this.testOneClass(Klass, methodPattern);
        main.log.level = logLevel; // restored to initial level
    }
    var duration = ((Date.now() - startTime) / 1000).toFixed(2);
    return this._logReport(specificClass, classCount, duration);
};

TestSeries.prototype._logReport = function (specificClass, classCount, duration) {
    var numIssues = this.errorCount + this.failedCount + this.warningCount;
    var classes = specificClass ? 'class ' + specificClass : classCount + ' classes';

    var report = 'Completed tests. (' + classes + ', ' + this.testCount + ' tests, ' +
        this.checkCount + ' checks in ' + duration + 's)\n\n';
    if (numIssues === 0) {
        if (this.testCount || this.checkCount) report += 'SUCCESS!';
        else report += '*** 0 TESTS DONE ***  Check your filter?';
        // Less important test data
        if (this.todoCount) report += '  (Todos: ' + this.todoCount + ')';
        if (this.count) report += '\n(generic count: ' + this.count + ')';
        main.log.info(report);
    } else {
        report += '*** ISSUES: exceptions: ' + this.errorCount +
            ', failed: ' + this.failedCount +
            ', warnings: ' + this.warningCount + ' ***';
        main.log.error(report);
    }
    return numIssues;
};
<commit_msg>TestSeries pattern ignores case<commit_after>'use strict';

var main = require('../main');

/** @class */
function TestSeries() {
    this.testCases = {};
    this.testCount = this.failedCount = this.errorCount = 0;
    this.warningCount = 0;
}
module.exports = TestSeries;

TestSeries.FAILED_ASSERTION_MSG = 'Failed assertion: ';

TestSeries.prototype.add = function (klass) {
    this.testCases[main.funcName(klass)] = klass;
    return klass;
};

TestSeries.prototype.testOneClass = function (Klass, methodPattern) {
    var pattern = methodPattern ? methodPattern.toLowerCase() : '';

    for (var method in Klass.prototype) {
        if (typeof Klass.prototype[method] !== 'function') continue;
        if (method.substr(0,4) !== 'test') continue;
        if (method.toLowerCase().indexOf(pattern) === -1) continue;
        this.testCount++;
        var test = new Klass(main.funcName(Klass) + '#' + method);
        test.series = this;
        try {
            test[method].call(test);
            if (this.testCount === 1 && methodPattern) test.showInUi('First test matching "' + methodPattern + '"');
        } catch(e) {
            if (e.message.startsWith(TestSeries.FAILED_ASSERTION_MSG)) {
                this.failedCount++;
                e.message = e.message.substr(TestSeries.FAILED_ASSERTION_MSG.length);
                main.log.error('Test failed: ' + main.funcName(test) + ': ' + e.message + '\n');
            } else {
                this.errorCount++;
                main.log.error('Exception during test: ' + main.funcName(test) + ':\n' + e.stack + '\n');
            }
            test.showInUi(e.message);
        }
    }
};

/** Runs the registered test cases
 * @param {string} [specificClass] - name of single class to test. E.g. "TestSpeed"
 * @param {string} [methodPattern] - if given, only test names containing this pattern are run
 * @return {number} - number of issues detected (exceptions + errors + warnings); 0 if all fine
 */
TestSeries.prototype.run = function (specificClass, methodPattern) {
    var logLevel = main.log.level;
    var classCount = 0;
    this.testCount = this.checkCount = this.count = 0;
    this.failedCount = this.errorCount = this.warningCount = this.todoCount = 0;
    var startTime = Date.now();

    for (var t in this.testCases) {
        if (specificClass && t !== specificClass) continue;
        classCount++;
        var Klass = this.testCases[t];
        this.testOneClass(Klass, methodPattern);
        main.log.level = logLevel; // restored to initial level
    }
    var duration = ((Date.now() - startTime) / 1000).toFixed(2);
    return this._logReport(specificClass, classCount, duration);
};

TestSeries.prototype._logReport = function (specificClass, classCount, duration) {
    var numIssues = this.errorCount + this.failedCount + this.warningCount;
    var classes = specificClass ? 'class ' + specificClass : classCount + ' classes';

    var report = 'Completed tests. (' + classes + ', ' + this.testCount + ' tests, ' +
        this.checkCount + ' checks in ' + duration + 's)\n\n';
    if (numIssues === 0) {
        if (this.testCount || this.checkCount) report += 'SUCCESS!';
        else report += '*** 0 TESTS DONE ***  Check your filter?';
        // Less important test data
        if (this.todoCount) report += '  (Todos: ' + this.todoCount + ')';
        if (this.count) report += '\n(generic count: ' + this.count + ')';
        main.log.info(report);
    } else {
        report += '*** ISSUES: exceptions: ' + this.errorCount +
            ', failed: ' + this.failedCount +
            ', warnings: ' + this.warningCount + ' ***';
        main.log.error(report);
    }
    return numIssues;
};
<|endoftext|>


<commit_before>'use strict';

var log = require('../log');
var main = require('../main');

var FAILED_ASSERTION_MSG = 'Failed assertion: ';

/** @class */
function TestSeries() {
    this.testCases = {};
    this.testCount = 0;
    this.failedCount = this.errorCount = 0;
    this.failedCount0 = this.errorCount0 = 0;
    this.brokenCount = this.fixedCount = 0;
    this.currentTest = '';
    this.inBrokenTest = false;
}
module.exports = TestSeries;

TestSeries.prototype.add = function (klass) {
    this.testCases[main.funcName(klass)] = klass;
    return klass;
};

TestSeries.prototype.testOneClass = function (Klass, methodPattern) {
    var pattern = methodPattern ? methodPattern.toLowerCase() : '';

    for (var method in Klass.prototype) {
        if (typeof Klass.prototype[method] !== 'function') continue;
        if (method.substr(0,4) !== 'test') continue;
        if (method.toLowerCase().indexOf(pattern) === -1) continue;
        this.testCount++;
        this.currentTest = main.funcName(Klass) + '#' + method;
        var test = new Klass(this.currentTest);
        test.series = this;

        this._testOneMethod(test, test[method], methodPattern);
    }
};

TestSeries.prototype._testOneMethod = function (test, method, methodPattern) {
    try {
        this.inBrokenTest = false;

        method.call(test);

        if (this.inBrokenTest) this._endBrokenTest(/*failed=*/false);
        if (this.testCount === 1 && methodPattern) test.showInUi('First test matching "' + methodPattern + '"');
    } catch(e) {
        if (this.inBrokenTest && !main.debug) {
            return this._endBrokenTest(/*failed=*/true);
        }
        var msg = e.message;
        if (msg.startsWith(FAILED_ASSERTION_MSG)) {
            this.failedCount++;
            msg = msg.substr(FAILED_ASSERTION_MSG.length);
            log.error('Test failed: ' + this.currentTest + ': ' + msg + '\n');
        } else {
            this.errorCount++;
            log.error('Exception during test: ' + this.currentTest + ':\n' + e.stack + '\n');
        }
        test.showInUi(msg);
    }
};

TestSeries.prototype.failTest = function (msg, comment) {
    comment = comment ? comment + ': ' : '';
    throw new Error(FAILED_ASSERTION_MSG + comment + msg);
};

TestSeries.prototype.startBrokenTest = function () {
    this.inBrokenTest = true;
    this.failedCount0 = this.failedCount;
    this.errorCount0 = this.errorCount;
};

TestSeries.prototype._endBrokenTest = function (failed) {
    if (failed) {
        log.info('BROKEN: ' + this.currentTest);
        this.brokenCount++;
    } else {
        log.info('FIXED: ' + this.currentTest);
        this.fixedCount++;
    }
    this.failedCount = this.failedCount0;
    this.errorCount = this.errorCount0;
};

/** Runs the registered test cases
 * @param {string} [specificClass] - name of single class to test. E.g. "TestSpeed"
 * @param {string} [methodPattern] - if given, only test names containing this pattern are run
 * @return {number} - number of issues detected (exceptions + errors + warnings); 0 if all fine
 */
TestSeries.prototype.run = function (specificClass, methodPattern) {
    var logLevel = log.level;
    var classCount = 0;
    this.testCount = this.checkCount = this.count = 0;
    this.failedCount = this.errorCount = this.todoCount = 0;
    this.brokenCount = this.fixedCount = 0;
    var startTime = Date.now();

    for (var t in this.testCases) {
        if (specificClass && t !== specificClass) continue;
        classCount++;
        var Klass = this.testCases[t];
        this.testOneClass(Klass, methodPattern);
        log.setLevel(logLevel); // restored to initial level
    }
    var duration = ((Date.now() - startTime) / 1000).toFixed(2);
    return this._logReport(specificClass, classCount, duration);
};

TestSeries.prototype._logReport = function (specificClass, classCount, duration) {
    var numIssues = this.errorCount + this.failedCount;
    var classes = specificClass ? 'class ' + specificClass : classCount + ' classes';

    var report = 'Completed tests. (' + classes + ', ' + this.testCount + ' tests, ' +
        this.checkCount + ' checks in ' + duration + 's)\n\n';

    if (numIssues === 0) {
        if (this.testCount || this.checkCount) report += 'SUCCESS!';
        else report += '*** 0 TESTS DONE ***  Check your filter?';

        if (this.brokenCount || this.fixedCount) {
            report += ' (known broken: ' + this.brokenCount +
                (this.fixedCount ? ', fixed: ' + this.fixedCount : '') + ')';
        }
        if (this.todoCount) report += '  (Todos: ' + this.todoCount + ')';
        if (this.count) report += '\n(generic count: ' + this.count + ')';
        log.info(report);
    } else {
        report += '*** ISSUES: exceptions: ' + this.errorCount +
            ', failed: ' + this.failedCount + ' ***';
        log.error(report);
    }
    return numIssues;
};
<commit_msg>minor (can test a method not starting by "test" if exact pattern match)<commit_after>'use strict';

var log = require('../log');
var main = require('../main');

var FAILED_ASSERTION_MSG = 'Failed assertion: ';

/** @class */
function TestSeries() {
    this.testCases = {};
    this.testCount = 0;
    this.failedCount = this.errorCount = 0;
    this.failedCount0 = this.errorCount0 = 0;
    this.brokenCount = this.fixedCount = 0;
    this.currentTest = '';
    this.inBrokenTest = false;
}
module.exports = TestSeries;

TestSeries.prototype.add = function (klass) {
    this.testCases[main.funcName(klass)] = klass;
    return klass;
};

TestSeries.prototype.testOneClass = function (Klass, methodPattern) {
    var pattern = methodPattern ? methodPattern.toLowerCase() : '';

    for (var method in Klass.prototype) {
        if (typeof Klass.prototype[method] !== 'function') continue;
        if (method.substr(0,4) !== 'test' && method !== methodPattern) continue;
        if (method.toLowerCase().indexOf(pattern) === -1) continue;
        this.testCount++;
        this.currentTest = main.funcName(Klass) + '#' + method;
        var test = new Klass(this.currentTest);
        test.series = this;

        this._testOneMethod(test, test[method], methodPattern);
    }
};

TestSeries.prototype._testOneMethod = function (test, method, methodPattern) {
    try {
        this.inBrokenTest = false;

        method.call(test);

        if (this.inBrokenTest) this._endBrokenTest(/*failed=*/false);
        if (this.testCount === 1 && methodPattern) test.showInUi('First test matching "' + methodPattern + '"');
    } catch(e) {
        if (this.inBrokenTest && !main.debug) {
            return this._endBrokenTest(/*failed=*/true);
        }
        var msg = e.message;
        if (msg.startsWith(FAILED_ASSERTION_MSG)) {
            this.failedCount++;
            msg = msg.substr(FAILED_ASSERTION_MSG.length);
            log.error('Test failed: ' + this.currentTest + ': ' + msg + '\n');
        } else {
            this.errorCount++;
            log.error('Exception during test: ' + this.currentTest + ':\n' + e.stack + '\n');
        }
        test.showInUi(msg);
    }
};

TestSeries.prototype.failTest = function (msg, comment) {
    comment = comment ? comment + ': ' : '';
    throw new Error(FAILED_ASSERTION_MSG + comment + msg);
};

TestSeries.prototype.startBrokenTest = function () {
    this.inBrokenTest = true;
    this.failedCount0 = this.failedCount;
    this.errorCount0 = this.errorCount;
};

TestSeries.prototype._endBrokenTest = function (failed) {
    if (failed) {
        log.info('BROKEN: ' + this.currentTest);
        this.brokenCount++;
    } else {
        log.info('FIXED: ' + this.currentTest);
        this.fixedCount++;
    }
    this.failedCount = this.failedCount0;
    this.errorCount = this.errorCount0;
};

/** Runs the registered test cases
 * @param {string} [specificClass] - name of single class to test. E.g. "TestSpeed"
 * @param {string} [methodPattern] - if given, only test names containing this pattern are run
 * @return {number} - number of issues detected (exceptions + errors + warnings); 0 if all fine
 */
TestSeries.prototype.run = function (specificClass, methodPattern) {
    var logLevel = log.level;
    var classCount = 0;
    this.testCount = this.checkCount = this.count = 0;
    this.failedCount = this.errorCount = this.todoCount = 0;
    this.brokenCount = this.fixedCount = 0;
    var startTime = Date.now();

    for (var t in this.testCases) {
        if (specificClass && t !== specificClass) continue;
        classCount++;
        var Klass = this.testCases[t];
        this.testOneClass(Klass, methodPattern);
        log.setLevel(logLevel); // restored to initial level
    }
    var duration = ((Date.now() - startTime) / 1000).toFixed(2);
    return this._logReport(specificClass, classCount, duration);
};

TestSeries.prototype._logReport = function (specificClass, classCount, duration) {
    var numIssues = this.errorCount + this.failedCount;
    var classes = specificClass ? 'class ' + specificClass : classCount + ' classes';

    var report = 'Completed tests. (' + classes + ', ' + this.testCount + ' tests, ' +
        this.checkCount + ' checks in ' + duration + 's)\n\n';

    if (numIssues === 0) {
        if (this.testCount || this.checkCount) report += 'SUCCESS!';
        else report += '*** 0 TESTS DONE ***  Check your filter?';

        if (this.brokenCount || this.fixedCount) {
            report += ' (known broken: ' + this.brokenCount +
                (this.fixedCount ? ', fixed: ' + this.fixedCount : '') + ')';
        }
        if (this.todoCount) report += '  (Todos: ' + this.todoCount + ')';
        if (this.count) report += '\n(generic count: ' + this.count + ')';
        log.info(report);
    } else {
        report += '*** ISSUES: exceptions: ' + this.errorCount +
            ', failed: ' + this.failedCount + ' ***';
        log.error(report);
    }
    return numIssues;
};
<|endoftext|>


<commit_before>/*
 * testRunner.js - top level test suite
 *
 * Copyright © 2017, JEDLSoft
 *
 * 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.
 */

var util = require("util");
var fs = require("fs");

var path = require("../lib/Path.js");
var TestLoader = require("./TestLoader.js");
var NodeLoader = require("../lib/NodeLoader.js");

var nodeunit = require("nodeunit");
var reporter = nodeunit.reporters.minimal;

var suiteDefinitions = {
	"core": [
	    "util",
	    "root"
	],
	"standard": [
		"util",
		"root",
		"calendar",
		"date",
		"daterange",
		"durfmt",
		"number",
		"maps",
		"ctype"
	],
	"full": [
		"util",
		"root",
		"calendar",
		"date",
		"daterange",
		"durfmt",
		"number",
		"maps",
		"ctype",
		"strings-ext",
		"phone",
		"units",
		"name",
		"address",
		"collate"
	]
};

// override the possible node environment to make the tests uniform
process.env.TZ = "";
process.env.LANG = "";
process.env.LC_ALL = "";

var assembly = "dynamic";
var compilation = "uncompiled";
var size = "full";
var suite = suiteDefinitions.full;

// Usage: testSuite.js [assembly_style [compilation_style [suite_name_or_collection]]]
if (process.argv.length > 2) {
	if (process.argv.length > 3) {
		if (process.argv.length > 4) {
			if (process.argv.length > 5) {
				set = process.argv[5];
			}

			size = process.argv[4];
			if (suiteDefinitions[size]) {
                console.log("Only running set " + size);
                suite = suiteDefinitions[size];
			} else if (suiteDefinitions.full.indexOf(size) > -1) {
                console.log("Only running suite " + size);
                suite = [size];
			} else {
			    if (size !== "all") {
			        console.log("Suite " + size + " is unrecognized. Testing all suites by default.");
			    } else {
			        console.log("Testing all suites.");
			    }
                suite = suiteDefinitions.full;
			}
		}
		compilation = process.argv[3];
		if (compilation !== "uncompiled" && compilation !== "compiled") {
			console.log("Compilation " + compilation + " is unknown. Using 'compiled' by default.");
			compilation = "compiled";
		}
	}
	assembly = process.argv[2];
	if (assembly !== "assembled" && assembly !== "dynamicdata" && assembly !== "dynamic") {
		// assembled: pre-assembled code and locale data together in one file
		// dynamicdata: pre-assembled code, but dynamically loaded locale data
		// dynamic: dynamically loaded code and locale data
		console.log("Assembly " + assembly + " is unknown. Using 'dynamic' by default.");
		compilation = "dynamic";
	}
}

console.log("Running " + compilation + " " + assembly + " suites: " + JSON.stringify(suite));

var fileName = "../output/js/ilib-ut" + ((assembly === "dynamicdata") ? "-dyn" : "") + ((compilation === "compiled") ? "-compiled" : "") + ".js";
var script = fs.readFileSync(fileName, "utf-8");
eval(script);

switch (assembly) {
default:
case "dynamic":
    ilib.setLoaderCallback(NodeLoader(ilib));

    ilib._dyncode = true; // indicate that we are using dynamically loaded code
    ilib._dyndata = true;
    break;
case "dynamicdata":
    ilib.setLoaderCallback(NodeLoader(ilib));

    ilib._dyncode = false;
    ilib._dyndata = true;
    break;
case "assembled":
    CType._init(true);
    NormString.init();

    ilib._dyncode = false;
    ilib._dyndata = false;
    break;
}

var suites;
var modules = {};

for (var i = 0; i < suite.length; i++) {
    console.log("Adding suite: " + suite[i]);
    suites = require("./" + path.join(suite[i], "nodeunit/testSuiteFiles.js")).files.forEach(function(file) {
        var test = require("./" + path.join(suite[i], "nodeunit", file));
        modules[suite[i]] = test;
    });
}

console.log("Running suites: " + JSON.stringify(Object.keys(modules)));

reporter.run(modules);<commit_msg>All unit tests pass now<commit_after>/*
 * testRunner.js - top level test suite
 *
 * Copyright © 2017, JEDLSoft
 *
 * 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.
 */

var util = require("util");
var fs = require("fs");

var path = require("../lib/Path.js");
var TestLoader = require("./TestLoader.js");
var NodeLoader = require("../lib/NodeLoader.js");

var nodeunit = require("nodeunit");
var reporter = nodeunit.reporters.minimal;

var suiteDefinitions = {
	"core": [
	    "util",
	    "root"
	],
	"standard": [
		"util",
		"root",
		"calendar",
		"date",
		"daterange",
		"durfmt",
		"number",
		"maps",
		"ctype"
	],
	"full": [
		"util",
		"root",
		"calendar",
		"date",
		"daterange",
		"durfmt",
		"number",
		"maps",
		"ctype",
		"strings-ext",
		"phone",
		"units",
		"name",
		"address",
		"collate"
	]
};

// override the possible node environment to make the tests uniform
process.env.TZ = "";
process.env.LANG = "";
process.env.LC_ALL = "";

var assembly = "dynamic";
var compilation = "uncompiled";
var size = "full";
var suite = suiteDefinitions.full;

// Usage: testSuite.js [assembly_style [compilation_style [suite_name_or_collection]]]
if (process.argv.length > 2) {
	if (process.argv.length > 3) {
		if (process.argv.length > 4) {
			if (process.argv.length > 5) {
				set = process.argv[5];
			}

			size = process.argv[4];
			if (suiteDefinitions[size]) {
                console.log("Only running set " + size);
                suite = suiteDefinitions[size];
			} else if (suiteDefinitions.full.indexOf(size) > -1) {
                console.log("Only running suite " + size);
                suite = [size];
			} else {
			    if (size !== "all") {
			        console.log("Suite " + size + " is unrecognized. Testing all suites by default.");
			    } else {
			        console.log("Testing all suites.");
			    }
                suite = suiteDefinitions.full;
			}
		}
		compilation = process.argv[3];
		if (compilation !== "uncompiled" && compilation !== "compiled") {
			console.log("Compilation " + compilation + " is unknown. Using 'compiled' by default.");
			compilation = "compiled";
		}
	}
	assembly = process.argv[2];
	if (assembly !== "assembled" && assembly !== "dynamicdata" && assembly !== "dynamic") {
		// assembled: pre-assembled code and locale data together in one file
		// dynamicdata: pre-assembled code, but dynamically loaded locale data
		// dynamic: dynamically loaded code and locale data
		console.log("Assembly " + assembly + " is unknown. Using 'dynamic' by default.");
		compilation = "dynamic";
	}
}

console.log("Running " + compilation + " " + assembly + " suites: " + JSON.stringify(suite));

var fileName = "../output/js/ilib-ut" + ((assembly === "dynamicdata") ? "-dyn" : "") + ((compilation === "compiled") ? "-compiled" : "") + ".js";
console.log("loading in " + fileName);
var script = fs.readFileSync(fileName, "utf-8");
eval(script);

switch (assembly) {
default:
case "dynamic":
    ilib.setLoaderCallback(NodeLoader(ilib));

    ilib._dyncode = true; // indicate that we are using dynamically loaded code
    ilib._dyndata = true;
    break;
case "dynamicdata":
    ilib.setLoaderCallback(NodeLoader(ilib));

    ilib._dyncode = false;
    ilib._dyndata = true;
    break;
case "assembled":
    CType._init(true);
    NormString.init();

    ilib._dyncode = false;
    ilib._dyndata = false;
    break;
}

var suites;
var modules = {};

for (var i = 0; i < suite.length; i++) {
    console.log("Adding suite: " + suite[i]);
    suites = require("./" + path.join(suite[i], "nodeunit/testSuiteFiles.js")).files.forEach(function(file) {
        var test = require("./" + path.join(suite[i], "nodeunit", file));
        modules[suite[i]] = test;
    });
}

reporter.run(modules);<|endoftext|>