<commit_before>var fs = require('fs');
var join = require('path').join;
var assert = require('assert');
var LineTransform = require('..').LineTransform;
var LineFilter = require('..').LineFilter;

function getStream(argument) {
    return fs.createReadStream(join(__dirname, 'input.txt'));
}

describe('LineFilter', function () {

    describe('without any include and exclude filter', function () {
        var lines = [], transform = new LineTransform(), filter = new LineFilter();

        getStream().pipe(transform).pipe(filter);

        it('shoould generate \'data\' events for each line of text and \'end\' event', function (done) {
            extractLinesOfText(lines, filter, done);
        });

        it('should generate 63 lines', function () {
            assert.equal(lines.length, 63);
            assert.equal(lines[0], 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.');
            assert.equal(lines[62], 'Quisque finibus eros nec faucibus laoreet.');
        });
    });

    describe('with single include and no exclude', function () {
        var lines = [], transform = new LineTransform(),
            filter = new LineFilter({ include: /P/});

        getStream().pipe(transform).pipe(filter);

        it('shoould generate \'data\' events for each line of text and \'end\' event', function (done) {
            extractLinesOfText(lines, filter, done);
        });

        it('should return only lines starting with \'P\'', function () {
            assert.equal(lines.length, 11);
            lines.forEach(function (line) {
                assert.equal(line.indexOf('P'), 0);
            });
        });
    });

    describe('with single exclude and no include', function () {
        var lines = [], transform = new LineTransform(),
            filter = new LineFilter({ exclude: /P/});

        getStream().pipe(transform).pipe(filter);

        it('shoould generate \'data\' events for each line of text and \'end\' event', function (done) {
            extractLinesOfText(lines, filter, done);
        });

        it('should return only lines not starting with \'P\'', function () {
            lines.forEach(function (line) {
                assert.notEqual(line.indexOf('P'), 0);
            });
        });
    });

});

function extractLinesOfText(lines, stream, cb) {
    var hasntEnded = true;

    stream.on('data', function (line) {
        assert.notEqual(line, null);
        assert(hasntEnded);
        lines.push(line);
    });

    stream.on('end', function () {
        hasntEnded = false;
        cb();
    });
}

// var LineTransform = require('./lib/transformer');
// var fs = require('fs');
//
// var stream = fs.createReadStream('.\\test\\input.txt');
// var transform = new LineTransform();
//
// stream.pipe(transform);
//
// transform.on('data', function(chunk) {
//   console.log('got %d bytes of data', chunk.length, chunk);
//   transform.pause();
//   console.log('there will be no more data for 1 second');
//   setTimeout(function() {
//     console.log('now data will start flowing again');
//     transform.resume();
//   }, 100);
// })
<commit_msg>Updated unit tests<commit_after>var fs = require('fs');
var join = require('path').join;
var assert = require('assert');
var LineTransform = require('..').LineTransform;
var LineFilter = require('..').LineFilter;

function getStream(argument) {
    return fs.createReadStream(join(__dirname, 'input.txt'));
}

describe('LineFilter', function () {

    describe('without any include and exclude filter', function () {
        var lines = [], transform = new LineTransform(), filter = new LineFilter();

        getStream().pipe(transform).pipe(filter);

        it('shoould generate \'data\' events for each line of text and \'end\' event', function (done) {
            extractLinesOfText(lines, filter, done);
        });

        it('should generate 63 lines', function () {
            assert.equal(lines.length, 63);
            assert.equal(lines[0], 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.');
            assert.equal(lines[62], 'Quisque finibus eros nec faucibus laoreet.');
        });
    });

    describe('with single include and no exclude', function () {
        var lines = [], transform = new LineTransform(),
            filter = new LineFilter({ include: /P/});

        getStream().pipe(transform).pipe(filter);

        it('shoould generate \'data\' events for each line of text and \'end\' event', function (done) {
            extractLinesOfText(lines, filter, done);
        });

        it('should return only lines starting with \'P\'', function () {
            assert.equal(lines.length, 11);
            lines.forEach(function (line) {
                assert.equal(line.indexOf('P'), 0);
            });
        });
    });

    describe('with single exclude and no include', function () {
        var lines = [], transform = new LineTransform(),
            filter = new LineFilter({ exclude: /P/});

        getStream().pipe(transform).pipe(filter);

        it('shoould generate \'data\' events for each line of text and \'end\' event', function (done) {
            extractLinesOfText(lines, filter, done);
        });

        it('should return only lines not starting with \'P\'', function () {
            assert.equal(lines.length, 52);
            lines.forEach(function (line) {
                assert.notEqual(line.indexOf('P'), 0);
            });
        });
    });

    describe('with several include and no exclude', function () {
        var lines = [], transform = new LineTransform(),
            filter = new LineFilter({ include: [/P/, /Sed/] });

        getStream().pipe(transform).pipe(filter);

        it('shoould generate \'data\' events for each line of text and \'end\' event', function (done) {
            extractLinesOfText(lines, filter, done);
        });

        it('should return lines starting with \'P\' and \'Sed\'', function () {
            assert.equal(lines.length, 16);
            lines.forEach(function (line) {
                assert(line.indexOf('P') === 0 || line.indexOf('Sed') === 0);
            });
        });
    });

    describe('with several excludes and no include', function () {
        var lines = [], transform = new LineTransform(),
            filter = new LineFilter({ exclude: [/P/ , /Sed/]});

        getStream().pipe(transform).pipe(filter);

        it('shoould generate \'data\' events for each line of text and \'end\' event', function (done) {
            extractLinesOfText(lines, filter, done);
        });

        it('should return only lines not starting with \'P\' nor \'Sed\'', function () {
            assert.equal(lines.length, 47);
            lines.forEach(function (line) {
                assert(line.indexOf('P') !== 0 && line.indexOf('Sed') !== 0);
            });
        });
    });

    describe('with some excludes and includes', function () {
        var lines = [], transform = new LineTransform(),
            filter = new LineFilter({ include: [/P/ , /Sed/], exclude: [/s\.$/] });

        getStream().pipe(transform).pipe(filter);

        it('shoould generate \'data\' events for each line of text and \'end\' event', function (done) {
            extractLinesOfText(lines, filter, done);
        });

        it('should return only lines starting with \'P\' nor \'Sed\' and not ending with \'s.\'', function () {
            assert.equal(lines.length, 11);
            lines.forEach(function (line) {
                assert(line.indexOf('P') === 0 || line.indexOf('Sed') === 0);
                assert.equal(line.indexOf('s.', line.length - 2), -1);
            });
        });
    });

});

function extractLinesOfText(lines, stream, cb) {
    var hasntEnded = true;

    stream.on('data', function (line) {
        assert.notEqual(line, null);
        assert(hasntEnded);
        lines.push(line);
    });

    stream.on('end', function () {
        hasntEnded = false;
        cb();
    });
}

// var LineTransform = require('./lib/transformer');
// var fs = require('fs');
//
// var stream = fs.createReadStream('.\\test\\input.txt');
// var transform = new LineTransform();
//
// stream.pipe(transform);
//
// transform.on('data', function(chunk) {
//   console.log('got %d bytes of data', chunk.length, chunk);
//   transform.pause();
//   console.log('there will be no more data for 1 second');
//   setTimeout(function() {
//     console.log('now data will start flowing again');
//     transform.resume();
//   }, 100);
// })
<|endoftext|>


<commit_before>// Get Canvas
var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  width = 512,
  height = 480;

canvas.width = width;
canvas.height = height;

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = "http://placekitten.com/512/480";
// Hero Image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
  heroReady = true;
};
heroImage.src = "http://placekitten.com/32/32";

// Monster Image
var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function () {
  monsterReady = true;
};
monsterImage.src = "http://placekitten.com/30/32";

// Game objects
var hero = {
  speed: 256,
  x: 0,
  y: 0
};

var monster = {
  x: 0,
  y: 0
};
var monstersCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
  keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
  delete keysDown[e.keyCode];
}, false);

var reset = function () {
  hero.x = canvas.width / 2;
  hero.y = canvas.height / 2;

  monster.x = 32 + (Math.random() * (canvas.width - 64));
  monster.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
  if (38 in keysDown) {
    hero.y -= hero.speed * modifier;
  }
  if (40 in keysDown) {
    hero.y += hero.speed * modifier;
  }
  if (37 in keysDown) {
    hero.x -= hero.speed * modifier;
  }
  if (39 in keysDown) {
    hero.x += hero.speed * modifier;
  }

  // Collision
  if (hero.x <= (monster.x + 32) && monster.x <= (hero.x + 32) && hero.y <= (monster.y + 32) && monster.y <= (hero.y + 32)) {
    ++monstersCaught;
    reset();
  }
};

// Render
var render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }

  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }

  if (monsterReady) {
    ctx.drawImage(monsterImage, monster.x, monster.y);
  }

  ctx.fillStyle = "rgb(250, 250, 250)";
  ctx.font = "24px Helvetica";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText("Monsters caught : " + monstersCaught, 32, 32);
};

var main = function () {
  var now = Date.now();
  var delta = now - then;

  update(delta / 1000);
  render();

  then = now;

  requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

var then = Date.now();
reset();
main();
<commit_msg>Update canvas.js<commit_after>// Get Canvas
var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  width = 512,
  height = 480;

canvas.width = width;
canvas.height = height;

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = "http://placepuppy.it/512/480";
// Hero Image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
  heroReady = true;
};
heroImage.src = "http://placepuppy.it/32/32";

// Monster Image
var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function () {
  monsterReady = true;
};
monsterImage.src = "http://placepuppy.it/30/32";

// Game objects
var hero = {
  speed: 256,
  x: 0,
  y: 0
};

var monster = {
  x: 0,
  y: 0
};
var monstersCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
  keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
  delete keysDown[e.keyCode];
}, false);

var reset = function () {
  hero.x = canvas.width / 2;
  hero.y = canvas.height / 2;

  monster.x = 32 + (Math.random() * (canvas.width - 64));
  monster.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
  if (38 in keysDown) {
    hero.y -= hero.speed * modifier;
  }
  if (40 in keysDown) {
    hero.y += hero.speed * modifier;
  }
  if (37 in keysDown) {
    hero.x -= hero.speed * modifier;
  }
  if (39 in keysDown) {
    hero.x += hero.speed * modifier;
  }

  // Collision
  if (hero.x <= (monster.x + 32) && monster.x <= (hero.x + 32) && hero.y <= (monster.y + 32) && monster.y <= (hero.y + 32)) {
    ++monstersCaught;
    reset();
  }
};

// Render
var render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }

  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }

  if (monsterReady) {
    ctx.drawImage(monsterImage, monster.x, monster.y);
  }

  ctx.fillStyle = "rgb(250, 250, 250)";
  ctx.font = "24px Helvetica";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText("Monsters caught : " + monstersCaught, 32, 32);
};

var main = function () {
  var now = Date.now();
  var delta = now - then;

  update(delta / 1000);
  render();

  then = now;

  requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

var then = Date.now();
reset();
main();
<|endoftext|>


<commit_before>
global.process.removeAllListeners();

global.process.on( "uncaughtException", function( err ) {
// do nothing if window was fully initialized
if ( window.initialized ) { return; }

// show the app window and dev tools while being in debug mode
if ( DEBUG ) {
	try {
		var nwWindow = require( "nw.gui" ).Window.get();
		nwWindow.show();
		nwWindow.showDevTools();
		return;
	} catch( e ) {}
}

// write to stderr and kill the process with error code 1
global.process.stderr.write([
	"Could not initialize application window",
	require( "util" ).inspect( err ),
	""
].join( "\n" ) );
global.process.exit( 1 );
});

require( "styles/app" );
require( "./app" );
<commit_msg>Fix indentation in main.js<commit_after>
global.process.removeAllListeners();

global.process.on( "uncaughtException", function( err ) {
	// do nothing if window was fully initialized
	if ( window.initialized ) { return; }

	// show the app window and dev tools while being in debug mode
	if ( DEBUG ) {
		try {
			var nwWindow = require( "nw.gui" ).Window.get();
			nwWindow.show();
			nwWindow.showDevTools();
			return;
		} catch( e ) {}
	}

	// write to stderr and kill the process with error code 1
	global.process.stderr.write([
		"Could not initialize application window",
		require( "util" ).inspect( err ),
		""
	].join( "\n" ) );
	global.process.exit( 1 );
});

require( "styles/app" );
require( "./app" );
<|endoftext|>


<commit_before>var languageMap = {
    "zh": "zh-CN",
    "cn": "zh-CN",
    "en": "en-US",
    "us": "en-US"
};
var source = {
    "zh-CN": {
        name: '名称',
        password: "密码",
        is: "是",
        or: "或",
        incorrect: "错误的",
        ".": '。',
        "?": "？",
        "!": "！",
        ":": "：",
        "": {
            "是……的": [/是(.+?)的/, "$1"]
        }
    },
    "en-US": {

    },
    "am": {},
    "ar": {},
    "bg": {},
    "bn": {},
    "ca": {},
    "cs": {},
    "da": {},
    "de": {},
    "el": {},
    "en-GB": {},
    "es-419": {},
    "es": {},
    "et": {},
    "fa": {},
    "fake-bidi": {},
    "fi": {},
    "fil": {},
    "fr": {},
    "gu": {},
    "he": {},
    "hi": {},
    "hr": {},
    "hu": {},
    "id": {},
    "it": {},
    "ja": {},
    "kn": {},
    "ko": {},
    "lt": {},
    "lv": {},
    "ml": {},
    "mr": {},
    "ms": {},
    "nb": {},
    "nl": {},
    "pl": {},
    "pt-BR": {},
    "pt-PT": {},
    "ro": {},
    "ru": {},
    "sk": {},
    "sl": {},
    "sr": {},
    "sv": {},
    "sw": {},
    "ta": {},
    "te": {},
    "th": {},
    "tr": {},
    "uk": {},
    "vi": {},
    "zh-TW": {},
    "zh-HK": {},
};
var navagatorLanguage = navigator.language ||/** ie~-10 */navigator.userLanguage || navigator.systemLanguage;

var isAdjective = function () {

}
function i18n(message, _source = source) {
    var _search = _source[navagatorLanguage] || source[navagatorLanguage];
    var checkSpell = _search[""];
    var translated = message.replace(/([\s\w]*)([^\s\w]|^)/g, function (match, message, quote) {
        return message.toLowerCase().split(/\s+/).map(a => _search[a]).join("") + (_search[quote] || qoute || "");
    });
    for (var k in checkSpell) {
        var [reg, rep] = checkSpell[k];
        translated = translated.replace(reg, rep);
    }
    return translated;
};
i18n.new = i18n.local = function (_source) {
    var localSource = extend({}, source);
    if (arguments.length > 1) {
        Object.keys(source).forEach(function (language, cx) {
            var Base = function () {
            };
            Base.prototype = source[language];
            var _base = new Base;
            extend(_base, arguments[cx]);
            localSource[language] = _base;
        });
    } else {
        for (let k in _source) {
            let language = languageMap[k] || k;
            let Base = function () {
            };
            if (language in source) {
                Base.prototype = source[language];
                var _base = new Base;
                extend(_base, _source[k]);
                localSource[language] = _base;
            } else {
                throw new Error(`不支持的语言类型${k}`);
            }
        }
    };
    return function (a, source = localSource) {
        return i18n(a, source);
    }
};
i18n.setLanguage = function (language) {
    language = languageMap[language] || language;
    if (language in source) {
        return navagatorLanguage = language;
    }
    throw new Error(`不支持的语言类型${k}`);
};<commit_msg>i18n支持templateString语法传参<commit_after>var languageMap = {
    "zh": "zh-CN",
    "cn": "zh-CN",
    "en": "en-US",
    "us": "en-US"
};
var source = {
    "zh-CN": {
        name: '名称',
        password: "密码",
        is: "是",
        or: "或",
        incorrect: "错误的",
        ".": '。',
        "?": "？",
        "!": "！",
        ":": "：",
        "": {
            "是……的": [/是(.+?)的/, "$1"]
        }
    },
    "en-US": {

    },
    "am": {},
    "ar": {},
    "bg": {},
    "bn": {},
    "ca": {},
    "cs": {},
    "da": {},
    "de": {},
    "el": {},
    "en-GB": {},
    "es-419": {},
    "es": {},
    "et": {},
    "fa": {},
    "fake-bidi": {},
    "fi": {},
    "fil": {},
    "fr": {},
    "gu": {},
    "he": {},
    "hi": {},
    "hr": {},
    "hu": {},
    "id": {},
    "it": {},
    "ja": {},
    "kn": {},
    "ko": {},
    "lt": {},
    "lv": {},
    "ml": {},
    "mr": {},
    "ms": {},
    "nb": {},
    "nl": {},
    "pl": {},
    "pt-BR": {},
    "pt-PT": {},
    "ro": {},
    "ru": {},
    "sk": {},
    "sl": {},
    "sr": {},
    "sv": {},
    "sw": {},
    "ta": {},
    "te": {},
    "th": {},
    "tr": {},
    "uk": {},
    "vi": {},
    "zh-TW": {},
    "zh-HK": {},
};
var navagatorLanguage = navigator.language ||/** ie~-10 */navigator.userLanguage || navigator.systemLanguage;

var isAdjective = function () {

}
function i18n(message, _source = source) {
    var _search = _source[navagatorLanguage] || source[navagatorLanguage];
    var checkSpell = _search[""];
    if (isArray(message)) {
        var args = arguments;
        if (message.length === 1) message = message[0];
        else return [].map.call(message, function (msg, cx) {
            return (cx > 0 ? args[cx] : "") + i18n(msg);
        }).join("");
    }
    var translated = message.replace(/([\s\w]*)([^\s\w]|^)/g, function (match, message, quote) {
        return (message && message.toLowerCase().split(/\s+/).map(a => _search[a]).join("")) + (quote && _search[quote] || quote || "");
    });
    for (var k in checkSpell) {
        var [reg, rep] = checkSpell[k];
        translated = translated.replace(reg, rep);
    }
    return translated;
};
i18n.new = i18n.local = function (_source) {
    var localSource = extend({}, source);
    if (arguments.length > 1) {
        Object.keys(source).forEach(function (language, cx) {
            var Base = function () {
            };
            Base.prototype = source[language];
            var _base = new Base;
            extend(_base, arguments[cx]);
            localSource[language] = _base;
        });
    } else {
        for (let k in _source) {
            let language = languageMap[k] || k;
            let Base = function () {
            };
            if (language in source) {
                Base.prototype = source[language];
                var _base = new Base;
                extend(_base, _source[k]);
                localSource[language] = _base;
            } else {
                throw new Error(`不支持的语言类型${k}`);
            }
        }
    };
    return function (a, source = localSource) {
        return i18n(a, source);
    }
};
i18n.loadSource = function (_source) {
    if (arguments.length > 1) {
        Object.keys(source).forEach(function (language, cx) {
            extend(source[language], arguments[cx]);
        });
    } else {
        for (let k in _source) {
            let language = languageMap[k] || k;
            if (language in source) {
                extend(source[language], _source[k]);
            } else {
                throw new Error(`不支持的语言类型${k}`);
            }
        }
    }
    return i18n;
};
i18n.setLanguage = function (language) {
    language = languageMap[language] || language;
    if (language in source) {
        navagatorLanguage = language;
    } else {
        throw new Error(`不支持的语言类型${k}`);
    }
    return i18n;
};<|endoftext|>


<commit_before>// Get Canvas
var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  width = 512,
  height = 480;

canvas.width = 512;
canvas.height = 480;

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = "http://placekitten.com/512/480";
// Hero Image
var heroReady = false;
var heroImage = new Image();
heroReady.onload = function () {
  heroReady = true;
};
heroImage.src = "http://placekitten.com/32/32";

// Monster Image
var monsterReady = false;
var monsterImage = new Image();
monsterReady.onload = function () {
  monsterReady = true;
};
monsterImage.src = "http://placekitten.com/30/32";

// Game objects
var hero = {
  speed: 256,
  x: 0,
  y: 0
};

var monster = {
  x: 0,
  y: 0
};
var monstersCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
  keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
  delete keysDown[e.keyCode];
}, false);

var reset = function () {
  hero.x = canvas.width / 2;
  hero.y = canvas.height / 2;

  monster.x = 32 + (Math.random() * (canvas.width - 64));
  monster.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
  if (38 in keysDown) {
    hero.y -= hero.speed * modifier;
    ++monstersCaught;
  }
  if (40 in keysDown) {
    hero.y += hero.speed * modifier;
    ++monstersCaught;
  }
  if (37 in keysDown) {
    hero.x -= hero.speed * modifier;
    ++monstersCaught;
  }
  if (39 in keysDown) {
    hero.x += hero.speed * modifier;
    ++monstersCaught;
  }

  // Collision
  if (hero.x <= (monster.x + 32) && monster.x <= (hero.x + 32) && hero.y <= (monster.y + 32) && monster.y <= (hero.y + 32)) {
    ++monstersCaught;
    reset();
  }
};

// Render
var render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }

  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }

  if (monsterReady) {
    ctx.drawImage(monsterImage, monster.x, monster.y);
  }

  ctx.fillStyle = "rgb(250, 250, 250)";
  ctx.font = "24px Helvetica";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText("Monsters caught : " + monstersCaught, 32, 32);
};

var main = function () {
  var now = Date.now();
  var delta = now - then;

  update(delta / 1000);
  render();

  then = now;

  requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

var then = Date.now();
reset();
main();
<commit_msg>Update canvas.js<commit_after>// Get Canvas
var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  width = 512,
  height = 480;

canvas.width = width;
canvas.height = height;

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = "http://placekitten.com/512/480";
// Hero Image
var heroReady = false;
var heroImage = new Image();
heroReady.onload = function () {
  heroReady = true;
};
heroImage.src = "http://placekitten.com/32/32";

// Monster Image
var monsterReady = false;
var monsterImage = new Image();
monsterReady.onload = function () {
  monsterReady = true;
};
monsterImage.src = "http://placekitten.com/30/32";

// Game objects
var hero = {
  speed: 256,
  x: 0,
  y: 0
};

var monster = {
  x: 0,
  y: 0
};
var monstersCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
  keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
  delete keysDown[e.keyCode];
}, false);

var reset = function () {
  hero.x = canvas.width / 2;
  hero.y = canvas.height / 2;

  monster.x = canvas.width / 2;
  //32 + (Math.random() * (canvas.width - 64));
  monster.y = canvas.height / 2;
  //32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
  if (38 in keysDown) {
    hero.y -= hero.speed * modifier;
    ++monstersCaught;
  }
  if (40 in keysDown) {
    hero.y += hero.speed * modifier;
    ++monstersCaught;
  }
  if (37 in keysDown) {
    hero.x -= hero.speed * modifier;
    ++monstersCaught;
  }
  if (39 in keysDown) {
    hero.x += hero.speed * modifier;
    ++monstersCaught;
  }

  // Collision
  if (hero.x <= (monster.x + 32) && monster.x <= (hero.x + 32) && hero.y <= (monster.y + 32) && monster.y <= (hero.y + 32)) {
    ++monstersCaught;
    reset();
  }
};

// Render
var render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }

  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }

  if (monsterReady) {
    ctx.drawImage(monsterImage, monster.x, monster.y);
  }

  ctx.fillStyle = "rgb(250, 250, 250)";
  ctx.font = "24px Helvetica";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText("Monsters caught : " + monstersCaught, 32, 32);
};

var main = function () {
  var now = Date.now();
  var delta = now - then;

  update(delta / 1000);
  render();

  then = now;

  requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

var then = Date.now();
reset();
main();
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var fs = require('fs-extra');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;

describe('ngbp-module:module', function () {

  var runGen;

  beforeEach(function () {
    runGen = helpers
      .run(path.join(__dirname, '../module'))
      .inDir(path.join(__dirname, './temp'))
      .withArguments(['newModule'])
      .withPrompt({
        modules: ['templates', 'uiRouter'],
        scaffold: ['controllers']
      })
      .withGenerators([[helpers.createDummyGenerator(), 'mocha:app']]);
  });

  it('creates files', function (done) {
    runGen.withOptions({ 'skip-install': true })
      .on('ready', function () {
        fs.ensureDirSync('./test/temp/src/app');
        fs.writeFileSync('./test/temp/src/app/app.js', "angular.module('test', ['existingModule'])");
      })
      .on('end', function () {
        assert.file([
          'test/temp/src/app/app.js',
          'test/temp/src/app/newModule/newModule.module.js'
        ]);
        done();
      });
  });

  it('updates app.js', function (done) {
    runGen.withOptions({ 'skip-install': true })
      .on('ready', function () {
        fs.ensureDirSync('./test/temp/src/app');
        fs.writeFileSync('./test/temp/src/app/app.js', "angular.module('test', ['existingModule'])");
      })
      .on('end', function () {
        assert.fileContent('test/temp/src/app/app.js', "angular.module('test', [\n    'existingModule',\n    'newModule'\n])");
        done();
      });
  });

  it('does not update app.js if expected syntax cannot be found', function (done) {
    runGen.withOptions({ 'skip-install': true })
      .on('ready', function () {
        fs.ensureDirSync('./test/temp/src/app');
        fs.writeFileSync('./test/temp/src/app/app.js', "angular.module('test')");
      })
      .on('end', function () {
        assert.fileContent('test/temp/src/app/app.js', "angular.module('test')");
        done();
      });
  });

});
<commit_msg>Updating tests to cover scaffold prompt options<commit_after>'use strict';

var path = require('path');
var fs = require('fs-extra');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;

describe('ngbp-module:module', function () {

  var runGen;

  beforeEach(function () {
    runGen = helpers
      .run(path.join(__dirname, '../module'))
      .inDir(path.join(__dirname, './temp'))
      .withArguments(['newModule'])
      .withPrompt({
        modules: ['templates', 'uiRouter'],
        scaffold: ['controllers', 'directives', 'filters', 'services', 'assets', 'styles', 'unit', 'e2e']
      })
      .withGenerators([[helpers.createDummyGenerator(), 'mocha:app']]);
  });

  it('creates files', function (done) {
    runGen.withOptions({ 'skip-install': true })
      .on('ready', function () {
        fs.ensureDirSync('./test/temp/src/app');
        fs.writeFileSync('./test/temp/src/app/app.js', "angular.module('test', ['existingModule'])");
      })
      .on('end', function () {
        assert.file([
          'test/temp/src/app/app.js',
          'test/temp/src/app/newModule/newModule.module.js',
          'test/temp/src/app/newModule/controllers/newModule.controllers.js',
          'test/temp/src/app/newModule/directives/newModule.directives.js',
          'test/temp/src/app/newModule/filters/newModule.filters.js',
          'test/temp/src/app/newModule/services/newModule.services.js',
          'test/temp/src/app/newModule/unit/newModule.spec.js',
          'test/temp/src/app/newModule/e2e/newModule.e2e.js'
        ]);
        done();
      });
  });

  it('updates app.js', function (done) {
    runGen.withOptions({ 'skip-install': true })
      .on('ready', function () {
        fs.ensureDirSync('./test/temp/src/app');
        fs.writeFileSync('./test/temp/src/app/app.js', "angular.module('test', ['existingModule'])");
      })
      .on('end', function () {
        assert.fileContent('test/temp/src/app/app.js', "angular.module('test', [\n    'existingModule',\n    'newModule'\n])");
        done();
      });
  });

  it('does not update app.js if expected syntax cannot be found', function (done) {
    runGen.withOptions({ 'skip-install': true })
      .on('ready', function () {
        fs.ensureDirSync('./test/temp/src/app');
        fs.writeFileSync('./test/temp/src/app/app.js', "angular.module('test')");
      })
      .on('end', function () {
        assert.fileContent('test/temp/src/app/app.js', "angular.module('test')");
        done();
      });
  });

});
<|endoftext|>


<commit_before>'use strict';

var $ = require('dominus');
var moment = require('moment');
var raf = require('raf');
var taunus = require('taunus');
var flexarea = require('flexarea');
var ponymark = require('ponymark');
var rome = require('rome/src/rome.standalone');
var textService = require('../../../../services/text');

module.exports = function () {
  var title = $('.ac-title');
  var slug = $('.ac-slug');
  var texts = $('.ac-text');
  var introduction = $('.ac-introduction');
  var body = $('.ac-body');
  var tags = $('.ac-tags');
  var schedule = $('.ac-schedule');
  var publication = $('.ac-publication');
  var preview = $.findOne('.ac-preview');
  var previewTitle = $('.ac-preview-title');
  var previewTags = $.findOne('.ac-preview-tags');
  var discardButton = $('.ac-discard');
  var saveButton = $('.ac-save');
  var status = $('.ac-status');
  var boundSlug = true;

  texts.forEach(function (text) {
    ponymark({ buttons: text, input: text, preview: preview });
  });
  texts.find('.pmk-input').forEach(flexarea);
  rome(publication[0], {
    appendTo: 'parent',
    initialValue: moment().weekday(7)
  });
  tags.on('keypress keydown paste', raf.bind(null, updateTags));
  title.on('keypress keydown paste', raf.bind(null, bindTitle));
  slug.on('keypress keydown', unbindSlug);
  discardButton.on('click', discard);
  saveButton.on('click', save);
  status.on('change', updateSaveButton);
  schedule.on('change', updateSaveButton);

  function updateSaveButton () {
    var scheduled = schedule.value();
    if (scheduled) {
      saveButton.text('Schedule');
      saveButton.attr('aria-label', 'Schedule this article for publication');
      return;
    }
    var selection = status.where(':checked').text();
    if (selection === 'draft') {
      saveButton.text('Save Draft');
      saveButton.attr('aria-label', 'You can access your drafts at any time');
    } else if (selection === 'publish') {
      saveButton.text('Publish');
      saveButton.attr('aria-label', 'Make the content immediately accessible!');
    }
  }

  function bindTitle () {
    updatePreviewTitle();

    if (boundSlug) {
      updateSlug();
    }
  }
  function unbindSlug () {
    boundSlug = false;
  }

  function updateSlug () {
    slug.value(textService.slug(title.value()));
  }

  function updatePreviewTitle () {
    previewTitle.text(title.value());
  }

  function updateTags () {
    var individualTags = textService.splitTags(tags.value());
    var model = {
      tags: individualTags
    };
    taunus.partial(previewTags, 'partials/tags', model);
  }

  function getRequestBody () {
    var individualTags = textService.splitTags(tags.value());
    var scheduled = schedule.value();
    var status = $('.ac-status:checked').value();
    var body = {
      title: title.value(),
      slug: slug.value(),
      introduction: introduction.value(),
      body: body.value(),
      tags: individualTags,
      status: status
    };
    if (scheduled) {
      body.publication = publication.value();
    }
    return body;
  }

  function save () {
    var body = getRequestBody();
    send(body);
  }

  function send (body) {
    console.log('I should put', body);
  }

  function discard () {
    console.log('I should discard the draft and redirect. Or just redirect if not stored in server');
  }
};
<commit_msg>Update compose.js<commit_after>'use strict';

var $ = require('dominus');
var moment = require('moment');
var raf = require('raf');
var taunus = require('taunus');
var flexarea = require('flexarea');
var ponymark = require('ponymark');
var rome = require('rome/src/rome.standalone');
var textService = require('../../../../services/text');

module.exports = function () {
  var title = $('.ac-title');
  var slug = $('.ac-slug');
  var texts = $('.ac-text');
  var introduction = $('.ac-introduction');
  var body = $('.ac-body');
  var tags = $('.ac-tags');
  var schedule = $('.ac-schedule');
  var publication = $('.ac-publication');
  var preview = $.findOne('.ac-preview');
  var previewTitle = $('.ac-preview-title');
  var previewTags = $.findOne('.ac-preview-tags');
  var discardButton = $('.ac-discard');
  var saveButton = $('.ac-save');
  var status = $('.ac-status');
  var boundSlug = true;

  texts.forEach(function (text) {
    ponymark({ buttons: text, input: text, preview: preview });
  });
  texts.find('.pmk-input').forEach(flexarea);
  rome(publication[0], {
    appendTo: 'parent',
    initialValue: moment().weekday(7)
  });
  tags.on('keypress keydown paste', raf.bind(null, updateTags));
  title.on('keypress keydown paste', raf.bind(null, bindTitle));
  slug.on('keypress keydown', unbindSlug);
  discardButton.on('click', discard);
  saveButton.on('click', save);
  status.on('change', updateSaveButton);
  schedule.on('change', updateSaveButton);

  function updateSaveButton () {
    var scheduled = schedule.value();
    if (scheduled) {
      saveButton.text('Schedule');
      saveButton.attr('aria-label', 'Schedule this article for publication');
      return;
    }
    var state = status.where(':checked').text();
    if (state === 'draft') {
      saveButton.text('Save Draft');
      saveButton.attr('aria-label', 'You can access your drafts at any time');
    } else if (state === 'publish') {
      saveButton.text('Publish');
      saveButton.attr('aria-label', 'Make the content immediately accessible!');
    }
  }

  function bindTitle () {
    updatePreviewTitle();

    if (boundSlug) {
      updateSlug();
    }
  }
  function unbindSlug () {
    boundSlug = false;
  }

  function updateSlug () {
    slug.value(textService.slug(title.value()));
  }

  function updatePreviewTitle () {
    previewTitle.text(title.value());
  }

  function updateTags () {
    var individualTags = textService.splitTags(tags.value());
    var model = {
      tags: individualTags
    };
    taunus.partial(previewTags, 'partials/tags', model);
  }

  function getRequestBody () {
    var individualTags = textService.splitTags(tags.value());
    var scheduled = schedule.value();
    var state = status.where(':checked').value();
    var body = {
      title: title.value(),
      slug: slug.value(),
      introduction: introduction.value(),
      body: body.value(),
      tags: individualTags,
      status: state
    };
    if (scheduled) {
      body.publication = publication.value();
    }
    return body;
  }

  function save () {
    var body = getRequestBody();
    send(body);
  }

  function send (body) {
    console.log('I should put', body);
  }

  function discard () {
    console.log('I should discard the draft and redirect. Or just redirect if not stored in server');
  }
};
<|endoftext|>


<commit_before>var direction = [0,0];
var jumped = false;
window.addEventListener("keydown", function(e) {
	switch(e.keyCode) {
		case 40:
            if(direction[0] == 0 && direction[1] == 0){
                testPlayer.currentFrameCounter = 0;
                testPlayer.currentFrame = 0;
            }
			direction[1] = -1;
            //testPlayer.currentAnimation = "";
			break;
		case 39:
            if(direction[0] == 0 && direction[1] == 0){
                testPlayer.currentFrameCounter = 0;
                testPlayer.currentFrame = 0;
            }
            testPlayer.directionFacing = "right";
			direction[0] = 1;
            testPlayer.currentAnimation = "runningRight";
           // testPlayer.currentFrameCounter = 0;
           // testPlayer.currentFrame = 0;
			break;
		case 38:
            if(direction[0] == 0 && direction[1] == 0){
                testPlayer.currentFrameCounter = 0;
                testPlayer.currentFrame = 0;
            }
			direction[1] = 1;
           // testPlayer.currentAnimation = "runningRight";
            //testPlayer.currentFrameCounter = 0;
            //testPlayer.currentFrame = 0;
			break;
		case 37:
            if(direction[0] == 0 && direction[1] == 0){
                testPlayer.currentFrameCounter = 0;
                testPlayer.currentFrame = 0;
            }
            testPlayer.directionFacing = "left";
			direction[0] = -1;
            testPlayer.currentAnimation = "runningLeft";
            //testPlayer.currentFrameCounter = 0;
            //testPlayer.currentFrame = 0;
			break;
        }
    });
window.addEventListener("keyup", function(e) {
	switch(e.keyCode) {
		case 40:
			direction[1] = 0;
			break;
		case 39:
			direction[0] = 0;
			break;
		case 38:
			direction[1] = 0;
			break;
		case 37:
			direction[0] = 0;
			break;
        case 32:
            jumped = true;
            break;
	}
})

var log = false;

var testPlayer = {
    sprite: {image:"mario", sizeX: 16, sizeY: 32, frames: {standardRight: [[80,0]], standardLeft: [[736,0]], runningRight: [[112,0],[127,0],[112,0], [96,0]], runningLeft: [[704,0],[720,0],[704,0], [688,0]]}},
	positionX: 193,
	positionY: 140,
	width: 35,
	height: 60,
	hp: 100,
	money: 50,
    currentAnimation: "standardRight",
    currentFrame: 0,
    currentFrameCounter: 0,
    directionFacing: "right",
	speed: 5,
    collider: null,
    isJuming: false,
    jumpSpeed: 0,
    Jump: function(height){
        if(!testPlayer.isJumping){
            testPlayer.isJumping = true;
            testPlayer.jumpspeed = height;
        }
    },
    Move: function(x,y, game){
        var p = game.Player;
        testPlayer.currentFrameCounter += 0.1;
        testPlayer.currentFrame = (parseInt(testPlayer.currentFrameCounter)) % testPlayer.sprite.frames[testPlayer.currentAnimation].length;
		game.offsetX += x;
		game.offsetY += y;
		var po = {positionX: testPlayer.getPositionX(game), positionY: testPlayer.getPositionY(game), width: p.width, height: p.height};
		var tc = game.getTerrainCollidersObject(po);
		testPlayer.collider = new SAT.Box(new SAT.Vector(po.positionX, po.positionY), po.width, po.height).toPolygon();
		game.checkCollisionAll(testPlayer.collider, tc, function(res) {
			game.offsetX -= res.overlapV.x;
			game.offsetY -= res.overlapV.y;

			testPlayer.collider.pos.x -= res.overlapV.x;
			testPlayer.collider.pos.y -= res.overlapV.y;

			if(game.offsetX < 0) {
				game.offsetX = 0;
				testPlayer.collider.pos.x = testPlayer.positionX;
			}
		});

		if(game.offsetX < 0) {
			game.offsetX = 0;
		}
    },
	Update: function(game) {
        if(direction[0] == 0 && direction[1] == 0){
            if(testPlayer.directionFacing == "right"){
                testPlayer.currentAnimation = "standardRight";
            }
            else{
                testPlayer.currentAnimation = "standardLeft";
            }
        }
        testPlayer.Move(direction[0] * testPlayer.speed,direction[1] * testPlayer.speed,game);
        game.applyGravity(testPlayer);

	},
	damage: function(damage) {
		if(testPlayer.hp - damage > 0){
			testPlayer.hp -= damage;
		}
		else{
			//Player is killed
			alert("Game Over!");
		}
	},
	Draw: function(d) {
		d.drawImage(document.getElementById(testPlayer.sprite.image), testPlayer.sprite.frames[testPlayer.currentAnimation][testPlayer.currentFrame][0], testPlayer.sprite.frames[testPlayer.currentAnimation][testPlayer.currentFrame][1], testPlayer.sprite.sizeX , testPlayer.sprite.sizeY, 0, 0, testPlayer.width, testPlayer.height);
	},
	getPositionX: function(game) {
		return game.offsetX + testPlayer.positionX;
	},
	getPositionY: function(game) {
		return game.offsetY + testPlayer.positionY;
	}
}<commit_msg>Added basic jumping<commit_after>var direction = [0,0];
var jumped = false;
window.addEventListener("keydown", function(e) {
	switch(e.keyCode) {
		case 40:
            if(direction[0] == 0 && direction[1] == 0){
                testPlayer.currentFrameCounter = 0;
                testPlayer.currentFrame = 0;
            }
			direction[1] = -1;
            //testPlayer.currentAnimation = "";
			break;
		case 39:
            if(direction[0] == 0 && direction[1] == 0){
                testPlayer.currentFrameCounter = 0;
                testPlayer.currentFrame = 0;
            }
            testPlayer.directionFacing = "right";
			direction[0] = 1;
            testPlayer.currentAnimation = "runningRight";
           // testPlayer.currentFrameCounter = 0;
           // testPlayer.currentFrame = 0;
			break;
		case 38:
            if(direction[0] == 0 && direction[1] == 0){
                testPlayer.currentFrameCounter = 0;
                testPlayer.currentFrame = 0;
            }
			direction[1] = 1;
           // testPlayer.currentAnimation = "runningRight";
            //testPlayer.currentFrameCounter = 0;
            //testPlayer.currentFrame = 0;
			break;
		case 37:
            if(direction[0] == 0 && direction[1] == 0){
                testPlayer.currentFrameCounter = 0;
                testPlayer.currentFrame = 0;
            }
            testPlayer.directionFacing = "left";
			direction[0] = -1;
            testPlayer.currentAnimation = "runningLeft";
            //testPlayer.currentFrameCounter = 0;
            //testPlayer.currentFrame = 0;
			break;
        case 32:
            console.log("TEST");
            jumped = true;
            break;
        }
    });
window.addEventListener("keyup", function(e) {
	switch(e.keyCode) {
		case 40:
			direction[1] = 0;
			break;
		case 39:
			direction[0] = 0;
			break;
		case 38:
			direction[1] = 0;
			break;
		case 37:
			direction[0] = 0;
			break;
        case 32:
            console.log("TEST");
            jumped = true;
            break;
	}
})

var log = false;

var testPlayer = {
    sprite: {image:"mario", sizeX: 16, sizeY: 32, frames: {standardRight: [[80,0]], standardLeft: [[736,0]], runningRight: [[112,0],[127,0],[112,0], [96,0]], runningLeft: [[704,0],[720,0],[704,0], [688,0]]}},
	positionX: 193,
	positionY: 140,
	width: 35,
	height: 60,
	hp: 100,
	money: 50,
    currentAnimation: "standardRight",
    currentFrame: 0,
    currentFrameCounter: 0,
    directionFacing: "right",
	speed: 5,
    collider: null,
    isJuming: false,
    jumpSpeed: 0,
    jumpHeight: 20,
    Jump: function(height){
        if(!testPlayer.isJumping){
            testPlayer.isJumping = true;
            testPlayer.jumpSpeed = height;
            console.log(testPlayer.jumpSpeed);
        }
    },
    ApplyJump: function(game){
        if(testPlayer.isJumping){
            testPlayer.Move(0,testPlayer.jumpSpeed, game);
            testPlayer.jumpSpeed -= 1;
            if(testPlayer.jumpSpeed < 0){
                testPlayer.jumpSpeed = 0;
            }
        }
    },
    Move: function(x,y, game){
        var p = game.Player;
        testPlayer.currentFrameCounter += 0.1;
        testPlayer.currentFrame = (parseInt(testPlayer.currentFrameCounter)) % testPlayer.sprite.frames[testPlayer.currentAnimation].length;
		game.offsetX += x;
		game.offsetY += y;
		var po = {positionX: testPlayer.getPositionX(game), positionY: testPlayer.getPositionY(game), width: p.width, height: p.height};
		var tc = game.getTerrainCollidersObject(po);
		testPlayer.collider = new SAT.Box(new SAT.Vector(po.positionX, po.positionY), po.width, po.height).toPolygon();
		game.checkCollisionAll(testPlayer.collider, tc, function(res) {
			game.offsetX -= res.overlapV.x;
			game.offsetY -= res.overlapV.y;

			testPlayer.collider.pos.x -= res.overlapV.x;
			testPlayer.collider.pos.y -= res.overlapV.y;

			if(game.offsetX < 0) {
				game.offsetX = 0;
				testPlayer.collider.pos.x = testPlayer.positionX;
			}
		});

		if(game.offsetX < 0) {
			game.offsetX = 0;
		}
    },
	Update: function(game) {
        if(direction[0] == 0 && direction[1] == 0){
            if(testPlayer.directionFacing == "right"){
                testPlayer.currentAnimation = "standardRight";
            }
            else{
                testPlayer.currentAnimation = "standardLeft";
            }
        }
        testPlayer.Move(direction[0] * testPlayer.speed,direction[1] * testPlayer.speed,game);
        game.applyGravity(testPlayer);
        if(jumped){
            //console.log(testPlayer.jumpHeight);
            testPlayer.Jump(testPlayer.jumpHeight);
        }
        testPlayer.ApplyJump(game);
      //  console.log(game.offsetY);

	},
	damage: function(damage) {
		if(testPlayer.hp - damage > 0){
			testPlayer.hp -= damage;
		}
		else{
			//Player is killed
			alert("Game Over!");
		}
	},
	Draw: function(d) {
		d.drawImage(document.getElementById(testPlayer.sprite.image), testPlayer.sprite.frames[testPlayer.currentAnimation][testPlayer.currentFrame][0], testPlayer.sprite.frames[testPlayer.currentAnimation][testPlayer.currentFrame][1], testPlayer.sprite.sizeX , testPlayer.sprite.sizeY, 0, 0, testPlayer.width, testPlayer.height);
	},
	getPositionX: function(game) {
		return game.offsetX + testPlayer.positionX;
	},
	getPositionY: function(game) {
		return game.offsetY + testPlayer.positionY;
	}
}<|endoftext|>


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

'use strict';

var os = require('os');
var TimeMock = require('time-mock');

var allocCluster = require('./lib/alloc-cluster.js');
var nullStatsd = require('uber-statsd-client/null');
var TChannelStatsd = require('../lib/statsd');
var timers = TimeMock(Date.now());

allocCluster.test('emits stats on call success', {
    numPeers: 2,
    channelOptions: {
        timers: timers
    }
}, function t(cluster, assert) {
    var server = cluster.channels[0];
    var client = cluster.channels[1];
    var serverHost = cluster.hosts[0]
        .replace(/:/g, '-')
        .replace(/\./g, '-');
    var statsd = nullStatsd(5);

    server.makeSubChannel({
        serviceName: 'reservoir'
    }).register('Reservoir::get', function get(req, res, h, b) {
        timers.setTimeout(function onSend() {
            res.headers.as = 'raw';
            res.sendOk(h, b);
        }, 500);
        timers.advance(500);
    });

    client.statTags = client.options.statTags = {
        app: 'pool',
        host: os.hostname(),
        cluster: 'c0',
        version: '1.0'
    };
    client.channelStatsd = new TChannelStatsd(client, statsd);
    var clientChan = client.makeSubChannel({
        serviceName: 'reservoir',
        peers: [server.hostPort],
        requestDefaults: {
            headers: {
                as: 'raw',
                cn: 'wat'
            }
        }
    });

    clientChan.request({
        serviceName: 'reservoir',
        hasNoParent: true,
        headers: {
            cn: 'inPipe'
        }
    }).send('Reservoir::get', 'ton', '20', onResponse);

    function onResponse(err, res, arg2, arg3) {
        if (err) {
            return assert.end(err);
        }
        assert.ok(res.ok, 'res should be ok');
        assert.deepEqual(statsd._buffer._elements, [{
            type: 'c',
            name: 'tchannel.outbound.calls.sent.inPipe.reservoir.Reservoir--get',
            value: null,
            delta: 1,
            time: null
        }, {
            type: 'c',
            name: 'tchannel.connections.initiated.' + serverHost,
            value: null,
            delta: 1,
            time: null
        }, {
            type: 'ms',
            name: 'tchannel.outbound.calls.per-attempt-latency.inPipe.reservoir.Reservoir--get.' + server.hostPort.replace(':', '-') + '.0',
            value: null,
            delta: null,
            time: 500
        }, {
            type: 'c',
            name: 'tchannel.outbound.calls.success.inPipe.reservoir.Reservoir--get',
            value: null,
            delta: 1,
            time: null
        }, {
            type: 'ms',
            name: 'tchannel.outbound.calls.latency.inPipe.reservoir.Reservoir--get',
            value: null,
            delta: null,
            time: 500
        }], 'stats keys/values as expected');

        assert.end();
    }
});

allocCluster.test('emits stats on call failure', {
    numPeers: 2,
    channelOptions: {
        timers: timers
    }
}, function t(cluster, assert) {
    var server = cluster.channels[0];
    var client = cluster.channels[1];
    var serverHost = cluster.hosts[0]
        .replace(/:/g, '-')
        .replace(/\./g, '-');
    var statsd = nullStatsd(5);

    server.makeSubChannel({
        serviceName: 'reservoir'
    }).register('Reservoir::get', function get(req, res, h, b) {
        timers.setTimeout(function onSend() {
            res.headers.as = 'raw';
            res.sendNotOk(h, '0');
        }, 500);
        timers.advance(500);
    });

    client.statTags = client.options.statTags = {
        app: 'pool',
        host: os.hostname(),
        cluster: 'c0',
        version: '1.0'
    };
    client.channelStatsd = new TChannelStatsd(client, statsd);
    var clientChan = client.makeSubChannel({
        serviceName: 'reservoir',
        peers: [server.hostPort],
        requestDefaults: {
            headers: {
                as: 'raw',
                cn: 'wat'
            }
        }
    });

    clientChan.request({
        serviceName: 'reservoir',
        hasNoParent: true,
        headers: {
            cn: 'inPipe'
        }
    }).send('Reservoir::get', 'ton', '20', onResponse);

    function onResponse(err, res, arg2, arg3) {
        if (err) {
            return assert.end(err);
        }
        assert.ok(res.ok === false, 'res should be not ok');
        assert.deepEqual(statsd._buffer._elements, [{
            type: 'c',
            name: 'tchannel.outbound.calls.sent.inPipe.reservoir.Reservoir--get',
            value: null,
            delta: 1,
            time: null
        }, {
            type: 'c',
            name: 'tchannel.connections.initiated.' + serverHost,
            value: null,
            delta: 1,
            time: null
        }, {
            type: 'ms',
            name: 'tchannel.outbound.calls.per-attempt-latency.inPipe.reservoir.Reservoir--get.' + server.hostPort.replace(':', '-') + '.0',
            value: null,
            delta: null,
            time: 500
        }, {
            type: 'c',
            name: 'tchannel.outbound.calls.app-errors.inPipe.reservoir.Reservoir--get.unknown',
            value: null,
            delta: 1,
            time: null
        }, {
            type: 'ms',
            name: 'tchannel.outbound.calls.latency.inPipe.reservoir.Reservoir--get',
            value: null,
            delta: null,
            time: 500
        }], 'stats keys/values as expected');

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

'use strict';

var os = require('os');
var TimeMock = require('time-mock');

var allocCluster = require('./lib/alloc-cluster.js');
var nullStatsd = require('uber-statsd-client/null');
var TChannelStatsd = require('../lib/statsd');
var timers = TimeMock(Date.now());

allocCluster.test('emits stats on call success', {
    numPeers: 2,
    channelOptions: {
        timers: timers
    }
}, function t(cluster, assert) {
    var server = cluster.channels[0];
    var client = cluster.channels[1];
    var serverHost = cluster.hosts[0]
        .replace(/:/g, '-')
        .replace(/\./g, '-');
    var statsd = nullStatsd(5);

    server.makeSubChannel({
        serviceName: 'reservoir'
    }).register('Reservoir::get', function get(req, res, h, b) {
        timers.setTimeout(function onSend() {
            res.headers.as = 'raw';
            res.sendOk(h, b);
        }, 500);
        timers.advance(500);
    });

    client.statTags = client.options.statTags = {
        app: 'pool',
        host: os.hostname(),
        cluster: 'c0',
        version: '1.0'
    };
    client.channelStatsd = new TChannelStatsd(client, statsd);
    var clientChan = client.makeSubChannel({
        serviceName: 'reservoir',
        peers: [server.hostPort],
        requestDefaults: {
            headers: {
                as: 'raw',
                cn: 'wat'
            }
        }
    });

    clientChan.request({
        serviceName: 'reservoir',
        hasNoParent: true,
        headers: {
            cn: 'inPipe'
        }
    }).send('Reservoir::get', 'ton', '20', onResponse);

    function onResponse(err, res, arg2, arg3) {
        if (err) {
            return assert.end(err);
        }
        assert.ok(res.ok, 'res should be ok');
        assert.deepEqual(statsd._buffer._elements, [{
            type: 'c',
            name: 'tchannel.outbound.calls.sent.inPipe.reservoir.Reservoir--get',
            value: null,
            delta: 1,
            time: null
        }, {
            type: 'c',
            name: 'tchannel.connections.initiated.' + serverHost,
            value: null,
            delta: 1,
            time: null
        }, {
            type: 'ms',
            name: 'tchannel.outbound.calls.per-attempt-latency.inPipe.reservoir.Reservoir--get.0',
            value: null,
            delta: null,
            time: 500
        }, {
            type: 'c',
            name: 'tchannel.outbound.calls.success.inPipe.reservoir.Reservoir--get',
            value: null,
            delta: 1,
            time: null
        }, {
            type: 'ms',
            name: 'tchannel.outbound.calls.latency.inPipe.reservoir.Reservoir--get',
            value: null,
            delta: null,
            time: 500
        }], 'stats keys/values as expected');

        assert.end();
    }
});

allocCluster.test('emits stats on call failure', {
    numPeers: 2,
    channelOptions: {
        timers: timers
    }
}, function t(cluster, assert) {
    var server = cluster.channels[0];
    var client = cluster.channels[1];
    var serverHost = cluster.hosts[0]
        .replace(/:/g, '-')
        .replace(/\./g, '-');
    var statsd = nullStatsd(5);

    server.makeSubChannel({
        serviceName: 'reservoir'
    }).register('Reservoir::get', function get(req, res, h, b) {
        timers.setTimeout(function onSend() {
            res.headers.as = 'raw';
            res.sendNotOk(h, '0');
        }, 500);
        timers.advance(500);
    });

    client.statTags = client.options.statTags = {
        app: 'pool',
        host: os.hostname(),
        cluster: 'c0',
        version: '1.0'
    };
    client.channelStatsd = new TChannelStatsd(client, statsd);
    var clientChan = client.makeSubChannel({
        serviceName: 'reservoir',
        peers: [server.hostPort],
        requestDefaults: {
            headers: {
                as: 'raw',
                cn: 'wat'
            }
        }
    });

    clientChan.request({
        serviceName: 'reservoir',
        hasNoParent: true,
        headers: {
            cn: 'inPipe'
        }
    }).send('Reservoir::get', 'ton', '20', onResponse);

    function onResponse(err, res, arg2, arg3) {
        if (err) {
            return assert.end(err);
        }
        assert.ok(res.ok === false, 'res should be not ok');
        assert.deepEqual(statsd._buffer._elements, [{
            type: 'c',
            name: 'tchannel.outbound.calls.sent.inPipe.reservoir.Reservoir--get',
            value: null,
            delta: 1,
            time: null
        }, {
            type: 'c',
            name: 'tchannel.connections.initiated.' + serverHost,
            value: null,
            delta: 1,
            time: null
        }, {
            type: 'ms',
            name: 'tchannel.outbound.calls.per-attempt-latency.inPipe.reservoir.Reservoir--get.0',
            value: null,
            delta: null,
            time: 500
        }, {
            type: 'c',
            name: 'tchannel.outbound.calls.app-errors.inPipe.reservoir.Reservoir--get.unknown',
            value: null,
            delta: 1,
            time: null
        }, {
            type: 'ms',
            name: 'tchannel.outbound.calls.latency.inPipe.reservoir.Reservoir--get',
            value: null,
            delta: null,
            time: 500
        }], 'stats keys/values as expected');

        assert.end();
    }
});
<|endoftext|>


<commit_before>const WEEK_DURATION = 7;

class MainController {
    constructor ($scope, AuthService, WeekService, StorageService, $timeout) {
        Object.assign(this, {$scope, AuthService, WeekService, StorageService, $timeout});
        this.title = Mealpler.titles;
        this.isShopListOpened = false;

        this.$scope.$on(EventType.AUTH, (e) => this.init());
        this.$scope.$on(EventType.MEALS, (e) => this.refresh());

        this.currentWeek = [];
        this.targetDatePicker = 'datePicker';

        this.firstDate = this.WeekService.getWeekStart(moment());
        this.lastDate = this.WeekService.getWeekEnd(moment(), WEEK_DURATION);

        this.refresh = this._refreshDashboard.bind(this);
        this.toggleShopList = this._toggleShopList.bind(this);
    }

    init() {
        this.setUserProfileAndLoginStatus();
        this._setCurrentWeek();
    }

    _setCurrentWeek(start = this.firstDate) {
        return this.WeekService.findDateRangeMealList(start, WEEK_DURATION).then((response) => {
            this.$timeout (() => {
                this.currentWeek = angular.copy(response);
            })
        });
    }

    _refreshDashboard(date) {
        if (date) this.firstDate = this.WeekService.getWeekStart(moment(date));
        return this._setCurrentWeek(date);
    }

    switchWeek(trend) {
        this._setFirstDay(trend);
        this._refreshDashboard();
        this.$scope.$broadcast(EventType.WEEKSTART, this.firstDate);
    }

    _setFirstDay(trend, date) {
        if (trend) {
            if (trend === 'past') {
                this.firstDate = moment(this.firstDate).subtract(1, 'day').startOf('week');
            } else if (trend === 'future') {
                this.firstDate = moment(this.firstDate).add(1, 'week').startOf('week');
            }
        } else if (date) {
            this.firstDate = moment(date);
        }
    }

    setUserProfileAndLoginStatus() {
        this.userIsLogged = this.AuthService.isLogged();
        this.user = this.AuthService.getUser();
        this.$scope.$apply();
    }

    signOut() {
        this.AuthService.signOut()
            .then(() => {})
            .catch((e) => console.log('Sign out failed due to: ' + e.message));
    }

    _toggleShopList(state) {
        if (typeof state != undefined) {
            this.setIsShopListOpened(state);
        } else {
            this.setIsShopListOpened(!this.isShoplistOpened);
        }
    }

    setIsShopListOpened(state) {
        this.isShopListOpened = state;
    }
}

Mealpler.controller('MainCtrl', MainController);
<commit_msg>MP-53: fixed setting last day of the week<commit_after>const WEEK_DURATION = 7;

class MainController {
    constructor ($scope, AuthService, WeekService, StorageService, $timeout) {
        Object.assign(this, {$scope, AuthService, WeekService, StorageService, $timeout});
        this.title = Mealpler.titles;
        this.isShopListOpened = false;

        this.$scope.$on(EventType.AUTH, (e) => this.init());
        this.$scope.$on(EventType.MEALS, (e) => this.refresh());

        this.currentWeek = [];
        this.targetDatePicker = 'datePicker';

        this.firstDate = this.WeekService.getWeekStart(moment());
        this.lastDate = this.WeekService.getWeekEnd(moment(), WEEK_DURATION);

        this.refresh = this._refreshDashboard.bind(this);
        this.toggleShopList = this._toggleShopList.bind(this);
    }

    init() {
        this.setUserProfileAndLoginStatus();
        this._setCurrentWeek();
    }

    _setCurrentWeek(start = this.firstDate) {
        return this.WeekService.findDateRangeMealList(start, WEEK_DURATION).then((response) => {
            this.$timeout (() => {
                this.currentWeek = angular.copy(response);
            })
        });
    }

    _refreshDashboard(date) {
        if (date) this.firstDate = this.WeekService.getWeekStart(moment(date));
        return this._setCurrentWeek(date);
    }

    switchWeek(trend) {
        this._setFirstAndLastDays(trend);
        this._refreshDashboard();
        this.$scope.$broadcast(EventType.WEEKSTART, this.firstDate);
    }

    _setFirstAndLastDays(trend, date) {
        if (trend) {
            if (trend === 'past') {
                this.firstDate = moment(this.firstDate).subtract(1, 'day').startOf('week');
            } else if (trend === 'future') {
                this.firstDate = moment(this.firstDate).add(1, 'week').startOf('week');
            }
        } else if (date) {
            this.firstDate = moment(date);
        }
        this.lastDate = this.WeekService.getWeekEnd(this.firstDate, WEEK_DURATION);
    }

    setUserProfileAndLoginStatus() {
        this.userIsLogged = this.AuthService.isLogged();
        this.user = this.AuthService.getUser();
        this.$scope.$apply();
    }

    signOut() {
        this.AuthService.signOut()
            .then(() => {})
            .catch((e) => console.log('Sign out failed due to: ' + e.message));
    }

    _toggleShopList(state) {
        if (typeof state != undefined) {
            this.setIsShopListOpened(state);
        } else {
            this.setIsShopListOpened(!this.isShoplistOpened);
        }
    }

    setIsShopListOpened(state) {
        this.isShopListOpened = state;
    }
}

Mealpler.controller('MainCtrl', MainController);
<|endoftext|>


<commit_before>"use strict";
/*jshint eqnull:true */
/*jshint globalstrict:true */
/*jshint node:true */
/* global describe */
/* global it */

var expect = require('expect.js');
var sinon = require('sinon');
var Promises = require('best-promise');
var qacServices = require('../lib/qac-services.js');
var fs = require('fs-promise');
var request = require('supertest');
var helper=require('../test/test-helper.js');
var html = require('js-to-html').html;
var Path = require('path');
helper.setup(qacServices);

describe("qac-services overview",function(){
    it("get cucardasToHtmlList",function(){
        var obt=qacServices.cucardasToHtmlList(
            "[![npm-version](https://img.shields.io/npm/v/multilang.svg)](https://npmjs.org/package/multilang)  \n\r "+
            "[![downloads](https://img.shields.io/npm/dm/multilang.svg)](https://npmjs.org/package/multilangx) "+
            "![extending](https://img.shields.io/badge/stability-extending-orange.svg)"+
            "![stable](https://img.shields.io/badge/stability-stable-green.svg)"
        );
        expect(obt).to.eql([
            html.td([
                html.img({src:"https://img.shields.io/badge/stability-extending-orange.svg", alt:"extending"}),
                html.img({src:"https://img.shields.io/badge/stability-stable-green.svg", alt:"stable"}),
            ]),
            html.td([
                html.a(
                    {href:"https://npmjs.org/package/multilang"},
                    [ html.img({src:"https://img.shields.io/npm/v/multilang.svg", alt:"npm-version"}) ]
                ),
            ]),
            html.td([
                html.a(
                    {href:"https://npmjs.org/package/multilangx"},
                    [ html.img({src:"https://img.shields.io/npm/dm/multilang.svg", alt:"downloads"}) ]
                ),
            ]),
            html.td(),
            html.td(),
            html.td(),
            html.td(),
            html.td(),
            html.td(),
            html.td(),
            html.td(),
        ]);
    });
    it("get projectNameToHtmlLink",function(){
        var oriUrl = qacServices.rootUrl;
        qacServices.rootUrl='/root/'
        var obt=qacServices.projectNameToHtmlLink('simple-org','proj-name');
        expect(obt).to.eql(
            html.a({href:"/root/simple-org/proj-name"}, "proj-name")
        );
        qacServices.rootUrl = oriUrl;
    });
    it("get projectActionButtons",function(){
        var oriUrl = qacServices.rootUrl;
        qacServices.rootUrl='/root/';
        qacServices.user='user-name';
        qacServices.production=false;
        var obt=qacServices.projectActionButtons('simple-org','proj-name');
        expect(obt).to.eql([
            html.td([
                html.a({
                    href: '/root/ask/delete/simple-org/proj-name',
                    'codenautas-confirm': 'row'
                },[html.img({src:'/delete.png', alg:'del', style:'height:18px'})])
            ]),
            html.td([
                html.a({
                    href:'/root/manual-push/simple-org/proj-name'
                }, [html.img({src:'/refresh.png', alt:'rfrsh', style:'height:18px'})])
            ])
        ]);
        qacServices.production=true;
        qacServices.user=false;
        qacServices.rootUrl = oriUrl;
    });
    describe('getOrganization',function() {
        function checkGetOrg(msg, result, userLogged) {
            it(msg, function(done) {
                sinon.stub(qacServices, "getInfo", function(organization, project){
                    if(!!project){
                        throw new Error("unexpected project name in getInfo");
                    }
                    if(organization!=='simple'){
                        throw new Error("wrong organization name in getInfo");
                    }
                    return Promises.resolve({
                        organization:{
                            projects:[{
                                projectName:'uno'
                            },{
                                projectName:'dos'
                            }],
                            path:'the-org-path'
                        }
                    });
                });
                sinon.stub(fs, 'readFile', function(nameCucardas){
                    //console.log("nameCucardas", nameCucardas);
                    switch(nameCucardas){
                        case Path.normalize('the-org-path/projects/uno/result/cucardas.md'): return Promises.resolve('[qa-control][issues] cu-uno');
                        case Path.normalize('the-org-path/projects/dos/result/cucardas.md'): return Promises.resolve('[qa-control][issues] cu-dos');
                        default: throw new Error('unexpected params in readFile of cucardas');
                    }
                });
                sinon.stub(qacServices, "cucardasToHtmlList", function(x){
                    return [html.td("list: "+x)];
                });
                sinon.stub(qacServices, "projectActionButtons", function(orga, proj){
                    return [html.td("b:"+orga+':'+proj)];
                });
                sinon.stub(qacServices, "projectNameToHtmlLink", function(orga, proj){
                    return "link: "+orga+','+proj;
                });
                if(userLogged) {
                    qacServices.user = 'pepe';
                }
                qacServices.getOrganizationPage('simple').then(function(oHtml){
                    //console.log(oHtml.toHtmlText({pretty:true}));
                    expect(oHtml).to.eql(result);
                }).then(function(){
                    qacServices.getInfo.restore();
                    qacServices.cucardasToHtmlList.restore();
                    qacServices.projectNameToHtmlLink.restore();
                    qacServices.projectActionButtons.restore();
                    fs.readFile.restore();
                    qacServices.user = null;
                }).then(done,done);
            });
        }
        checkGetOrg('simple organization page', html.table([
            html.tr([ html.th('project'), html.th({colspan:10},'cucardas') ]),
            html.tr([ html.td("link: simple,uno"), html.td( ["list: [qa-control][issues] cu-uno"]), html.td("b:simple:uno") ]),
            html.tr([ html.td("link: simple,dos"), html.td( ["list: [qa-control][issues] cu-dos"]), html.td("b:simple:dos") ]),
        ]));
        checkGetOrg('simple organization page authenticated',
            html.form({method:'post', action:qacServices.rootUrl},
                [html.table([
                    html.tr([ html.th('project'), html.th({colspan:10},'cucardas'), html.th({colspan:4},'actions') ]),
                    html.tr([ html.td("link: simple,uno"), html.td( ["list: [qa-control][issues] cu-uno"]), html.td("b:simple:uno") ]),
                    html.tr([ html.td("link: simple,dos"), html.td( ["list: [qa-control][issues] cu-dos"]), html.td("b:simple:dos") ]),
                    html.tr([ html.td({colspan:16, align:'right'}, [
                                html.input({type:'hidden', name:'action', value:'add'}),
                                html.input({type:'hidden', name:'organization', value:'simple'}),
                                html.input({type:'text', name:'project'}),
                                html.input({type:'submit', value:'New project...' })
                                ])
                            ])
                ])]
            ),
            true
        );
    });
    it.skip('make the overview', function(done) {
        var content;
        qacServices.makeOverviewMd('sourcetravelers').then(function(contentMd) {
            content = contentMd;
            return fs.readFile(helper.testConfig.repository.path+'/expected/resume-sourcetravelers.md', {encoding:'utf8'});
        }).then(function(expectedContent) {
            expect(content).to.be(expectedContent);
        }).then(done,done);
    });
    it("obtain html",function(done){
        var htmlContent = "random 123123123123 html content";
        var mock = sinon.stub(qacServices, 'makeOverviewHtml');
        mock.withArgs('sourcetravelers').returns(Promises.resolve(htmlContent));
        var server = createServer();
        var agent=request(server);
        agent
        .get('/sourcetravelers')
        .expect(htmlContent)
        .end(done);
    });
});

var express = require('express');

function createServer(opts, fn) {
    helper.setup(qacServices);
    var _serve = qacServices.overviewServe();
    var app = express();
    app.listen();
    app.use(_serve);
    return app;
}
<commit_msg>'simple admin page' test<commit_after>"use strict";
/*jshint eqnull:true */
/*jshint globalstrict:true */
/*jshint node:true */
/* global describe */
/* global it */

var expect = require('expect.js');
var sinon = require('sinon');
var Promises = require('best-promise');
var qacServices = require('../lib/qac-services.js');
var fs = require('fs-promise');
var request = require('supertest');
var helper=require('../test/test-helper.js');
var html = require('js-to-html').html;
var Path = require('path');
helper.setup(qacServices);

describe("qac-services overview",function(){
    it("get cucardasToHtmlList",function(){
        var obt=qacServices.cucardasToHtmlList(
            "[![npm-version](https://img.shields.io/npm/v/multilang.svg)](https://npmjs.org/package/multilang)  \n\r "+
            "[![downloads](https://img.shields.io/npm/dm/multilang.svg)](https://npmjs.org/package/multilangx) "+
            "![extending](https://img.shields.io/badge/stability-extending-orange.svg)"+
            "![stable](https://img.shields.io/badge/stability-stable-green.svg)"
        );
        expect(obt).to.eql([
            html.td([
                html.img({src:"https://img.shields.io/badge/stability-extending-orange.svg", alt:"extending"}),
                html.img({src:"https://img.shields.io/badge/stability-stable-green.svg", alt:"stable"}),
            ]),
            html.td([
                html.a(
                    {href:"https://npmjs.org/package/multilang"},
                    [ html.img({src:"https://img.shields.io/npm/v/multilang.svg", alt:"npm-version"}) ]
                ),
            ]),
            html.td([
                html.a(
                    {href:"https://npmjs.org/package/multilangx"},
                    [ html.img({src:"https://img.shields.io/npm/dm/multilang.svg", alt:"downloads"}) ]
                ),
            ]),
            html.td(),
            html.td(),
            html.td(),
            html.td(),
            html.td(),
            html.td(),
            html.td(),
            html.td(),
        ]);
    });
    it("get projectNameToHtmlLink",function(){
        var oriUrl = qacServices.rootUrl;
        qacServices.rootUrl='/root/'
        var obt=qacServices.projectNameToHtmlLink('simple-org','proj-name');
        expect(obt).to.eql(
            html.a({href:"/root/simple-org/proj-name"}, "proj-name")
        );
        qacServices.rootUrl = oriUrl;
    });
    it("get projectActionButtons",function(){
        var oriUrl = qacServices.rootUrl;
        qacServices.rootUrl='/root/';
        qacServices.user='user-name';
        qacServices.production=false;
        var obt=qacServices.projectActionButtons('simple-org','proj-name');
        expect(obt).to.eql([
            html.td([
                html.a({
                    href: '/root/ask/delete/simple-org/proj-name',
                    'codenautas-confirm': 'row'
                },[html.img({src:'/delete.png', alg:'del', style:'height:18px'})])
            ]),
            html.td([
                html.a({
                    href:'/root/manual-push/simple-org/proj-name'
                }, [html.img({src:'/refresh.png', alt:'rfrsh', style:'height:18px'})])
            ])
        ]);
        qacServices.production=true;
        qacServices.user=false;
        qacServices.rootUrl = oriUrl;
    });
    describe('getOrganization',function() {
        function checkGetOrg(msg, result, userLogged) {
            it(msg, function(done) {
                sinon.stub(qacServices, "getInfo", function(organization, project){
                    if(!!project){
                        throw new Error("unexpected project name in getInfo");
                    }
                    if(organization!=='simple'){
                        throw new Error("wrong organization name in getInfo");
                    }
                    return Promises.resolve({
                        organization:{
                            projects:[{
                                projectName:'uno'
                            },{
                                projectName:'dos'
                            }],
                            path:'the-org-path'
                        }
                    });
                });
                sinon.stub(fs, 'readFile', function(nameCucardas){
                    //console.log("nameCucardas", nameCucardas);
                    switch(nameCucardas){
                        case Path.normalize('the-org-path/projects/uno/result/cucardas.md'): return Promises.resolve('[qa-control][issues] cu-uno');
                        case Path.normalize('the-org-path/projects/dos/result/cucardas.md'): return Promises.resolve('[qa-control][issues] cu-dos');
                        default: throw new Error('unexpected params in readFile of cucardas');
                    }
                });
                sinon.stub(qacServices, "cucardasToHtmlList", function(x){
                    return [html.td("list: "+x)];
                });
                sinon.stub(qacServices, "projectActionButtons", function(orga, proj){
                    return [html.td("b:"+orga+':'+proj)];
                });
                sinon.stub(qacServices, "projectNameToHtmlLink", function(orga, proj){
                    return "link: "+orga+','+proj;
                });
                if(userLogged) {
                    qacServices.user = 'pepe';
                }
                qacServices.getOrganizationPage('simple').then(function(oHtml){
                    //console.log(oHtml.toHtmlText({pretty:true}));
                    expect(oHtml).to.eql(result);
                }).then(function(){
                    qacServices.getInfo.restore();
                    qacServices.cucardasToHtmlList.restore();
                    qacServices.projectNameToHtmlLink.restore();
                    qacServices.projectActionButtons.restore();
                    fs.readFile.restore();
                    qacServices.user = null;
                }).then(done,done);
            });
        }
        checkGetOrg('simple organization page', html.table([
            html.tr([ html.th('project'), html.th({colspan:10},'cucardas') ]),
            html.tr([ html.td("link: simple,uno"), html.td( ["list: [qa-control][issues] cu-uno"]), html.td("b:simple:uno") ]),
            html.tr([ html.td("link: simple,dos"), html.td( ["list: [qa-control][issues] cu-dos"]), html.td("b:simple:dos") ]),
        ]));
        checkGetOrg('simple organization page authenticated',
            html.form({method:'post', action:qacServices.rootUrl},
                [html.table([
                    html.tr([ html.th('project'), html.th({colspan:10},'cucardas'), html.th({colspan:4},'actions') ]),
                    html.tr([ html.td("link: simple,uno"), html.td( ["list: [qa-control][issues] cu-uno"]), html.td("b:simple:uno") ]),
                    html.tr([ html.td("link: simple,dos"), html.td( ["list: [qa-control][issues] cu-dos"]), html.td("b:simple:dos") ]),
                    html.tr([ html.td({colspan:16, align:'right'}, [
                                html.input({type:'hidden', name:'action', value:'add'}),
                                html.input({type:'hidden', name:'organization', value:'simple'}),
                                html.input({type:'text', name:'project'}),
                                html.input({type:'submit', value:'New project...' })
                                ])
                            ])
                ])]
            ),
            true
        );
    });
    describe('getAdmin',function() {
        function checkGetAdmin(msg, result, userLogged) {
            it(msg, function(done) {
                sinon.stub(qacServices, "getOrganizations", function(){ return Promises.resolve(['uno', 'dos']); });
                if(userLogged) {
                    qacServices.user = 'tito';
                }
                qacServices.getAdminPage().then(function(oHtml){
                    //console.log(oHtml.toHtmlText({pretty:true}));
                    expect(oHtml).to.eql(result);
                }).then(function(){
                    qacServices.getOrganizations.restore();
                }).then(done,done);
            });
        }
        checkGetAdmin('simple admin page',
                           html.table([
                                html.tr([html.th('organization')]),
                                html.tr([html.td([html.a({href:'/uno'}, 'uno')])]),
                                html.tr([html.td([html.a({href:'/dos'}, 'dos')])])
                                ]));
    });
    it.skip('make the overview', function(done) {
        var content;
        qacServices.makeOverviewMd('sourcetravelers').then(function(contentMd) {
            content = contentMd;
            return fs.readFile(helper.testConfig.repository.path+'/expected/resume-sourcetravelers.md', {encoding:'utf8'});
        }).then(function(expectedContent) {
            expect(content).to.be(expectedContent);
        }).then(done,done);
    });
    it("obtain html",function(done){
        var htmlContent = "random 123123123123 html content";
        var mock = sinon.stub(qacServices, 'makeOverviewHtml');
        mock.withArgs('sourcetravelers').returns(Promises.resolve(htmlContent));
        var server = createServer();
        var agent=request(server);
        agent
        .get('/sourcetravelers')
        .expect(htmlContent)
        .end(done);
    });
});

var express = require('express');

function createServer(opts, fn) {
    helper.setup(qacServices);
    var _serve = qacServices.overviewServe();
    var app = express();
    app.listen();
    app.use(_serve);
    return app;
}
<|endoftext|>


<commit_before>/**
 * PUSH Notification server V 0.3
 * (c) Telefonica Digital, 2012 - All rights reserver
 * Fernando Rodríguez Sela <frsela@tid.es>
 * Guillermo Lopez Leal <gll@tid.es>
 */

var log = require("../common/logger.js"),
    msgBroker = require("../common/msgbroker.js"),
    http = require('http');

////////////////////////////////////////////////////////////////////////////////
// Callback functions
////////////////////////////////////////////////////////////////////////////////

function onNewMessage(message) {
  log.debug("MB: " + message);
  var messageData = {};
  try {
    messageData = JSON.parse(message);
  } catch(e) {
    log.debug('WS::Queue::onNewMessage --> Not a valid JSON');
    return;
  }

  // Notify the hanset with the associated Data
  log.debug("Notifying node: " + JSON.stringify(messageData.uatoken));
  log.debug("Notify to " +
      messageData.data.interface.ip + ":" + messageData.data.interface.port
  );

  // HTTP Notification Message
  var options = {
    host: 'localhost',
    port: 8090,
    path: '/?ip=' + messageData.data.interface.ip + '&port=' + messageData.data.interface.port,
    method: 'GET'
  };

  var req = http.request(options, function(res) {
    log.debug('STATUS: ' + res.statusCode);
    log.debug('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
      log.debug('BODY: ' + chunk);
    });
  });

  req.on('error', function(e) {
    log.debug('problem with request: ' + e.message);
  });

  req.end();
}

////////////////////////////////////////////////////////////////////////////////

function server() {
}

server.prototype = {
  //////////////////////////////////////////////
  // Constructor
  //////////////////////////////////////////////

  init: function() {
    log.info("Starting UA-UDP server");

    // Subscribe to the UDP common Queue
    msgBroker.init(function() {
      var args = { durable: false, autoDelete: true, arguments: { 'x-ha-policy': 'all' } };
      msgBroker.subscribe("UDP", args, function(msg) { onNewMessage(msg); });
    });
  },

  stop: function(callback) {
    log.info("UDP::stop --> Closing UDP server");

    //Closing connection with msgBroker
    msgBroker.close();

    //Calling the callback
    callback(null);
  }
};

// Exports
exports.server = server;
<commit_msg>Simplified the HTTP response management<commit_after>/**
 * PUSH Notification server V 0.3
 * (c) Telefonica Digital, 2012 - All rights reserver
 * Fernando Rodríguez Sela <frsela@tid.es>
 * Guillermo Lopez Leal <gll@tid.es>
 */

var log = require("../common/logger.js"),
    msgBroker = require("../common/msgbroker.js"),
    http = require('http');

////////////////////////////////////////////////////////////////////////////////
// Callback functions
////////////////////////////////////////////////////////////////////////////////

function onNewMessage(message) {
  log.debug("MB: " + message);
  var messageData = {};
  try {
    messageData = JSON.parse(message);
  } catch(e) {
    log.debug('WS::Queue::onNewMessage --> Not a valid JSON');
    return;
  }

  // Notify the hanset with the associated Data
  log.debug("Notifying node: " + JSON.stringify(messageData.uatoken));
  log.debug("Notify to " +
      messageData.data.interface.ip + ":" + messageData.data.interface.port
  );

  // HTTP Notification Message
  var options = {
    host: 'localhost',
    port: 8090,
    path: '/?ip=' + messageData.data.interface.ip + '&port=' + messageData.data.interface.port,
    method: 'GET'
  };

  var req = http.request(options, function(res) {
    log.debug('Message status: ' + res.statusCode);
  });

  req.on('error', function(e) {
    log.debug('problem with request: ' + e.message);
  });

  req.end();
}

////////////////////////////////////////////////////////////////////////////////

function server() {
}

server.prototype = {
  //////////////////////////////////////////////
  // Constructor
  //////////////////////////////////////////////

  init: function() {
    log.info("Starting UA-UDP server");

    // Subscribe to the UDP common Queue
    msgBroker.init(function() {
      var args = { durable: false, autoDelete: true, arguments: { 'x-ha-policy': 'all' } };
      msgBroker.subscribe("UDP", args, function(msg) { onNewMessage(msg); });
    });
  },

  stop: function(callback) {
    log.info("UDP::stop --> Closing UDP server");

    //Closing connection with msgBroker
    msgBroker.close();

    //Calling the callback
    callback(null);
  }
};

// Exports
exports.server = server;
<|endoftext|>