<commit_before>// Copyright 2014, Renasar Technologies Inc.
/* jshint: node:true */

'use strict';

var di = require('di');

module.exports = taskGraphRunnerProtocolFactory;

di.annotate(taskGraphRunnerProtocolFactory, new di.Provide('Protocol.TaskGraphRunner'));
di.annotate(taskGraphRunnerProtocolFactory,
    new di.Inject(
        'Services.Messenger',
        'Protocol.Exchanges.TaskGraphRunner',
        'Assert',
        '_'
    )
);

function taskGraphRunnerProtocolFactory (messenger, taskGrapRunnerExchange, assert, _) {
    function TaskGraphRunnerProtocol() {
    }

    TaskGraphRunnerProtocol.prototype.getTaskGraphLibrary = function getTaskGraphLibrary(filter) {
        return messenger.request(
            taskGrapRunnerExchange.exchange,
            'methods.getTaskGraphLibrary',
            { filter: filter }
        ).then(function(message) {
            assert.object(message);
            return _.isEmpty(message.data) ? undefined : message.data.result;
        });
    };

    TaskGraphRunnerProtocol.prototype.getActiveTaskGraphs = function getActiveTaskGraphs(filter) {
        return messenger.request(
            taskGrapRunnerExchange.exchange,
            'methods.getActiveTaskGraphs',
            { filter: filter }
        ).then(function(message) {
            assert.object(message);
            return _.isEmpty(message.data) ? undefined : message.data.result;
        });
    };

    TaskGraphRunnerProtocol.prototype.defineTaskGraph = function defineTaskGraph(definition) {
        return messenger.request(
            taskGrapRunnerExchange.exchange,
            'methods.defineTaskGraph',
            { definition: definition }
        ).then(function(message) {
            assert.object(message);
            return _.isEmpty(message.data) ? undefined : message.data.result;
        });
    };

    TaskGraphRunnerProtocol.prototype.runTaskGraph = function runTaskGraph(name, options) {
        return messenger.request(
            taskGrapRunnerExchange.exchange,
            'methods.runTaskGraph',
            { name: name, options: options }
        ).then(function(message) {
            assert.object(message);
            return _.isEmpty(message.data) ? undefined : message.data.result;
        });
    };

    TaskGraphRunnerProtocol.prototype.cancelTaskGraph = function cancelTaskGraph(instance) {
        return messenger.request(
            taskGrapRunnerExchange.exchange,
            'methods.cancelTaskGraph',
            { instance: instance }
        ).then(function(message) {
            assert.object(message);
            return _.isEmpty(message.data) ? undefined : message.data.result;
        });
    };

    TaskGraphRunnerProtocol.prototype.pauseTaskGraph = function pauseTaskGraph(instance) {
        return messenger.request(
            taskGrapRunnerExchange.exchange,
            'methods.pauseTaskGraph',
            { instance: instance }
        ).then(function(message) {
            assert.object(message);
            return _.isEmpty(message.data) ? undefined : message.data.result;
        });
    };

    TaskGraphRunnerProtocol.prototype.resumeTaskGraph = function resumeTaskGraph(instance) {
        return messenger.request(
            taskGrapRunnerExchange.exchange,
            'methods.resumeTaskGraph',
            { instance: instance }
        ).then(function(message) {
            assert.object(message);
            return _.isEmpty(message.data) ? undefined : message.data.result;
        });
    };

    TaskGraphRunnerProtocol.prototype.subscribeGetTaskGraphLibrary =
                        function subscribeGetTaskGraphLibrary(callback) {
        return messenger.subscribe(
            taskGrapRunnerExchange.exchange,
            'methods.getTaskGraphLibrary', function(message) {
                var _callback = callback;
                assert.object(message);
                var result = _callback(message.data ? message.data.filter : undefined);
                message.respond({ result: result });
            }
        );
    };

    TaskGraphRunnerProtocol.prototype.subscribeDefineTaskGraph =
                                        function subscribeDefineTaskGraph(callback) {
        return messenger.subscribe(
            taskGrapRunnerExchange.exchange,
            'methods.subscribeDefineTaskGraph', function(message) {
                var _callback = callback;
                assert.object(message);
                assert.object(message.data);
                assert.object(message.data.definition);
                var result = _callback(message.data.definition);
                message.respond({ result: result });
            }
        );
    };

    TaskGraphRunnerProtocol.prototype.subscribeGetActiveTaskGraphs =
                                        function subscribeGetActiveTaskGraphs(callback) {
        return messenger.subscribe(
            taskGrapRunnerExchange.exchange,
            'methods.subscribeGetActiveTaskGraphs', function(message) {
                var _callback = callback;
                assert.object(message);
                var result = _callback(message.data ? message.data.filter : undefined);
                message.respond({ result: result });
            }
        );
    };

    TaskGraphRunnerProtocol.prototype.subscribeRunTaskGraph =
                                        function subscribeRunTaskGraph(callback) {
        return messenger.subscribe(
            taskGrapRunnerExchange.exchange,
            'methods.subscribeRunTaskGraph', function(message) {
                var _callback = callback;
                assert.object(message);
                assert.object(message.data);
                assert.string(message.data.name);
                assert.object(message.data.options);
                var result = _callback(message.data.name, message.data.options);
                message.respond({ result: result });
            }
        );
    };

    TaskGraphRunnerProtocol.prototype.subscribeCancelTaskGraph =
                                        function subscribeCancelTaskGraph(callback) {
        return messenger.subscribe(
            taskGrapRunnerExchange.exchange,
            'methods.subscribeCancelTaskGraph', function(message) {
                var _callback = callback;
                assert.object(message);
                assert.object(message.data);
                assert.string(message.data.instance);
                var result = _callback(message.data.instance);
                message.respond({ result: result });
            }
        );
    };

    TaskGraphRunnerProtocol.prototype.subscribePauseTaskGraph =
                                        function subscribePauseTaskGraph(callback) {
        return messenger.subscribe(
            taskGrapRunnerExchange.exchange,
            'methods.subscribePauseTaskGraph', function(message) {
                var _callback = callback;
                assert.object(message);
                assert.object(message.data);
                assert.string(message.data.instance);
                var result = _callback(message.data.instance);
                message.respond({ result: result });
            }
        );
    };

    TaskGraphRunnerProtocol.prototype.subscribeResumeTaskGraph =
                                        function subscribeResumeTaskGraph(callback) {
        return messenger.subscribe(
            taskGrapRunnerExchange.exchange,
            'methods.subscribeResumeTaskGraph', function(message) {
                var _callback = callback;
                assert.object(message);
                assert.object(message.data);
                assert.string(message.data.instance);
                var result = _callback(message.data.instance);
                message.respond({ result: result });
            }
        );
    };

    return new TaskGraphRunnerProtocol();
}
<commit_msg>adding getProperties to taskgraph protocol<commit_after>// Copyright 2014, Renasar Technologies Inc.
/* jshint: node:true */

'use strict';

var di = require('di');

module.exports = taskGraphRunnerProtocolFactory;

di.annotate(taskGraphRunnerProtocolFactory, new di.Provide('Protocol.TaskGraphRunner'));
di.annotate(taskGraphRunnerProtocolFactory,
    new di.Inject(
        'Services.Messenger',
        'Protocol.Exchanges.TaskGraphRunner',
        'Assert',
        '_'
    )
);

function taskGraphRunnerProtocolFactory (messenger, taskGrapRunnerExchange, assert, _) {
    function TaskGraphRunnerProtocol() {
    }

    TaskGraphRunnerProtocol.prototype.getTaskGraphLibrary = function getTaskGraphLibrary(filter) {
        return messenger.request(
            taskGrapRunnerExchange.exchange,
            'methods.getTaskGraphLibrary',
            { filter: filter }
        ).then(function(message) {
            assert.object(message);
            return _.isEmpty(message.data) ? undefined : message.data.result;
        });
    };

    TaskGraphRunnerProtocol.prototype.getActiveTaskGraphs = function getActiveTaskGraphs(filter) {
        return messenger.request(
            taskGrapRunnerExchange.exchange,
            'methods.getActiveTaskGraphs',
            { filter: filter }
        ).then(function(message) {
            assert.object(message);
            return _.isEmpty(message.data) ? undefined : message.data.result;
        });
    };

    TaskGraphRunnerProtocol.prototype.defineTaskGraph = function defineTaskGraph(definition) {
        return messenger.request(
            taskGrapRunnerExchange.exchange,
            'methods.defineTaskGraph',
            { definition: definition }
        ).then(function(message) {
            assert.object(message);
            return _.isEmpty(message.data) ? undefined : message.data.result;
        });
    };

    TaskGraphRunnerProtocol.prototype.runTaskGraph = function runTaskGraph(name, options) {
        return messenger.request(
            taskGrapRunnerExchange.exchange,
            'methods.runTaskGraph',
            { name: name, options: options }
        ).then(function(message) {
            assert.object(message);
            return _.isEmpty(message.data) ? undefined : message.data.result;
        });
    };

    TaskGraphRunnerProtocol.prototype.cancelTaskGraph = function cancelTaskGraph(instance) {
        return messenger.request(
            taskGrapRunnerExchange.exchange,
            'methods.cancelTaskGraph',
            { instance: instance }
        ).then(function(message) {
            assert.object(message);
            return _.isEmpty(message.data) ? undefined : message.data.result;
        });
    };

    TaskGraphRunnerProtocol.prototype.pauseTaskGraph = function pauseTaskGraph(instance) {
        return messenger.request(
            taskGrapRunnerExchange.exchange,
            'methods.pauseTaskGraph',
            { instance: instance }
        ).then(function(message) {
            assert.object(message);
            return _.isEmpty(message.data) ? undefined : message.data.result;
        });
    };

    TaskGraphRunnerProtocol.prototype.resumeTaskGraph = function resumeTaskGraph(instance) {
        return messenger.request(
            taskGrapRunnerExchange.exchange,
            'methods.resumeTaskGraph',
            { instance: instance }
        ).then(function(message) {
            assert.object(message);
            return _.isEmpty(message.data) ? undefined : message.data.result;
        });
    };

    TaskGraphRunnerProtocol.prototype.getTaskGraphProperties = function getTaskGraphProperties(instance) {
        return messenger.request(
            taskGrapRunnerExchange.exchange,
            'methods.getTaskGraphProperties',
            { instance: instance }
        ).then(function(message) {
                assert.object(message);
                return _.isEmpty(message.data) ? undefined : message.data.result;
            });
    };

    TaskGraphRunnerProtocol.prototype.subscribeGetTaskGraphLibrary =
                        function subscribeGetTaskGraphLibrary(callback) {
        return messenger.subscribe(
            taskGrapRunnerExchange.exchange,
            'methods.getTaskGraphLibrary', function(message) {
                var _callback = callback;
                assert.object(message);
                var result = _callback(message.data ? message.data.filter : undefined);
                message.respond({ result: result });
            }
        );
    };

    TaskGraphRunnerProtocol.prototype.subscribeDefineTaskGraph =
                                        function subscribeDefineTaskGraph(callback) {
        return messenger.subscribe(
            taskGrapRunnerExchange.exchange,
            'methods.subscribeDefineTaskGraph', function(message) {
                var _callback = callback;
                assert.object(message);
                assert.object(message.data);
                assert.object(message.data.definition);
                var result = _callback(message.data.definition);
                message.respond({ result: result });
            }
        );
    };

    TaskGraphRunnerProtocol.prototype.subscribeGetActiveTaskGraphs =
                                        function subscribeGetActiveTaskGraphs(callback) {
        return messenger.subscribe(
            taskGrapRunnerExchange.exchange,
            'methods.subscribeGetActiveTaskGraphs', function(message) {
                var _callback = callback;
                assert.object(message);
                var result = _callback(message.data ? message.data.filter : undefined);
                message.respond({ result: result });
            }
        );
    };

    TaskGraphRunnerProtocol.prototype.subscribeRunTaskGraph =
                                        function subscribeRunTaskGraph(callback) {
        return messenger.subscribe(
            taskGrapRunnerExchange.exchange,
            'methods.subscribeRunTaskGraph', function(message) {
                var _callback = callback;
                assert.object(message);
                assert.object(message.data);
                assert.string(message.data.name);
                assert.object(message.data.options);
                var result = _callback(message.data.name, message.data.options);
                message.respond({ result: result });
            }
        );
    };

    TaskGraphRunnerProtocol.prototype.subscribeCancelTaskGraph =
                                        function subscribeCancelTaskGraph(callback) {
        return messenger.subscribe(
            taskGrapRunnerExchange.exchange,
            'methods.subscribeCancelTaskGraph', function(message) {
                var _callback = callback;
                assert.object(message);
                assert.object(message.data);
                assert.string(message.data.instance);
                var result = _callback(message.data.instance);
                message.respond({ result: result });
            }
        );
    };

    TaskGraphRunnerProtocol.prototype.subscribePauseTaskGraph =
                                        function subscribePauseTaskGraph(callback) {
        return messenger.subscribe(
            taskGrapRunnerExchange.exchange,
            'methods.subscribePauseTaskGraph', function(message) {
                var _callback = callback;
                assert.object(message);
                assert.object(message.data);
                assert.string(message.data.instance);
                var result = _callback(message.data.instance);
                message.respond({ result: result });
            }
        );
    };

    TaskGraphRunnerProtocol.prototype.subscribeResumeTaskGraph =
                                        function subscribeResumeTaskGraph(callback) {
        return messenger.subscribe(
            taskGrapRunnerExchange.exchange,
            'methods.subscribeResumeTaskGraph', function(message) {
                var _callback = callback;
                assert.object(message);
                assert.object(message.data);
                assert.string(message.data.instance);
                var result = _callback(message.data.instance);
                message.respond({ result: result });
            }
        );
    };

    TaskGraphRunnerProtocol.prototype.subscribeGetTaskGraphProperties =
        function subscribeGetTaskGraphProperties(callback) {
            return messenger.subscribe(
                taskGrapRunnerExchange.exchange,
                'methods.subscribeGetTaskGraphProperties', function(message) {
                    var _callback = callback;
                    assert.object(message);
                    assert.object(message.data);
                    assert.string(message.data.instance);
                    var result = _callback(message.data.instance);
                    message.respond({ result: result });
                }
            );
        };

    return new TaskGraphRunnerProtocol();
}
<|endoftext|>


<commit_before>(function() {

	var url = window.location,
		body = document.body,
		slides = document.querySelectorAll('div.slide'),
		progress = document.querySelector('div.progress div'),
		slideList = [];

	for(var i = 0, slidesLength = slides.length; i < slidesLength; i++) {
		slides[i].firstChild.addEventListener('click', enterFull, false);
		slideList[i] = slides[i].id;
	}

	function resizeFull(p) {
		if(typeof p == 'boolean' && !p) {
			var transform = 'none';
		} else {
			var sx = body.clientWidth / window.innerWidth,
				sy = body.clientHeight / window.innerHeight,
				transform = 'scale(' + (1/Math.max(sx, sy)) + ')';
		}
		body.style.MozTransform = transform;
		body.style.WebkitTransform = transform;
		body.style.OTransform = transform;
		body.style.msTransform = transform;
		body.style.transform = transform;
	}

	function turnSlide(e) {
		var current = slideList.indexOf(url.hash.substr(1)), target;
		if(e) {
			if(e.type == 'keydown') {
				var prevent = true;
				switch(e.which) {
					case 33 : // PgUp
					case 38 : // Up
					case 37 : // Left
					case 75 : // k
						current--;
						break;
					case 34 : // PgDown
					case 40 : // Down
					case 39 : // Right
					case 74 : // j
						current++;
						break;
					case 36 : // Home
						current = 0;
						break;
					case 35 : // End
						current = slideList.length-1;
						break;
					case 32 : // Space
						current += e.shiftKey ? -1 : 1;
						break;
					default:
						prevent = false;
				}
				if(prevent) e.preventDefault();
			}
			if(e.type == 'click') {
				current = slideList.indexOf(e.target.parentNode.parentNode.id);
			}
		} else {
			current = (current+1) ? current : 0;
		}
		target = slideList[current];
		if(target) url.hash = target;
		updateProgress();
	}

	function enterFull(e) {
		body.className = 'full';
		resizeFull(true);
		turnSlide(e);
		updateProgress();
		if(!isFull()) history.pushState(null, null, url.pathname + '?full' + url.hash);
		window.addEventListener('resize', resizeFull, false);
		document.addEventListener('keyup', exitFullKey, false);
		document.removeEventListener('keydown', enterFullKey, false);
	}

	function enterFullKey(e) {
		if(e.which != 13) return;
		enterFull();
	}

	function exitFull() {
		body.className = 'list';
		resizeFull(false);
		var hash = url.hash;
		history.pushState(null, null, url.pathname.replace('?full', ''));
		url.hash = hash;
		window.removeEventListener('resize', resizeFull, false);
		document.removeEventListener('keyup', exitFullKey, false);
		document.addEventListener('keydown', enterFullKey, false);
	}

	function exitFullKey(e) {
		if(e.which != 27) return;
		exitFull();
	}

	function isFull() {
		return url.search.substr(1) == 'full';
	}

	function updateProgress() {
		if(!progress) return;
		progress.style.width = (100/(slideList.length-1) * slideList.indexOf(url.hash.substr(1))).toFixed(2) + '%';
	}

	window.addEventListener('DOMContentLoaded', function() {
		if(isFull()) enterFull();
	}, false);
	document.addEventListener('keydown', turnSlide, false);
	document.addEventListener('keydown', enterFullKey, false);

})();<commit_msg>Fix issue #30<commit_after>(function() {

	var url = window.location,
		body = document.body,
		slides = document.querySelectorAll('div.slide'),
		progress = document.querySelector('div.progress div'),
		slideList = [];

	for(var i = 0, slidesLength = slides.length; i < slidesLength; i++) {
		slides[i].firstChild.addEventListener('click', enterFull, false);
		slideList[i] = slides[i].id;
	}

	function resizeFull(p) {
		if(typeof p == 'boolean' && !p) {
			var transform = 'none';
		} else {
			var sx = body.clientWidth / window.innerWidth,
				sy = body.clientHeight / window.innerHeight,
				transform = 'scale(' + (1/Math.max(sx, sy)) + ')';
		}
		body.style.MozTransform = transform;
		body.style.WebkitTransform = transform;
		body.style.OTransform = transform;
		body.style.msTransform = transform;
		body.style.transform = transform;
	}

	function turnSlide(e) {
		var current = slideList.indexOf(url.hash.substr(1)), target;
		if(e) {
			if(e.type == 'keydown') {
				var prevent = true;
				switch(e.which) {
					case 33 : // PgUp
					case 38 : // Up
					case 37 : // Left
					case 75 : // k
						current--;
						break;
					case 34 : // PgDown
					case 40 : // Down
					case 39 : // Right
					case 74 : // j
						current++;
						break;
					case 36 : // Home
						current = 0;
						break;
					case 35 : // End
						current = slideList.length-1;
						break;
					case 32 : // Space
						current += e.shiftKey ? -1 : 1;
						break;
					default:
						prevent = false;
				}
				if(prevent) e.preventDefault();
			}
			if(e.type == 'click') {
				current = slideList.indexOf(e.target.parentNode.parentNode.id);
			}
		} else {
			current = (current+1) ? current : 0;
		}
		target = slideList[current];
		if(target) url.hash = target;
		updateProgress();
	}

	function enterFull(e) {
		body.className = 'full';
		resizeFull(true);
		turnSlide(e);
		updateProgress();
		if(!isFull()) history.pushState(null, null, url.pathname + '?full' + url.hash);
		window.addEventListener('resize', resizeFull, false);
		document.addEventListener('keyup', exitFullKey, false);
		document.removeEventListener('keydown', enterFullKey, false);
	}

	function enterFullKey(e) {
		if(e.which != 13) return;
		enterFull();
	}

	function exitFull() {
		body.className = 'list';
		resizeFull(false);
		var hash = url.hash;
		history.pushState(null, null, url.pathname.replace('?full', ''));
		url.hash = hash;
		window.removeEventListener('resize', resizeFull, false);
		document.removeEventListener('keyup', exitFullKey, false);
		document.addEventListener('keydown', enterFullKey, false);
	}

	function exitFullKey(e) {
		if(e.which != 27) return;
		exitFull();
	}

	function isFull() {
		return url.search.substr(1) == 'full';
	}

	function updateProgress() {
		if(!progress) return;
		progress.style.width = (100/(slideList.length-1) * slideList.indexOf(url.hash.substr(1))).toFixed(2) + '%';
	}

	window.addEventListener('DOMContentLoaded', function() {
		if(isFull()) enterFull();
	}, false);
	window.addEventListener("popstate", function() {
		var current_slide_number = slideList.indexOf(url.hash.substr(1));
		if (-1 === current_slide_number) { exitFull(); }
	}, false);

	document.addEventListener('keydown', turnSlide, false);
	document.addEventListener('keydown', enterFullKey, false);

})();
<|endoftext|>


<commit_before>
goog.require('goog.debug.Console');
goog.require('goog.testing.jsunit');
goog.require('ydn.async');
goog.require('ydn.db.Core');
goog.require('goog.testing.PropertyReplacer');

var reachedFinalContinuation, basic_schema;
var table_name = 't1';
var stubs;

var setUp = function() {
  var c = new goog.debug.Console();
  c.setCapturing(true);
  goog.debug.LogManager.getRoot().setLevel(goog.debug.Logger.Level.FINE);
  //goog.debug.Logger.getLogger('ydn.gdata.MockServer').setLevel(goog.debug.Logger.Level.FINEST);
  goog.debug.Logger.getLogger('ydn.db').setLevel(goog.debug.Logger.Level.FINEST);
  ydn.db.IndexedDbWrapper.DEBUG = true;

	basic_schema = new ydn.db.DatabaseSchema(1);
  var index = new ydn.db.IndexSchema('id');
  var store = new ydn.db.StoreSchema(table_name, 'id', false, [index]);
	basic_schema.addStore(store);
};

var tearDown = function() {
  assertTrue('The final continuation was not reached', reachedFinalContinuation);
};

var test_1_idb_basic = function() {

  var options = {preference: ['indexeddb']};
  var db_name = 'test_core_basic_1';
  var db = new ydn.db.Core(db_name, basic_schema, options);

  var val = {id: 'a', value: Math.random()};

  var t1_fired = false;
  var result;

  waitForCondition(
      // Condition
      function() { return t1_fired; },
      // Continuation
      function() {
        assertSame('correct obj', val, result);
        reachedFinalContinuation = true;

      },
      100, // interval
      2000); // maxTimeout

  db.transaction(function(tx) {
    console.log('tx started.');
    var store = tx.objectStore(table_name);
    store.put(val);
    tx.addEventListener('complete', function(e) {
      console.log('put ok: ' + e.target.result);
      store = tx.objectStore(table_name);
      store.get('a');
      tx.addEventListener('complete', function(e) {
        t1_fired = true;
        result = e.target.result;
        console.log('get ok: ' + JSON.stringify(result));
      }, false);
    }, false);
  }, table_name, 'readwrite');
};

var testCase = new goog.testing.ContinuationTestCase();
testCase.autoDiscoverTests();
G_testRunner.initialize(testCase);

<commit_msg>core test.<commit_after>
goog.require('goog.debug.Console');
goog.require('goog.testing.jsunit');
goog.require('ydn.async');
goog.require('ydn.db.Core');
goog.require('goog.testing.PropertyReplacer');

var reachedFinalContinuation, basic_schema;
var table_name = 't1';
var stubs;

var setUp = function() {
  var c = new goog.debug.Console();
  c.setCapturing(true);
  goog.debug.LogManager.getRoot().setLevel(goog.debug.Logger.Level.FINE);
  //goog.debug.Logger.getLogger('ydn.gdata.MockServer').setLevel(goog.debug.Logger.Level.FINEST);
  goog.debug.Logger.getLogger('ydn.db').setLevel(goog.debug.Logger.Level.FINEST);
  ydn.db.IndexedDbWrapper.DEBUG = true;

	basic_schema = new ydn.db.DatabaseSchema(1);
  var index = new ydn.db.IndexSchema('id');
  var store = new ydn.db.StoreSchema(table_name, 'id', false, [index]);
	basic_schema.addStore(store);
};

var tearDown = function() {
  assertTrue('The final continuation was not reached', reachedFinalContinuation);
};

var test_1_idb_basic = function() {

  var db_type =  'indexeddb';
  var options = {preference: [db_type]};
  var db_name = 'test_core_basic_1';
  var db = new ydn.db.Core(db_name, basic_schema, options);

  var val = {id: 'a', value: Math.random()};

  var t1_fired = false;
  var result;

  waitForCondition(
      // Condition
      function() { return t1_fired; },
      // Continuation
      function() {
        assertEquals('database type', db_type, db.type());
        assertEquals('correct obj', val.value, result.value);
        reachedFinalContinuation = true;

      },
      100, // interval
      2000); // maxTimeout

  db.transaction(function(tx) {
    console.log('tx started.');
    var store = tx.objectStore(table_name);
    var request = store.put(val);
    request.onsuccess = function(e) {
      console.log('put ok: ' + e.target.result);
      store.get('a').onsuccess = function(e) {
        t1_fired = true;
        result = e.target.result;
        console.log('get ok: ' + JSON.stringify(result));
      };
    };
  }, table_name, 'readwrite');
};

var test_2_websql_basic = function() {

  var db_type =  'websql';
  var options = {preference: [db_type]};
  var db_name = 'test_core_basic_1';
  var db = new ydn.db.Core(db_name, basic_schema, options);

  var val = {id: 'a', value: Math.random()};

  var t1_fired = false;
  var result;

  waitForCondition(
    // Condition
    function() { return t1_fired; },
    // Continuation
    function() {
      assertEquals('database type', db_type, db.type());
      assertEquals('correct val', val.value, result.value);
      reachedFinalContinuation = true;

    },
    100, // interval
    2000); // maxTimeout

  db.transaction(function(tx) {
    // note _default_ column
    tx.executeSql('INSERT OR REPLACE INTO ' + table_name +
      ' (id, _default_) VALUES (?, ?)', [val.id, JSON.stringify(val)], function(e) {
      console.log(e);
      console.log('Received put result ');
      tx.executeSql('SELECT * FROM ' + table_name +
        ' WHERE id = ?', [val.id], function(transaction, e) {
        console.log(e);
        var row = e.rows.item(0);
        result = JSON.parse(row['_default_']);
        console.log('Received get result ' + result);
        t1_fired = true;
      }, function error_cb(e) {
        console.log(e);
        fail('wrong sql?');
      })
    });
  }, table_name, 'readwrite');
};

var testCase = new goog.testing.ContinuationTestCase();
testCase.autoDiscoverTests();
G_testRunner.initialize(testCase);

<|endoftext|>


<commit_before>var chai = require('chai'),
   Hapi = require('hapi'),
   assert = chai.assert,
   Joi = require('joi'),
   swagger = require('../lib/index.js');

describe('docs tags', function() {

  var server;

  beforeEach(function(done) {
    server = new Hapi.Server({debug: false});
    server.pack.register(swagger, function(err) {
      assert.ifError(err)
      done();
    });
  });

  afterEach(function(done) {
    server.stop(function() {
      server = null;
      done();
    });
  });

  it('loads the docs without error', function(done){
    server.route({
        method: 'GET',
        path: '/test',
        handler: function(request, response) {
          reply('ok');
        },
        config: {
          tags: ['api'],
          validate: {
            query: Joi.any()
          }
        }
    });

    server.inject({method: 'GET', url: '/docs'}, function(response) {
      assert(response.statusCode === 200)
      done();
    })
  });

  it('filters routes by tags', function(done){
    server.route([
      {
          method: 'GET',
          path: '/test',
          handler: function(request, response) {
            reply('ok');
          },
          config: {
            tags: ['api', 'test'],
            validate: {
              query: Joi.any()
            }
          }
      },
      {
          method: 'GET',
          path: '/notest',
          handler: function(request, response) {
            reply('ok');
          },
          config: {
            tags: ['api', 'not'],
            validate: {
              query: Joi.any()
            }
          }
      }
    ]);

    server.inject({method: 'GET', url: '/docs?tags=test'}, function(response) {
      assert(response.statusCode === 200)
      assert(response.result.apis.length == 1 && response.result.apis[0].path == 'test')
      done();
    })
  });

  it('filters out routes with minus tags', function(done){
    server.route([
      {
          method: 'GET',
          path: '/include',
          handler: function(request, response) {
            reply('ok');
          },
          config: {
            tags: ['api', 'include'],
            validate: {
              query: Joi.any()
            }
          }
      },
      {
          method: 'GET',
          path: '/notinclude',
          handler: function(request, response) {
            reply('ok');
          },
          config: {
            tags: ['api', 'include', 'notinclude'],
            validate: {
              query: Joi.any()
            }
          }
      }
    ]);

    server.inject({method: 'GET', url: '/docs?tags=include,-notinclude'}, function(response) {
      assert(response.statusCode === 200)
      assert(response.result.apis.length == 1 && response.result.apis[0].path == 'include')
      done();
    })
  });

  it('filters in only routes with both tags when plus operator is used', function(done){
    server.route([
      {
          method: 'GET',
          path: '/onetag',
          handler: function(request, response) {
            reply('ok');
          },
          config: {
            tags: ['api', 'include'],
            validate: {
              query: Joi.any()
            }
          }
      },
      {
          method: 'GET',
          path: '/bothtags',
          handler: function(request, response) {
            reply('ok');
          },
          config: {
            tags: ['api', 'include', 'alsoinclude'],
            validate: {
              query: Joi.any()
            }
          }
      }
    ]);

    server.inject({method: 'GET', url: '/docs?tags=include,+alsoinclude'}, function(response) {
      assert(response.statusCode === 200)
      assert(response.result.apis.length == 1 && response.result.apis[0].path == 'bothtags')
      done();
    })
  });

  it('returns 404 if no routes are returned', function(done){
    server.route([
      {
          method: 'GET',
          path: '/onetag',
          handler: function(request, response) {
            reply('ok');
          },
          config: {
            tags: ['api', 'include'],
            validate: {
              query: Joi.any()
            }
          }
      },
      {
          method: 'GET',
          path: '/bothtags',
          handler: function(request, response) {
            reply('ok');
          },
          config: {
            tags: ['alsoinclude'],
            validate: {
              query: Joi.any()
            }
          }
      }
    ]);

    server.inject({method: 'GET', url: '/docs?tags=notvalid'}, function(response) {
      assert(response.statusCode === 404)
      done();
    })
  });

});

describe('docs path', function() {

  var server;

  beforeEach(function(done) {
    server = new Hapi.Server({debug: false});
    server.pack.register(swagger, function(err) {
      assert.ifError(err)
      done();
    });
  });

  afterEach(function(done) {
    server.stop(function() {
      server = null;
      done();
    });
  });

  it('returns routes filtered by path', function(done){
    server.route([
      {
          method: 'GET',
          path: '/parent/child1',
          handler: function(request, response) {
            reply('ok');
          },
          config: {
            tags: ['api', 'include'],
            validate: {
              query: Joi.any()
            }
          }
      },
      {
          method: 'GET',
          path: '/parent/child2',
          handler: function(request, response) {
            reply('ok');
          },
          config: {
            tags: ['api', 'alsoinclude'],
            validate: {
              query: Joi.any()
            }
          }
      },
      {
          method: 'GET',
          path: '/parent2/child2',
          handler: function(request, response) {
            reply('ok');
          },
          config: {
            tags: ['alsoinclude'],
            validate: {
              query: Joi.any()
            }
          }
      }
    ]);

    server.inject({method: 'GET', url: '/docs?path=parent'}, function(response) {
      console.log(response.result)
      assert(response.statusCode === 200)
      assert(response.result.apis.length == 2)
      done();
    })
  });
})<commit_msg>small refactor<commit_after>var chai = require('chai'),
   Hapi = require('hapi'),
   assert = chai.assert,
   Joi = require('joi'),
   swagger = require('../lib/index.js');

var defaultHandler = function(request, response) {
  reply('ok');
};

describe('docs tags', function() {

  var server;

  beforeEach(function(done) {
    server = new Hapi.Server({debug: false});
    server.pack.register(swagger, function(err) {
      assert.ifError(err)
      done();
    });
  });

  afterEach(function(done) {
    server.stop(function() {
      server = null;
      done();
    });
  });

  it('loads the docs without error', function(done){
    server.route({
        method: 'GET',
        path: '/test',
        handler: defaultHandler,
        config: {
          tags: ['api']
        }
    });

    server.inject({method: 'GET', url: '/docs'}, function(response) {
      assert(response.statusCode === 200);
      done();
    });
  });

  it('filters routes by tags', function(done){
    server.route([
      {
          method: 'GET',
          path: '/test',
          handler: defaultHandler,
          config: {
            tags: ['api', 'test']
          }
      },
      {
          method: 'GET',
          path: '/notest',
          handler: defaultHandler,
          config: {
            tags: ['api', 'not']
          }
      }
    ]);

    server.inject({method: 'GET', url: '/docs?tags=test'}, function(response) {
      assert(response.statusCode === 200);
      assert(response.result.apis.length == 1 && response.result.apis[0].path == 'test');
      done();
    });
  });

  it('filters out routes with minus tags', function(done){
    server.route([
      {
          method: 'GET',
          path: '/include',
          handler: defaultHandler,
          config: {
            tags: ['api', 'include']
          }
      },
      {
          method: 'GET',
          path: '/notinclude',
          handler: defaultHandler,
          config: {
            tags: ['api', 'include', 'notinclude']
          }
      }
    ]);

    server.inject({method: 'GET', url: '/docs?tags=include,-notinclude'}, function(response) {
      assert(response.statusCode === 200);
      assert(response.result.apis.length == 1 && response.result.apis[0].path == 'include');
      done();
    });
  });

  it('filters in only routes with both tags when plus operator is used', function(done){
    server.route([
      {
          method: 'GET',
          path: '/onetag',
          handler: defaultHandler,
          config: {
            tags: ['api', 'include']
          }
      },
      {
          method: 'GET',
          path: '/bothtags',
          handler: defaultHandler,
          config: {
            tags: ['api', 'include', 'alsoinclude']
          }
      }
    ]);

    server.inject({method: 'GET', url: '/docs?tags=include,+alsoinclude'}, function(response) {
      assert(response.statusCode === 200);
      assert(response.result.apis.length == 1 && response.result.apis[0].path == 'bothtags');
      done();
    });
  });

  it('returns 404 if no routes are returned', function(done){
    server.route([
      {
          method: 'GET',
          path: '/onetag',
          handler: defaultHandler,
          config: {
            tags: ['api', 'include']
          }
      },
      {
          method: 'GET',
          path: '/bothtags',
          handler: defaultHandler,
          config: {
            tags: ['alsoinclude']
          }
      }
    ]);

    server.inject({method: 'GET', url: '/docs?tags=notvalid'}, function(response) {
      assert(response.statusCode === 404);
      done();
    })
  });
});

describe('docs path', function() {

  var server;

  beforeEach(function(done) {
    server = new Hapi.Server({debug: false});
    server.pack.register(swagger, function(err) {
      assert.ifError(err)
      done();
    });
  });

  afterEach(function(done) {
    server.stop(function() {
      server = null;
      done();
    });
  });

  it('returns routes filtered by path', function(done){
    server.route([
      {
          method: 'GET',
          path: '/parent/child1',
          handler: defaultHandler,
          config: {
            tags: ['api', 'include']
          }
      },
      {
          method: 'GET',
          path: '/parent/child2',
          handler: defaultHandler,
          config: {
            tags: ['api', 'alsoinclude']
          }
      },
      {
          method: 'GET',
          path: '/parent2/child2',
          handler: defaultHandler,
          config: {
            tags: ['alsoinclude']
          }
      }
    ]);

    server.inject({method: 'GET', url: '/docs?path=parent'}, function(response) {
      assert(response.statusCode === 200);
      assert(response.result.apis.length == 2);
      done();
    });
  });
});<|endoftext|>


<commit_before>/* global describe, it*/
/* jslint node: true, esnext: true */

"use strict";

const fs = require('fs');
const chai = require('chai');
const assert = chai.assert;
const expect = chai.expect;
const should = chai.should();

const endpointImpl = require('../lib/endpointImplementation');

describe('endpoint definition', function () {

  describe('should have correct direction', function () {

    it('for in', function () {
      const endpoint = endpointImpl.createEndpoint('e1', {
        direction: 'in'
      });
      assert(endpoint.direction === 'in');
      assert(endpoint.isIn, "isIn when in");
    });

    it('for out', function () {
      const endpoint = endpointImpl.createEndpoint('e1', {
        direction: 'out'
      });
      assert(endpoint.direction === 'out');
      assert(endpoint.isOut, "isOut when out");
    });

    it('for inout', function () {
      const endpoint = endpointImpl.createEndpoint('e1', {
        direction: 'inout'
      });
      assert(endpoint.direction === 'inout');
      assert(endpoint.isOut, "isOut when inout");
      assert(endpoint.isIn, "isOut when inout");
    });

  });

});
<commit_msg>test(endpoint): more declaration tests added<commit_after>/* global describe, it*/
/* jslint node: true, esnext: true */

"use strict";

const fs = require('fs');
const chai = require('chai');
const assert = chai.assert;
const expect = chai.expect;
const should = chai.should();

const endpointImpl = require('../lib/endpointImplementation');

describe('endpoint definition', function () {

	describe('with implementation function', function () {
		it('implementation present', function () {
			function myImplementation() {}
			const endpoint = endpointImpl.createEndpoint('e1', {
				implementation: myImplementation
			});
			assert(endpoint.implementation === myImplementation);
		});
	});

	describe('with target', function () {
		it('target present', function () {
			const endpoint = endpointImpl.createEndpoint('e1', {
				target: "myTarget"
			});
			assert(endpoint.target === 'myTarget');
		});
	});

	describe('should have correct direction', function () {
		it('for in', function () {
			const endpoint = endpointImpl.createEndpoint('e1', {
				direction: 'in'
			});
			assert(endpoint.direction === 'in');
			assert(endpoint.isIn, "isIn when in");
		});

		it('for out', function () {
			const endpoint = endpointImpl.createEndpoint('e1', {
				direction: 'out'
			});
			assert(endpoint.direction === 'out');
			assert(endpoint.isOut, "isOut when out");
		});

		it('for inout', function () {
			const endpoint = endpointImpl.createEndpoint('e1', {
				direction: 'inout'
			});
			assert(endpoint.direction === 'inout');
			assert(endpoint.isOut, "isOut when inout");
			assert(endpoint.isIn, "isIn when inout");
		});
	});

});
<|endoftext|>


<commit_before>'use strict';

var chai = require('chai')
  , expect = chai.expect
  , util = require('util')
  , hwError = require('../lib/hw-error');

describe('hw-error', function () {

  describe('build', function () {

    it('should build a simple error', function () {
      var error;
      error = hwError.build('INTERNAL');
      expect(error).to.be.an.instanceof(Error);
      expect(error).to.have.property('name', 'INTERNAL');
      expect(error).to.have.property('message', '');
      expect(error.toString()).to.equal('INTERNAL');
      expect(error.stack).to.match(/^INTERNAL\n[ ]+at Context.<anonymous> (.*\/errorSpec.js:.*)\n.*/);
    });

    it('should build an error with message', function () {
      var error;
      error = hwError.build('INTERNAL', 'test error');
      expect(error).to.be.an.instanceof(Error);
      expect(error).to.have.property('name', 'INTERNAL');
      expect(error).to.have.property('message', 'test error');
      expect(error.toString()).to.equal('INTERNAL: test error');
      expect(error.stack).to.match(/^INTERNAL: test error\n[ ]+at Context.<anonymous> (.*\/errorSpec.js:.*)\n.*/);
    });

    it('should build an error with object', function () {
      var o, error;
      o = {a: 4};
      o.toString = util.format.bind(null, '[a : %s]', o.a);
      error = hwError.build('INTERNAL', o);
      expect(error).to.be.an.instanceof(Error);
      expect(error).to.have.property('name', 'INTERNAL');
      expect(error).to.have.property('message', '{"a":4}');
      expect(error.toString()).to.equal('[a : 4]');
      expect(error).to.have.property('a', 4);
      expect(error.stack).to.match(/^INTERNAL: {"a":4}\n[ ]+at Context.<anonymous> (.*\/errorSpec.js:.*)\n.*/);
    });

  });

  describe('throw', function () {

    it('should throw a simple error', function () {
      try {
        hwError.throw('INTERNAL');
      } catch (error) {
        expect(error).to.be.an.instanceof(Error);
        expect(error).to.have.property('name', 'INTERNAL');
        expect(error).to.have.property('message', '');
        expect(error.toString()).to.equal('INTERNAL');
        expect(error.stack).to.match(/^INTERNAL\n[ ]+at Context.<anonymous> (.*\/errorSpec.js:.*)\n.*/);
      }
    });

    it('should throw an error with message', function () {
      try {
        hwError.throw('INTERNAL', 'test error');
      } catch (error) {
        expect(error).to.be.an.instanceof(Error);
        expect(error).to.have.property('name', 'INTERNAL');
        expect(error).to.have.property('message', 'test error');
        expect(error.toString()).to.equal('INTERNAL: test error');
        expect(error.stack).to.match(/INTERNAL: test error\n[ ]+at Context.<anonymous> (.*\/errorSpec.js:.*)\n.*/);
      }
    });

    it('should throw an error with object', function () {
      var o;
      o = {a: 4};
      o.toString = util.format.bind(null, '[a : %s]', o.a);
      try {
        hwError.throw('INTERNAL', o);
      } catch (error) {
        expect(error).to.be.an.instanceof(Error);
        expect(error).to.have.property('name', 'INTERNAL');
        expect(error).to.have.property('message', '{"a":4}');
        expect(error.toString()).to.equal('[a : 4]');
        expect(error).to.have.property('a', 4);
        expect(error.stack).to.match(/INTERNAL: {"a":4}\n[ ]+at Context.<anonymous> (.*\/errorSpec.js:.*)\n.*/);
      }
    });

    it('should throw a not found error', function () {
      try {
        hwError.throwNotFound();
      } catch (error) {
        expect(error).to.be.an.instanceof(Error);
        expect(error).to.have.property('name', 'NOT_FOUND');
        expect(error).to.have.property('message', '');
        expect(error.toString()).to.equal('NOT_FOUND');
        expect(error.stack).to.match(/NOT_FOUND\n[ ]+at Context.<anonymous> (.*\/errorSpec.js:.*)\n.*/);
      }
    });

  });

  describe('send', function () {

    var res = {
      status: function (statusCode) {
        this.statusCode = statusCode;
        return this;
      },
      json: function (body) {
        this.body = body;
        return this;
      }
    };

    beforeEach(function () {
      res.statusCode = null;
      res.body = null;
    });

    describe('simple error', function () {

      it('should send a simple bad format error', function () {
        hwError.send(res, 'BAD_FORMAT');
        expect(res).to.have.property('statusCode', 400);
        expect(res).to.have.property('body').that.eql({message: 'bad request format'});
      });

      it('should send a simple authorization error', function () {
        hwError.send(res, 'AUTHORIZATION');
        expect(res).to.have.property('statusCode', 401);
        expect(res).to.have.property('body').that.eql({message: 'authorization required'});
      });

      it('should send a simple forbidden error', function () {
        hwError.send(res, 'FORBIDDEN');
        expect(res).to.have.property('statusCode', 403);
        expect(res).to.have.property('body').that.eql({message: 'access forbidden'});
      });

      it('should send a simple not found error', function () {
        hwError.send(res, 'NOT_FOUND');
        expect(res).to.have.property('statusCode', 404);
        expect(res).to.have.property('body').that.eql({message: 'resource not found'});
      });

      it('should send a simple conflict error', function () {
        hwError.send(res, 'CONFLICT');
        expect(res).to.have.property('statusCode', 409);
        expect(res).to.have.property('body').that.eql({message: 'resource conflict'});
      });

      it('should send a simple internal error', function () {
        hwError.send(res, 'INTERNAL');
        expect(res).to.have.property('statusCode', 500);
        expect(res).to.have.property('body').that.eql({message: 'internal error'});
      });

    });

    describe('message error', function () {

      it('should send a bad format error with message', function () {
        hwError.send(res, {name: 'BAD_FORMAT', message: 'field required'});
        expect(res).to.have.property('statusCode', 400);
        expect(res).to.have.property('body').that.eql({message: 'field required'});
      });

      it('should send a authorization error with message', function () {
        hwError.send(res, {name: 'AUTHORIZATION', message: 'authorization needed'});
        expect(res).to.have.property('statusCode', 401);
        expect(res).to.have.property('body').that.eql({message: 'authorization needed'});
      });

      it('should send a forbidden error with message', function () {
        hwError.send(res, {name: 'FORBIDDEN', message: 'you are not allowed'});
        expect(res).to.have.property('statusCode', 403);
        expect(res).to.have.property('body').that.eql({message: 'you are not allowed'});
      });

      it('should send a not found error with message', function () {
        hwError.send(res, {name: 'NOT_FOUND', message: 'page not found'});
        expect(res).to.have.property('statusCode', 404);
        expect(res).to.have.property('body').that.eql({message: 'page not found'});
      });

      it('should send a simple conflict error', function () {
        hwError.send(res, {name: 'CONFLICT', message: 'resource already exists'});
        expect(res).to.have.property('statusCode', 409);
        expect(res).to.have.property('body').that.eql({message: 'resource already exists'});
      });

      it('should send a simple internal error', function () {
        hwError.send(res, {name: 'INTERNAL', message: 'oops'});
        expect(res).to.have.property('statusCode', 500);
        expect(res).to.have.property('body').that.eql({message: 'oops'});
      });

    });

    it('should send an error with body', function () {
      hwError.send(res, {name: 'INTERNAL', body: {a: 4, b: 5}});
      expect(res).to.have.property('statusCode', 500);
      expect(res).to.have.property('body').that.eql({a: 4, b: 5});
    });

    it('should send an error with schema errors', function () {
      hwError.send(res, {name: 'INTERNAL', schemaErrors: [{a: 4}, {b: 5}]});
      expect(res).to.have.property('statusCode', 500);
      expect(res).to.have.property('body').that.eql([{a: 4}, {b: 5}]);
    });

    it('should send a simple error with logs', function () {
      var level = logger.getLevel();
      logger.setLevel('debug');
      hwError.send(res);
      logger.setLevel(level);
      expect(res).to.have.property('statusCode', 500);
      expect(res).to.have.property('body').that.eql({message: 'internal error'});
    });

  });

});<commit_msg>initial import<commit_after>'use strict';

var chai = require('chai')
  , expect = chai.expect
  , util = require('util')
  , hwError = require('../lib/hw-error')
  , logger = require('hw-logger');

describe('hw-error', function () {

  describe('build', function () {

    it('should build a simple error', function () {
      var error;
      error = hwError.build('INTERNAL');
      expect(error).to.be.an.instanceof(Error);
      expect(error).to.have.property('name', 'INTERNAL');
      expect(error).to.have.property('message', '');
      expect(error.toString()).to.equal('INTERNAL');
      expect(error.stack).to.match(/^INTERNAL\n[ ]+at Context.<anonymous> (.*\/errorSpec.js:.*)\n.*/);
    });

    it('should build an error with message', function () {
      var error;
      error = hwError.build('INTERNAL', 'test error');
      expect(error).to.be.an.instanceof(Error);
      expect(error).to.have.property('name', 'INTERNAL');
      expect(error).to.have.property('message', 'test error');
      expect(error.toString()).to.equal('INTERNAL: test error');
      expect(error.stack).to.match(/^INTERNAL: test error\n[ ]+at Context.<anonymous> (.*\/errorSpec.js:.*)\n.*/);
    });

    it('should build an error with object', function () {
      var o, error;
      o = {a: 4};
      o.toString = util.format.bind(null, '[a : %s]', o.a);
      error = hwError.build('INTERNAL', o);
      expect(error).to.be.an.instanceof(Error);
      expect(error).to.have.property('name', 'INTERNAL');
      expect(error).to.have.property('message', '{"a":4}');
      expect(error.toString()).to.equal('[a : 4]');
      expect(error).to.have.property('a', 4);
      expect(error.stack).to.match(/^INTERNAL: {"a":4}\n[ ]+at Context.<anonymous> (.*\/errorSpec.js:.*)\n.*/);
    });

  });

  describe('throw', function () {

    it('should throw a simple error', function () {
      try {
        hwError.throw('INTERNAL');
      } catch (error) {
        expect(error).to.be.an.instanceof(Error);
        expect(error).to.have.property('name', 'INTERNAL');
        expect(error).to.have.property('message', '');
        expect(error.toString()).to.equal('INTERNAL');
        expect(error.stack).to.match(/^INTERNAL\n[ ]+at Context.<anonymous> (.*\/errorSpec.js:.*)\n.*/);
      }
    });

    it('should throw an error with message', function () {
      try {
        hwError.throw('INTERNAL', 'test error');
      } catch (error) {
        expect(error).to.be.an.instanceof(Error);
        expect(error).to.have.property('name', 'INTERNAL');
        expect(error).to.have.property('message', 'test error');
        expect(error.toString()).to.equal('INTERNAL: test error');
        expect(error.stack).to.match(/INTERNAL: test error\n[ ]+at Context.<anonymous> (.*\/errorSpec.js:.*)\n.*/);
      }
    });

    it('should throw an error with object', function () {
      var o;
      o = {a: 4};
      o.toString = util.format.bind(null, '[a : %s]', o.a);
      try {
        hwError.throw('INTERNAL', o);
      } catch (error) {
        expect(error).to.be.an.instanceof(Error);
        expect(error).to.have.property('name', 'INTERNAL');
        expect(error).to.have.property('message', '{"a":4}');
        expect(error.toString()).to.equal('[a : 4]');
        expect(error).to.have.property('a', 4);
        expect(error.stack).to.match(/INTERNAL: {"a":4}\n[ ]+at Context.<anonymous> (.*\/errorSpec.js:.*)\n.*/);
      }
    });

    it('should throw a not found error', function () {
      try {
        hwError.throwNotFound();
      } catch (error) {
        expect(error).to.be.an.instanceof(Error);
        expect(error).to.have.property('name', 'NOT_FOUND');
        expect(error).to.have.property('message', '');
        expect(error.toString()).to.equal('NOT_FOUND');
        expect(error.stack).to.match(/NOT_FOUND\n[ ]+at Context.<anonymous> (.*\/errorSpec.js:.*)\n.*/);
      }
    });

  });

  describe('send', function () {

    var res = {
      status: function (statusCode) {
        this.statusCode = statusCode;
        return this;
      },
      json: function (body) {
        this.body = body;
        return this;
      }
    };

    beforeEach(function () {
      res.statusCode = null;
      res.body = null;
    });

    describe('simple error', function () {

      it('should send a simple bad format error', function () {
        hwError.send(res, 'BAD_FORMAT');
        expect(res).to.have.property('statusCode', 400);
        expect(res).to.have.property('body').that.eql({message: 'bad request format'});
      });

      it('should send a simple authorization error', function () {
        hwError.send(res, 'AUTHORIZATION');
        expect(res).to.have.property('statusCode', 401);
        expect(res).to.have.property('body').that.eql({message: 'authorization required'});
      });

      it('should send a simple forbidden error', function () {
        hwError.send(res, 'FORBIDDEN');
        expect(res).to.have.property('statusCode', 403);
        expect(res).to.have.property('body').that.eql({message: 'access forbidden'});
      });

      it('should send a simple not found error', function () {
        hwError.send(res, 'NOT_FOUND');
        expect(res).to.have.property('statusCode', 404);
        expect(res).to.have.property('body').that.eql({message: 'resource not found'});
      });

      it('should send a simple conflict error', function () {
        hwError.send(res, 'CONFLICT');
        expect(res).to.have.property('statusCode', 409);
        expect(res).to.have.property('body').that.eql({message: 'resource conflict'});
      });

      it('should send a simple internal error', function () {
        hwError.send(res, 'INTERNAL');
        expect(res).to.have.property('statusCode', 500);
        expect(res).to.have.property('body').that.eql({message: 'internal error'});
      });

    });

    describe('message error', function () {

      it('should send a bad format error with message', function () {
        hwError.send(res, {name: 'BAD_FORMAT', message: 'field required'});
        expect(res).to.have.property('statusCode', 400);
        expect(res).to.have.property('body').that.eql({message: 'field required'});
      });

      it('should send a authorization error with message', function () {
        hwError.send(res, {name: 'AUTHORIZATION', message: 'authorization needed'});
        expect(res).to.have.property('statusCode', 401);
        expect(res).to.have.property('body').that.eql({message: 'authorization needed'});
      });

      it('should send a forbidden error with message', function () {
        hwError.send(res, {name: 'FORBIDDEN', message: 'you are not allowed'});
        expect(res).to.have.property('statusCode', 403);
        expect(res).to.have.property('body').that.eql({message: 'you are not allowed'});
      });

      it('should send a not found error with message', function () {
        hwError.send(res, {name: 'NOT_FOUND', message: 'page not found'});
        expect(res).to.have.property('statusCode', 404);
        expect(res).to.have.property('body').that.eql({message: 'page not found'});
      });

      it('should send a simple conflict error', function () {
        hwError.send(res, {name: 'CONFLICT', message: 'resource already exists'});
        expect(res).to.have.property('statusCode', 409);
        expect(res).to.have.property('body').that.eql({message: 'resource already exists'});
      });

      it('should send a simple internal error', function () {
        hwError.send(res, {name: 'INTERNAL', message: 'oops'});
        expect(res).to.have.property('statusCode', 500);
        expect(res).to.have.property('body').that.eql({message: 'oops'});
      });

    });

    it('should send an error with body', function () {
      hwError.send(res, {name: 'INTERNAL', body: {a: 4, b: 5}});
      expect(res).to.have.property('statusCode', 500);
      expect(res).to.have.property('body').that.eql({a: 4, b: 5});
    });

    it('should send an error with schema errors', function () {
      hwError.send(res, {name: 'INTERNAL', schemaErrors: [{a: 4}, {b: 5}]});
      expect(res).to.have.property('statusCode', 500);
      expect(res).to.have.property('body').that.eql([{a: 4}, {b: 5}]);
    });

    it('should send a simple error with logs', function () {
      var level = logger.getLevel();
      logger.setLevel('debug');
      hwError.send(res);
      logger.setLevel(level);
      expect(res).to.have.property('statusCode', 500);
      expect(res).to.have.property('body').that.eql({message: 'internal error'});
    });

  });

});<|endoftext|>


<commit_before>window.onload = function() {

var crimeArray = new Array(5);

//Defines map
//Attaches event to "click"
var map = new GMaps({
  div: '#map',
  lat: 51.5286417,
  lng: -0.1015987,
  zoom: 12,
  click: function(event) {
    var lat = event.latLng.lat();
    var lng = event.latLng.lng();
    $('#latlng').val(lat + ', ' + lng);

    crimeQuery("http://data.police.uk/api/crimes-street/all-crime?lat=" +
      lat + "&lng=" + lng + "&date=2014-01", "#jan", 0);
    crimeQuery("http://data.police.uk/api/crimes-street/all-crime?lat=" +
      lat + "&lng=" + lng + "&date=2014-02", "#feb", 1);
    crimeQuery("http://data.police.uk/api/crimes-street/all-crime?lat=" +
      lat + "&lng=" + lng + "&date=2014-03", "#march", 2);
    crimeQuery("http://data.police.uk/api/crimes-street/all-crime?lat=" +
      lat + "&lng=" + lng + "&date=2014-04", "#april", 3);
    crimeQuery("http://data.police.uk/api/crimes-street/all-crime?lat=" +
      lat + "&lng=" + lng + "&date=2014-05", "#may", 4);
  }
});

function crimeQuery(path_json, div_id, crimeIndex) {
  $.getJSON(path_json, function(data) {
    $("#map").remove();
    var categories = new Array();
    //will be filled with total numbers for each crime category
    var crimeNumbers = new Array();

    var categories = _.pluck(data, 'category'); //list all values
    var categories = _.uniq(categories); //boils down to unique values

    for (var i = 0; i < categories.length; i++) {
      var totalByCategory = _.filter(data, function(data) {
        return data.category == categories[i]
      });
      crimeNumbers.push(totalByCategory.length);
    }

    var crime = _.zip(categories, crimeNumbers); //assembles the two arrays
    crimeArray[crimeIndex] = crime;

    var tableData = crime;
    var $table = $("

");

    for (var y = 0; y < tableData.length; y++) {
      var $line = $("

");
      $line.append($("	").html(tableData[y][0]));
      $line.append($("	").html(tableData[y][1]));
      $table.append($line);
    }
    $table.appendTo($(div_id));

    var ok = true;
    for (var i = 0; i < crimeArray.length; i++) {
      if(!crimeArray[i]) {
        ok = false;
        break;
      }
    }
    if(ok) {
      stats();
    }
  });
}

function stats() {
  //Functions
  function stuff(month1, month2, month3, month4, month5, total) {
    var av = (month1 + month2 + month3 + month4 + month5) / total;
    var diff = (month5 / av * 100) - 100;
    return {
      average: av,
      monthDiff: diff
    };
  };

  var stat1 = crimeArray[0];
  var stat2 = crimeArray[1];
  var stat3 = crimeArray[2];
  var stat4 = crimeArray[3];
  var stat5 = crimeArray[4];
  var numberOfMonths = 5;

  var average1 = stuff(stat1[0][1], stat2[0][1], stat3[0][1], stat4[0][1], stat5[0][1], 5);
  console.log("The average " + stat1[0][0] + " arrests is: " + Math.round(average1.average));
  console.log("This month, " + stat1[0][0] + "  arrests changed by: " + Math.round(average1.monthDiff) + "%");
  $("#results").append("

").html("The average of" + stat1[0][0] + "  arrests per month is " + Math.round(average1.average) + "
" + "This month, " + stat1[0][0] + " arrests changed by " + Math.round(average1.monthDiff) + "%");

  /*@TODO in stats()
    function stuff( as many parameters as we have gVar.crimeArray ) {
      calculate average
      valculate diff
      return {
        average: av,
        monthDiff: diff
      }
    } see line 138 and following

    append to #results:
    "The average of " + stat5[i][0] + (...) + average
    Same thing for diff
    see line 157 for example
  */
}

}

<commit_msg>remove useless intermediate variable<commit_after>window.onload = function() {

var crimeArray = new Array(5);

//Defines map
//Attaches event to "click"
var map = new GMaps({
  div: '#map',
  lat: 51.5286417,
  lng: -0.1015987,
  zoom: 12,
  click: function(event) {
    var lat = event.latLng.lat();
    var lng = event.latLng.lng();
    $('#latlng').val(lat + ', ' + lng);

    crimeQuery("http://data.police.uk/api/crimes-street/all-crime?lat=" +
      lat + "&lng=" + lng + "&date=2014-01", "#jan", 0);
    crimeQuery("http://data.police.uk/api/crimes-street/all-crime?lat=" +
      lat + "&lng=" + lng + "&date=2014-02", "#feb", 1);
    crimeQuery("http://data.police.uk/api/crimes-street/all-crime?lat=" +
      lat + "&lng=" + lng + "&date=2014-03", "#march", 2);
    crimeQuery("http://data.police.uk/api/crimes-street/all-crime?lat=" +
      lat + "&lng=" + lng + "&date=2014-04", "#april", 3);
    crimeQuery("http://data.police.uk/api/crimes-street/all-crime?lat=" +
      lat + "&lng=" + lng + "&date=2014-05", "#may", 4);
  }
});

function crimeQuery(path_json, div_id, crimeIndex) {
  $.getJSON(path_json, function(data) {
    $("#map").remove();
    var categories = new Array();
    //will be filled with total numbers for each crime category
    var crimeNumbers = new Array();

    var categories = _.pluck(data, 'category'); //list all values
    var categories = _.uniq(categories); //boils down to unique values

    for (var i = 0; i < categories.length; i++) {
      var totalByCategory = _.filter(data, function(data) {
        return data.category == categories[i]
      });
      crimeNumbers.push(totalByCategory.length);
    }

    var crime = _.zip(categories, crimeNumbers); //assembles the two arrays
    crimeArray[crimeIndex] = crime;

    var $table = $("

");
    for (var y = 0; y < crime.length; y++) {
      var $line = $("

");
      $line.append($("	").html(crime[y][0]));
      $line.append($("	").html(crime[y][1]));
      $table.append($line);
    }
    $table.appendTo($(div_id));

    var ok = true;
    for (var i = 0; i < crimeArray.length; i++) {
      if(!crimeArray[i]) {
        ok = false;
        break;
      }
    }
    if(ok) {
      stats();
    }
  });
}

function stats() {
  //Functions
  function stuff(month1, month2, month3, month4, month5, total) {
    var av = (month1 + month2 + month3 + month4 + month5) / total;
    var diff = (month5 / av * 100) - 100;
    return {
      average: av,
      monthDiff: diff
    };
  };

  var stat1 = crimeArray[0];
  var stat2 = crimeArray[1];
  var stat3 = crimeArray[2];
  var stat4 = crimeArray[3];
  var stat5 = crimeArray[4];
  var numberOfMonths = 5;

  var average1 = stuff(stat1[0][1], stat2[0][1], stat3[0][1], stat4[0][1], stat5[0][1], 5);
  console.log("The average " + stat1[0][0] + " arrests is: " + Math.round(average1.average));
  console.log("This month, " + stat1[0][0] + "  arrests changed by: " + Math.round(average1.monthDiff) + "%");
  $("#results").append("

").html("The average of" + stat1[0][0] + "  arrests per month is " + Math.round(average1.average) + "
" + "This month, " + stat1[0][0] + " arrests changed by " + Math.round(average1.monthDiff) + "%");

  /*@TODO in stats()
    function stuff( as many parameters as we have gVar.crimeArray ) {
      calculate average
      valculate diff
      return {
        average: av,
        monthDiff: diff
      }
    } see line 138 and following

    append to #results:
    "The average of " + stat5[i][0] + (...) + average
    Same thing for diff
    see line 157 for example
  */
}

}

<|endoftext|>


<commit_before>var assert = require('power-assert');
var fs = require('fs');

var FrontNote = require('../lib/frontnote');
var File = require('../lib/file/file');
var files = [
    './guide/index.html',
    './guide/test-sass-sample.html',
    './guide/assets/js/main.js',
    './guide/assets/js/ripple-effect.js',
    './guide/assets/css/style.css',
    './guide/assets/fonts/fontawesome-webfont.ttf',
    './guide/assets/fonts/fontawesome-webfont.eot',
    './guide/assets/fonts/FontAwesome.otf',
    './guide/assets/fonts/fontawesome-webfont.svg',
    './guide/assets/fonts/fontawesome-webfont.woff',
    './guide/assets/images/favicon.ico',
    './guide/assets/images/frontnote.png',
    './guide/assets/lib/highlight.pack.js',
    './guide/assets/lib/jquery.js',
    './guide/assets/lib/jquery.mousewheel.js'
];
var noAssertFiles = [
    './guide/index.html',
    './guide/test-sass-sample.html'
];
require('./const/pattern')();
require('./file/file')();
require('./parser/parser')();
require('./helper/template-helper')();
require('./render/render')();
require('./debug/debug')();

describe('frontnote', function() {
    var frontnote;
    beforeEach(function() {
        frontnote = new FrontNote();
    });
    it('init', function() {
        assert.deepEqual(frontnote.options,{
            overview: process.cwd() + '/lib/../styleguide.md',
            template: process.cwd() + '/lib/../template/index.html',
            includeAssetPath: 'assets/**/*',
            css: './style.css',
            script: null,
            out: process.cwd() + '/guide',
            title: 'StyleGuide',
            verbose: false,
            clean: false,
            cache: true
        });
        assert(typeof FrontNote.noop === 'function');
        assert(FrontNote.noop() === undefined);
    });

    it('default render', function(done) {
        frontnote.render('./test/sass/*.scss',function() {
            for (var i = 0, len = files.length; i < len; i++) {
                assert(fs.existsSync(files[i]));
            }
            done();
        });
    });

    it('verbose & clean & array asset path', function(done) {
        frontnote = new FrontNote({
            clean: true,
            verbose: true,
            includeAssetPath: ['assets/**/*']
        });
        frontnote.render('./test/sass/*.scss',function() {
            for (var i = 0, len = files.length; i < len; i++) {
                assert(fs.existsSync(files[i]));
            }
            done();
        });
    });

    it('no asset path', function(done) {
        frontnote = new FrontNote({
            clean: true,
            includeAssetPath: null
        });
        frontnote.render('./test/sass/*.scss',function() {
            for (var i = 0, len = noAssertFiles.length; i < len; i++) {
                assert(fs.existsSync(files[i]) === true);
            }
            done();
        });
    });

    it('render with overview', function(done) {
        frontnote = new FrontNote({
            clean: true,
            overview: './test/sass/overview.md'
        });
        frontnote.render('./test/sass/*.scss',function() {
            for (var i = 0, len = files.length; i < len; i++) {
                assert(fs.existsSync(files[i]) === true);
            }
            done();
        });
    });
});<commit_msg>cacheレンダリングテスト追加<commit_after>var assert = require('power-assert');
var fs = require('fs');

var FrontNote = require('../lib/frontnote');
var File = require('../lib/file/file');
var files = [
    './guide/index.html',
    './guide/test-sass-sample.html',
    './guide/assets/js/main.js',
    './guide/assets/js/ripple-effect.js',
    './guide/assets/css/style.css',
    './guide/assets/fonts/fontawesome-webfont.ttf',
    './guide/assets/fonts/fontawesome-webfont.eot',
    './guide/assets/fonts/FontAwesome.otf',
    './guide/assets/fonts/fontawesome-webfont.svg',
    './guide/assets/fonts/fontawesome-webfont.woff',
    './guide/assets/images/favicon.ico',
    './guide/assets/images/frontnote.png',
    './guide/assets/lib/highlight.pack.js',
    './guide/assets/lib/jquery.js',
    './guide/assets/lib/jquery.mousewheel.js'
];
var noAssertFiles = [
    './guide/index.html',
    './guide/test-sass-sample.html'
];
require('./const/pattern')();
require('./file/file')();
require('./parser/parser')();
require('./helper/template-helper')();
require('./render/render')();
require('./debug/debug')();

describe('frontnote', function() {
    var frontnote;
    beforeEach(function() {
        frontnote = new FrontNote();
    });
    it('init', function() {
        assert.deepEqual(frontnote.options,{
            overview: process.cwd() + '/lib/../styleguide.md',
            template: process.cwd() + '/lib/../template/index.html',
            includeAssetPath: 'assets/**/*',
            css: './style.css',
            script: null,
            out: process.cwd() + '/guide',
            title: 'StyleGuide',
            verbose: false,
            clean: false,
            cache: true
        });
        assert(typeof FrontNote.noop === 'function');
        assert(FrontNote.noop() === undefined);
    });

    it('default render', function(done) {
        frontnote.render('./test/sass/*.scss',function() {
            for (var i = 0, len = files.length; i < len; i++) {
                assert(fs.existsSync(files[i]));
            }
            done();
        });
    });

    it('cache render', function(done) {
        frontnote.render('./test/sass/*.scss',function() {
            for (var i = 0, len = files.length; i < len; i++) {
                assert(fs.existsSync(files[i]));
            }
            done();
        });
    });

    it('verbose & clean & array asset path', function(done) {
        frontnote = new FrontNote({
            clean: true,
            verbose: true,
            includeAssetPath: ['assets/**/*']
        });
        frontnote.render('./test/sass/*.scss',function() {
            for (var i = 0, len = files.length; i < len; i++) {
                assert(fs.existsSync(files[i]));
            }
            done();
        });
    });

    it('no asset path', function(done) {
        frontnote = new FrontNote({
            clean: true,
            includeAssetPath: null
        });
        frontnote.render('./test/sass/*.scss',function() {
            for (var i = 0, len = noAssertFiles.length; i < len; i++) {
                assert(fs.existsSync(files[i]) === true);
            }
            done();
        });
    });

    it('render with overview', function(done) {
        frontnote = new FrontNote({
            clean: true,
            overview: './test/sass/overview.md'
        });
        frontnote.render('./test/sass/*.scss',function() {
            for (var i = 0, len = files.length; i < len; i++) {
                assert(fs.existsSync(files[i]) === true);
            }
            done();
        });
    });
});<|endoftext|>


<commit_before>/**
  @module data

  @main data
*/

window.DS = Ember.Namespace.create({
  // this one goes past 11
  CURRENT_API_REVISION: 12
});
<commit_msg>Docs for DS namespace<commit_after>/**
  @module data
  @main data
*/

/**
  All Ember Data methods and functions are defined inside of this namespace.

  @class DS
  @static
*/

window.DS = Ember.Namespace.create({
  /**
    Current API revision. See
    [BREAKING_CHANGES.md](https://github.com/emberjs/data/blob/master/BREAKING_CHANGES.md)
    for more information.

    @property CURRENT_API_REVISION
    @type Integer
  */
  CURRENT_API_REVISION: 12
});
<|endoftext|>


<commit_before>"use strict";
//Define the modules required to mocha testing
const assert = require("chai").assert;
const http = require ("http");
const expect = require("chai").expect;
const should = require("should");
const aws = require ("aws-sdk");
const seeder = require("../src/seeder.js");
const dataApp = require("../index.js");

describe("Port function",function(){
  it("Port should return number",function(){
    let myport = dataApp.prototype.port;
    assert(typeof myport, "number");
  });

  it("Port value should be >= 0 and < 65536",function () {
  http.get(`http://localhost:${dataApp.prototype.port}`, function (response) {
    assert.equal(response.statusCode, 200);
    });
  });
});

describe("Check the dynamodb function",function(){
  it("Endpoint should listen to the port",function () {
     let server;
     before(function () {
      server = dynamodbOptions.listen(port);
     });
     after(function () {
      assert.ok;
     });
    });

  it("Should be an object",function(){
    let dynamoOptions = dataApp.prototype.dynamodbOptions;
    let raw = new aws.DynamoDB(dynamoOptions);
    raw.should.be.type("object");
  });

  it("Should be an object",function(){
    let dynamoOptions =  dataApp.prototype.dynamodbOptions;
    let doc = new aws.DynamoDB(dynamoOptions);
    doc.should.be.type("object");
  });
});

describe ("Start handler function",function(){
  it ("Should not  be null",function(){
    let handler = dataApp.prototype.startHandler;
    assert(handler =! null);
  });
});

describe ("createTable functon",function(){
  it ("Should check as a function",function(){
    const tbl = dataApp.prototype.createTable;
    assert.equal(typeof tbl, "function");
  });
});

describe ("Check the Seeder file",function(){
  it("Table name shoud be a string",function(){
    let tblName = seeder.writeSeeds.name;
    expect(tblName).to.be.a("string");
  });
});
<commit_msg>Mocha waits for done callback before exiting an asycnhronous test. This fixes another later test failing due to a problem in asynchronous http.get().<commit_after>"use strict";
//Define the modules required to mocha testing
const assert = require("chai").assert;
const http = require ("http");
const expect = require("chai").expect;
const should = require("should");
const aws = require ("aws-sdk");
const seeder = require("../src/seeder.js");
const dataApp = require("../index.js");

describe("Port function",function(){
  it("Port should return number",function(){
    let myport = dataApp.prototype.port;
    assert(typeof myport, "number");
  });

  it("Port value should be >= 0 and < 65536",function(done){
    http.get(`http://localhost:${dataApp.prototype.port}`, function (response) {
      assert.equal(response.statusCode, 200);
      done();
    });
  });
});

describe("Check the dynamodb function",function(){
  it("Endpoint should listen to the port",function () {
     let server;
     before(function () {
      server = dynamodbOptions.listen(port);
     });
     after(function () {
      assert.ok;
     });
    });

  it("Should be an object",function(){
    let dynamoOptions = dataApp.prototype.dynamodbOptions;
    let raw = new aws.DynamoDB(dynamoOptions);
    raw.should.be.type("object");
  });

  it("Should be an object",function(){
    let dynamoOptions =  dataApp.prototype.dynamodbOptions;
    let doc = new aws.DynamoDB(dynamoOptions);
    doc.should.be.type("object");
  });
});

describe ("Start handler function",function(){
  it ("Should not  be null",function(){
    let handler = dataApp.prototype.startHandler;
    assert(handler =! null);
  });
});

describe ("createTable functon",function(){
  it ("Should check as a function",function(){
    const tbl = dataApp.prototype.createTable;
    assert.equal(typeof tbl, "function");
  });
});

describe ("Check the Seeder file",function(){
  it("Table name shoud be a string",function(){
    let tblName = seeder.writeSeeds.name;
    expect(tblName).to.be.a("string");
  });
});
<|endoftext|>


<commit_before>const path = require('path')
const stylesheetsPath = path.join(__dirname, 'app', 'assets', 'stylesheets', 'uploadcare')

module.exports = {
	'input': path.join(stylesheetsPath, 'widget.pcss'),
	'output': path.join(stylesheetsPath, 'widget.css'),
	'local-plugins': true,
	'use': [
		'postcss-import',
		'postcss-each',
		'postcss-inline-svg',
		'postcss-custom-media',
		'postcss-nested',
		'postcss-css-variables',
		'postcss-calc',
		'postcss-color-function',
		'autoprefixer',
		'postcss-reporter',
	],
	'postcss-import': {
		path: stylesheetsPath,
		plugins: [
			require('stylelint'),
			require('postcss-apply'),
			require('postcss-prefixer')('uploadcare--', {
				ignore: [
					/uploadcare-|ord-/,
					'.bottom',
					'.right',
				],
			}),
		],
	},
	'postcss-inline-svg': {path: path.join(__dirname, 'app', 'assets', 'images', 'uploadcare', 'svg')},
	'postcss-reporter': {clearMessages: true},
}
<commit_msg>Update postcss config<commit_after>const path = require('path')
const stylesheetsPath = path.join(__dirname, 'app', 'assets', 'stylesheets', 'uploadcare')

module.exports = {
	'input': path.join(stylesheetsPath, 'widget.pcss'),
	'output': path.join(stylesheetsPath, 'widget.css'),
	'local-plugins': true,
	'use': [
		'postcss-import',
		'postcss-each',
		'postcss-inline-svg',
		'postcss-custom-media',
		'postcss-nested',
		'postcss-css-variables',
		'postcss-calc',
		'postcss-color-function',
		'postcss-flexbugs-fixes',
		'autoprefixer',
		'postcss-reporter',
	],
	'postcss-import': {
		path: stylesheetsPath,
		plugins: [
			require('stylelint'),
			require('postcss-apply'),
			require('postcss-prefixer')('uploadcare--', {
				ignore: [
					/^uploadcare-|^ord-/,
					'.bottom',
					'.right',
				],
			}),
		],
	},
	'postcss-inline-svg': {path: path.join(__dirname, 'app', 'assets', 'images', 'uploadcare', 'svg')},
	'postcss-reporter': {clearMessages: true},
	'autoprefixer': {browsers: ['last 2 versions', 'ie >= 10']},
}
<|endoftext|>


<commit_before>var IrcStream = require(process.env.IRCSTREAM_COV ? '../irc-stream-cov' : '../');
var Client = require('irc').Client;
var sulfur = require('sulfur');
var Smell = require('smell');
var EE = require('events').EventEmitter;

// [Server, (client, irc-stream)] helper class
function Connection(istreamOpts) {
  EE.call(this);
  // 1. set up irc server
  this.ircd = require('ircdkit')({
    requireNickname: true
  });
  this.ircd.listen(6667);
  this.log = new Smell();
  sulfur.absorb(this.log, 'ircd');
  this.bot = null;
  this.person = null;
  var self = this;
  this.ircd.on('connection', function (c) {
    c.on('authenticated', function () {
      self.log.info(c.mask + " connected");
      self[c.nickname === 'bot' ? 'bot' : 'person'] = c;
    });

    c.on('PRIVMSG', function (target, message) {
      // bot sends to person, person sends to bot:
      //self.log.info('server handle "' + message + '" for', target);
      var dest = self[self.bot.id === c.id ? 'person' : 'bot'];
      dest.send(':' + c.nickname + ' PRIVMSG ' + target + ' :' + message);
    });

    c.on('disconnected', function () {
      self.log.info(c.mask + " disconnected.");
    });
  });

  // both client use the same irc client options
  var ircOpts = { channel: [ '#test' ] };

  // 2. connect the ircStream `bot` to the server
  this.istream = new IrcStream('localhost', 'bot', ircOpts, istreamOpts);
  sulfur.absorb(this.istream.log, 'irc-stream');

  // 3. connect the irc.Client `dude` to the server
  self.client = new Client('localhost', 'dude', ircOpts);
  self.client.addListener('error', function () {});

  this.resps = [];
  self.client.addListener('message', function (from, to, message) {
    self.resps.push({ from: from, to: to, message: message});
  });
  self.client.addListener('registered', function () {
    self.emit('ready', self.istream, self.client);
  });
}
Connection.prototype = new EE();

Connection.prototype.close = function () {
  this.client.disconnect();
  this.istream.bot.disconnect();
  this.ircd.close();
};

// -------------------------------------------------------------

exports.pmsAndParticipate = function (t) {
  var istreamOpts = {
    answerPms: true,
    participationChance: 1
  };
  var conn = new Connection(istreamOpts);

  // send messages from person to bot when ready
  conn.on('ready', function (istream, person) {
    person.say('bot', 'getting this?');
    person.say('#test', 'bot: hi');
    person.say('#test', 'participate');

    setTimeout(function () {
      // intercept in istream just afterwards
      var m1 = istream.read();
      var excp1 = { user: 'dude', name: 'dude', message: 'getting this?'};
      t.deepEqual(m1, excp1, 'pm read');

      var m2 = istream.read();
      var excp2 = { user: '#test:dude', name: 'dude', message: 'hi' };
      t.deepEqual(m2, excp2, 'chan message read');

      var m3 = istream.read();
      var excp3 = { user: "#test:dude", name: "dude", message: "participate" };
      t.deepEqual(m3, excp3, 'unrelated participation message read');

      var m4 = istream.read();
      t.equal(m4, null, 'no fourth message');

      conn.close();
      t.done();
    }, 100);
  });
};

exports.ignoreChannel = function (t) {
  var istreamOpts = {
    ignoreChannel: true
  };
  var conn = new Connection(istreamOpts);

  // send messages from person to bot when ready
  conn.on('ready', function (istream, person) {
    person.say('bot', 'getting this?');
    person.say('#test', 'bot: hi');
    person.say('#test', 'participate');

    setTimeout(function () {
      // intercept in istream just afterwards
      var m1 = istream.read();
      t.deepEqual(m1, null, 'ignoring pms and chan');

      conn.close();
      t.done();
    }, 100);
  });
};

exports.defaultOptsResponses = function (t) {
  var istreamOpts = {};
  var conn = new Connection(istreamOpts);

  // send messages from person to bot when ready
  conn.on('ready', function (istream, person) {
    person.say('#test', 'bot: hi');
    person.say('#test', 'participate');
    person.say('bot', 'getting this?');

    setTimeout(function () {
      // intercept in istream just afterwards
      var m1 = istream.read();
      var excp1 = { user: '#test:dude', name: 'dude', message: 'hi' };
      t.deepEqual(m1, excp1, 'chan message read on default');

      var m2 = istream.read();
      t.deepEqual(m2, null, 'not participating');

      var m3 = istream.read();
      t.deepEqual(m3, null, 'ignoring pms');

      var m4 = istream.read();
      t.equal(m4, null, 'no fourth message');

      // write responses from bot to person finally
      istream.write({ user: 'dude', message: 'bonk' });
      istream.write({ user: '#test:dude', message: 'really?'});
      istream.write({ user: '#test:dude', message: 'that is insane'});
      setTimeout(function () {
        var resps = conn.resps;
        var r1 = { from: 'bot', to: 'dude', message: 'bonk' };
        var r2 = { from: 'bot', to: '#test', message: 'dude: really?'};
        var r3 = { from: 'bot', to: '#test', message: 'that is insane'};
        t.deepEqual(resps[0], r1, 'pm to person');
        t.deepEqual(resps[1], r2, 'chan msg 1 to person (highlighted)');
        t.deepEqual(resps[2], r3, 'chan msg 2 to person (not highlighted)');

        conn.close();
        t.done();
      }, 100);
    }, 100);
  });
};

exports.neverHighlight = function (t) {
  var istreamOpts = {
    neverHighlight: true
  };
  var conn = new Connection(istreamOpts);

  // send messages from person to bot when ready
  conn.on('ready', function (istream) {
    // write messages from bot to person
    istream.write({ user: 'dude', message: 'bonk' });
    istream.write({ user: '#test:dude', message: 'really?'});
    istream.write({ user: '#test:dude', message: 'that is insane'});
    setTimeout(function () {
      var resps = conn.resps;
      var r1 = { from: 'bot', to: 'dude', message: 'bonk' };
      var r2 = { from: 'bot', to: '#test', message: 'really?'};
      var r3 = { from: 'bot', to: '#test', message: 'that is insane'};
      t.deepEqual(resps[0], r1, 'pm to person');
      t.deepEqual(resps[1], r2, 'chan msg 1 to person (not highlighted)');
      t.deepEqual(resps[2], r3, 'chan msg 2 to person (same)');

      conn.close();
      t.done();
    }, 100);
  });
};

exports.alwaysHighlight = function (t) {
  var istreamOpts = {
    alwaysHighlight: true
  };
  var conn = new Connection(istreamOpts);

  // send messages from person to bot when ready
  conn.on('ready', function (istream) {
    // write messages from bot to person
    istream.write({ user: 'dude', message: 'bonk' });
    istream.write({ user: '#test:dude', message: 'really?'});
    istream.write({ user: '#test:dude', message: 'that is insane'});
    setTimeout(function () {
      var resps = conn.resps;
      var r1 = { from: 'bot', to: 'dude', message: 'bonk' };
      var r2 = { from: 'bot', to: '#test', message: 'dude: really?'};
      var r3 = { from: 'bot', to: '#test', message: 'dude: that is insane'};
      t.deepEqual(resps[0], r1, 'pm to person');
      t.deepEqual(resps[1], r2, 'chan msg 1 to person (highlight)');
      t.deepEqual(resps[2], r3, 'chan msg 2 to person (highlight again)');

      conn.close();
      t.done();
    }, 100);
  });
};
<commit_msg>still timing issues?<commit_after>var IrcStream = require(process.env.IRCSTREAM_COV ? '../irc-stream-cov' : '../');
var Client = require('irc').Client;
var sulfur = require('sulfur');
var Smell = require('smell');
var EE = require('events').EventEmitter;

// [Server, (client, irc-stream)] helper class
function Connection(istreamOpts) {
  EE.call(this);
  // 1. set up irc server
  this.ircd = require('ircdkit')({
    requireNickname: true
  });
  this.ircd.listen(6667);
  this.log = new Smell();
  sulfur.absorb(this.log, 'ircd');
  this.bot = null;
  this.person = null;
  var self = this;
  this.ircd.on('connection', function (c) {
    c.on('authenticated', function () {
      self.log.info(c.mask + " connected");
      self[c.nickname === 'bot' ? 'bot' : 'person'] = c;
    });

    c.on('PRIVMSG', function (target, message) {
      // bot sends to person, person sends to bot:
      //self.log.info('server handle "' + message + '" for', target);
      var dest = self[self.bot.id === c.id ? 'person' : 'bot'];
      dest.send(':' + c.nickname + ' PRIVMSG ' + target + ' :' + message);
    });

    c.on('disconnected', function () {
      self.log.info(c.mask + " disconnected.");
    });
  });

  // both client use the same irc client options
  var ircOpts = { channel: [ '#test' ] };

  // 2. connect the ircStream `bot` to the server
  this.istream = new IrcStream('localhost', 'bot', ircOpts, istreamOpts);
  sulfur.absorb(this.istream.log, 'irc-stream');

  // 3. connect the irc.Client `dude` to the server
  this.istream.bot.on('registered', function () {
    self.client = new Client('localhost', 'dude', ircOpts);
    self.client.addListener('error', function () {});

    self.resps = [];
    self.client.addListener('message', function (from, to, message) {
      self.resps.push({ from: from, to: to, message: message});
    });
    self.client.addListener('registered', function () {
      self.emit('ready', self.istream, self.client);
    });
  });
}
Connection.prototype = new EE();

Connection.prototype.close = function () {
  this.client.disconnect();
  this.istream.bot.disconnect();
  this.ircd.close();
};

// -------------------------------------------------------------

exports.pmsAndParticipate = function (t) {
  var istreamOpts = {
    answerPms: true,
    participationChance: 1
  };
  var conn = new Connection(istreamOpts);

  // send messages from person to bot when ready
  conn.on('ready', function (istream, person) {
    person.say('bot', 'getting this?');
    person.say('#test', 'bot: hi');
    person.say('#test', 'participate');

    setTimeout(function () {
      // intercept in istream just afterwards
      var m1 = istream.read();
      var excp1 = { user: 'dude', name: 'dude', message: 'getting this?'};
      t.deepEqual(m1, excp1, 'pm read');

      var m2 = istream.read();
      var excp2 = { user: '#test:dude', name: 'dude', message: 'hi' };
      t.deepEqual(m2, excp2, 'chan message read');

      var m3 = istream.read();
      var excp3 = { user: "#test:dude", name: "dude", message: "participate" };
      t.deepEqual(m3, excp3, 'unrelated participation message read');

      var m4 = istream.read();
      t.equal(m4, null, 'no fourth message');

      conn.close();
      t.done();
    }, 500);
  });
};

exports.ignoreChannel = function (t) {
  var istreamOpts = {
    ignoreChannel: true
  };
  var conn = new Connection(istreamOpts);

  // send messages from person to bot when ready
  conn.on('ready', function (istream, person) {
    person.say('bot', 'getting this?');
    person.say('#test', 'bot: hi');
    person.say('#test', 'participate');

    setTimeout(function () {
      // intercept in istream just afterwards
      var m1 = istream.read();
      t.deepEqual(m1, null, 'ignoring pms and chan');

      conn.close();
      t.done();
    }, 500);
  });
};

exports.defaultOptsResponses = function (t) {
  var istreamOpts = {};
  var conn = new Connection(istreamOpts);

  // send messages from person to bot when ready
  conn.on('ready', function (istream, person) {
    person.say('#test', 'bot: hi');
    person.say('#test', 'participate');
    person.say('bot', 'getting this?');

    setTimeout(function () {
      // intercept in istream just afterwards
      var m1 = istream.read();
      var excp1 = { user: '#test:dude', name: 'dude', message: 'hi' };
      t.deepEqual(m1, excp1, 'chan message read on default');

      var m2 = istream.read();
      t.deepEqual(m2, null, 'not participating');

      var m3 = istream.read();
      t.deepEqual(m3, null, 'ignoring pms');

      var m4 = istream.read();
      t.equal(m4, null, 'no fourth message');

      // write responses from bot to person finally
      istream.write({ user: 'dude', message: 'bonk' });
      istream.write({ user: '#test:dude', message: 'really?'});
      istream.write({ user: '#test:dude', message: 'that is insane'});
      setTimeout(function () {
        var resps = conn.resps;
        var r1 = { from: 'bot', to: 'dude', message: 'bonk' };
        var r2 = { from: 'bot', to: '#test', message: 'dude: really?'};
        var r3 = { from: 'bot', to: '#test', message: 'that is insane'};
        t.deepEqual(resps[0], r1, 'pm to person');
        t.deepEqual(resps[1], r2, 'chan msg 1 to person (highlighted)');
        t.deepEqual(resps[2], r3, 'chan msg 2 to person (not highlighted)');

        conn.close();
        t.done();
      }, 500);
    }, 500);
  });
};

exports.neverHighlight = function (t) {
  var istreamOpts = {
    neverHighlight: true
  };
  var conn = new Connection(istreamOpts);

  // send messages from person to bot when ready
  conn.on('ready', function (istream) {
    // write messages from bot to person
    istream.write({ user: 'dude', message: 'bonk' });
    istream.write({ user: '#test:dude', message: 'really?'});
    istream.write({ user: '#test:dude', message: 'that is insane'});
    setTimeout(function () {
      var resps = conn.resps;
      var r1 = { from: 'bot', to: 'dude', message: 'bonk' };
      var r2 = { from: 'bot', to: '#test', message: 'really?'};
      var r3 = { from: 'bot', to: '#test', message: 'that is insane'};
      t.deepEqual(resps[0], r1, 'pm to person');
      t.deepEqual(resps[1], r2, 'chan msg 1 to person (not highlighted)');
      t.deepEqual(resps[2], r3, 'chan msg 2 to person (same)');

      conn.close();
      t.done();
    }, 500);
  });
};

exports.alwaysHighlight = function (t) {
  var istreamOpts = {
    alwaysHighlight: true
  };
  var conn = new Connection(istreamOpts);

  // send messages from person to bot when ready
  conn.on('ready', function (istream) {
    // write messages from bot to person
    istream.write({ user: 'dude', message: 'bonk' });
    istream.write({ user: '#test:dude', message: 'really?'});
    istream.write({ user: '#test:dude', message: 'that is insane'});
    setTimeout(function () {
      var resps = conn.resps;
      var r1 = { from: 'bot', to: 'dude', message: 'bonk' };
      var r2 = { from: 'bot', to: '#test', message: 'dude: really?'};
      var r3 = { from: 'bot', to: '#test', message: 'dude: that is insane'};
      t.deepEqual(resps[0], r1, 'pm to person');
      t.deepEqual(resps[1], r2, 'chan msg 1 to person (highlight)');
      t.deepEqual(resps[2], r3, 'chan msg 2 to person (highlight again)');

      conn.close();
      t.done();
    }, 500);
  });
};
<|endoftext|>


<commit_before>'use strict';

var Item = require('../lib/item'),
		Table = require('../lib/table'),
		Schema = require('../lib/schema'),
    chai = require('chai'),
    expect = chai.expect,
    helper = require('./test-helper');

chai.should();

describe('item', function() {
	it('JSON.stringify should only serialize attrs', function() {
		var schema = new Schema();
		schema.Number('num');
		schema.String('name');

    var table = new Table('mockTable', schema, helper.mockSerializer(), helper.mockDynamoDB());
    var attrs = {num: 1, name: 'foo'};
    var item = new Item(attrs, table);
    var stringified = JSON.stringify(item);

    stringified.should.equal(JSON.stringify(attrs));
  });
});
<commit_msg>jshint fixes<commit_after>'use strict';

var Item   = require('../lib/item'),
    Table  = require('../lib/table'),
    Schema = require('../lib/schema'),
    chai   = require('chai'),
    helper = require('./test-helper');

chai.should();

describe('item', function() {
  it('JSON.stringify should only serialize attrs', function() {
    var schema = new Schema();
    schema.Number('num');
    schema.String('name');

    var table = new Table('mockTable', schema, helper.mockSerializer(), helper.mockDynamoDB());
    var attrs = {num: 1, name: 'foo'};
    var item = new Item(attrs, table);
    var stringified = JSON.stringify(item);

    stringified.should.equal(JSON.stringify(attrs));
  });
});
<|endoftext|>


<commit_before>/**
 * Searches a content string for titles by the keyword
 * @param {string} contents - File contents as a utf8 string
 * @param {object} cfg - Config object
 * @param {string} [title] - Title to search for
 */
module.exports = (contents, cfg, title) => {
  const regexFlags = cfg.caseSensitive ? 'g' : 'gi'
  const re = new RegExp(`${cfg.keyword}\\s${title || '(.*)'}`, regexFlags)

  const matches = contents.match(re)
  if (matches) {
    return matches.map(title => title.replace(new RegExp(`${cfg.keyword} `, regexFlags), ''))
  }
}<commit_msg>Fix linter<commit_after>/**
 * Searches a content string for titles by the keyword
 * @param {string} contents - File contents as a utf8 string
 * @param {object} cfg - Config object
 * @param {string} [title] - Title to search for
 */
module.exports = (contents, cfg, title) => {
  const regexFlags = cfg.caseSensitive ? 'g' : 'gi'
  const re = new RegExp(`${cfg.keyword}\\s${title || '(.*)'}`, regexFlags)

  const matches = contents.match(re)
  if (matches) {
    return matches.map(title => title.replace(new RegExp(`${cfg.keyword} `, regexFlags), ''))
  }
}
<|endoftext|>