<commit_before>var SSH = require('../'),
    exec = require('child_process').exec;

function run(cmd) {
        exec(cmd, function(err, stdout, stderr) {
            console.log(cmd);
            console.log('err', err);
            console.log('stdout', stdout);
            console.log('stderr', stderr);
        });
}

describe('ssh-kit', function() {
    beforeEach(function() {
        this.ssh = new SSH();
    });

    it('connects to ssh', function(done) {
        var dir = __dirname,
            _this = this;

        run('pwd');
        run('whoami');
        run('cd ~ && pwd');

        run('cp ' + dir + '/ssh_kit_test_key /home/travis/.ssh/id_rsa');
        run('chmod 600 /home/travis/.ssh/id_rsa');

        run('cat ' + dir + '/ssh_kit_test_key.pub >> /home/travis/.ssh/authorized_keys');

        run('chmod 600 /home/travis/.ssh/authorized_keys');

        run('ls -la /home/travis/.ssh');

        setTimeout(function() {
            _this.ssh.set('host', 'localhost');
            _this.ssh.set('sshKey', dir + '/ssh_kit_test_key');
            _this.ssh.exec('ls');
            _this.ssh.on('finish', done);
        }, 500);

    });
});
<commit_msg>setup before test suite<commit_after>var SSH = require('../'),
    exec = require('child_process').exec;

function run(cmd) {
    exec(cmd, function(err, stdout, stderr) {
        console.log(cmd);
        console.log('err', err);
        console.log('stdout', stdout);
        console.log('stderr', stderr);
    });
}

before(function(done) {
    var dir = __dirname,
        cmd = [
            'cp ' + dir + '/ssh_kit_test_key /home/travis/.ssh/id_rsa',
            'chmod 600 /home/travis/.ssh/id_rsa',
            'cat ' + dir + '/ssh_kit_test_key.pub >> /home/travis/.ssh/authorized_keys',
            'chmod 600 /home/travis/.ssh/authorized_keys'
        ].join(' && ');

    exec(cmd, function(err, stdout, stderr) {
        if (err) {
            console.err(err);
            process.exit(1);
        }

        console.log('executing: ' + cmd);
        console.log('stdour: ' + stdout);
        console.log('stderr: ' + stderr);
        done();
    });
});

describe('ssh-kit', function() {
    beforeEach(function() {
        this.ssh = new SSH();
    });

    it('connects to ssh', function(done) {
        this.ssh.set('host', 'localhost');
        this.ssh.set('sshKey', dir + '/ssh_kit_test_key');
        this.ssh.exec('ls');
        this.ssh.on('finish', done);
    });
});
<|endoftext|>


<commit_before>$(window).ready(function(){

	//main menu flyouts or mbmenu releacment
	//$( '#MenuView .parent, #HeaderLinksView .parent, #ShortcutsMenu .parent' ).hover(
	$( '.nav > .parent' ).hover(
		function(){
			if ( $(this).find('ul') ){
				$(this).find('ul').stop(true, true).delay(0).fadeIn(250);
			}
		},
		function(){
			if ( $(this).find('ul') ){
				$(this).find('ul').stop(true, true).fadeOut(250);
			}
		}
	);

	/*Resizes the app to fill the browser's window case smaller'*/
	var viewportHeight = $(window).height();
	var wrapperDivHeight = $('body > div').outerHeight(true)
	var appChromeHeight = 0;
	var bufferHeight = 0;
	var recentlyViewedHeight = 0;

	if ( $('#LoginPageView').length > 0 ) {
		appChromeHeight = 38 + $('#FooterView').outerHeight(true);
		if ( wrapperDivHeight < viewportHeight  ){
			bufferHeight = viewportHeight - appChromeHeight;
			$('#LoginView').height(  bufferHeight   );
		}
	} else {
		recentlyViewedHeight = $('#RecentlyViewedView').outerHeight(true);
		appChromeHeight = recentlyViewedHeight + $('#MenuView').outerHeight(true) + $('#HeaderView').outerHeight(true) + $('#FooterView').outerHeight(true);
		if ( wrapperDivHeight < viewportHeight  ){
			bufferHeight = viewportHeight - appChromeHeight;
			$('#RecentlyViewedView').height( $('#RecentlyViewedView').height() + bufferHeight   );
		}
	}

	/*Dropdowns - Dropkick*/

	$('#edit-form select, .search-view-1 select, #inline-edit-form select').dropkick();

	$('html').click(function(e) {
		$.each($('td > select'), function(index, value) {
			$(value).dropkick('close');
		});
	});

	/*Checkboxes
	 from: http://webdesign.maratz.com/lab/fancy-checkboxes-and-radio-buttons/jquery.html
	 * */

	function setupCheckboxes( $context ) {

		if ( $('input:checkbox', $context ).length ) {
			$('input:checkbox', $context ).each(function(){
				$(this).parent().removeClass('c_on');
			});
			$('label input:checked', $context ).each(function(){
				$(this).parent('label').addClass('c_on');
		    });
		}

		$('label', $context[0] ).
		    live( 'click', { $inputContext:$(this).content  },
				function( event ){
			        if ( $('input:checkbox', event.data.$inputContext ).length ) {
						$('input:checkbox', event.data.$inputContext ).each(function(){
							$(this).parent().removeClass('c_on');
						});
						$('label input:checked', event.data.$inputContext ).each(function(){
							$(this).parent('label').addClass('c_on');
					    });
					}
			});
	}

    //we're doing that because the multiselect widget isn't generated yet..
    window.setTimeout(
    	function setCheckboxes(){
    		setupCheckboxes( $('#search-form') );
    		setupCheckboxes( $('#app-search') );
    	},
    1000 );

    /*Labels*/

    $(".overlay-label-field > input").live('focus', function(){
	    $(this).prev().fadeOut(100);
	});

	$(".overlay-label-field > input").live('blur', function(){
	    if($(this).val() == "") {
	        $(this).prev().fadeIn(250);
	    }
	});

});

// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function f(){ log.history = log.history || []; log.history.push(arguments); if(this.console) { var args = arguments, newarr; args.callee = args.callee.caller; newarr = [].slice.call(args); if (typeof console.log === 'object') log.apply.call(console.log, console, newarr); else console.log.apply(console, newarr);}};

// make it safe to use console.log always
(function(a){function b(){}for(var c="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),d;!!(d=c.pop());){a[d]=a[d]||b;}})
(function(){try{console.log();return window.console;}catch(a){return (window.console={});}}());<commit_msg>query to show/hide label overlaid on field<commit_after>$(window).ready(function(){

	//main menu flyouts or mbmenu releacment
	//$( '#MenuView .parent, #HeaderLinksView .parent, #ShortcutsMenu .parent' ).hover(
	$( '.nav > .parent' ).hover(
		function(){
			if ( $(this).find('ul') ){
				$(this).find('ul').stop(true, true).delay(0).fadeIn(250);
			}
		},
		function(){
			if ( $(this).find('ul') ){
				$(this).find('ul').stop(true, true).fadeOut(250);
			}
		}
	);

	/*Resizes the app to fill the browser's window case smaller'*/
	var viewportHeight = $(window).height();
	var wrapperDivHeight = $('body > div').outerHeight(true)
	var appChromeHeight = 0;
	var bufferHeight = 0;
	var recentlyViewedHeight = 0;

	if ( $('#LoginPageView').length > 0 ) {
		appChromeHeight = 38 + $('#FooterView').outerHeight(true);
		if ( wrapperDivHeight < viewportHeight  ){
			bufferHeight = viewportHeight - appChromeHeight;
			$('#LoginView').height(  bufferHeight   );
		}
	} else {
		recentlyViewedHeight = $('#RecentlyViewedView').outerHeight(true);
		appChromeHeight = recentlyViewedHeight + $('#MenuView').outerHeight(true) + $('#HeaderView').outerHeight(true) + $('#FooterView').outerHeight(true);
		if ( wrapperDivHeight < viewportHeight  ){
			bufferHeight = viewportHeight - appChromeHeight;
			$('#RecentlyViewedView').height( $('#RecentlyViewedView').height() + bufferHeight   );
		}
	}

	/*Dropdowns - Dropkick*/

	$('#edit-form select, .search-view-1 select, #inline-edit-form select').dropkick();

	$('html').click(function(e) {
		$.each($('td > select'), function(index, value) {
			$(value).dropkick('close');
		});
	});

	/*Checkboxes
	 from: http://webdesign.maratz.com/lab/fancy-checkboxes-and-radio-buttons/jquery.html
	 * */

	function setupCheckboxes( $context ) {

		if ( $('input:checkbox', $context ).length ) {
			$('input:checkbox', $context ).each(function(){
				$(this).parent().removeClass('c_on');
			});
			$('label input:checked', $context ).each(function(){
				$(this).parent('label').addClass('c_on');
		    });
		}

		$('label', $context[0] ).
		    live( 'click', { $inputContext:$(this).content  },
				function( event ){
			        if ( $('input:checkbox', event.data.$inputContext ).length ) {
						$('input:checkbox', event.data.$inputContext ).each(function(){
							$(this).parent().removeClass('c_on');
						});
						$('label input:checked', event.data.$inputContext ).each(function(){
							$(this).parent('label').addClass('c_on');
					    });
					}
			});
	}

    //we're doing that because the multiselect widget isn't generated yet..
    window.setTimeout(
    	function setCheckboxes(){
    		setupCheckboxes( $('#search-form') );
    		setupCheckboxes( $('#app-search') );
    	},
    1000 );

	$(".overlay-label-field > input").live('focus', function(){
		$(this).prev().fadeOut(100);
	});

	$(".overlay-label-field > input").live('blur', function(){
		if($(this).val() == "") {
			$(this).prev().fadeIn(250);
		}
	});

});

// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function f(){ log.history = log.history || []; log.history.push(arguments); if(this.console) { var args = arguments, newarr; args.callee = args.callee.caller; newarr = [].slice.call(args); if (typeof console.log === 'object') log.apply.call(console.log, console, newarr); else console.log.apply(console, newarr);}};

// make it safe to use console.log always
(function(a){function b(){}for(var c="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),d;!!(d=c.pop());){a[d]=a[d]||b;}})
(function(){try{console.log();return window.console;}catch(a){return (window.console={});}}());<|endoftext|>


<commit_before>
var Core = require('../venacava.js').Core
, assert = require('assert')
, EventEmitter = require('events').EventEmitter
, redisClient = require('../src/redisClient')
;

var randomId = function () {
    return 'test' + Math.floor(Math.random() * 1000000);
};

describe('core', function () {

    var redis
    , newCore = function (channel, attrs) {
	if (typeof channel === 'object') {
	    attrs = channel;
	    channel = randomId();
	}
	else if (!channel) {
	    channel = randomId();
	}
	return new Core(channel, attrs);
    }
    ;

    it('should be constructable', function () {
	newCore({x: 1});
    });

    it('should have a channel attribute', function () {
	assert(newCore().channel, 'core did not have a channel property');
    });

    describe('#fetch', function () {

	it('should exist', function () {
	    var core = newCore();
	    assert(core.fetch, 'core did not have a fetch property');
	    assert(typeof core.fetch === 'function', 'core.fetch was not a function');
	});

	it('should restore previously set values', function (done) {
	    var core = newCore()
	    ;
	    core.set('x', Math.random(), function (err) {
		assert.ifError(err);

		var dup = newCore(core.channel, {x: Math.random()});
		dup.fetch(function (err) {
		    assert.ifError(err);
		    assert.equal(core.get('x'), dup.get('x'), 'failed to fetch');
		    done();
		});
	    });
	});

	it('should restore previously set arrays', function (done) {
	    var core = newCore()
	    , val = [Math.random()]
	    ;
	    core.set('x', val, function (err) {
		assert.ifError(err);

		var dup = newCore(core.channel, {x: Math.random()});
		dup.fetch(function (err) {
		    assert.ifError(err);
		    assert.deepEqual(dup.get('x'), val, 'failed to fetch array');
		    done();
		});
	    });
	});

	it('should restore previously set object', function (done) {
	    var core = newCore()
	    , val = {y: Math.random()}
	    ;
	    core.set('x', val, function (err) {
		assert.ifError(err);

		var dup = newCore(core.channel, {x: Math.random()});
		dup.fetch(function (err) {
		    assert.ifError(err);
		    assert.deepEqual(dup.get('x'), val, 'failed to fetch object');
		    done();
		});
	    });

	});

    });

    describe('#get', function () {

	it('should exist', function () {
	    var core = newCore();
	    assert(core.get);
	    assert.equal(typeof core.get, 'function', '"get" was not a function');
	});

	it('should synchronously return a single cached value for a single argument', function () {
	    var x = Math.random()
	    , core = newCore({x: x})
	    ;
	    assert.equal(core.get('x'), x, 'did not get the initial cached value');
	});

    });

    describe('#toJSON', function () {
	it('should synchronously return a cloned copy of the cached attrs', function () {
	    var attrs = {
		x: Math.random()
	    }
	    , core = newCore(attrs)
	    , cloned = core.toJSON()
	    ;
	    assert.deepEqual(cloned, attrs, 'did not get the initial cached attrs');
	    var y = cloned.x = Math.random();
	    assert.notDeepEqual(cloned, core.toJSON(), 'failed to successfully modify cloned attributes');
	});
    });

    describe('#set', function () {
	it('should synchronously modify a single cached value for a single argument', function () {
	    var attrs = {
		x: Math.random()
	    }
	    , core = newCore(attrs)
	    , y = Math.random()
	    ;
	    core.set('x', y);
	    assert.equal(core.get('x'), y);
	});

	it('should synchronously modify a set of cached values for an object argument', function () {
	    var attrs = {
		x: Math.random()
		, y: Math.random()
		, z: Math.random()
	    }
	    , core = newCore(attrs)
	    , newAttrs = {
		x: Math.random()
		, y: Math.random()
	    }
	    ;
	    core.set(newAttrs)
	    assert.equal(newAttrs.x, core.get('x'), 'failed to set x through object argument');
	    assert.equal(newAttrs.y, core.get('y'), 'failed to set y through object argument');
	    assert.equal(attrs.z, core.get('z'), 'failed to preserve z after object argument');
	});

	describe(':async', function () {
	    it('should be provided', function (done) {
		newCore({x: 1}).set('x', 2, done);
	    });

	    it('should guarantee that the value is stored in the fetch source', function (done) {
		var core = newCore()
		, x = Math.random()
		;
		core.set('x', x, function (err) {
		    assert.ifError(err);
		    var dup = newCore(core.channel);
		    dup.fetch(function (err) {
			assert.ifError(err);
			assert.equal(dup.get('x'), x);
			return done();
		    });
		});
	    });
	});
    });

    describe('#has', function () {
	it('should exist', function () {
	    var core = newCore();
	    assert(core.has, '"has" does not exist');
	    assert.equal(typeof core.has, 'function', '"has" is not a function');
	});

	it('should indicate the existence of an attribute', function () {
	    var core = newCore({x: 1});
	    assert(core.has('x'), 'core did not properly indicate existing attribute.');
	    assert(!core.has('y'), 'core did not properly indicate existing attribute.');
	});
    });

    describe('#unset', function () {
	it('should exist', function () {
	    var core = newCore();
	    assert(core.unset, '"unset" does not exist');
	    assert.equal(typeof core.unset, 'function', '"unset" is not a function');
	});

	it('should change the truthiness of associated has', function () {
	    var core = newCore({x: 1});
	    core.unset('x')
	    assert(!core.has('x'), 'unset did not change "has" value');
	});

	it('should change whether the attribute appears on toJSON ', function () {
	    var core = newCore({x: 1});
	    core.unset('x');
	    assert(!core.toJSON().hasOwnProperty('x'), 'unset did not change "has" value');
	});

	it('should unset multiple keys when given an object', function () {
	    var core = newCore({x: 1, y: 2, z: 3});
	    core.unset({x: true, y: true});
	    assert.deepEqual(core.toJSON(), {z: 3}, 'multiple properties were not unset');
	});

	describe(':async', function () {
	    it('should exist', function (done) {
		newCore({x: 1}).unset('x', done);
	    });

	    it('should guarantee that the property was unset in the fetch source', function (done) {
		var core = newCore()
		, x = Math.random()
		;
		core.set('x', 1, function (err) {
		    assert.ifError(err);
		    core.unset('x', function (err) {
			assert.ifError(err);
			var dup = newCore(core.channel);
			dup.fetch(function (err) {
			    assert.ifError(err);
			    assert(!dup.has('x'), 'property was not removed.');
			    return done();
			});
		    });
		});
	    });
	});
    });

    describe('#clear', function () {

	it('should exist', function () {
	    var core = newCore();
	    assert(core.clear, 'core did not have a "clear" property');
	    assert(typeof core.clear, 'function', '"clear" property was not a function')
	});

	it('should provide async', function (done) {
	    newCore({x: 1}).clear(done);
	});

	it('should clear all properties', function (done) {
	    var core = newCore();
	    core.set('x', 1, function (err) {
		assert.ifError(err);
		core.clear(function (err) {
		    assert.ifError(err);
		    var dup = newCore(core.channel);
		    dup.fetch(function (err) {
			assert.ifError(err);
			assert.deepEqual(dup.toJSON(), {}, 'core was not cleared in the backend: ' + JSON.stringify(dup.toJSON()));
			return done();
		    });

		});
	    });
	});

    });

    describe('#exists', function () {
	it('should exist', function () {
	    assert(Core.exists, 'Core.exists does not exist.');
	});

	it('should return false for non-existent channels', function (done) {
	    var channel = newCore().channel;
	    Core.exists(channel, function (err, exists) {
		assert.ifError(err);
		assert(!exists, 'claimed existence.');
		done();
	    });
	});

	it('should return true for existing channels', function (done) {
	    var core = newCore();
	    core.set('x', 1);
	    Core.exists(core.channel, function (err, exists) {
		assert.ifError(err);
		assert(exists, 'claimed non-existence.');
		done();
	    });
	});

	describe(':instance', function () {

	    it('should exist', function () {
		assert(newCore().exists);
	    });

	    it('should return false for non-extistent channels', function (done) {
		newCore().exists(function (err, exists) {
		    assert.ifError(err);
		    assert(!exists, 'claimed existence');
		    done();
		});
	    });

	    it('should return true  for existing channels', function (done) {
		var core = newCore();
		core.set('x', 1);
		newCore(core.channel).exists(function (err, exists) {
		    assert.ifError(err);
		    assert(exists, 'claimed non-existence');
		    done();
		});
	    });

	});
    });

    describe('#erase', function () {

	it('should exist', function () {
	    assert(Core.erase)
	});

	it('should erase existing cores', function (done) {
	    var core = newCore();
	    core.set('x', 1);
	    Core.erase(core.channel);
	    Core.exists(core.channel, function (err, exists) {
		assert.ifError(err);
		assert(!exists, 'core was not erased.');
		done();
	    })
	});

	describe(':instance', function () {

	    it('should exist', function () {
		assert(newCore().erase);
	    });

	    it('should erase the core', function (done) {
		var core = newCore();
		core.set('x', 1);
		core.erase();
		Core.exists(core.channel, function (err, exists) {
		    assert.ifError(err);
		    assert(!exists, 'core was not erased.');
		    done();
		});
	    });

	});

    });

    describe('redis subscription', function () {

	it('should send "set" updates', function (done) {
	    var subRedis = redisClient.create()
	    , core = newCore()
	    , attrs = {x: 1}
	    ;
	    subRedis.on('message', function (channel, msg) {
		var obj = JSON.parse(msg);
		assert.equal(channel, core.channel, 'received message on unknown channel.');
		assert(obj.hasOwnProperty('subject'), 'message did not have a subject.')
		assert.equal(obj.subject, 'set', 'message subject was not "set".');
		assert(obj.hasOwnProperty('body'), 'message did not have a body');
		assert.deepEqual(obj.body, attrs, 'wrong message body');
		done();
	    });

	    subRedis.subscribe(core.channel);
	    subRedis.on('subscribe', function (channel, count) {
		assert.equal(channel, core.channel, 'subscribed to unknown channel.');
		core.set(attrs);
	    });
	});

	it('should send "unset" updates', function (done) {
	    var subRedis = redisClient.create()
	    , core = newCore()
	    , attrs = {x: 1}
	    ;
	    subRedis.on('message', function (channel, msg) {
		var obj = JSON.parse(msg);
		assert.equal(channel, core.channel, 'received message on unknown channel.');
		assert(obj.hasOwnProperty('subject'), 'message did not have a subject.')
		assert.equal(obj.subject, 'unset', 'message subject was not "unset".');
		assert(obj.hasOwnProperty('body'), 'message did not have a body');
		assert(obj.body.hasOwnProperty('x'), 'message body did not have the expected atribute');
		done();
	    });

	    subRedis.subscribe(core.channel);
	    subRedis.on('subscribe', function (channel, count) {
		assert.equal(channel, core.channel, 'subscribed to unknown channel.');
		core.unset('x');
	    });
	});

	it('should send "erased" updates', function (done) {
	    var subRedis = redisClient.create()
	    , core = newCore()
	    ;
	    core.set('x', 1);
	    subRedis.on('message', function (channel, msg) {
		var obj = JSON.parse(msg);
		assert.equal(channel, core.channel, 'received message on unknown channel.');
		assert(obj.hasOwnProperty('subject'), 'message did not have a subject.')
		assert.equal(obj.subject, 'erased', 'message subject was not unset.');
		done();
	    });

	    subRedis.subscribe(core.channel);
	    subRedis.on('subscribe', function (channel, count) {
		assert.equal(channel, core.channel, 'subscribed to unknown channel.');
		core.erase();
	    });
	});

    });
});
      <commit_msg>Add a passing core test for obj sets.<commit_after>
var Core = require('../venacava.js').Core
, assert = require('assert')
, EventEmitter = require('events').EventEmitter
, redisClient = require('../src/redisClient')
;

var randomId = function () {
    return 'test' + Math.floor(Math.random() * 1000000);
};

describe('core', function () {

    var redis
    , newCore = function (channel, attrs) {
	if (typeof channel === 'object') {
	    attrs = channel;
	    channel = randomId();
	}
	else if (!channel) {
	    channel = randomId();
	}
	return new Core(channel, attrs);
    }
    ;

    it('should be constructable', function () {
	newCore({x: 1});
    });

    it('should have a channel attribute', function () {
	assert(newCore().channel, 'core did not have a channel property');
    });

    describe('#fetch', function () {

	it('should exist', function () {
	    var core = newCore();
	    assert(core.fetch, 'core did not have a fetch property');
	    assert(typeof core.fetch === 'function', 'core.fetch was not a function');
	});

	it('should restore previously set values', function (done) {
	    var core = newCore()
	    ;
	    core.set('x', Math.random(), function (err) {
		assert.ifError(err);

		var dup = newCore(core.channel, {x: Math.random()});
		dup.fetch(function (err) {
		    assert.ifError(err);
		    assert.equal(core.get('x'), dup.get('x'), 'failed to fetch');
		    done();
		});
	    });
	});

	it('should restore previously set arrays', function (done) {
	    var core = newCore()
	    , val = [Math.random()]
	    ;
	    core.set('x', val, function (err) {
		assert.ifError(err);

		var dup = newCore(core.channel, {x: Math.random()});
		dup.fetch(function (err) {
		    assert.ifError(err);
		    assert.deepEqual(dup.get('x'), val, 'failed to fetch array');
		    done();
		});
	    });
	});

	it('should restore previously set object', function (done) {
	    var core = newCore()
	    , val = {y: Math.random()}
	    ;
	    core.set('x', val, function (err) {
		assert.ifError(err);

		var dup = newCore(core.channel, {x: Math.random()});
		dup.fetch(function (err) {
		    assert.ifError(err);
		    assert.deepEqual(dup.get('x'), val, 'failed to fetch object');
		    done();
		});
	    });

	});

    });

    describe('#get', function () {

	it('should exist', function () {
	    var core = newCore();
	    assert(core.get);
	    assert.equal(typeof core.get, 'function', '"get" was not a function');
	});

	it('should synchronously return a single cached value for a single argument', function () {
	    var x = Math.random()
	    , core = newCore({x: x})
	    ;
	    assert.equal(core.get('x'), x, 'did not get the initial cached value');
	});

    });

    describe('#toJSON', function () {
	it('should synchronously return a cloned copy of the cached attrs', function () {
	    var attrs = {
		x: Math.random()
	    }
	    , core = newCore(attrs)
	    , cloned = core.toJSON()
	    ;
	    assert.deepEqual(cloned, attrs, 'did not get the initial cached attrs');
	    var y = cloned.x = Math.random();
	    assert.notDeepEqual(cloned, core.toJSON(), 'failed to successfully modify cloned attributes');
	});
    });

    describe('#set', function () {
	it('should synchronously modify a single cached value for a single argument', function () {
	    var attrs = {
		x: Math.random()
	    }
	    , core = newCore(attrs)
	    , y = Math.random()
	    ;
	    core.set('x', y);
	    assert.equal(core.get('x'), y);
	});

	it('should synchronously modify a set of cached values for an object argument', function () {
	    var attrs = {
		x: Math.random()
		, y: Math.random()
		, z: Math.random()
	    }
	    , core = newCore(attrs)
	    , newAttrs = {
		x: Math.random()
		, y: Math.random()
	    }
	    ;
	    core.set(newAttrs)
	    assert.equal(newAttrs.x, core.get('x'), 'failed to set x through object argument');
	    assert.equal(newAttrs.y, core.get('y'), 'failed to set y through object argument');
	    assert.equal(attrs.z, core.get('z'), 'failed to preserve z after object argument');
	});

	describe(':async', function () {
	    it('should be provided', function (done) {
		newCore({x: 1}).set('x', 2, done);
	    });

	    it('should guarantee that the value is stored in the fetch source', function (done) {
		var core = newCore()
		, x = Math.random()
		;
		core.set('x', x, function (err) {
		    assert.ifError(err);
		    var dup = newCore(core.channel);
		    dup.fetch(function (err) {
			assert.ifError(err);
			assert.equal(dup.get('x'), x);
			return done();
		    });
		});
	    });
	});
    });

    describe('#has', function () {
	it('should exist', function () {
	    var core = newCore();
	    assert(core.has, '"has" does not exist');
	    assert.equal(typeof core.has, 'function', '"has" is not a function');
	});

	it('should indicate the existence of an attribute', function () {
	    var core = newCore({x: 1});
	    assert(core.has('x'), 'core did not properly indicate existing attribute.');
	    assert(!core.has('y'), 'core did not properly indicate existing attribute.');
	});
    });

    describe('#unset', function () {
	it('should exist', function () {
	    var core = newCore();
	    assert(core.unset, '"unset" does not exist');
	    assert.equal(typeof core.unset, 'function', '"unset" is not a function');
	});

	it('should change the truthiness of associated has', function () {
	    var core = newCore({x: 1});
	    core.unset('x')
	    assert(!core.has('x'), 'unset did not change "has" value');
	});

	it('should change whether the attribute appears on toJSON ', function () {
	    var core = newCore({x: 1});
	    core.unset('x');
	    assert(!core.toJSON().hasOwnProperty('x'), 'unset did not change "has" value');
	});

	it('should unset multiple keys when given an object', function () {
	    var core = newCore({x: 1, y: 2, z: 3});
	    core.unset({x: true, y: true});
	    assert.deepEqual(core.toJSON(), {z: 3}, 'multiple properties were not unset');
	});

	describe(':async', function () {
	    it('should exist', function (done) {
		newCore({x: 1}).unset('x', done);
	    });

	    it('should guarantee that the property was unset in the fetch source', function (done) {
		var core = newCore()
		, x = Math.random()
		;
		core.set('x', 1, function (err) {
		    assert.ifError(err);
		    core.unset('x', function (err) {
			assert.ifError(err);
			var dup = newCore(core.channel);
			dup.fetch(function (err) {
			    assert.ifError(err);
			    assert(!dup.has('x'), 'property was not removed.');
			    return done();
			});
		    });
		});
	    });
	});
    });

    describe('#clear', function () {

	it('should exist', function () {
	    var core = newCore();
	    assert(core.clear, 'core did not have a "clear" property');
	    assert(typeof core.clear, 'function', '"clear" property was not a function')
	});

	it('should provide async', function (done) {
	    newCore({x: 1}).clear(done);
	});

	it('should clear all properties', function (done) {
	    var core = newCore();
	    core.set('x', 1, function (err) {
		assert.ifError(err);
		core.clear(function (err) {
		    assert.ifError(err);
		    var dup = newCore(core.channel);
		    dup.fetch(function (err) {
			assert.ifError(err);
			assert.deepEqual(dup.toJSON(), {}, 'core was not cleared in the backend: ' + JSON.stringify(dup.toJSON()));
			return done();
		    });

		});
	    });
	});

    });

    describe('#exists', function () {
	it('should exist', function () {
	    assert(Core.exists, 'Core.exists does not exist.');
	});

	it('should return false for non-existent channels', function (done) {
	    var channel = newCore().channel;
	    Core.exists(channel, function (err, exists) {
		assert.ifError(err);
		assert(!exists, 'claimed existence.');
		done();
	    });
	});

	it('should return true for existing channels', function (done) {
	    var core = newCore();
	    core.set('x', 1);
	    Core.exists(core.channel, function (err, exists) {
		assert.ifError(err);
		assert(exists, 'claimed non-existence.');
		done();
	    });
	});

	it('should return true for existing channels; obj version', function (done) {
	    var core = newCore();
	    core.set({
		x: 1
	    });
	    Core.exists(core.channel, function (err, exists) {
		assert.ifError(err);
		assert(exists, 'claimed non-existence.');
		done();
	    });
	});

	describe(':instance', function () {

	    it('should exist', function () {
		assert(newCore().exists);
	    });

	    it('should return false for non-extistent channels', function (done) {
		newCore().exists(function (err, exists) {
		    assert.ifError(err);
		    assert(!exists, 'claimed existence');
		    done();
		});
	    });

	    it('should return true  for existing channels', function (done) {
		var core = newCore();
		core.set('x', 1);
		newCore(core.channel).exists(function (err, exists) {
		    assert.ifError(err);
		    assert(exists, 'claimed non-existence');
		    done();
		});
	    });

	});
    });

    describe('#erase', function () {

	it('should exist', function () {
	    assert(Core.erase)
	});

	it('should erase existing cores', function (done) {
	    var core = newCore();
	    core.set('x', 1);
	    Core.erase(core.channel);
	    Core.exists(core.channel, function (err, exists) {
		assert.ifError(err);
		assert(!exists, 'core was not erased.');
		done();
	    })
	});

	describe(':instance', function () {

	    it('should exist', function () {
		assert(newCore().erase);
	    });

	    it('should erase the core', function (done) {
		var core = newCore();
		core.set('x', 1);
		core.erase();
		Core.exists(core.channel, function (err, exists) {
		    assert.ifError(err);
		    assert(!exists, 'core was not erased.');
		    done();
		});
	    });

	});

    });

    describe('redis subscription', function () {

	it('should send "set" updates', function (done) {
	    var subRedis = redisClient.create()
	    , core = newCore()
	    , attrs = {x: 1}
	    ;
	    subRedis.on('message', function (channel, msg) {
		var obj = JSON.parse(msg);
		assert.equal(channel, core.channel, 'received message on unknown channel.');
		assert(obj.hasOwnProperty('subject'), 'message did not have a subject.')
		assert.equal(obj.subject, 'set', 'message subject was not "set".');
		assert(obj.hasOwnProperty('body'), 'message did not have a body');
		assert.deepEqual(obj.body, attrs, 'wrong message body');
		done();
	    });

	    subRedis.subscribe(core.channel);
	    subRedis.on('subscribe', function (channel, count) {
		assert.equal(channel, core.channel, 'subscribed to unknown channel.');
		core.set(attrs);
	    });
	});

	it('should send "unset" updates', function (done) {
	    var subRedis = redisClient.create()
	    , core = newCore()
	    , attrs = {x: 1}
	    ;
	    subRedis.on('message', function (channel, msg) {
		var obj = JSON.parse(msg);
		assert.equal(channel, core.channel, 'received message on unknown channel.');
		assert(obj.hasOwnProperty('subject'), 'message did not have a subject.')
		assert.equal(obj.subject, 'unset', 'message subject was not "unset".');
		assert(obj.hasOwnProperty('body'), 'message did not have a body');
		assert(obj.body.hasOwnProperty('x'), 'message body did not have the expected atribute');
		done();
	    });

	    subRedis.subscribe(core.channel);
	    subRedis.on('subscribe', function (channel, count) {
		assert.equal(channel, core.channel, 'subscribed to unknown channel.');
		core.unset('x');
	    });
	});

	it('should send "erased" updates', function (done) {
	    var subRedis = redisClient.create()
	    , core = newCore()
	    ;
	    core.set('x', 1);
	    subRedis.on('message', function (channel, msg) {
		var obj = JSON.parse(msg);
		assert.equal(channel, core.channel, 'received message on unknown channel.');
		assert(obj.hasOwnProperty('subject'), 'message did not have a subject.')
		assert.equal(obj.subject, 'erased', 'message subject was not unset.');
		done();
	    });

	    subRedis.subscribe(core.channel);
	    subRedis.on('subscribe', function (channel, count) {
		assert.equal(channel, core.channel, 'subscribed to unknown channel.');
		core.erase();
	    });
	});

    });
});
      <|endoftext|>


<commit_before>'use strict';

jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
jest.unmock('request-promise-native');
const alpha = require('../')();
const delay = require('delay');
const TIME = 5000;

test(`intraday data works`, () => {
  expect.assertions(2);
  return delay(TIME)
    .then(() => alpha.data.intraday(`msft`))
    .then(data => {
      expect(data['Meta Data']).toBeDefined();
      expect(data['Time Series (1min)']).toBeDefined();
    });
});

test(`daily data works`, () => {
  expect.assertions(2);
  return delay(TIME)
    .then(() => alpha.data.daily(`msft`))
    .then(data => {
      expect(data['Meta Data']).toBeDefined();
      expect(data['Time Series (Daily)']).toBeDefined();
    });
});

test(`daily adjusted data works`, () => {
  expect.assertions(2);
  return delay(TIME)
    .then(() => alpha.data.daily_adjusted(`msft`))
    .then(data => {
      expect(data['Meta Data']).toBeDefined();
      expect(data['Time Series (Daily)']).toBeDefined();
    });
});

test(`weekly data works`, () => {
  expect.assertions(2);
  return delay(TIME)
    .then(() => alpha.data.weekly(`msft`))
    .then(data => {
      expect(data['Meta Data']).toBeDefined();
      expect(data['Weekly Time Series']).toBeDefined();
    });
});

test(`weekly adjusted data works`, () => {
  expect.assertions(2);
  return delay(TIME)
    .then(() => alpha.data.weekly_adjusted(`msft`))
    .then(data => {
      expect(data['Meta Data']).toBeDefined();
      expect(data['Weekly Adjusted Time Series']).toBeDefined();
    });
});

test(`monthly data works`, () => {
  expect.assertions(2);
  return delay(TIME)
    .then(() => alpha.data.monthly(`msft`))
    .then(data => {
      expect(data['Meta Data']).toBeDefined();
      expect(data['Monthly Time Series']).toBeDefined();
    });
});

test(`weekly adjusted data works`, () => {
  expect.assertions(2);
  return delay(TIME)
    .then(() => alpha.data.monthly_adjusted(`msft`))
    .then(data => {
      expect(data['Meta Data']).toBeDefined();
      expect(data['Monthly Adjusted Time Series']).toBeDefined();
    });
});

test(`batch data works`, () => {
  expect.assertions(9);
  return delay(TIME)
    .then(() => alpha.data.batch('MSFT,FB,AAPL'))
    .then(data => {
      expect(data['Meta Data']).toBeDefined();
      expect(data['Stock Quotes']).toBeDefined();
      expect(data['Stock Quotes'].length).toEqual(3);
      data['Stock Quotes'].forEach(quote => {
        expect(quote['1. symbol']).toBeDefined();
      });
      expect(data['Stock Quotes'][0]['1. symbol']).toEqual('MSFT');
      expect(data['Stock Quotes'][1]['1. symbol']).toEqual('FB');
      expect(data['Stock Quotes'][2]['1. symbol']).toEqual('AAPL');
    });
});

test(`batch data works with array input`, () => {
  expect.assertions(9);
  return delay(TIME)
    .then(() => alpha.data.batch(['MSFT', 'FB', 'AAPL']))
    .then(data => {
      expect(data['Meta Data']).toBeDefined();
      expect(data['Stock Quotes']).toBeDefined();
      expect(data['Stock Quotes'].length).toEqual(3);
      data['Stock Quotes'].forEach(quote => {
        expect(quote['1. symbol']).toBeDefined();
      });
      expect(data['Stock Quotes'][0]['1. symbol']).toEqual('MSFT');
      expect(data['Stock Quotes'][1]['1. symbol']).toEqual('FB');
      expect(data['Stock Quotes'][2]['1. symbol']).toEqual('AAPL');
    });
});
<commit_msg>Add global quote test<commit_after>'use strict';

jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
jest.unmock('request-promise-native');
const alpha = require('../')();
const delay = require('delay');
const TIME = 5000;

test(`intraday data works`, () => {
  expect.assertions(2);
  return delay(TIME)
    .then(() => alpha.data.intraday(`msft`))
    .then(data => {
      expect(data['Meta Data']).toBeDefined();
      expect(data['Time Series (1min)']).toBeDefined();
    });
});

test(`daily data works`, () => {
  expect.assertions(2);
  return delay(TIME)
    .then(() => alpha.data.daily(`msft`))
    .then(data => {
      expect(data['Meta Data']).toBeDefined();
      expect(data['Time Series (Daily)']).toBeDefined();
    });
});

test(`daily adjusted data works`, () => {
  expect.assertions(2);
  return delay(TIME)
    .then(() => alpha.data.daily_adjusted(`msft`))
    .then(data => {
      expect(data['Meta Data']).toBeDefined();
      expect(data['Time Series (Daily)']).toBeDefined();
    });
});

test(`weekly data works`, () => {
  expect.assertions(2);
  return delay(TIME)
    .then(() => alpha.data.weekly(`msft`))
    .then(data => {
      expect(data['Meta Data']).toBeDefined();
      expect(data['Weekly Time Series']).toBeDefined();
    });
});

test(`weekly adjusted data works`, () => {
  expect.assertions(2);
  return delay(TIME)
    .then(() => alpha.data.weekly_adjusted(`msft`))
    .then(data => {
      expect(data['Meta Data']).toBeDefined();
      expect(data['Weekly Adjusted Time Series']).toBeDefined();
    });
});

test(`monthly data works`, () => {
  expect.assertions(2);
  return delay(TIME)
    .then(() => alpha.data.monthly(`msft`))
    .then(data => {
      expect(data['Meta Data']).toBeDefined();
      expect(data['Monthly Time Series']).toBeDefined();
    });
});

test(`weekly adjusted data works`, () => {
  expect.assertions(2);
  return delay(TIME)
    .then(() => alpha.data.monthly_adjusted(`msft`))
    .then(data => {
      expect(data['Meta Data']).toBeDefined();
      expect(data['Monthly Adjusted Time Series']).toBeDefined();
    });
});

test(`global quote data works`, () => {
  expect.assertions(2);
  return delay(TIME)
    .then(() => alpha.data.quote(`msft`))
    .then(data => {
      expect(data['Global Quote']).toBeDefined();
      expect(data['Global Quote']['01. symbol']).toEqual('MSFT');
    });
});

test(`batch data works`, () => {
  expect.assertions(9);
  return delay(TIME)
    .then(() => alpha.data.batch('MSFT,FB,AAPL'))
    .then(data => {
      expect(data['Meta Data']).toBeDefined();
      expect(data['Stock Quotes']).toBeDefined();
      expect(data['Stock Quotes'].length).toEqual(3);
      data['Stock Quotes'].forEach(quote => {
        expect(quote['1. symbol']).toBeDefined();
      });
      expect(data['Stock Quotes'][0]['1. symbol']).toEqual('MSFT');
      expect(data['Stock Quotes'][1]['1. symbol']).toEqual('FB');
      expect(data['Stock Quotes'][2]['1. symbol']).toEqual('AAPL');
    });
});

test(`batch data works with array input`, () => {
  expect.assertions(9);
  return delay(TIME)
    .then(() => alpha.data.batch(['MSFT', 'FB', 'AAPL']))
    .then(data => {
      expect(data['Meta Data']).toBeDefined();
      expect(data['Stock Quotes']).toBeDefined();
      expect(data['Stock Quotes'].length).toEqual(3);
      data['Stock Quotes'].forEach(quote => {
        expect(quote['1. symbol']).toBeDefined();
      });
      expect(data['Stock Quotes'][0]['1. symbol']).toEqual('MSFT');
      expect(data['Stock Quotes'][1]['1. symbol']).toEqual('FB');
      expect(data['Stock Quotes'][2]['1. symbol']).toEqual('AAPL');
    });
});
<|endoftext|>


<commit_before>import { shallowMount } from '@vue/test-utils';
import Vuex from 'vuex';
import {createLocalVue} from './helper';
import AlumniCard from '../components/home/alumni.vue';
import UwCard from '../components/_templates/card.vue';
const localVue = createLocalVue(Vuex);

describe('User Is an Alumni', () => {
  let store;

  beforeEach(() => {
    store = new Vuex.Store({
      state: {
        user: {
          affiliations: {
            alumni: true,
          }
        }
      }
    });
  });

  it('Display Alumni Card', () => {
    const wrapper = shallowMount(AlumniCard, { store, localVue });
    expect(
      wrapper.findComponent(UwCard).exists()
    ).toBe(true);
    expect(
      wrapper.findAll('h3').at(0).text()
    ).toBe('Alumni and Alumni Association');
    expect(
      wrapper.findAll('h4').at(0).text()
    ).toBe('University of Washington Alumni Association (UWAA)');

    let link1 = wrapper.findAll('a').at(0);
    expect(link1.text()).toBe('Alumni News, Events and Services');
    expect(link1.attributes().href
    ).toBe('https://www.washington.edu/alumni');

    let link2 = wrapper.findAll('a').at(1);
    expect(link2.text()).toBe('Columns Magazine');
    expect(link2.attributes().href
    ).toBe('https://magazine.washington.edu/');

    let link3 = wrapper.findAll('a').at(2)
    expect(link3.text()).toBe('Learn about the UWAA');
    expect(link3.attributes().href
    ).toBe('https://www.washington.edu/cms/alumni/membership/');
  });

  describe('User Not an Alumni', () => {
    let store;

    beforeEach(() => {
      store = new Vuex.Store({
        state: {
          user: {
            affiliations: {
              alumni: false,
            }
          }
        }
      });
    });

    it('Hide Alumni Card', () => {
      const wrapper = shallowMount(AlumniCard, { store, localVue });
      expect(wrapper.findComponent(UwCard).exists()).toBe(false);
    });
  });
});
<commit_msg>MUWM-4765: simply tests<commit_after>import { shallowMount } from '@vue/test-utils';
import Vuex from 'vuex';
import {createLocalVue} from './helper';
import AlumniCard from '../components/home/alumni.vue';
import UwCard from '../components/_templates/card.vue';
const localVue = createLocalVue(Vuex);

describe('Alumni Card', () => {
  let store;

  beforeEach(() => {
    store = new Vuex.Store({
      state: {
        user: {
          affiliations: {
            alumni: false,
          }
        }
      }
    });
  });

  it('Display card if user is alumni', () => {
    store.state.user.affiliations.alumni = true;
    const wrapper = shallowMount(AlumniCard, { store, localVue });
    expect(
      wrapper.findComponent(UwCard).exists()
    ).toBe(true);
    expect(
      wrapper.findAll('h3').at(0).text()
    ).toBe('Alumni and Alumni Association');
    expect(
      wrapper.findAll('h4').at(0).text()
    ).toBe('University of Washington Alumni Association (UWAA)');

    let link1 = wrapper.findAll('a').at(0);
    expect(link1.text()).toBe('Alumni News, Events and Services');
    expect(link1.attributes().href
    ).toBe('https://www.washington.edu/alumni');

    let link2 = wrapper.findAll('a').at(1);
    expect(link2.text()).toBe('Columns Magazine');
    expect(link2.attributes().href
    ).toBe('https://magazine.washington.edu/');

    let link3 = wrapper.findAll('a').at(2)
    expect(link3.text()).toBe('Learn about the UWAA');
    expect(link3.attributes().href
    ).toBe('https://www.washington.edu/cms/alumni/membership/');
  });

  it('Hide card is user is not alumni', () => {
    const wrapper = shallowMount(AlumniCard, { store, localVue });
    expect(wrapper.findComponent(UwCard).exists()).toBe(false);
  });
});
<|endoftext|>


<commit_before>'use strict';

var chai = require('chai');
var expect = chai.expect;

var Bookshelf = require('bookshelf');
var bookshelf = Bookshelf.initialize({
  client: 'sqlite',
  connection: {
    filename: ':memory:'
  },
  pool: {
    max: 1
  }
});

<commit_msg>Remove unused file.<commit_after><|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')
const fetch = require('node-fetch')
const sizeOf = require('image-size')
const amphtmlValidator = require('amphtml-validator')
const prettier = require('prettier')
const { load } = require('cheerio')
const { sync: glob } = require('glob')

const boilerplate = `<noscript></noscript>`
const htmlPaths = glob('./public/amp/post/*/index.html')

Promise.all([
  amphtmlValidator.getInstance(),
  prettier.resolveConfig('./public/xxx.html'),
]).then(async ([validator, prettierConfig]) => {
  for (let htmlPath of htmlPaths) {
    const html = fs.readFileSync(htmlPath, 'utf8')
    const $ = load(html, {})
    $('script')
      .not('[type="application/ld+json"]')
      .not('[src^="https://cdn.ampproject.org"]')
      .remove()

    let styles = $('style')
      .map((_i, el) => $(el).html())
      .toArray()
      .join('\n')

    styles += `
    amp-social-share[type=hatena_bookmark] {
      width: 60px;
      height: 44px;
      font-family: Verdana;
      background-color: #00a4de;
      font-weight: 700;
      color: #fff;
      line-height: 44px;
      text-align: center;
      font-size: 28px;
    }
    amp-social-share[type=pocket] {
      width: 60px;
      height: 44px;
      background-color: #EF4056;
      background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -4 16 23" width="16" height="14" fill="white" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="1.414"><path fill-rule="nonzero" d="M12.533 6.84L8.77 10.45c-.213.204-.486.306-.76.306-.273 0-.547-.102-.76-.306L3.488 6.84c-.437-.418-.45-1.113-.032-1.55.42-.438 1.114-.452 1.55-.033l3.005 2.88 3.01-2.88c.44-.42 1.13-.405 1.55.032.42.43.41 1.13-.03 1.55zm3.388-5.028c-.2-.572-.75-.956-1.36-.956H1.45c-.6 0-1.144.376-1.357.936-.063.166-.095.34-.095.515v4.828l.055.96c.232 2.184 1.365 4.092 3.12 5.423.03.024.063.047.095.07l.02.015c.94.687 1.992 1.152 3.128 1.382.524.105 1.06.16 1.592.16.492 0 .986-.046 1.472-.136.058-.02.116-.03.175-.04.016 0 .033-.01.05-.02 1.088-.24 2.098-.69 3.004-1.35l.02-.02.09-.07c1.75-1.33 2.88-3.24 3.12-5.43l.05-.96V2.3c0-.167-.02-.333-.08-.495z "></path></svg>');
      /* MIT License | https://icon.now.sh/ */
    }
    `

    $('style').remove()
    // $('noscript').remove()
    $('head').append($(boilerplate))
    $('head').append($(`<style amp-custom>${styles}</style>`))

    for (let el of $('[style]').toArray()) {
      const cssStr = $(el).attr('style')
      // The inline style specified in tag 'xxx' is too long - it contains 1669 bytes whereas the limit is 1000 bytes.
      if (cssStr.length > 1000) {
        $(el).attr('style', null)
      }
    }

    for (let el of $('img').toArray()) {
      el.tagName = 'amp-img'
      $(el).attr('layout', 'responsive')
      $(el).attr('loading', null)

      let src = $(el).attr('srcset') ? $(el).attr('srcset').split(',').reverse()[0].split(' ')[0].trim() : $(el).attr('src')
      if (!src) {
        return
      }
      if (src.startsWith('/')) {
        src = path.resolve(path.join(__dirname, '..', 'public', src))
      } else if (src.startsWith('data:')) {
        const data = src.split('base64,')[1]
        src = Buffer.from(data, 'base64')
      } else if (src.startsWith('http')) {
        src = await fetch(src).then(res => res.buffer())
      }
      const { width, height } = sizeOf(src)

      $(el).attr('width', width)
      $(el).attr('height', height)
    }

    $('iframe').each((_i, el) => {
      el.tagName = 'amp-iframe'
      $(el).attr('layout', 'responsive')
      // $(el).attr('height', 'responsive')
      $(el).attr('allowtransparency', 'allowtransparency')
      $(el).attr('mozallowfullscreen', null)
      $(el).attr('webkitallowfullscreen', null)
    })
    $('head').append(
      $(
        `<script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"></script>`
      )
    )

    $('audio').each((_i, el) => {
      el.tagName = 'amp-audio'
    })
    $('head').append(
      $(
        `<script async custom-element="amp-audio" src="https://cdn.ampproject.org/v0/amp-audio-0.1.js"></script>`
      )
    )

    $('body').append(
      $(
        `<amp-install-serviceworker src="https://blog.leko.jp/sw.js" layout="nodisplay">></amp-install-serviceworker>`
      )
    )
    $('head').append(
      $(
        `<script async custom-element="amp-install-serviceworker" src="https://cdn.ampproject.org/v0/amp-install-serviceworker-0.1.js"></script>`
      )
    )

    $('body').prepend(
      $(
        `
        <amp-analytics type="gtag" data-credentials="include">

        </amp-analytics>
        `
      )
    )
    $('head').append(
      $(
        `<script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script>`
      )
    )

    $('#ad-placeholder-1').prepend(
      $(`
        <amp-ad
          width="100vw" height=320
          type="adsense"
          data-ad-client="ca-pub-7627436148097691"
          data-ad-slot="7829116882"
          data-auto-format="rspv"
          data-full-width
        >

        </amp-ad>
      `)
    )
    $('#ad-placeholder-2').prepend(
      $(`
        <amp-ad
          width="100vw" height=320
          type="adsense"
          data-ad-client="ca-pub-7627436148097691"
          data-ad-slot="4546695031"
          data-auto-format="rspv"
          data-full-width
        >

        </amp-ad>
      `)
    )
    $('head').append(
      $(
        `<script async custom-element="amp-ad" src="https://cdn.ampproject.org/v0/amp-ad-0.1.js"></script>`
      )
    )

    const canonicalUrl = $('link[rel="canonical"]').attr('href')
    $('.after-post').before(`

        <amp-social-share type="twitter"></amp-social-share>
        <amp-social-share type="hatena_bookmark" layout="container" data-share-endpoint="http://b.hatena.ne.jp/entry/${canonicalUrl}">B!</amp-social-share>
        <amp-social-share type="pocket" layout="container" data-share-endpoint="http://getpocket.com/edit?url=${canonicalUrl}"></amp-social-share>
        <amp-social-share type="facebook" data-param-app_id="1434873820060880"></amp-social-share>
        <amp-social-share type="system"></amp-social-share>

    `)
    $('head').append(
      $(
        `<script async custom-element="amp-social-share" src="https://cdn.ampproject.org/v0/amp-social-share-0.1.js"></script>`
      )
    )

    // const ad1 = `
    // `
    // const ad2 = `
    // `
    // $('.after-post').after(ad2)

    $('html').attr('amp', '')

    const ampHTML = $.html().replace('amp=""', 'amp')

    const prettierAmpHTML = prettier.format(ampHTML, {
      ...prettierConfig,
      parser: 'html',
    })
    const lines = prettierAmpHTML.split('\n')
    const result = validator.validateString(prettierAmpHTML)
    if (result.status !== 'PASS') {
      console.error('\n\n\n', result.status, htmlPath)
      const errors = result.errors.map(error => {
        const { serverity, line, message, specUrl } = error
        const code = `${line}: ${lines[line - 1]}`
        return [serverity, code, message, specUrl].join('\n')
      })
      console.error(errors.join('\n\n'))
      continue
    }

    fs.writeFileSync(htmlPath, ampHTML, 'utf8')
    console.log(result.status, htmlPath)
  }
})
<commit_msg>Parallel amplify<commit_after>const fs = require('fs')
const path = require('path')
const fetch = require('node-fetch')
const sizeOf = require('image-size')
const amphtmlValidator = require('amphtml-validator')
const prettier = require('prettier')
const { load } = require('cheerio')
const { sync: glob } = require('glob')

const boilerplate = `<noscript></noscript>`
const htmlPaths = glob('./public/amp/post/*/index.html')

Promise.all([
  amphtmlValidator.getInstance(),
  prettier.resolveConfig('./public/xxx.html'),
]).then(async ([validator, prettierConfig]) => {
  return Promise.all(htmlPaths.map(htmlPath => {
    const html = fs.readFileSync(htmlPath, 'utf8')
    const $ = load(html, {})
    $('script')
      .not('[type="application/ld+json"]')
      .not('[src^="https://cdn.ampproject.org"]')
      .remove()

    let styles = $('style')
      .map((_i, el) => $(el).html())
      .toArray()
      .join('\n')

    styles += `
    amp-social-share[type=hatena_bookmark] {
      width: 60px;
      height: 44px;
      font-family: Verdana;
      background-color: #00a4de;
      font-weight: 700;
      color: #fff;
      line-height: 44px;
      text-align: center;
      font-size: 28px;
    }
    amp-social-share[type=pocket] {
      width: 60px;
      height: 44px;
      background-color: #EF4056;
      background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -4 16 23" width="16" height="14" fill="white" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="1.414"><path fill-rule="nonzero" d="M12.533 6.84L8.77 10.45c-.213.204-.486.306-.76.306-.273 0-.547-.102-.76-.306L3.488 6.84c-.437-.418-.45-1.113-.032-1.55.42-.438 1.114-.452 1.55-.033l3.005 2.88 3.01-2.88c.44-.42 1.13-.405 1.55.032.42.43.41 1.13-.03 1.55zm3.388-5.028c-.2-.572-.75-.956-1.36-.956H1.45c-.6 0-1.144.376-1.357.936-.063.166-.095.34-.095.515v4.828l.055.96c.232 2.184 1.365 4.092 3.12 5.423.03.024.063.047.095.07l.02.015c.94.687 1.992 1.152 3.128 1.382.524.105 1.06.16 1.592.16.492 0 .986-.046 1.472-.136.058-.02.116-.03.175-.04.016 0 .033-.01.05-.02 1.088-.24 2.098-.69 3.004-1.35l.02-.02.09-.07c1.75-1.33 2.88-3.24 3.12-5.43l.05-.96V2.3c0-.167-.02-.333-.08-.495z "></path></svg>');
      /* MIT License | https://icon.now.sh/ */
    }
    `

    $('style').remove()
    // $('noscript').remove()
    $('head').append($(boilerplate))
    $('head').append($(`<style amp-custom>${styles}</style>`))

    for (let el of $('[style]').toArray()) {
      const cssStr = $(el).attr('style')
      // The inline style specified in tag 'xxx' is too long - it contains 1669 bytes whereas the limit is 1000 bytes.
      if (cssStr.length > 1000) {
        $(el).attr('style', null)
      }
    }

    for (let el of $('img').toArray()) {
      el.tagName = 'amp-img'
      $(el).attr('layout', 'responsive')
      $(el).attr('loading', null)

      let src = $(el).attr('srcset') ? $(el).attr('srcset').split(',').reverse()[0].split(' ')[0].trim() : $(el).attr('src')
      if (!src) {
        return
      }
      if (src.startsWith('/')) {
        src = path.resolve(path.join(__dirname, '..', 'public', src))
      } else if (src.startsWith('data:')) {
        const data = src.split('base64,')[1]
        src = Buffer.from(data, 'base64')
      } else if (src.startsWith('http')) {
        src = await fetch(src).then(res => res.buffer())
      }
      const { width, height } = sizeOf(src)

      $(el).attr('width', width)
      $(el).attr('height', height)
    }

    $('iframe').each((_i, el) => {
      el.tagName = 'amp-iframe'
      $(el).attr('layout', 'responsive')
      // $(el).attr('height', 'responsive')
      $(el).attr('allowtransparency', 'allowtransparency')
      $(el).attr('mozallowfullscreen', null)
      $(el).attr('webkitallowfullscreen', null)
    })
    $('head').append(
      $(
        `<script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"></script>`
      )
    )

    $('audio').each((_i, el) => {
      el.tagName = 'amp-audio'
    })
    $('head').append(
      $(
        `<script async custom-element="amp-audio" src="https://cdn.ampproject.org/v0/amp-audio-0.1.js"></script>`
      )
    )

    $('body').append(
      $(
        `<amp-install-serviceworker src="https://blog.leko.jp/sw.js" layout="nodisplay">></amp-install-serviceworker>`
      )
    )
    $('head').append(
      $(
        `<script async custom-element="amp-install-serviceworker" src="https://cdn.ampproject.org/v0/amp-install-serviceworker-0.1.js"></script>`
      )
    )

    $('body').prepend(
      $(
        `
        <amp-analytics type="gtag" data-credentials="include">

        </amp-analytics>
        `
      )
    )
    $('head').append(
      $(
        `<script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script>`
      )
    )

    $('#ad-placeholder-1').prepend(
      $(`
        <amp-ad
          width="100vw" height=320
          type="adsense"
          data-ad-client="ca-pub-7627436148097691"
          data-ad-slot="7829116882"
          data-auto-format="rspv"
          data-full-width
        >

        </amp-ad>
      `)
    )
    $('#ad-placeholder-2').prepend(
      $(`
        <amp-ad
          width="100vw" height=320
          type="adsense"
          data-ad-client="ca-pub-7627436148097691"
          data-ad-slot="4546695031"
          data-auto-format="rspv"
          data-full-width
        >

        </amp-ad>
      `)
    )
    $('head').append(
      $(
        `<script async custom-element="amp-ad" src="https://cdn.ampproject.org/v0/amp-ad-0.1.js"></script>`
      )
    )

    const canonicalUrl = $('link[rel="canonical"]').attr('href')
    $('.after-post').before(`

        <amp-social-share type="twitter"></amp-social-share>
        <amp-social-share type="hatena_bookmark" layout="container" data-share-endpoint="http://b.hatena.ne.jp/entry/${canonicalUrl}">B!</amp-social-share>
        <amp-social-share type="pocket" layout="container" data-share-endpoint="http://getpocket.com/edit?url=${canonicalUrl}"></amp-social-share>
        <amp-social-share type="facebook" data-param-app_id="1434873820060880"></amp-social-share>
        <amp-social-share type="system"></amp-social-share>

    `)
    $('head').append(
      $(
        `<script async custom-element="amp-social-share" src="https://cdn.ampproject.org/v0/amp-social-share-0.1.js"></script>`
      )
    )

    // const ad1 = `
    // `
    // const ad2 = `
    // `
    // $('.after-post').after(ad2)

    $('html').attr('amp', '')

    const ampHTML = $.html().replace('amp=""', 'amp')

    const prettierAmpHTML = prettier.format(ampHTML, {
      ...prettierConfig,
      parser: 'html',
    })
    const lines = prettierAmpHTML.split('\n')
    const result = validator.validateString(prettierAmpHTML)
    if (result.status !== 'PASS') {
      console.error('\n\n\n', result.status, htmlPath)
      const errors = result.errors.map(error => {
        const { serverity, line, message, specUrl } = error
        const code = `${line}: ${lines[line - 1]}`
        return [serverity, code, message, specUrl].join('\n')
      })
      console.error(errors.join('\n\n'))
      continue
    }

    fs.writeFileSync(htmlPath, ampHTML, 'utf8')
    console.log(result.status, htmlPath)
  }))
})
<|endoftext|>


<commit_before>import { includes } from 'underscore';
import Backbone from 'backbone';

export default Backbone.View.extend({
  // Default view
  itemView: '',

  // Defines the View per type
  itemsView: '',

  itemType: 'type',

  autoAdd: 0,

  initialize(opts = {}, config) {
    this.config = config || opts.config || {};

    this.autoAdd && this.listenTo(this.collection, 'add', this.addTo);

    this.init();
  },

  init() {},

  /**
   * Add new model to the collection
   * @param {Model} model
   * @private
   * */
  addTo(model) {
    this.add(model);
  },

  itemViewNotFound(type) {
    const { config, ns } = this;
    const { em } = config;
    const warn = `${ns ? `[${ns}]: ` : ''}'${type}' type not found`;
    em && em.logWarning(warn);
  },

  /**
   * Render new model inside the view
   * @param {Model} model
   * @param {Object} fragment Fragment collection
   * @private
   * */
  add(model, fragment) {
    const { config, reuseView, itemsView = {} } = this;
    const inputTypes = [
      'button',
      'checkbox',
      'color',
      'date',
      'datetime-local',
      'email',
      'file',
      'hidden',
      'image',
      'month',
      'number',
      'password',
      'radio',
      'range',
      'reset',
      'search',
      'submit',
      'tel',
      'text',
      'time',
      'url',
      'week'
    ];
    var frag = fragment || null;
    var itemView = this.itemView;
    var typeField = model.get(this.itemType);
    let view;

    if (itemsView[typeField]) {
      itemView = itemsView[typeField];
    } else if (
      typeField &&
      !itemsView[typeField] &&
      !includes(inputTypes, typeField)
    ) {
      this.itemViewNotFound(typeField);
    }

    if (model.view && reuseView) {
      view = model.view;
    } else {
      view = new itemView({ model, config }, config);
    }

    var rendered = view.render().el;

    if (frag) frag.appendChild(rendered);
    else this.$el.append(rendered);
  },

  render() {
    var frag = document.createDocumentFragment();
    this.$el.empty();

    if (this.collection.length)
      this.collection.each(function(model) {
        this.add(model, frag);
      }, this);

    this.$el.append(frag);
    this.onRender();
    return this;
  },

  onRender() {}
});
<commit_msg>Update DomainView<commit_after>import { includes } from 'underscore';
import Backbone from 'backbone';

export default Backbone.View.extend({
  // Default view
  itemView: '',

  // Defines the View per type
  itemsView: '',

  itemType: 'type',

  autoAdd: 0,

  initialize(opts = {}, config) {
    this.config = config || opts.config || {};
    this.autoAdd && this.listenTo(this.collection, 'add', this.addTo);
    this.items = [];
    this.init();
  },

  init() {},

  /**
   * Add new model to the collection
   * @param {Model} model
   * @private
   * */
  addTo(model) {
    this.add(model);
  },

  itemViewNotFound(type) {
    const { config, ns } = this;
    const { em } = config;
    const warn = `${ns ? `[${ns}]: ` : ''}'${type}' type not found`;
    em && em.logWarning(warn);
  },

  /**
   * Render new model inside the view
   * @param {Model} model
   * @param {Object} fragment Fragment collection
   * @private
   * */
  add(model, fragment) {
    const { config, reuseView, items, itemsView = {} } = this;
    const inputTypes = [
      'button',
      'checkbox',
      'color',
      'date',
      'datetime-local',
      'email',
      'file',
      'hidden',
      'image',
      'month',
      'number',
      'password',
      'radio',
      'range',
      'reset',
      'search',
      'submit',
      'tel',
      'text',
      'time',
      'url',
      'week'
    ];
    var frag = fragment || null;
    var itemView = this.itemView;
    var typeField = model.get(this.itemType);
    let view;

    if (itemsView[typeField]) {
      itemView = itemsView[typeField];
    } else if (
      typeField &&
      !itemsView[typeField] &&
      !includes(inputTypes, typeField)
    ) {
      this.itemViewNotFound(typeField);
    }

    if (model.view && reuseView) {
      view = model.view;
    } else {
      view = new itemView({ model, config }, config);
    }

    items && items.push(view);
    const rendered = view.render().el;

    if (frag) frag.appendChild(rendered);
    else this.$el.append(rendered);
  },

  render() {
    var frag = document.createDocumentFragment();
    this.clearItems();
    this.$el.empty();

    if (this.collection.length)
      this.collection.each(function(model) {
        this.add(model, frag);
      }, this);

    this.$el.append(frag);
    this.onRender();
    return this;
  },

  onRender() {},

  remove() {
    this.clearItems();
    Backbone.View.prototype.remove.apply(this, arguments);
  },

  clearItems() {
    const items = this.items || [];
    // TODO Traits do not update the target anymore
    // items.forEach(item => item.remove());
    // this.items = [];
  }
});
<|endoftext|>


<commit_before>/**
* @description MeshCentral accelerator
* @author Ylian Saint-Hilaire
* @copyright Intel Corporation 2018-2021
* @license Apache-2.0
* @version v0.0.1
*/

/*xjslint node: true */
/*xjslint plusplus: true */
/*xjslint maxlen: 256 */
/*jshint node: true */
/*jshint strict: false */
/*jshint esversion: 6 */
"use strict";

const crypto = require('crypto');
var certStore = null;

// When the parent process terminates, we exit also.
process.on('disconnect', function () { process.exit(); });

// Handle parent messages
process.on('message', function (message) { module.exports.processMessage(message); });

// Process an incoming message
module.exports.processMessage = function(message) {
    switch (message.action) {
        case 'sign': {
            if (typeof message.key == 'number') { message.key = certStore[message.key].key; }
            try {
                const sign = crypto.createSign('SHA384');
                sign.end(Buffer.from(message.data, 'binary'));
                process.send(sign.sign(message.key).toString('binary'));
            } catch (e) { process.send(null); }
            break;
        }
        case 'setState': {
            certStore = message.certs;
            break;
        }
        case 'indexMcRec': {
            //console.log('indexMcRec', message.data);
            require(require('path').join(__dirname, 'mcrec.js')).indexFile(message.data);
            break;
        }
        default: {
            console.log('Unknown accelerator action: ' + message.action + '.');
            break;
        }
    }
}<commit_msg>Delayed mcrec indexing by 5 seconds.<commit_after>/**
* @description MeshCentral accelerator
* @author Ylian Saint-Hilaire
* @copyright Intel Corporation 2018-2021
* @license Apache-2.0
* @version v0.0.1
*/

/*xjslint node: true */
/*xjslint plusplus: true */
/*xjslint maxlen: 256 */
/*jshint node: true */
/*jshint strict: false */
/*jshint esversion: 6 */
"use strict";

const crypto = require('crypto');
var certStore = null;

// When the parent process terminates, we exit also.
process.on('disconnect', function () { process.exit(); });

// Handle parent messages
process.on('message', function (message) { module.exports.processMessage(message); });

// Process an incoming message
module.exports.processMessage = function(message) {
    switch (message.action) {
        case 'sign': {
            if (typeof message.key == 'number') { message.key = certStore[message.key].key; }
            try {
                const sign = crypto.createSign('SHA384');
                sign.end(Buffer.from(message.data, 'binary'));
                process.send(sign.sign(message.key).toString('binary'));
            } catch (e) { process.send(null); }
            break;
        }
        case 'setState': {
            certStore = message.certs;
            break;
        }
        case 'indexMcRec': {
            //console.log('indexMcRec', message.data);
            // Hold 5 seconds before starting to index
            setTimeout(function () { require(require('path').join(__dirname, 'mcrec.js')).indexFile(message.data); }, 5000);
            break;
        }
        default: {
            console.log('Unknown accelerator action: ' + message.action + '.');
            break;
        }
    }
}<|endoftext|>


<commit_before>// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Iplookup utility functions
 *
 * @package    moodlecore
 * @subpackage iplookup
 * @copyright  2008 Petr Skoda (http://skodak.org)
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

M.core_iplookup = {};

M.core_iplookup.init = function(Y, latitude, longitude) {
    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        var point = new GLatLng(latitude, longitude);
        map.setCenter(point, 4);
        map.addOverlay(new GMarker(point));
        map.setMapType(G_HYBRID_MAP);

        Y.on('unload', function() {
            if (GBrowserIsCompatible()) {
                GUnload();
            }
        }, document.body);
    }
}
<commit_msg>fixed unterminated JS statement<commit_after>// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Iplookup utility functions
 *
 * @package    moodlecore
 * @subpackage iplookup
 * @copyright  2008 Petr Skoda (http://skodak.org)
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

M.core_iplookup = {};

M.core_iplookup.init = function(Y, latitude, longitude) {
    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        var point = new GLatLng(latitude, longitude);
        map.setCenter(point, 4);
        map.addOverlay(new GMarker(point));
        map.setMapType(G_HYBRID_MAP);

        Y.on('unload', function() {
            if (GBrowserIsCompatible()) {
                GUnload();
            }
        }, document.body);
    }
};
<|endoftext|>


<commit_before>var timeoutID1;
var timeoutID2;

/**
 * Prints the given error message.
 * @param {string} msg - The error message to print.
 */
function error(msg) {  // eslint-disable-line no-unused-vars
  if (timeoutID1) {
    window.clearTimeout(timeoutID1);
  }
  if (timeoutID2) {
    window.clearTimeout(timeoutID2);
  }
  var element = document.getElementById('msg');
  element.innerHTML = msg;
  element.className = 'error';
  timeoutID1 = window.setTimeout(function() {
    if (element.className !== 'error') {
      return;
    }
    element.className = 'error-hide';
    timeoutID2 = window.setTimeout(function() {
      element.innerHTML = '';
      element.className = '';
    }, 500);
  }, 10000);
}

/**
 * Prints the given informational message.
 * @param {string} msg - The information message to print.
 */
function info(msg) {
  var element = document.getElementById('msg');
  element.innerHTML = msg;
  element.className = 'info';
}

/**
 * Converts an address object into a dictionary.
 * @param {PaymentAddress} addr - The address to convert.
 * @return {object} The resulting dictionary.
 */
function toDictionary(addr) {  // eslint-disable-line no-unused-vars
  var dict = {};
  if (addr) {
    dict.country = addr.country;
    dict.region = addr.region;
    dict.city = addr.city;
    dict.dependentLocality = addr.dependentLocality;
    dict.addressLine = addr.addressLine;
    dict.postalCode = addr.postalCode;
    dict.sortingCode = addr.sortingCode;
    dict.languageCode = addr.languageCode;
    dict.organization = addr.organization;
    dict.recipient = addr.recipient;
    dict.careOf = addr.careOf;
    dict.phone = addr.phone;
  }
  return dict;
}

/**
 * Called when the payment request is complete.
 * @param {string} message - The human readable message to display.
 * @param {PaymentResponse} respo - The payment response.
 */
function done(message, resp) {  // eslint-disable-line no-unused-vars
  var element = document.getElementById('contents');
  element.innerHTML = message;

  var shippingOption =
      resp.shippingOption ? 'shipping option: ' + shippingOption + '
' : '';

  var shippingAddress = resp.shippingAddress ?
      'shipping address: ' +
          JSON.stringify(toDictionary(shippingAddress), undefined, 2) +
          '
' :
      '';

  var instrument =
      'instrument:' + JSON.stringify(instrumentDetails, undefined, 2) + '
';

  var method = 'method: ' + methodName + '
';
  var email = resp.payerEmail ? 'email: ' + payerEmail + '
' : '';
  var phone = resp.payerPhone ? 'phone: ' + payerPhone + '
' : '';

  info(email + phone + shippingOption + shippingAddress + method + instrument);
}
<commit_msg>Fix done() func<commit_after>var timeoutID1;
var timeoutID2;

/**
 * Prints the given error message.
 * @param {string} msg - The error message to print.
 */
function error(msg) {  // eslint-disable-line no-unused-vars
  if (timeoutID1) {
    window.clearTimeout(timeoutID1);
  }
  if (timeoutID2) {
    window.clearTimeout(timeoutID2);
  }
  var element = document.getElementById('msg');
  element.innerHTML = msg;
  element.className = 'error';
  timeoutID1 = window.setTimeout(function() {
    if (element.className !== 'error') {
      return;
    }
    element.className = 'error-hide';
    timeoutID2 = window.setTimeout(function() {
      element.innerHTML = '';
      element.className = '';
    }, 500);
  }, 10000);
}

/**
 * Prints the given informational message.
 * @param {string} msg - The information message to print.
 */
function info(msg) {
  var element = document.getElementById('msg');
  element.innerHTML = msg;
  element.className = 'info';
}

/**
 * Converts an address object into a dictionary.
 * @param {PaymentAddress} addr - The address to convert.
 * @return {object} The resulting dictionary.
 */
function toDictionary(addr) {  // eslint-disable-line no-unused-vars
  var dict = {};
  if (addr) {
    dict.country = addr.country;
    dict.region = addr.region;
    dict.city = addr.city;
    dict.dependentLocality = addr.dependentLocality;
    dict.addressLine = addr.addressLine;
    dict.postalCode = addr.postalCode;
    dict.sortingCode = addr.sortingCode;
    dict.languageCode = addr.languageCode;
    dict.organization = addr.organization;
    dict.recipient = addr.recipient;
    dict.careOf = addr.careOf;
    dict.phone = addr.phone;
  }
  return dict;
}

/**
 * Called when the payment request is complete.
 * @param {string} message - The human readable message to display.
 * @param {PaymentResponse} respo - The payment response.
 */
function done(message, resp) {  // eslint-disable-line no-unused-vars
  var element = document.getElementById('contents');
  element.innerHTML = message;

  var shippingOption = resp.shippingOption ?
      'shipping option: ' + resp.shippingOption + '
' :
      '';

  var shippingAddress = resp.shippingAddress ?
      'shipping address: ' +
          JSON.stringify(toDictionary(resp.shippingAddress), undefined, 2) +
          '
' :
      '';

  var instrument =
      'instrument:' + JSON.stringify(resp.details, undefined, 2) + '
';

  var method = 'method: ' + resp.methodName + '
';
  var email = resp.payerEmail ? 'email: ' + resp.payerEmail + '
' : '';
  var phone = resp.payerPhone ? 'phone: ' + resp.payerPhone + '
' : '';

  info(email + phone + shippingOption + shippingAddress + method + instrument);
}
<|endoftext|>


<commit_before>var dirco = require('../')
, util = require('util')
, patter = /^.+\.js$/i; //find all .js files

dirco(__dirname+'/../', {depth:-1, stats:false},function(err, result) {
  console.log(find(result,patter));
});

function find(root, patter) {
    var item, items = []
    , i ;
    for(i=0; i<root.length;i++) {
      item = root[i];
      if(item.name.match(patter)) {
        items.push(item.path);
      } else {
        if(item.children) {
          items = items.concat(find(item.children, patter));
        }
      }
    }
    return items;
}
<commit_msg>update test<commit_after>var dirco = require('../') //used the ES5 version, use require('../lib/dirco') for ES6
, util = require('util')
, patter = /^.+\.js$/i; //find all .js files

dirco(__dirname+'/../', {depth:-1, stats:false},function(err, result) {
  console.log(find(result,patter));
});

function find(root, patter) {
    var item, items = []
    , i ;
    for(i=0; i<root.length;i++) {
      item = root[i];
      if(item.name.match(patter)) {
        items.push(item.path);
      } else {
        if(item.children) {
          items = items.concat(find(item.children, patter));
        }
      }
    }
    return items;
}
<|endoftext|>


<commit_before>var timeoutID1;
var timeoutID2;

/**
 * Prints the given error message.
 * @param {string} msg - The error message to print.
 */
function error(msg) {  // eslint-disable-line no-unused-vars
  if (timeoutID1) {
    window.clearTimeout(timeoutID1);
  }
  if (timeoutID2) {
    window.clearTimeout(timeoutID2);
  }
  var element = document.getElementById('msg');
  element.innerHTML = msg;
  element.className = 'error';
  timeoutID1 = window.setTimeout(function() {
    if (element.className !== 'error') {
      return;
    }
    element.className = 'error-hide';
    timeoutID2 = window.setTimeout(function() {
      element.innerHTML = '';
      element.className = '';
    }, 500);
  }, 10000);
}

/**
 * Prints the given informational message.
 * @param {string} msg - The information message to print.
 */
function info(msg) {
  var element = document.getElementById('msg');
  element.innerHTML = msg;
  element.className = 'info';
}

/**
 * Converts an address object into a dictionary.
 * @param {PaymentAddress} addr - The address to convert.
 * @return {object} The resulting dictionary.
 */
function toDictionary(addr) {  // eslint-disable-line no-unused-vars
  var dict = {};
  if (addr) {
    dict.country = addr.country;
    dict.region = addr.region;
    dict.city = addr.city;
    dict.dependentLocality = addr.dependentLocality;
    dict.addressLine = addr.addressLine;
    dict.postalCode = addr.postalCode;
    dict.sortingCode = addr.sortingCode;
    dict.languageCode = addr.languageCode;
    dict.organization = addr.organization;
    dict.recipient = addr.recipient;
    dict.careOf = addr.careOf;
    dict.phone = addr.phone;
  }
  return dict;
}

/**
 * Called when the payment request is complete.
 * @param {string} message - The human readable message to display.
 * @param {PaymentResponse} respo - The payment response.
 */
function done(message, resp) {  // eslint-disable-line no-unused-vars
  var element = document.getElementById('contents');
  element.innerHTML = message;

  var shippingOption = resp.shippingOption ?
      'shipping option: ' + resp.shippingOption + '
' :
      '';

  var shippingAddress = resp.shippingAddress ?
      'shipping address: ' +
          JSON.stringify(toDictionary(resp.shippingAddress), undefined, 2) +
          '
' :
      '';

  var instrument =
      'instrument:' + JSON.stringify(resp.details, undefined, 2) + '
';

  var method = 'method: ' + resp.methodName + '
';
  var email = resp.payerEmail ? 'email: ' + resp.payerEmail + '
' : '';
  var phone = resp.payerPhone ? 'phone: ' + resp.payerPhone + '
' : '';

  info(email + phone + shippingOption + shippingAddress + method + instrument);
}
<commit_msg>Remove careOf<commit_after>var timeoutID1;
var timeoutID2;

/**
 * Prints the given error message.
 * @param {string} msg - The error message to print.
 */
function error(msg) {  // eslint-disable-line no-unused-vars
  if (timeoutID1) {
    window.clearTimeout(timeoutID1);
  }
  if (timeoutID2) {
    window.clearTimeout(timeoutID2);
  }
  var element = document.getElementById('msg');
  element.innerHTML = msg;
  element.className = 'error';
  timeoutID1 = window.setTimeout(function() {
    if (element.className !== 'error') {
      return;
    }
    element.className = 'error-hide';
    timeoutID2 = window.setTimeout(function() {
      element.innerHTML = '';
      element.className = '';
    }, 500);
  }, 10000);
}

/**
 * Prints the given informational message.
 * @param {string} msg - The information message to print.
 */
function info(msg) {
  var element = document.getElementById('msg');
  element.innerHTML = msg;
  element.className = 'info';
}

/**
 * Converts an address object into a dictionary.
 * @param {PaymentAddress} addr - The address to convert.
 * @return {object} The resulting dictionary.
 */
function toDictionary(addr) {  // eslint-disable-line no-unused-vars
  var dict = {};
  if (addr) {
    dict.country = addr.country;
    dict.region = addr.region;
    dict.city = addr.city;
    dict.dependentLocality = addr.dependentLocality;
    dict.addressLine = addr.addressLine;
    dict.postalCode = addr.postalCode;
    dict.sortingCode = addr.sortingCode;
    dict.languageCode = addr.languageCode;
    dict.organization = addr.organization;
    dict.recipient = addr.recipient;
    dict.phone = addr.phone;
  }
  return dict;
}

/**
 * Called when the payment request is complete.
 * @param {string} message - The human readable message to display.
 * @param {PaymentResponse} respo - The payment response.
 */
function done(message, resp) {  // eslint-disable-line no-unused-vars
  var element = document.getElementById('contents');
  element.innerHTML = message;

  var shippingOption = resp.shippingOption ?
      'shipping option: ' + resp.shippingOption + '
' :
      '';

  var shippingAddress = resp.shippingAddress ?
      'shipping address: ' +
          JSON.stringify(toDictionary(resp.shippingAddress), undefined, 2) +
          '
' :
      '';

  var instrument =
      'instrument:' + JSON.stringify(resp.details, undefined, 2) + '
';

  var method = 'method: ' + resp.methodName + '
';
  var email = resp.payerEmail ? 'email: ' + resp.payerEmail + '
' : '';
  var phone = resp.payerPhone ? 'phone: ' + resp.payerPhone + '
' : '';

  info(email + phone + shippingOption + shippingAddress + method + instrument);
}
<|endoftext|>


<commit_before>'use strict'

const assert = require('assert')
const Driver = require('./../index').Driver
const ExpectedConditions = require('./../index').ExpectedConditions
const ChromeService = require('./../index').ChromeService
const CDP = require('chrome-remote-interface')
const fs = require('fs')
const expect = require('chai').expect
const createMockServer = require('./../fixtures/server')

// impelement some of the selenium form handling tests
// https://github.com/SeleniumHQ/selenium/blob/master/java/client/test/org/openqa/selenium/FormHandlingTest.java
describe('form handling', function () {
  const baseHtml = fs.readFileSync(__dirname + '/../fixtures/static/base.html', 'utf-8')
  const baseUrl = process.env.CHROMINATOR_MOCK_SERVER_BASE_URL
  var driver
  var service

  before(function (done) {
    service = new ChromeService()
    service.start().then((result) => {
      driver = result
      done()
    })
  })

  after(function (done) {
    service.stop().then(() => {
        done()
    })
  })

  it('click on submit input element', function (done) {
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector({selector: '#submitButton'})
      }).then((node) => {
          return node.click()
      }).then(() => {
          return driver.waitForTitle('Result Page')
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  it('click on unclickable element does nothing', function (done) {
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector({selector: 'body'})
      }).then((node) => {
          return node.click()
      }).then(() => {
          return driver.waitForTitle('Form Page')
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  it('click on image button', function (done) {
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector({selector: '#imageButton'})
      }).then((node) => {
          return node.click()
      }).then(() => {
          return driver.waitForTitle('Result Page')
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  it('enter text in text area', function (done) {
      let node
      const title = 'conan the barbarian'
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector('#comment')
      }).then((result) => {
          node = result
          return node.sendKeys(title)
      }).then(() => {
          return node.getProperty('value')
      }).then((value) => {
          expect(value).to.equal(title)
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  it('enter upper case text in text area', function (done) {
      let node
      const title = 'Conan The BarBarian'
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector('#comment')
      }).then((result) => {
          node = result
          return node.sendKeys(title)
      }).then(() => {
          return node.getProperty('value')
      }).then((value) => {
          expect(value).to.equal(title)
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  it('enter form with new line literal', function (done) {
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector('#name')
      }).then((node) => {
          return node.sendKeys('\n')
      }).then(() => {
          return driver.waitForTitle('Result Page')
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  it('enter data in form fields', function (done) {
      let node
      const title = 'conan the barbarian'
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector('#movie')
      }).then((result) => {
          node = result
          return node.getProperty('value')
      }).then((value) => {
          expect(value).to.equal(title)
          // TODO support Node.clear
          return node.setProperty('value', '')
      }).then(() => {
          return node.sendKeys('some text')
      }).then(() => {
          return node.getProperty('value')
      }).then((value) => {
          expect(value).to.equal('some text')
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  // TODO placeholder for file input elements

  it('sendKeys appends text in inputs', function (done) {
      let node
      const title = 'conan the barbarian'
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector('#name')
      }).then((result) => {
          node = result
          return node.sendKeys('conan ')
      }).then(() => {
          return node.sendKeys('the barbarian')
      }).then(() => {
          return node.getProperty('value')
      }).then((value) => {
          expect(value).to.equal(title)
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  xit('sendKeys appends text in inputs with existing value', function (done) {
      let node
      const title = 'conan the barbarian II'
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector('#movie')
      }).then((result) => {
          node = result
          return node.sendKeys(' II')
      }).then(() => {
          return node.getProperty('value')
      }).then((value) => {
          expect(title).to.equal(value)
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  it('append text in text area', function (done) {
      let node
      const title = 'conan the barbarian'
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector('#comment')
      }).then((result) => {
          node = result
          return node.sendKeys('conan ')
      }).then(() => {
          return node.sendKeys('the barbarian')
      }).then(() => {
          return node.getProperty('value')
      }).then((value) => {
          expect(title).to.equal(value)
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  xit('handle form with javascript action', function (done) {
      // TODO support alerts
  })

  const clickOnSubmit = function(selector, done) {
      let node
      const name = 'arnold'
      driver.navigate({url: baseUrl + '/html5_submit_button.html'}).then(() => {
          return driver.querySelector('#name')
      }).then((result) => {
          node = result
          return node.sendKeys(name)
      }).then(() => {
          return driver.querySelector(selector)
      }).then((result) => {
          return result.click()
      }).then(() => {
          return driver.waitForTitle('Result Page')
      }).then(() => {
          return driver.currentUrl()
      }).then((value) => {
          expect(value).to.contain('name='+name)
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  }

  it('click on submit button', function (done) {
      clickOnSubmit('#internal_explicit_submit', done)
  })
})
<commit_msg>external explicit submit is broken<commit_after>'use strict'

const assert = require('assert')
const Driver = require('./../index').Driver
const ExpectedConditions = require('./../index').ExpectedConditions
const ChromeService = require('./../index').ChromeService
const CDP = require('chrome-remote-interface')
const fs = require('fs')
const expect = require('chai').expect
const createMockServer = require('./../fixtures/server')

// impelement some of the selenium form handling tests
// https://github.com/SeleniumHQ/selenium/blob/master/java/client/test/org/openqa/selenium/FormHandlingTest.java
describe('form handling', function () {
  const baseHtml = fs.readFileSync(__dirname + '/../fixtures/static/base.html', 'utf-8')
  const baseUrl = process.env.CHROMINATOR_MOCK_SERVER_BASE_URL
  var driver
  var service

  before(function (done) {
    service = new ChromeService()
    service.start().then((result) => {
      driver = result
      done()
    })
  })

  after(function (done) {
    service.stop().then(() => {
        done()
    })
  })

  it('click on submit input element', function (done) {
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector({selector: '#submitButton'})
      }).then((node) => {
          return node.click()
      }).then(() => {
          return driver.waitForTitle('Result Page')
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  it('click on unclickable element does nothing', function (done) {
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector({selector: 'body'})
      }).then((node) => {
          return node.click()
      }).then(() => {
          return driver.waitForTitle('Form Page')
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  it('click on image button', function (done) {
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector({selector: '#imageButton'})
      }).then((node) => {
          return node.click()
      }).then(() => {
          return driver.waitForTitle('Result Page')
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  it('enter text in text area', function (done) {
      let node
      const title = 'conan the barbarian'
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector('#comment')
      }).then((result) => {
          node = result
          return node.sendKeys(title)
      }).then(() => {
          return node.getProperty('value')
      }).then((value) => {
          expect(value).to.equal(title)
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  it('enter upper case text in text area', function (done) {
      let node
      const title = 'Conan The BarBarian'
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector('#comment')
      }).then((result) => {
          node = result
          return node.sendKeys(title)
      }).then(() => {
          return node.getProperty('value')
      }).then((value) => {
          expect(value).to.equal(title)
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  it('enter form with new line literal', function (done) {
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector('#name')
      }).then((node) => {
          return node.sendKeys('\n')
      }).then(() => {
          return driver.waitForTitle('Result Page')
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  it('enter data in form fields', function (done) {
      let node
      const title = 'conan the barbarian'
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector('#movie')
      }).then((result) => {
          node = result
          return node.getProperty('value')
      }).then((value) => {
          expect(value).to.equal(title)
          // TODO support Node.clear
          return node.setProperty('value', '')
      }).then(() => {
          return node.sendKeys('some text')
      }).then(() => {
          return node.getProperty('value')
      }).then((value) => {
          expect(value).to.equal('some text')
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  // TODO placeholder for file input elements

  it('sendKeys appends text in inputs', function (done) {
      let node
      const title = 'conan the barbarian'
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector('#name')
      }).then((result) => {
          node = result
          return node.sendKeys('conan ')
      }).then(() => {
          return node.sendKeys('the barbarian')
      }).then(() => {
          return node.getProperty('value')
      }).then((value) => {
          expect(value).to.equal(title)
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  xit('sendKeys appends text in inputs with existing value', function (done) {
      let node
      const title = 'conan the barbarian II'
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector('#movie')
      }).then((result) => {
          node = result
          return node.sendKeys(' II')
      }).then(() => {
          return node.getProperty('value')
      }).then((value) => {
          expect(title).to.equal(value)
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  it('append text in text area', function (done) {
      let node
      const title = 'conan the barbarian'
      driver.navigate({url: baseUrl + '/form.html'}).then(() => {
          return driver.querySelector('#comment')
      }).then((result) => {
          node = result
          return node.sendKeys('conan ')
      }).then(() => {
          return node.sendKeys('the barbarian')
      }).then(() => {
          return node.getProperty('value')
      }).then((value) => {
          expect(title).to.equal(value)
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  })

  xit('handle form with javascript action', function (done) {
      // TODO support alerts
  })

  const clickOnSubmit = function(selector, done) {
      let node
      const name = 'arnold'
      driver.navigate({url: baseUrl + '/html5_submit_button.html'}).then(() => {
          return driver.querySelector('#name')
      }).then((result) => {
          node = result
          return node.sendKeys(name)
      }).then(() => {
          return driver.querySelector(selector)
      }).then((result) => {
          return result.click()
      }).then(() => {
          return driver.waitForTitle('Result Page')
      }).then(() => {
          return driver.currentUrl()
      }).then((value) => {
          expect(value).to.contain('name='+name)
      }).then(() => {
          done()
      }).catch((err) => {
          done(err)
      })
  }

  it('click on submit button', function (done) {
      clickOnSubmit('#internal_explicit_submit', done)
  })

  xit('click on external explicit submit button', function (done) {
      clickOnSubmit('#external_explicit_submit', done)
  })
})
<|endoftext|>


<commit_before>
export default function removeChildNode(parent, child) {
  if (!parent.hasChild(child)) {
    return {};
  }

  let rootNode = this.rootNode.clone();
  let changeParent = rootNode.findNodeById(parent.id);
  let changeChild = rootNode.findNodeById(child.id);

  changeParent.removeChild(changeChild);

  return {
    rootNode,
    activeNodeId: this.activeNodeId === child.id ? parent.id : this.activeNodeId
  };
}
<commit_msg>fix active node removal bug<commit_after>
export default function removeChildNode(parent, child) {
  if (!parent.hasChild(child)) {
    return {};
  }

  let rootNode = this.rootNode.clone();
  let activeNodeId = this.activeNodeId;
  let changeParent = rootNode.findNodeById(parent.id);
  let changeChild = rootNode.findNodeById(child.id);

  changeParent.removeChild(changeChild);

  // change active node with parent node if active node is one of deletions
  if (parent.findNodeById(activeNodeId)) {
    activeNodeId = parent.id;
  }

  return {
    rootNode,
    activeNodeId
  };
}
<|endoftext|>