<commit_before>#! /usr/bin/env node

const chalk = require('chalk');

const inquirer = require('inquirer');

const is_nil = require('lodash.isnil');
const template = require('lodash.template');

const {die, done, fail, Git, log, Package, stat} = require('tools/common');

const git = Git(process.cwd());

const confirm_tmpl = template('Your repository will be modified:'
	+ '\n' + '  - \'<%= releaseBranch %>\' will be merge into master',
	+ '\n' + '  - master will be tagged with \'<%= releaseTag %>\'',
	+ '\n' + '  - master will be pushed which will trigger a deployment.'
);

function check_branch({pkg, branch}) {
	log('- check branch ... ');
	const release_branch = pkg.releaseBranch;
	if (release_branch !== branch) {
		fail(new Error(`${branch} != ${release_branch}`));
	}
	done();
	return {pkg, branch};
}

function check_changelog({pkg, branch}) {
	log('- check changelog ... ');
	return stat(pkg.changelog)
		.then(({path, stats}) => {
			if (is_nil(stats) || !stats.isFile()) {
				throw new Error(`File '${path}' does not exist or is not a regular file!`);
			}
			done();
			return {pkg, branch}
		})
		.catch(fail);
}

function check_status({pkg, branch}) {
	log('- check repository status ... ');
	return git.status()
		.then(status => {
			if (status.length !== 0) {
				throw new Error('Some changes are not committed yet');
			}
			done();
			return {pkg, branch};
		})
		.catch(fail);
}

function publish({pkg, branch}) {
	log('- publish ... ');
	return Promise.resolve()
		.then(() => git.checkout('master'))
		.then(() => git.merge(branch))
		.then(() => git.tag(`v${pkg.version}`))
		// .then(() => git.push())
		.then(() => {
			done();
			return {pkg, branch};
		})
		.catch(fail);
}

function prompt({pkg, branch}) {
	return inquirer.prompt([{
		name: 'confirmed',
		type: 'input',
		message: () => {
			const ui = new inquirer.ui.BottomBar();
			ui.log.write(chalk.yellow(confirm_tmpl(pkg)));
			return 'Are you sure you want to continue ? (type "I agree" to confirm)';
		},
		filter: input => input === 'I agree'
	}])
	.then(answers => {
		if (answers.confirmed) {
			return {pkg, branch};
		}
		throw new Error('Release publication aborted!');
	});
}

Promise.all([Package(), git.branch()])
	.then(([pkg, branch]) => ({pkg, branch}))
	.then(check_branch)
	.then(check_changelog)
	.then(check_status)
	.then(prompt)
	.then(publish)
	.catch(die);
<commit_msg>fix confirm message template<commit_after>#! /usr/bin/env node

const chalk = require('chalk');

const inquirer = require('inquirer');

const is_nil = require('lodash.isnil');
const template = require('lodash.template');

const {die, done, fail, Git, log, Package, stat} = require('tools/common');

const git = Git(process.cwd());

const confirm_tmpl = template('Your repository will be modified:'
	+ '\n' + '  - \'<%= releaseBranch %>\' will be merge into master,'
	+ '\n' + '  - master will be tagged with \'<%= releaseTag %>\','
	+ '\n' + '  - master will be pushed which will trigger a deployment.'
);

function check_branch({pkg, branch}) {
	log('- check branch ... ');
	const release_branch = pkg.releaseBranch;
	if (release_branch !== branch) {
		fail(new Error(`${branch} != ${release_branch}`));
	}
	done();
	return {pkg, branch};
}

function check_changelog({pkg, branch}) {
	log('- check changelog ... ');
	return stat(pkg.changelog)
		.then(({path, stats}) => {
			if (is_nil(stats) || !stats.isFile()) {
				throw new Error(`File '${path}' does not exist or is not a regular file!`);
			}
			done();
			return {pkg, branch}
		})
		.catch(fail);
}

function check_status({pkg, branch}) {
	log('- check repository status ... ');
	return git.status()
		.then(status => {
			if (status.length !== 0) {
				throw new Error('Some changes are not committed yet');
			}
			done();
			return {pkg, branch};
		})
		.catch(fail);
}

function publish({pkg, branch}) {
	log('- publish ... ');
	return Promise.resolve()
		.then(() => git.checkout('master'))
		.then(() => git.merge(branch))
		.then(() => git.tag(`v${pkg.version}`))
		// .then(() => git.push())
		.then(() => {
			done();
			return {pkg, branch};
		})
		.catch(fail);
}

function prompt({pkg, branch}) {
	return inquirer.prompt([{
		name: 'confirmed',
		type: 'input',
		message: () => {
			const ui = new inquirer.ui.BottomBar();
			ui.log.write(chalk.yellow(confirm_tmpl(pkg)));
			return 'Are you sure you want to continue ? (type "I agree" to confirm)';
		},
		filter: input => input === 'I agree'
	}])
	.then(answers => {
		if (answers.confirmed) {
			return {pkg, branch};
		}
		throw new Error('Release publication aborted!');
	});
}

Promise.all([Package(), git.branch()])
	.then(([pkg, branch]) => ({pkg, branch}))
	.then(check_branch)
	.then(check_changelog)
	.then(check_status)
	.then(prompt)
	.then(publish)
	.catch(die);
<|endoftext|>


<commit_before>/**
 * test-gulp.jslint
 * Some basic tests to ensure that
 * package is working as intended.
 *
 * Copyright (C) 2014 Karim Alibhai.
 **/

(function () {
    "use strict";

    var fs = require('fs'),
        path = require('path'),
        strip = require('stripcolorcodes'),
        test = require('tape'),
        Vinyl = require('vinyl'),
        jslint = require('../'),
        lint = function (why, file, dir) {
            var goodCode = true;

            // directives
            dir = dir || {};

            // create test
            test(why, function (t) {
                t.plan(1);

                // hook in custom reporter
                dir.reporter = function (evt) {
                    if (goodCode && evt.pass) {
                        t.ok(true, 'lint passed (' + file + ')');
                    } else {
                        t.ok(!goodCode, 'lint failed (' + file + ')');
                    }
                };

                // create stream
                var str = jslint(dir);

                // read in sample file
                fs.readFile(path.resolve(__dirname, './' + file), function (err, data) {
                    if (err) {
                        t.fail(err);
                    } else {
                        // prepare callback
                        str.on('error', function (err) {
                            err = String(err);

                            if (err.indexOf('failed') === -1) {
                                t.fail(err);
                            }
                        });

                        // push file into stream
                        str.write(new Vinyl({
                            base: __dirname,
                            cwd: path.resolve(__dirname, '../'),
                            path: path.join(__dirname, file),
                            contents: data
                        }));
                    }
                });
            });

            // allow test to expect failure
            return {
                fail: function () {
                    goodCode = false;
                }
            };
        };

    lint('with good code', 'test-good.js');
    lint('with bad code', 'test-nomen.js').fail();
    lint('with directives', 'test-nomen.js', {
        nomen: true
    });
    lint('with good code (with shebang)', 'test-shebang.js', {
        node: true
    });
    lint('with good code (missing globals)', 'test-jquery.js').fail();
    lint('with good code (given globals)', 'test-jquery.js', {
        global: ['$']
    });
    lint('with good code (given predef)', 'test-jquery.js', {
        predef: ['$']
    });

    test('stream support', function (t) {
        t.plan(1);

        var str = jslint();

        str.on('error', function () {
            t.ok(true, 'errored out on stream');
        });

        str.write({
            isStream: function () {
                return true;
            }
        });
    });

    test('null input', function (t) {
        t.plan(1);

        var str = jslint();

        str.on('data', function () {
            t.ok(true, 'ignored null');
        });

        str.on('error', function () {
            t.ok(false, 'errored out on null');
        });

        str.write({
            isStream: function () {
                return false;
            },
            isNull: function () {
                return true;
            }
        });
    });

    test('custom reporter via string', function (t) {
        t.plan(3);

        var str = jslint({
            reporter: path.resolve(__dirname, './test-reporter.js')
        });

        str.on('data', function () {
            t.ok(global.GULP_JSLINT_REPORTER, 'reporter fired');
            t.ok(global.GULP_JSLINT_REPORTER.hasOwnProperty('pass'), 'lint status is in event data');
            t.ok(global.GULP_JSLINT_REPORTER.hasOwnProperty('file'), 'source file is in event data');
        });

        fs.readFile(path.resolve(__dirname, './test-good.js'), function (err, data) {
            if (err) {
                t.fail(err);
            } else {
                str.write(new Vinyl({
                    base: __dirname,
                    cwd: path.resolve(__dirname, '../'),
                    path: path.join(__dirname, 'test-good.js'),
                    contents: data
                }));
            }
        });
    });

    test('custom reporter via function', function (t) {
        t.plan(3);

        var str = jslint({
            reporter: function (evt) {
                t.ok(true, 'reporter fired');
                t.ok(evt.hasOwnProperty('pass'), 'lint status is in event data');
                t.ok(evt.hasOwnProperty('file'), 'source file is in event data');
            }
        });

        fs.readFile(path.resolve(__dirname, './test-good.js'), function (err, data) {
            if (err) {
                t.fail(err);
            } else {
                str.write(new Vinyl({
                    base: __dirname,
                    cwd: path.resolve(__dirname, '../'),
                    path: path.join(__dirname, 'test-good.js'),
                    contents: data
                }));
            }
        });
    });

    test('custom bad reporter (object)', function (t) {
        t.plan(4);

        var str = jslint({
            reporter: {
                what: 'this object should be ignored'
            }
        });

        str.on('error', function (err) {
            var message = strip(String(err));
            t.ok(message.indexOf('Error') > -1, 'valid error');
            t.ok(message.indexOf('gulp-jslint') > -1, 'valid source');
            t.ok(message.indexOf('failed to lint') > -1, 'valid description');
            t.ok(message.indexOf(path.join('test', 'test-nomen.js')) > -1, 'valid filename');
        });

        fs.readFile(path.resolve(__dirname, './test-nomen.js'), function (err, data) {
            if (err) {
                t.fail(err);
            } else {
                str.write(new Vinyl({
                    base: __dirname,
                    cwd: path.resolve(__dirname, '../'),
                    path: path.join(__dirname, 'test-nomen.js'),
                    contents: data
                }));
            }
        });
    });

    test('custom bad reporter (missing module)', function (t) {
        t.plan(1);

        var str = jslint({
            reporter: 'some-random-ass-reporter'
        });

        str.on('error', function () {
            t.ok(true, 'errored out');
        });

        fs.readFile(path.resolve(__dirname, './test-good.js'), function (err, data) {
            if (err) {
                t.fail(err);
            } else {
                str.write(new Vinyl({
                    base: __dirname,
                    cwd: path.resolve(__dirname, '../'),
                    path: path.join(__dirname, 'test-good.js'),
                    contents: data
                }));
            }
        });
    });
}());
<commit_msg>change reporter procedure in unit tests<commit_after>/**
 * test-gulp.jslint
 * Some basic tests to ensure that
 * package is working as intended.
 *
 * Copyright (C) 2014 Karim Alibhai.
 **/

(function () {
    "use strict";

    var fs = require('fs'),
        path = require('path'),
        strip = require('stripcolorcodes'),
        test = require('tape'),
        Vinyl = require('vinyl'),
        jslint = require('../'),
        lint = function (why, file, dir) {
            var goodCode = true;

            // directives
            dir = dir || {};

            // create test
            test(why, function (t) {
                t.plan(1);

                // create stream with custom reporter
                var str = jslint(dir);
                str.pipe(jslint.reporter(function (evt) {
                    if (goodCode && evt.success) {
                        t.ok(true, 'lint passed (' + file + ')');
                    } else {
                        t.ok(!goodCode, 'lint failed (' + file + ')');
                    }
                }));

                // read in sample file
                fs.readFile(path.resolve(__dirname, './' + file), function (err, data) {
                    if (err) {
                        t.fail(err);
                    } else {
                        // prepare callback
                        str.on('error', function (err) {
                            err = String(err);

                            if (err.indexOf('failed') === -1) {
                                t.fail(err);
                            }
                        });

                        // push file into stream
                        str.write(new Vinyl({
                            base: __dirname,
                            cwd: path.resolve(__dirname, '../'),
                            path: path.join(__dirname, file),
                            contents: data
                        }));
                    }
                });
            });

            // allow test to expect failure
            return {
                fail: function () {
                    goodCode = false;
                }
            };
        };

    lint('with good code', 'test-good.js');
    lint('with bad code', 'test-nomen.js').fail();
    lint('with directives', 'test-nomen.js', {
        nomen: true
    });
    lint('with good code (with shebang)', 'test-shebang.js', {
        node: true
    });
    lint('with good code (missing globals)', 'test-jquery.js').fail();
    lint('with good code (given globals)', 'test-jquery.js', {
        global: ['$']
    });
    lint('with good code (given predef)', 'test-jquery.js', {
        predef: ['$']
    });

    test('stream support', function (t) {
        t.plan(1);

        var str = jslint();

        str.on('error', function () {
            t.ok(true, 'errored out on stream');
        });

        str.write({
            isStream: function () {
                return true;
            }
        });
    });

    test('null input', function (t) {
        t.plan(1);

        var str = jslint();

        str.on('data', function () {
            t.ok(true, 'ignored null');
        });

        str.on('error', function () {
            t.ok(false, 'errored out on null');
        });

        str.write({
            isStream: function () {
                return false;
            },
            isNull: function () {
                return true;
            }
        });
    });

    test('custom reporter via string', function (t) {
        t.plan(3);

        var str = jslint();
        str.pipe(jslint.reporter(require('./test-reporter')));

        str.on('data', function () {
            t.ok(!!global.GULP_JSLINT_REPORTER, 'reporter fired');
            t.ok(global.GULP_JSLINT_REPORTER.hasOwnProperty('pass'), 'lint status is in event data');
            t.ok(global.GULP_JSLINT_REPORTER.hasOwnProperty('file'), 'source file is in event data');
        });

        fs.readFile(path.resolve(__dirname, './test-good.js'), function (err, data) {
            if (err) {
                t.fail(err);
            } else {
                str.write(new Vinyl({
                    base: __dirname,
                    cwd: path.resolve(__dirname, '../'),
                    path: path.join(__dirname, 'test-good.js'),
                    contents: data
                }));
            }
        });
    });

    test('custom reporter via function', function (t) {
        t.plan(3);

        var str = jslint({
            reporter: function (evt) {
                t.ok(true, 'reporter fired');
                t.ok(evt.hasOwnProperty('pass'), 'lint status is in event data');
                t.ok(evt.hasOwnProperty('file'), 'source file is in event data');
            }
        });

        fs.readFile(path.resolve(__dirname, './test-good.js'), function (err, data) {
            if (err) {
                t.fail(err);
            } else {
                str.write(new Vinyl({
                    base: __dirname,
                    cwd: path.resolve(__dirname, '../'),
                    path: path.join(__dirname, 'test-good.js'),
                    contents: data
                }));
            }
        });
    });

    test('custom bad reporter (object)', function (t) {
        t.plan(4);

        var str = jslint();
        str.pipe(jslint.reporter({
            what: 'this object should be ignored'
        }));

        str.on('error', function (err) {
            var message = strip(String(err));
            t.ok(message.indexOf('Error') > -1, 'valid error');
            t.ok(message.indexOf('gulp-jslint') > -1, 'valid source');
            t.ok(message.indexOf('failed to lint') > -1, 'valid description');
            t.ok(message.indexOf(path.join('test', 'test-nomen.js')) > -1, 'valid filename');
        });

        fs.readFile(path.resolve(__dirname, './test-nomen.js'), function (err, data) {
            if (err) {
                t.fail(err);
            } else {
                str.write(new Vinyl({
                    base: __dirname,
                    cwd: path.resolve(__dirname, '../'),
                    path: path.join(__dirname, 'test-nomen.js'),
                    contents: data
                }));
            }
        });
    });

    test('custom bad reporter (missing module)', function (t) {
        t.plan(1);

        var str = jslint();
        str.pipe(jslint.reporter('some-random-ass-reporter'));

        str.on('error', function () {
            t.ok(true, 'errored out');
        });

        fs.readFile(path.resolve(__dirname, './test-good.js'), function (err, data) {
            if (err) {
                t.fail(err);
            } else {
                str.write(new Vinyl({
                    base: __dirname,
                    cwd: path.resolve(__dirname, '../'),
                    path: path.join(__dirname, 'test-good.js'),
                    contents: data
                }));
            }
        });
    });
}());
<|endoftext|>


<commit_before>"use strict";

var holidays = {
    neujahr:        {enabled: true,  "en": "New Year's Day",      "de": "Neujahr",                      "ru": "Новый Год",                              desc: "calender",    date: "01.01", offset: 0},
    dreikoenige:    {enabled: true,  "en": "Epiphany",            "de": "Heilige Drei Könige",          "ru": "День трёх Королей",                      desc: "religion",    date: "06.01", offset: 5, comment_en: "(BW, BY, ST)", comment_de: "(BW, BY, ST)", comment_ru: "(BW, BY, ST)"},
    weiberfastnacht:{enabled: true,  "en": "Old Maids' Day",      "de": "Weiberfastnacht",              "ru": "ба́бий четве́рг",                          desc: "calender",    easterOffset: -52},
    rosenmontag:    {enabled: true,  "en": "Rose Monday",         "de": "Rosenmontag",                  "ru": "Розовый понедельник",                    desc: "calender",    easterOffset: -48},
    faschingsdienstag: {enabled: true,  "en": "Mardi Gras",       "de": "Faschingsdienstag",            "ru": "???",                                    desc: "calender",    easterOffset: -47},
    aschermittwoch: {enabled: true,  "en": "Ash Wednesday",       "de": "Aschermittwoch",               "ru": "Пе́пельная среда́",                        desc: "calender",    easterOffset: -46},
    valentinstag:   {enabled: false, "en": "Valentine's Day",     "de": "Valentinstag",                 "ru": "Валенти́нов день",                        desc: "calender",    date: "14.02", offset: 44},
    weltfrauentag:  {enabled: false, "en": "International Women's Day", "de": "Weltfrauentag",          "ru": "междунаро́дный же́нский день",             desc: "political",   date: "08.03", offset: 66},
    palmsonntag:    {enabled: false, "en": "Palm Sunday",         "de": "Palmsonntag",                  "ru": "Ве́рбное Воскресе́нье",                    desc: "religion",    easterOffset: -7},
    gruendonnerstag:{enabled: false, "en": "Holy Thursday",       "de": "Gründonnerstag",               "ru": "Вели́кий четве́рг",                        desc: "religion",    easterOffset: -3},
    karfreitag:     {enabled: true,  "en": "Good Friday",         "de": "Karfreitag",                   "ru": "Великая пятница",                        desc: "religion",    easterOffset: -2},
    ostersonntag:   {enabled: true,  "en": "Easter Sunday",       "de": "Ostersonntag",                 "ru": "Католическая пасха - Воскресение",       desc: "religion",    easterOffset: 0},
    ostermontag:    {enabled: true,  "en": "Easter Monday",       "de": "Ostermontag",                  "ru": "Католическая пасха - Понедельник",       desc: "religion",    easterOffset: 1},
    walpurgisnacht: {enabled: false, "en": "Walpurgis Night",     "de": "Walpurgisnacht",               "ru": "???",                                    desc: "calender",    date: "30.04", offset: 119},
    maifeiertag:    {enabled: true,  "en": "Labour Day",          "de": "Tag der Arbeit", "ru": "День Труда",                             desc: "political",   date: "01.05", offset: 120},
    chimmelfahrt:   {enabled: false, "en": "Ascension of Christ", "de": "Christi Himmelfahrt (Vatertag)", "ru": "Католическое Вознесение ",               desc: "religion",    easterOffset: 39},
    muttertag:      {enabled: false, "en": "Mother's Day",        "de": "Muttertag",                    "ru": "День ма́тери",                            desc: "calender",    april30Offset: 14},
    kindertag:      {enabled: false, "en": "Kid's Day",           "de": "Kindertag",                    "ru": "???",                                    desc: "calender",    date: "01.06", offset: 151},
    pfingstsonntag: {enabled: true,  "en": "Whitsunday",          "de": "Pfingstsonntag",               "ru": "Католическая Троица - Воскресение",      desc: "religion",    easterOffset: 49},
    pfingstmontag:  {enabled: true,  "en": "Whit Monday",         "de": "Pfingstmontag",                "ru": "Католическая Троица - Понедельник",      desc: "religion",    easterOffset: 50},
    siebenschlaefer:{enabled: false, "en": "St Swtithin's Day",   "de": "Siebenschläfertag",            "ru": "сеногно́й",                               desc: "calender",    date: "27.06", offset: 177},
    fronleichnam:   {enabled: false, "en": "Corpus Christi",      "de": "Fronleichnam",                 "ru": "Праздник Тела и Крови Христовых",        desc: "religion",    easterOffset: 60,                       comment_en: "(BW, BY, HE, NW, RP, SL (SA, TH not everywhere))", comment_de: "(BW, BY, HE, NW, RP, SL (SA, TH nicht überall))", comment_ru: "(BW, BY, HE, NW, RP, SL (SA, TH не везде))"},
    friedensfest:   {enabled: false, "en": "Peace Festival",      "de": "Friedensfest",                 "ru": "???",                                    desc: "religion",    date: "08.08", offset: 219},
    mhimmelfahrt:   {enabled: false, "en": "Assumption of Mary",  "de": "Mariä Himmelfahrt",            "ru": "Вознесение Девы Марии",                  desc: "religion",    date: "15.08", offset: 226, comment_en: "(BY (not everywhere), SL)",                        comment_de: "(BY (nicht überall), SL)",                        comment_ru: "(BY (не везде), SL)"},
    michaelistag:   {enabled: false, "en": "Michaelmas",          "de": "Michaelistag",                 "ru": "???",                                    desc: "religion",    date: "29.09", offset: 271},
    erntedankfest:  {enabled: false, "en": "Harvest festival",    "de": "Erntedankfest",                "ru": "пра́здник урожа́я",                        desc: "religion",    michaelisOffset: 7},
    einheitstag:    {enabled: true,  "en": "Day of German unity", "de": "Tag der deutschen Einheit",    "ru": "День объединения Германии",              desc: "political",   date: "03.10", offset: 275},
    autnationaltag: {enabled: false, "en": "National Day Austria","de": "Nationalfeiertag in Österreich", "ru": "Австрийский национальный день",        desc: "political",   date: "26.10", offset: 298},
    reformationstag:{enabled: false, "en": "Reformation Day",     "de": "Reformationstag",              "ru": "День Реформации (Хэллоуин)",             desc: "religion",    date: "31.10", offset: 303, comment_en: "(BB, MV, SA, ST, TH)",                             comment_de: "(BB, MV, SA, ST, TH)",                            comment_ru: "(BB, MV, SA, ST, TH)"},
    allerheiligen:  {enabled: true,  "en": "All Saints' Day",     "de": "Allerheiligen",                "ru": "День всех святых (Хэллоуин)",            desc: "religion",    date: "01.11", offset: 304, comment_en: "(BW, BY, NW, RP, SL)",                             comment_de: "(BW, BY, NW, RP, SL)",                            comment_ru: "(BW, BY, NW, RP, SL)"},
    allerseelen:    {enabled: false, "en": "All Souls' Day",      "de": "Allerseelen",                  "ru": "День Всех Душ",                          desc: "religion",    date: "02.11", offset: 305},
    martinstag:     {enabled: true,  "en": "Saint Martin's Day",  "de": "Martinstag",                   "ru": "???",                                    desc: "religion",    date: "11.11", offset: 314},
    volkstrauertag: {enabled: false, "en": "Remembrance Day",     "de": "Volkstrauertag",               "ru": "???",                                    desc: "political",   advent4Offset: -35},
    bussbettag:     {enabled: true,  "en": "Penance Day",         "de": "Buß- und Bettag",              "ru": "день покая́ния и моли́твы",                desc: "religion",    advent4Offset: -32,             comment_en: "(SA)", comment_de: "(SA)", comment_ru: "(SA)"},
    totensonntag:   {enabled: true,  "en": "Sunday of the Dead",  "de": "Totensonntag",                 "ru": "???",                                    desc: "religion",    advent4Offset: -28},
    nikolaustag:    {enabled: true,  "en": "St Nicholas' Day",    "de": "Nikolaustag",                  "ru": "День Свято́го Никола́я",                   desc: "religion",    date: "06.12", offset: 339},
    advent1:        {enabled: false, "en": "1st Advent",          "de": "1. Advent",                    "ru": "1. адве́нт",                              desc: "religion",    advent4Offset: -21},
    advent2:        {enabled: false, "en": "2nd Advent",          "de": "2. Advent",                    "ru": "2. адве́нт",                              desc: "religion",    advent4Offset: -14},
    advent3:        {enabled: false, "en": "3rd Advent",          "de": "3. Advent",                    "ru": "3. адве́нт",                              desc: "religion",    advent4Offset: -7},
    advent4:        {enabled: false, "en": "4th Advent",          "de": "4. Advent",                    "ru": "4. адве́нт",                              desc: "religion",    advent4Offset: 0},
    heiligabend:    {enabled: true,  "en": "Christmas Eve",       "de": "Heiligabend",                  "ru": "Католическое Рождество",                 desc: "religion",    date: "24.12", offset: 357},
    weihnachtstag1: {enabled: false, "en": "Christmas Day",       "de": "1. Weihnachtstag",             "ru": "Католическое Рождество - Первый день",   desc: "religion",    date: "25.12", offset: 358},
    weihnachtstag2: {enabled: true,  "en": "2nd Christmas Day",   "de": "2. Weihnachtstag",             "ru": "Католическое Рождество - Второй день",   desc: "religion",    date: "26.12", offset: 359},
    silvester:      {enabled: true,  "en": "New Year's Eve",      "de": "Silvester",                    "ru": "Новый год",                              desc: "calender",    date: "31.12", offset: 364}
};

if (typeof module !== "undefined" && module.parent) {
    module.exports = {
        holidays: holidays
    };
}

<commit_msg>Reformation day in more countries<commit_after>"use strict";

var holidays = {
    neujahr:        {enabled: true,  "en": "New Year's Day",      "de": "Neujahr",                      "ru": "Новый Год",                              desc: "calender",    date: "01.01", offset: 0},
    dreikoenige:    {enabled: true,  "en": "Epiphany",            "de": "Heilige Drei Könige",          "ru": "День трёх Королей",                      desc: "religion",    date: "06.01", offset: 5, comment_en: "(BW, BY, ST)", comment_de: "(BW, BY, ST)", comment_ru: "(BW, BY, ST)"},
    weiberfastnacht:{enabled: true,  "en": "Old Maids' Day",      "de": "Weiberfastnacht",              "ru": "ба́бий четве́рг",                          desc: "calender",    easterOffset: -52},
    rosenmontag:    {enabled: true,  "en": "Rose Monday",         "de": "Rosenmontag",                  "ru": "Розовый понедельник",                    desc: "calender",    easterOffset: -48},
    faschingsdienstag: {enabled: true,  "en": "Mardi Gras",       "de": "Faschingsdienstag",            "ru": "???",                                    desc: "calender",    easterOffset: -47},
    aschermittwoch: {enabled: true,  "en": "Ash Wednesday",       "de": "Aschermittwoch",               "ru": "Пе́пельная среда́",                        desc: "calender",    easterOffset: -46},
    valentinstag:   {enabled: false, "en": "Valentine's Day",     "de": "Valentinstag",                 "ru": "Валенти́нов день",                        desc: "calender",    date: "14.02", offset: 44},
    weltfrauentag:  {enabled: false, "en": "International Women's Day", "de": "Weltfrauentag",          "ru": "междунаро́дный же́нский день",             desc: "political",   date: "08.03", offset: 66},
    palmsonntag:    {enabled: false, "en": "Palm Sunday",         "de": "Palmsonntag",                  "ru": "Ве́рбное Воскресе́нье",                    desc: "religion",    easterOffset: -7},
    gruendonnerstag:{enabled: false, "en": "Holy Thursday",       "de": "Gründonnerstag",               "ru": "Вели́кий четве́рг",                        desc: "religion",    easterOffset: -3},
    karfreitag:     {enabled: true,  "en": "Good Friday",         "de": "Karfreitag",                   "ru": "Великая пятница",                        desc: "religion",    easterOffset: -2},
    ostersonntag:   {enabled: true,  "en": "Easter Sunday",       "de": "Ostersonntag",                 "ru": "Католическая пасха - Воскресение",       desc: "religion",    easterOffset: 0},
    ostermontag:    {enabled: true,  "en": "Easter Monday",       "de": "Ostermontag",                  "ru": "Католическая пасха - Понедельник",       desc: "religion",    easterOffset: 1},
    walpurgisnacht: {enabled: false, "en": "Walpurgis Night",     "de": "Walpurgisnacht",               "ru": "???",                                    desc: "calender",    date: "30.04", offset: 119},
    maifeiertag:    {enabled: true,  "en": "Labour Day",          "de": "Tag der Arbeit", "ru": "День Труда",                             desc: "political",   date: "01.05", offset: 120},
    chimmelfahrt:   {enabled: false, "en": "Ascension of Christ", "de": "Christi Himmelfahrt (Vatertag)", "ru": "Католическое Вознесение ",               desc: "religion",    easterOffset: 39},
    muttertag:      {enabled: false, "en": "Mother's Day",        "de": "Muttertag",                    "ru": "День ма́тери",                            desc: "calender",    april30Offset: 14},
    kindertag:      {enabled: false, "en": "Kid's Day",           "de": "Kindertag",                    "ru": "???",                                    desc: "calender",    date: "01.06", offset: 151},
    pfingstsonntag: {enabled: true,  "en": "Whitsunday",          "de": "Pfingstsonntag",               "ru": "Католическая Троица - Воскресение",      desc: "religion",    easterOffset: 49},
    pfingstmontag:  {enabled: true,  "en": "Whit Monday",         "de": "Pfingstmontag",                "ru": "Католическая Троица - Понедельник",      desc: "religion",    easterOffset: 50},
    siebenschlaefer:{enabled: false, "en": "St Swtithin's Day",   "de": "Siebenschläfertag",            "ru": "сеногно́й",                               desc: "calender",    date: "27.06", offset: 177},
    fronleichnam:   {enabled: false, "en": "Corpus Christi",      "de": "Fronleichnam",                 "ru": "Праздник Тела и Крови Христовых",        desc: "religion",    easterOffset: 60,                       comment_en: "(BW, BY, HE, NW, RP, SL (SA, TH not everywhere))", comment_de: "(BW, BY, HE, NW, RP, SL (SA, TH nicht überall))", comment_ru: "(BW, BY, HE, NW, RP, SL (SA, TH не везде))"},
    friedensfest:   {enabled: false, "en": "Peace Festival",      "de": "Friedensfest",                 "ru": "???",                                    desc: "religion",    date: "08.08", offset: 219},
    mhimmelfahrt:   {enabled: false, "en": "Assumption of Mary",  "de": "Mariä Himmelfahrt",            "ru": "Вознесение Девы Марии",                  desc: "religion",    date: "15.08", offset: 226, comment_en: "(BY (not everywhere), SL)",                        comment_de: "(BY (nicht überall), SL)",                        comment_ru: "(BY (не везде), SL)"},
    michaelistag:   {enabled: false, "en": "Michaelmas",          "de": "Michaelistag",                 "ru": "???",                                    desc: "religion",    date: "29.09", offset: 271},
    erntedankfest:  {enabled: false, "en": "Harvest festival",    "de": "Erntedankfest",                "ru": "пра́здник урожа́я",                        desc: "religion",    michaelisOffset: 7},
    einheitstag:    {enabled: true,  "en": "Day of German unity", "de": "Tag der deutschen Einheit",    "ru": "День объединения Германии",              desc: "political",   date: "03.10", offset: 275},
    autnationaltag: {enabled: false, "en": "National Day Austria","de": "Nationalfeiertag in Österreich", "ru": "Австрийский национальный день",        desc: "political",   date: "26.10", offset: 298},
    reformationstag:{enabled: false, "en": "Reformation Day",     "de": "Reformationstag",              "ru": "День Реформации (Хэллоуин)",             desc: "religion",    date: "31.10", offset: 303, comment_en: "(BB, HB, HH, MV, NI, SA, SH, ST, TH)",             comment_de: "(BB, HB, HH, MV, NI, SA, SH, ST, TH)",            comment_ru: "(BB, HB, HH, MV, NI, SA, SH, ST, TH)"},
    allerheiligen:  {enabled: true,  "en": "All Saints' Day",     "de": "Allerheiligen",                "ru": "День всех святых (Хэллоуин)",            desc: "religion",    date: "01.11", offset: 304, comment_en: "(BW, BY, NW, RP, SL)",                             comment_de: "(BW, BY, NW, RP, SL)",                            comment_ru: "(BW, BY, NW, RP, SL)"},
    allerseelen:    {enabled: false, "en": "All Souls' Day",      "de": "Allerseelen",                  "ru": "День Всех Душ",                          desc: "religion",    date: "02.11", offset: 305},
    martinstag:     {enabled: true,  "en": "Saint Martin's Day",  "de": "Martinstag",                   "ru": "???",                                    desc: "religion",    date: "11.11", offset: 314},
    volkstrauertag: {enabled: false, "en": "Remembrance Day",     "de": "Volkstrauertag",               "ru": "???",                                    desc: "political",   advent4Offset: -35},
    bussbettag:     {enabled: true,  "en": "Penance Day",         "de": "Buß- und Bettag",              "ru": "день покая́ния и моли́твы",                desc: "religion",    advent4Offset: -32,             comment_en: "(SA)", comment_de: "(SA)", comment_ru: "(SA)"},
    totensonntag:   {enabled: true,  "en": "Sunday of the Dead",  "de": "Totensonntag",                 "ru": "???",                                    desc: "religion",    advent4Offset: -28},
    nikolaustag:    {enabled: true,  "en": "St Nicholas' Day",    "de": "Nikolaustag",                  "ru": "День Свято́го Никола́я",                   desc: "religion",    date: "06.12", offset: 339},
    advent1:        {enabled: false, "en": "1st Advent",          "de": "1. Advent",                    "ru": "1. адве́нт",                              desc: "religion",    advent4Offset: -21},
    advent2:        {enabled: false, "en": "2nd Advent",          "de": "2. Advent",                    "ru": "2. адве́нт",                              desc: "religion",    advent4Offset: -14},
    advent3:        {enabled: false, "en": "3rd Advent",          "de": "3. Advent",                    "ru": "3. адве́нт",                              desc: "religion",    advent4Offset: -7},
    advent4:        {enabled: false, "en": "4th Advent",          "de": "4. Advent",                    "ru": "4. адве́нт",                              desc: "religion",    advent4Offset: 0},
    heiligabend:    {enabled: true,  "en": "Christmas Eve",       "de": "Heiligabend",                  "ru": "Католическое Рождество",                 desc: "religion",    date: "24.12", offset: 357},
    weihnachtstag1: {enabled: false, "en": "Christmas Day",       "de": "1. Weihnachtstag",             "ru": "Католическое Рождество - Первый день",   desc: "religion",    date: "25.12", offset: 358},
    weihnachtstag2: {enabled: true,  "en": "2nd Christmas Day",   "de": "2. Weihnachtstag",             "ru": "Католическое Рождество - Второй день",   desc: "religion",    date: "26.12", offset: 359},
    silvester:      {enabled: true,  "en": "New Year's Eve",      "de": "Silvester",                    "ru": "Новый год",                              desc: "calender",    date: "31.12", offset: 364}
};

if (typeof module !== "undefined" && module.parent) {
    module.exports = {
        holidays: holidays
    };
}

<|endoftext|>


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

    var TextModel = Backbone.Model.extend({
        defaults: {"num" : 0, "value" : ""},
        replace : function (str) {
          this.set("value", str);
          var currVal = this.get("num");
          this.set("num", currVal+1)
        }

    });

    var TextView = Backbone.View.extend({
        render: function () {
            var counter = this.model.get("num");
            var textVal = this.model.get("value");
            var btn = '<button id="clr">Clear</button>';
            var input = '<input type="text" value="' + textVal + '" />';
            this.$el.html(textVal + "

" + input + btn + "</div" + "
" + counter + "
")
        },
        initialize: function () {
            this.model.on("change", this.render, this);
            // last argument 'this' ensures that render's
            // 'this' means the view, not the model
        },
        events : {
            "click #clr" : "clear",
            "keypress input" : "updateOnEnter"
        },
        replace : function () {
            var str = this.$el.find("input").val();
            this.model.replace(str);
        },
        clear: function () {
            this.model.replace("");
        },
        updateOnEnter: function (e){
            if(e.keyCode == 13) {
                this.replace();
            }
        },
    });

    var TextCollection = Backbone.Collection.extend({
        model : TextModel
    });

    var TextCollectionView = Backbone.View.extend({
        render : function () {
            var btn = '<button id="addbutton">Add Text</button>';
            var div = '

';
            var del = '<button id="del">Delete Last Item</button>';
            this.$el.html(div + btn + del);
        },

        initialize : function () {
            this.listenTo(this.collection, 'add', this.addView);
            this.arr = [];
        },
        events : {
            "click #addbutton" : "addModel",
            "click #del" : "delModel"
        },
        addModel : function () {
            this.collection.add({});
            // collection adds a model, fires add event, then listener calls this.addView(model)
        },
        addView : function (newModel) {
            newModel.set("value","");
            var view = new TextView({model : newModel});
            this.arr.push(view);
            view.render();
            this.$("#text-list").append(view.$el);
        },
        delModel : function () {
            var view = this.arr.pop();
            view.remove();
        }
    });

    var textCollection = new TextCollection();

    var textCollectionView = new TextCollectionView({ collection : textCollection});

    textCollectionView.render();

    $("#listdiv").append(textCollectionView.$el);

});<commit_msg>replaced code with template to display the html<commit_after>
$(document).ready( function () {

    var TextModel = Backbone.Model.extend({
      defaults: {"num" : 0, "value" : "", "lastVal" : ""},
      replace : function (str) {
        this.set("value", str);
        var currVal = this.get("num");
        var currText = this.get("value");
        if (currText !== this.get("lastVal")) {
          this.set("num", currVal+1);
        }
      }
    });

    function useMustacheTemplates() {
              _.templateSettings = {
                  interpolate: /\{\{(.+?)\}\}/g
              };
          }
    useMustacheTemplates();
    var TextView = Backbone.View.extend({

        template: _.template('{{textVal}}

 <input type="text" value="{{textVal}}" /> <button id="clr">Clear</button>

 {{counter}}
'),

        render: function () {
          var data = {counter:this.model.get("num"),
                      textVal:this.model.get("value")};

            //var counter = this.model.get("num");
            //var textVal = this.model.get("value");
            //var btn = '<button id="clr">Clear</button>';
            //var input = '<input type="text" value="' + textVal + '" />';
            //this.$el.html(textVal + "

" + input + btn + "</div" + "
" + counter + "
")

            this.$el.html(this.template(data));
            // $(document.body).append(this.$el);
        },
        initialize: function () {
          this.model.on("change", this.render, this);

            // last argument 'this' ensures that render's
            // 'this' means the view, not the model
        },
        events : {
            "click #clr" : "clear",
            "keypress input" : "updateOnEnter"
        },
        replace : function () {

            var str = this.$el.find("input").val();
            this.model.replace(str);
        },
        clear: function () {
            this.model.set("lastVal", this.model.get("value"));
            this.model.replace("");
        },
        updateOnEnter: function (e){
            if(e.keyCode == 13) {
                this.replace();
            }
        },
    });

    var TextCollection = Backbone.Collection.extend({
        model : TextModel
    });

    var TextCollectionView = Backbone.View.extend({
        render : function () {
            var btn = '<button id="addbutton">Add Text</button>';
            var div = '

';
            var del = '<button id="del">Delete Last Item</button>';
            this.$el.html(div + btn + del);
        },

        initialize : function () {
            this.listenTo(this.collection, 'add', this.addView);
            this.arr = [];
        },
        events : {
            "click #addbutton" : "addModel",
            "click #del" : "delModel"
        },
        addModel : function () {
            this.collection.add({});
            // collection adds a model, fires add event, then listener calls this.addView(model)
        },
        addView : function (newModel) {
            newModel.set("value","");
            var view = new TextView({model : newModel});
            this.arr.push(view);
            view.render();
            this.$("#text-list").append(view.$el);
        },
        delModel : function () {
            var view = this.arr.pop();
            view.remove();
        }
    });

    var textCollection = new TextCollection();

    var textCollectionView = new TextCollectionView({ collection : textCollection});

    textCollectionView.render();

    $("#listdiv").append(textCollectionView.$el);

});<|endoftext|>


<commit_before>"use strict"

const tls = require("tls")
const net = require("net")
const constants = require("constants")

const toPull = require("stream-to-pull-stream")
const toStream = require("pull-stream-to-stream")
const Connection = require("interface-connection").Connection

const OpenSSLGenerator = require("zeronet-crypto/helper").OpenSSLGenerator

const debug = require("debug")
const log = debug("zeronet:crypto:tls")

function pipeThroughNet(dup, cb) {
  const s = net.createServer((socket) => {
    s.close()
    cb(null, socket)
  }).on("error", e => cb(e))
  s.listen(() => {
    const c = net.createConnection(s.address(), () => {
      dup.pipe(c).pipe(dup)
    })
  })
}

module.exports = function TLSSupport(protocol) {

  const gen = new OpenSSLGenerator()

  let rsa_cert
  let rsa_wait = []

  gen.rsa((err, res) => {
    if (err) throw err
    rsa_cert = res
    rsa_wait.forEach(wait => rsa_crypto(wait[0], wait[1], wait[2]))
  })

  const rsa_crypto = (conn, options, cb) => {
    if (options.isServer && !rsa_cert) return rsa_wait.push([conn, options, cb])
    log(options, "tls handshake init", rsa_cert)
    let stream = toStream(conn)
    pipeThroughNet(stream, (err, socket) => {
      if (err) return cb(err)

      const next = err => {
        if (err) return cb(err)
        cb(null, new Connection(toPull.duplex(stream)))
      }

      if (options.isServer) {
        stream = tls.connect({
          socket,
          isServer: true,
          key: rsa_cert.privkey,
          cert: rsa_cert.cert,
          agent: true,
          requestCert: false,
          rejectUnauthorized: false,
          ciphers: "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:AES128-GCM-SHA256:AES128-SHA256:HIGH:" +
            "!aNULL:!eNULL:!EXPORT:!DSS:!DES:!RC4:!3DES:!MD5:!PSK",
          honorCipherOrder: true,
          secureOptions: constants.SSL_OP_NO_SSLv3 | constants.SSL_OP_NO_SSLv2
        }, next)
      } else {
        stream = tls.connect({
          socket,
          isServer: false,
          requestCert: true,
          rejectUnauthorized: false,
          secureOptions: constants.SSL_OP_NO_SSLv3 | constants.SSL_OP_NO_SSLv2
        }, next)
      }
      log("tls ready", options)
      stream.on("error", console.error)
    })
  }
  protocol.crypto.add("tls-rsa", rsa_crypto)
}
<commit_msg>Pass socket error to cb<commit_after>"use strict"

const tls = require("tls")
const net = require("net")
const constants = require("constants")

const toPull = require("stream-to-pull-stream")
const toStream = require("pull-stream-to-stream")
const Connection = require("interface-connection").Connection

const OpenSSLGenerator = require("zeronet-crypto/helper").OpenSSLGenerator

const debug = require("debug")
const log = debug("zeronet:crypto:tls")

function pipeThroughNet(dup, cb) {
  const s = net.createServer((socket) => {
    s.close()
    cb(null, socket)
  }).on("error", e => cb(e))
  s.listen(() => {
    const c = net.createConnection(s.address(), () => {
      dup.pipe(c).pipe(dup)
    })
  })
}

module.exports = function TLSSupport(protocol) {

  const gen = new OpenSSLGenerator()

  let rsa_cert
  let rsa_wait = []

  gen.rsa((err, res) => {
    if (err) throw err
    rsa_cert = res
    rsa_wait.forEach(wait => rsa_crypto(wait[0], wait[1], wait[2]))
  })

  const rsa_crypto = (conn, options, cb) => {
    if (options.isServer && !rsa_cert) return rsa_wait.push([conn, options, cb])
    log(options, "tls handshake init", rsa_cert)
    let stream = toStream(conn)
    pipeThroughNet(stream, (err, socket) => {
      if (err) return cb(err)

      const next = err => {
        if (err) return cb(err)
        cb(null, new Connection(toPull.duplex(stream)))
      }

      if (options.isServer) {
        stream = tls.connect({
          socket,
          isServer: true,
          key: rsa_cert.privkey,
          cert: rsa_cert.cert,
          agent: true,
          requestCert: false,
          rejectUnauthorized: false,
          ciphers: "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:AES128-GCM-SHA256:AES128-SHA256:HIGH:" +
            "!aNULL:!eNULL:!EXPORT:!DSS:!DES:!RC4:!3DES:!MD5:!PSK",
          honorCipherOrder: true,
          secureOptions: constants.SSL_OP_NO_SSLv3 | constants.SSL_OP_NO_SSLv2
        }, next)
      } else {
        stream = tls.connect({
          socket,
          isServer: false,
          requestCert: true,
          rejectUnauthorized: false,
          secureOptions: constants.SSL_OP_NO_SSLv3 | constants.SSL_OP_NO_SSLv2
        }, next)
      }
      log("tls ready", options)
      stream.on("error", e => next(e))
    })
  }
  protocol.crypto.add("tls-rsa", rsa_crypto)
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010 Shoichi Sakane <sakane@tanu.org>, All rights reserved.
 * See the file LICENSE in the top level directory for more details.
 */

//==== DONT TOUCH BELOW ===
//==== INTERNAL USE ===
/*
 * tzOffset: (integer, internally)
 * firstRetrieve: (integer, internally)
 * totalPoints: (integer, internally)
 *     the number of total points in the canvas.
 *     288 points will be plotted if both xrange and updateInterval are default.
 * xtickFormat:
 * xtickSize:
 * flotXAxisBase:
 * flotSeriesBase:
 * flotLegendBase:
 * flotGridBase:
 * errorbarPointStyle:
 */

function print_log(m, critical)
{
  console.log(m);
  if (critical) {
    document.getElementById("divConsole").style.color = "#ff0000";
  } else {
    document.getElementById("divConsole").style.color = "#000000";
  }
  document.getElementById("divConsole").innerHTML = m.bold();
}

function fatal_error(m)
{
  print_log(m, true);
  throw 'aborted';
}

/*
 * initialization
 */
var _wrenDataSet = [];
var _wrenEvTimeout = null;

/*
 * XXX need to check the contents of wrenObj.
 */
function wren_init()
{
  if (typeof(wrenObj) == 'undefined') {
    fatal_error('ERROR: wrenObj.type must be defined.');
  }

  /* check whether type exists */
  if (typeof(wrenObj.type) == 'undefined') {
    console.log('ERROR: wrenObj.type must be defined.');
  }

  /* check type and set query attributes */
  if (wrenObj.type == 'kiwi') {
    kiwi_init(wrenObj);
  } else if (wrenObj.type == 'fiap') {
    fiap_init(wrenObj);
  } else if (wrenObj.type == 'kii') {
    kii_init(wrenObj);
  } else {
    console.log('ERROR: wrenObj.type must be either kiwi, fiap, or kii.');
  }

  /* check wrenObj.tz */
  if (typeof(wrenObj.tz) == 'undefined') {
    wrenObj.tz = 0;
  }
  wrenObj.tzOffset = (wrenObj.tz * 3600000); // wrenObj.tz * 60 * 60 * 1000

  /* check wrenObj.updateInterval and wrenObj.totalPoints */
  if (!wrenObj.hasOwnProperty('updateInterval')) {
    wrenObj.updateInterval = 600000;
  }
  if (!wrenObj.hasOwnProperty('xrange')) {
    wrenObj.xrange = 172800000;
  }
  wrenObj.totalPoints = wrenObj.xrange / wrenObj.updateInterval;

  /*
   * if xrange is more than 2.5 days, the xtick format will be YY/mm/dd,
   * otherwise HH:MM:DD.
   */
  if (wrenObj.xrange >= 889032704) {
    /* 2 months */
    wrenObj.xtickFormat = "%m/%d";
    wrenObj.xtickSize = [ 15, "day" ];
  } else if (wrenObj.xrange >= 216000000) {
    /* 2.5 days */
    wrenObj.xtickFormat = "%H:%M";
    wrenObj.xtickSize = [ 12, "hour" ];
  } else if (wrenObj.xrange >= 86400000) {
    /* 1 day */
    wrenObj.xtickFormat = "%H:%M";
    wrenObj.xtickSize = [ 6, "hour" ];
  } else if (wrenObj.xrange >= 43200000) {
    /* 12 hours */
    wrenObj.xtickFormat = "%H:%M";
    wrenObj.xtickSize = [ 1, "hour" ];
  } else if (wrenObj.xrange >= 3600000) {
    /* 1 hour */
    wrenObj.xtickFormat = "%H:%M";
    wrenObj.xtickSize = [ 15, "minute" ];
  } else {
    wrenObj.xtickFormat = "%H:%M:%S";
    wrenObj.xtickSize = [ wrenObj.xrange / 1000 / 5, "second" ];
  }

  wrenObj.flotXAxisBase = {
    mode: "time",
    timezone: "browser",
    tickSize: wrenObj.xtickSize,
    timeformat: wrenObj.xtickFormat,
  //  tickFormatter: tick_x_format,
  //  minTickSize: [ 20, "second" ],
    axisLabel: "Time",
    axisLabelUseCanvas: true,
    axisLabelFontSizePixels: 10,
    axisLabelFontFamily: 'Verdana, Arial',
    axisLabelPadding: 10
  };

  wrenObj.flotSeriesBase = {
    lines: {
      lineWidth: 1.2
    },
    bars: {
      align: "center",
      fillColor: { colors: [{ opacity: 0.4 }, { opacity: 0.4 }] },
      barWidth: 500,
      lineWidth: 1
    }
  };

  wrenObj.flotLegendBase = {
    noColumns: 0,
    position:"nw"
  };

  wrenObj.flotGridBase = {
    backgroundColor: { colors: ["#ffffff", "#EDF5FF"] }
  };

  wrenObj.errorbarPointStyle = {
    radius: 0,
    errorbars: "y",
    yerr: {
      show:true,
      asymmetric:true,
      upperCap:"-",
      lowerCap:"-",
      radius:5
    } };
}

function dataset_init()
{
  /* clear the dataset */
  for (var i = 0; i < wrenObj.dataDef.length; i++) {
    _wrenDataSet[i] = [];
  }
  wrenObj.firstRetrieve = true;
}

function tick_x_format(v, axis) {
  var date = new Date(v);
  if (date.getSeconds() % xxx == 0) {
    var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    return hours + ":" + minutes + ":" + seconds;
  } else {
    return "";
  }
}

/*
 * @param member a list of indexes, e.g. [ 1, 2 ]
 */
function get_float_axes(member) {
  var v_yaxes = [];
  for (var i = 0; i < member.length; i++) {
    var idx = member[i];
    var d = {
      min: wrenObj.dataDef[idx].min,
      max: wrenObj.dataDef[idx].max,
      tickSize:wrenObj.dataDef[idx].ytick,
      axisLabel: wrenObj.dataDef[idx].unit,
      axisLabelUseCanvas: true,
      axisLabelFontSizePixels: 12,
      axisLabelFontFamily: 'Verdana, Arial',
      axisLabelPadding: 6
    };
    if (wrenObj.dataDef[idx].yaxis == 2)
      d["position"] = "right";
    v_yaxes.push(d);
  }
  return {
    series: wrenObj.flotSeriesBase,
    xaxis: wrenObj.flotXAxisBase,
    yaxes: v_yaxes,
    legend: wrenObj.flotLegendBase,
    grid: wrenObj.flotGridBase,
  };
}

/*
 * @param member a list of indexes, e.g. [ 1, 2 ]
 */
function update_flot_data(member) {
  var ret = [];
  for (var i = 0; i < member.length; i++) {
    var idx = member[i];
//console.log(_wrenDataSet[idx]);
    var dataset = {
      label: wrenObj.dataDef[idx].label + ": " + _wrenDataSet[idx][0][1] + " " + wrenObj.dataDef[idx].unit,
      data: _wrenDataSet[idx],
      lines: { show: true, fill: false, lineWidth: 1.2 },
      color: wrenObj.dataDef[idx].color,
      //clickable: "true",
      //hoverable: "true",
    };
    if (wrenObj.dataDef[idx].yaxis == 2)
      dataset['yaxis'] = 2;
    if (_wrenDataSet[idx][0].length == 4)
      dataset['points'] = wrenObj.errorbarPointStyle;
    ret.push(dataset);
  }
  return ret;
}

/*
 * flotDef: defines a combination of dataDefs.
 *   = [ {
 *         flot: <canvas id>,
 *         set: [ <# of list of dataDefs> ]
 *       }, {...} ]
 */
function update_canvas()
{
  for (var i = 0; i < wrenObj.flotDef.length; i++) {
    var canvas = wrenObj.flotDef[i].flot;
    var dataset = update_flot_data(wrenObj.flotDef[i].set);
    var opt = get_float_axes(wrenObj.flotDef[i].set);
    $.plot($(canvas), dataset, opt);
  }
}

/*
 * dataDef: defines a set of parameter for a single line or points.
 *   = [ {
 *         key: [ <list of keys> ],
 *         label: "<label>",
 *         unit: "<unit>",
 *         color: "<color>",
 *         min: <number>,
 *         max: <number>,
 *         ytick: <number>,
 *         yaxis: <option: 2>
 *     }, {...} ]
 */

/*
 * update the dataset, _wrenDataSet.
 * @param res a list of points in json.
 * @param i index of the target in dataDef.
 * XXX this function needs to be reviewd..
 */
function wren_update_dataset(res, i)
{
  var kvt = [];
  for (var j = 0; j < wrenObj.dataDef[i].key.length; j++) {
    kvt[j] = res[wrenObj.dataDef[i].key[j]];
//console.log('kvt', j, kvt[j]);
  }
  for (var k = 0; k < kvt[0].length; k++) {
    var d = kvt[0][k];
    if (wrenObj.dataDef[i].key.length > 1) {
      /*
       * assuming it's an errorbar chart.
       */
      var y = kvt[0][k][1];
      var found = false;
//console.log('#of res', wrenObj.dataDef[i].key.length);
      for (var j = 1; j < wrenObj.dataDef[i].key.length; j++) {
        for (var q = 0; q < kvt[j].length; q++) {
          if (kvt[j][q][0] == kvt[0][k][0]) {
            found = true;
            z = kvt[j][q][1];
            if (z > y)
              z -= y;
            else
              z = y - z;
            d.push(z);
            break;
          }
        }
        if (wrenObj.dataDef[i].key.length > 1 && found == false) {
          console.log('ERROR: no suitable value for', wrenObj.dataDef[i].key[0], kvt[0][k][0]);
        }
      }
    }
    _wrenDataSet[i].unshift(d);
  }
}

function fill_dataset(i)
{
//console.log('before filled: _wrenDataSet', i, _wrenDataSet[i]);
//console.log('  length', _wrenDataSet[i].length);
  var x = _wrenDataSet[i][_wrenDataSet[i].length - 1][0];
  var jmax = wrenObj.totalPoints - _wrenDataSet[i].length;
  for (var j = 0; j < jmax; j++) {
    var d = [x -= wrenObj.updateInterval];
    for (var k = 0; k < wrenObj.dataDef[i].key.length; k++) {
      d.push(0);
    }
    _wrenDataSet[i].push(d);
  }
//console.log('filled _wrenDataSet[i].length', _wrenDataSet[i].length);
}

/*
 * send a query.
 */
function send_query()
{
  /* call the proper function for query. */
  var q = wrenObj.query.update_query(wrenObj);
  $.ajax({
    url: q.server_url,
    type: wrenObj.query.type,
    cache: false,
    headers: wrenObj.query.headers,
    dataType: wrenObj.query.dataType,
    scriptCharset: wrenObj.query.scriptCharset,
    data: q.query_data,
    success: wrenObj.query.cb_recv_response,
  })
  .fail(function(xhr, status, err) { cb_query_error(xhr, status, err); });
}

function set_timeout()
{
  _wrenEvTimeout = setTimeout(send_query, wrenObj.updateInterval);
}

function cb_query_error(xhr, st, err)
{
  clearTimeout(_wrenEvTimeout);
  var m = "[XMLHttpRequest: " + xhr.st + "]" +
      "[textStatus: " + st + "]" +
      "[errorThrown : " + err.message + "]";
  // XXX it should be done according to the error code from the server.
  if (document.getElementById('inputRetry').checked == true) {
    print_log(m, true);
    set_timeout();
  } else {
    /* abort */
    fatal_error(m);
  }
}

/*
 * dispatcher of the functions to process the response.
 */
function cb_recv_response(res)
{
  clearTimeout(_wrenEvTimeout);
  document.getElementById('divConsole').innerHTML = null;
  /* once it gets multiple data, it will get one data from next time. */
  if (wrenObj.firstRetrieve == true) {
    wrenObj.firstRetrieve = false;
    parse_response_at_once(res);
  }
  else {
    parse_response(res);
  }
  // XXX should it be done here ?
  query_clear_state(wrenObj);
}

/*
 * it deals with one record.
 * callback function to parse the response.
 * update the data set and canvas.
 */
function parse_response(res)
{
  /* parse the response */
  res = wren_obj_canonicalize(res, wrenObj.tzOffset);
  for (var i = 0; i < wrenObj.dataDef.length; i++) {
    _wrenDataSet[i].pop();  // remove the oldest record.
    wren_update_dataset(res, i);
  }
  update_canvas();
  set_timeout();
}

/*
 * it deals with all records in the duratoin.
 * callback function to parse the response at once.
 * update the data set and canvas.
 */
function parse_response_at_once(res)
{
  /* parse the response */
  res = wren_obj_canonicalize(res, wrenObj.tzOffset);
  for (var i = 0; i < wrenObj.dataDef.length; i++) {
    wren_update_dataset(res, i);
    fill_dataset(i);
  }
  update_canvas();
  set_timeout();
}

/********
 *
 * callback for events.
 */

function ev_click_start()
{
  clearTimeout(_wrenEvTimeout);
  if (document.getElementById('inputRefresh').checked == true) {
    dataset_init();
  }
  send_query();
}

function ev_click_stop()
{
  clearTimeout(_wrenEvTimeout);
}

/* this function may be overrided. */
function ev_init_local()
{
  /* dummy */
}

function ev_init()
{
  document.getElementById('btnStop').addEventListener('click', ev_click_stop, false);
  document.getElementById('btnStart').addEventListener('click', ev_click_start, false);

  /* it's for localization */
  ev_init_local()
}

$(document).ready(function() {
  wren_init();
  dataset_init();
  ev_init();
});
<commit_msg>a debug code was deleted.<commit_after>/*
 * Copyright (C) 2010 Shoichi Sakane <sakane@tanu.org>, All rights reserved.
 * See the file LICENSE in the top level directory for more details.
 */

//==== DONT TOUCH BELOW ===
//==== INTERNAL USE ===
/*
 * tzOffset: (integer, internally)
 * firstRetrieve: (integer, internally)
 * totalPoints: (integer, internally)
 *     the number of total points in the canvas.
 *     288 points will be plotted if both xrange and updateInterval are default.
 * xtickFormat:
 * xtickSize:
 * flotXAxisBase:
 * flotSeriesBase:
 * flotLegendBase:
 * flotGridBase:
 * errorbarPointStyle:
 */

function print_log(m, critical)
{
  if (critical) {
    document.getElementById("divConsole").style.color = "#ff0000";
  } else {
    document.getElementById("divConsole").style.color = "#000000";
  }
  document.getElementById("divConsole").innerHTML = m.bold();
}

function fatal_error(m)
{
  print_log(m, true);
  throw 'aborted';
}

/*
 * initialization
 */
var _wrenDataSet = [];
var _wrenEvTimeout = null;

/*
 * XXX need to check the contents of wrenObj.
 */
function wren_init()
{
  if (typeof(wrenObj) == 'undefined') {
    fatal_error('ERROR: wrenObj.type must be defined.');
  }

  /* check whether type exists */
  if (typeof(wrenObj.type) == 'undefined') {
    console.log('ERROR: wrenObj.type must be defined.');
  }

  /* check type and set query attributes */
  if (wrenObj.type == 'kiwi') {
    kiwi_init(wrenObj);
  } else if (wrenObj.type == 'fiap') {
    fiap_init(wrenObj);
  } else if (wrenObj.type == 'kii') {
    kii_init(wrenObj);
  } else {
    console.log('ERROR: wrenObj.type must be either kiwi, fiap, or kii.');
  }

  /* check wrenObj.tz */
  if (typeof(wrenObj.tz) == 'undefined') {
    wrenObj.tz = 0;
  }
  wrenObj.tzOffset = (wrenObj.tz * 3600000); // wrenObj.tz * 60 * 60 * 1000

  /* check wrenObj.updateInterval and wrenObj.totalPoints */
  if (!wrenObj.hasOwnProperty('updateInterval')) {
    wrenObj.updateInterval = 600000;
  }
  if (!wrenObj.hasOwnProperty('xrange')) {
    wrenObj.xrange = 172800000;
  }
  wrenObj.totalPoints = wrenObj.xrange / wrenObj.updateInterval;

  /*
   * if xrange is more than 2.5 days, the xtick format will be YY/mm/dd,
   * otherwise HH:MM:DD.
   */
  if (wrenObj.xrange >= 889032704) {
    /* 2 months */
    wrenObj.xtickFormat = "%m/%d";
    wrenObj.xtickSize = [ 15, "day" ];
  } else if (wrenObj.xrange >= 216000000) {
    /* 2.5 days */
    wrenObj.xtickFormat = "%H:%M";
    wrenObj.xtickSize = [ 12, "hour" ];
  } else if (wrenObj.xrange >= 86400000) {
    /* 1 day */
    wrenObj.xtickFormat = "%H:%M";
    wrenObj.xtickSize = [ 6, "hour" ];
  } else if (wrenObj.xrange >= 43200000) {
    /* 12 hours */
    wrenObj.xtickFormat = "%H:%M";
    wrenObj.xtickSize = [ 1, "hour" ];
  } else if (wrenObj.xrange >= 3600000) {
    /* 1 hour */
    wrenObj.xtickFormat = "%H:%M";
    wrenObj.xtickSize = [ 15, "minute" ];
  } else {
    wrenObj.xtickFormat = "%H:%M:%S";
    wrenObj.xtickSize = [ wrenObj.xrange / 1000 / 5, "second" ];
  }

  wrenObj.flotXAxisBase = {
    mode: "time",
    timezone: "browser",
    tickSize: wrenObj.xtickSize,
    timeformat: wrenObj.xtickFormat,
  //  tickFormatter: tick_x_format,
  //  minTickSize: [ 20, "second" ],
    axisLabel: "Time",
    axisLabelUseCanvas: true,
    axisLabelFontSizePixels: 10,
    axisLabelFontFamily: 'Verdana, Arial',
    axisLabelPadding: 10
  };

  wrenObj.flotSeriesBase = {
    lines: {
      lineWidth: 1.2
    },
    bars: {
      align: "center",
      fillColor: { colors: [{ opacity: 0.4 }, { opacity: 0.4 }] },
      barWidth: 500,
      lineWidth: 1
    }
  };

  wrenObj.flotLegendBase = {
    noColumns: 0,
    position:"nw"
  };

  wrenObj.flotGridBase = {
    backgroundColor: { colors: ["#ffffff", "#EDF5FF"] }
  };

  wrenObj.errorbarPointStyle = {
    radius: 0,
    errorbars: "y",
    yerr: {
      show:true,
      asymmetric:true,
      upperCap:"-",
      lowerCap:"-",
      radius:5
    } };
}

function dataset_init()
{
  /* clear the dataset */
  for (var i = 0; i < wrenObj.dataDef.length; i++) {
    _wrenDataSet[i] = [];
  }
  wrenObj.firstRetrieve = true;
}

function tick_x_format(v, axis) {
  var date = new Date(v);
  if (date.getSeconds() % xxx == 0) {
    var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    return hours + ":" + minutes + ":" + seconds;
  } else {
    return "";
  }
}

/*
 * @param member a list of indexes, e.g. [ 1, 2 ]
 */
function get_float_axes(member) {
  var v_yaxes = [];
  for (var i = 0; i < member.length; i++) {
    var idx = member[i];
    var d = {
      min: wrenObj.dataDef[idx].min,
      max: wrenObj.dataDef[idx].max,
      tickSize:wrenObj.dataDef[idx].ytick,
      axisLabel: wrenObj.dataDef[idx].unit,
      axisLabelUseCanvas: true,
      axisLabelFontSizePixels: 12,
      axisLabelFontFamily: 'Verdana, Arial',
      axisLabelPadding: 6
    };
    if (wrenObj.dataDef[idx].yaxis == 2)
      d["position"] = "right";
    v_yaxes.push(d);
  }
  return {
    series: wrenObj.flotSeriesBase,
    xaxis: wrenObj.flotXAxisBase,
    yaxes: v_yaxes,
    legend: wrenObj.flotLegendBase,
    grid: wrenObj.flotGridBase,
  };
}

/*
 * @param member a list of indexes, e.g. [ 1, 2 ]
 */
function update_flot_data(member) {
  var ret = [];
  for (var i = 0; i < member.length; i++) {
    var idx = member[i];
//console.log(_wrenDataSet[idx]);
    var dataset = {
      label: wrenObj.dataDef[idx].label + ": " + _wrenDataSet[idx][0][1] + " " + wrenObj.dataDef[idx].unit,
      data: _wrenDataSet[idx],
      lines: { show: true, fill: false, lineWidth: 1.2 },
      color: wrenObj.dataDef[idx].color,
      //clickable: "true",
      //hoverable: "true",
    };
    if (wrenObj.dataDef[idx].yaxis == 2)
      dataset['yaxis'] = 2;
    if (_wrenDataSet[idx][0].length == 4)
      dataset['points'] = wrenObj.errorbarPointStyle;
    ret.push(dataset);
  }
  return ret;
}

/*
 * flotDef: defines a combination of dataDefs.
 *   = [ {
 *         flot: <canvas id>,
 *         set: [ <# of list of dataDefs> ]
 *       }, {...} ]
 */
function update_canvas()
{
  for (var i = 0; i < wrenObj.flotDef.length; i++) {
    var canvas = wrenObj.flotDef[i].flot;
    var dataset = update_flot_data(wrenObj.flotDef[i].set);
    var opt = get_float_axes(wrenObj.flotDef[i].set);
    $.plot($(canvas), dataset, opt);
  }
}

/*
 * dataDef: defines a set of parameter for a single line or points.
 *   = [ {
 *         key: [ <list of keys> ],
 *         label: "<label>",
 *         unit: "<unit>",
 *         color: "<color>",
 *         min: <number>,
 *         max: <number>,
 *         ytick: <number>,
 *         yaxis: <option: 2>
 *     }, {...} ]
 */

/*
 * update the dataset, _wrenDataSet.
 * @param res a list of points in json.
 * @param i index of the target in dataDef.
 * XXX this function needs to be reviewd..
 */
function wren_update_dataset(res, i)
{
  var kvt = [];
  for (var j = 0; j < wrenObj.dataDef[i].key.length; j++) {
    kvt[j] = res[wrenObj.dataDef[i].key[j]];
//console.log('kvt', j, kvt[j]);
  }
  for (var k = 0; k < kvt[0].length; k++) {
    var d = kvt[0][k];
    if (wrenObj.dataDef[i].key.length > 1) {
      /*
       * assuming it's an errorbar chart.
       */
      var y = kvt[0][k][1];
      var found = false;
//console.log('#of res', wrenObj.dataDef[i].key.length);
      for (var j = 1; j < wrenObj.dataDef[i].key.length; j++) {
        for (var q = 0; q < kvt[j].length; q++) {
          if (kvt[j][q][0] == kvt[0][k][0]) {
            found = true;
            z = kvt[j][q][1];
            if (z > y)
              z -= y;
            else
              z = y - z;
            d.push(z);
            break;
          }
        }
        if (wrenObj.dataDef[i].key.length > 1 && found == false) {
          console.log('ERROR: no suitable value for', wrenObj.dataDef[i].key[0], kvt[0][k][0]);
        }
      }
    }
    _wrenDataSet[i].unshift(d);
  }
}

function fill_dataset(i)
{
//console.log('before filled: _wrenDataSet', i, _wrenDataSet[i]);
//console.log('  length', _wrenDataSet[i].length);
  var x = _wrenDataSet[i][_wrenDataSet[i].length - 1][0];
  var jmax = wrenObj.totalPoints - _wrenDataSet[i].length;
  for (var j = 0; j < jmax; j++) {
    var d = [x -= wrenObj.updateInterval];
    for (var k = 0; k < wrenObj.dataDef[i].key.length; k++) {
      d.push(0);
    }
    _wrenDataSet[i].push(d);
  }
//console.log('filled _wrenDataSet[i].length', _wrenDataSet[i].length);
}

/*
 * send a query.
 */
function send_query()
{
  /* call the proper function for query. */
  var q = wrenObj.query.update_query(wrenObj);
  $.ajax({
    url: q.server_url,
    type: wrenObj.query.type,
    cache: false,
    headers: wrenObj.query.headers,
    dataType: wrenObj.query.dataType,
    scriptCharset: wrenObj.query.scriptCharset,
    data: q.query_data,
    success: wrenObj.query.cb_recv_response,
  })
  .fail(function(xhr, status, err) { cb_query_error(xhr, status, err); });
}

function set_timeout()
{
  _wrenEvTimeout = setTimeout(send_query, wrenObj.updateInterval);
}

function cb_query_error(xhr, st, err)
{
  clearTimeout(_wrenEvTimeout);
  var m = "[XMLHttpRequest: " + xhr.st + "]" +
      "[textStatus: " + st + "]" +
      "[errorThrown : " + err.message + "]";
  // XXX it should be done according to the error code from the server.
  if (document.getElementById('inputRetry').checked == true) {
    print_log(m, true);
    set_timeout();
  } else {
    /* abort */
    fatal_error(m);
  }
}

/*
 * dispatcher of the functions to process the response.
 */
function cb_recv_response(res)
{
  clearTimeout(_wrenEvTimeout);
  document.getElementById('divConsole').innerHTML = null;
  /* once it gets multiple data, it will get one data from next time. */
  if (wrenObj.firstRetrieve == true) {
    wrenObj.firstRetrieve = false;
    parse_response_at_once(res);
  }
  else {
    parse_response(res);
  }
  // XXX should it be done here ?
  query_clear_state(wrenObj);
}

/*
 * it deals with one record.
 * callback function to parse the response.
 * update the data set and canvas.
 */
function parse_response(res)
{
  /* parse the response */
  res = wren_obj_canonicalize(res, wrenObj.tzOffset);
  for (var i = 0; i < wrenObj.dataDef.length; i++) {
    _wrenDataSet[i].pop();  // remove the oldest record.
    wren_update_dataset(res, i);
  }
  update_canvas();
  set_timeout();
}

/*
 * it deals with all records in the duratoin.
 * callback function to parse the response at once.
 * update the data set and canvas.
 */
function parse_response_at_once(res)
{
  /* parse the response */
  res = wren_obj_canonicalize(res, wrenObj.tzOffset);
  for (var i = 0; i < wrenObj.dataDef.length; i++) {
    wren_update_dataset(res, i);
    fill_dataset(i);
  }
  update_canvas();
  set_timeout();
}

/********
 *
 * callback for events.
 */

function ev_click_start()
{
  clearTimeout(_wrenEvTimeout);
  if (document.getElementById('inputRefresh').checked == true) {
    dataset_init();
  }
  send_query();
}

function ev_click_stop()
{
  clearTimeout(_wrenEvTimeout);
}

/* this function may be overrided. */
function ev_init_local()
{
  /* dummy */
}

function ev_init()
{
  document.getElementById('btnStop').addEventListener('click', ev_click_stop, false);
  document.getElementById('btnStart').addEventListener('click', ev_click_start, false);

  /* it's for localization */
  ev_init_local()
}

$(document).ready(function() {
  wren_init();
  dataset_init();
  ev_init();
});
<|endoftext|>


<commit_before>(() => {
    'use strict';

    angular
        .module('app')
        .controller('sidebarCtrl', sidebarCtrl);

    function sidebarCtrl($scope) {

        $scope.leftSidebarSchema = [{
            name: 'Система досягнень',
            route: '',
            submenu: [
                {
                    name: 'Початківці',
                    route: ''
                }, {
                    name: 'Відкривачі',
                    route: ''
                }, {
                    name: 'Слідопити',
                    route: ''
                }, {
                    name: 'Рейнджери',
                    route: ''
                }, {
                    name: 'Командири',
                    route: ''
                }
            ]
        }, {
            name: 'Мої нагороди',
            route: '',
            submenu: [
                {
                    name: 'Медалі',
                    route: ''
                }, {
                    name: 'Планки',
                    route: ''
                }, {
                    name: 'За табори',
                    route: ''
                }, {
                    name: 'За походи',
                    route: ''
                }, {
                    name: 'Зірки',
                    route: ''
                }, {
                    name: 'Чверть/рік',
                    route: ''
                }, {
                    name: 'Начання',
                    route: ''
                }
            ]
        }, {
            name: 'Виконую',
            route: ''
        }, {
            name: 'Адмініструю',
            route: ''
        }, {
            name: 'Мій загін',
            route: ''
        }, {
            name: 'Мої друзі',
            route: ''
        }, {
            name: 'Бібліотека',
            route: '#/library'
        }, {
            name: 'Налаштування',
            route: '#/settings'
        }, {
            name: 'Тех.підтримка',
            route: ''
        }, {
            name: 'Створити',
            route: ''
        }];
    }
})();<commit_msg>add menu link<commit_after>(() => {
    'use strict';

    angular
        .module('app')
        .controller('sidebarCtrl', sidebarCtrl);

    function sidebarCtrl($scope) {

        $scope.leftSidebarSchema = [{
            name: 'Система досягнень',
            route: '',
            submenu: [
                {
                    name: 'Початківці',
                    route: ''
                }, {
                    name: 'Відкривачі',
                    route: ''
                }, {
                    name: 'Слідопити',
                    route: ''
                }, {
                    name: 'Рейнджери',
                    route: ''
                }, {
                    name: 'Командири',
                    route: ''
                }
            ]
        }, {
            name: 'Мої нагороди',
            route: '',
            submenu: [
                {
                    name: 'Медалі',
                    route: ''
                }, {
                    name: 'Планки',
                    route: ''
                }, {
                    name: 'За табори',
                    route: ''
                }, {
                    name: 'За походи',
                    route: ''
                }, {
                    name: 'Зірки',
                    route: ''
                }, {
                    name: 'Чверть/рік',
                    route: ''
                }, {
                    name: 'Начання',
                    route: ''
                }
            ]
        }, {
            name: 'Виконую',
            route: ''
        }, {
            name: 'Адмініструю',
            route: ''
        }, {
            name: 'Мій загін',
            route: ''
        }, {
            name: 'Мої друзі',
            route: ''
        }, {
            name: 'Бібліотека',
            route: '#/library'
        }, {
            name: 'Налаштування',
            route: '#/settings'
        }, {
            name: 'Підтвердити',
            route: '#/confirm-users'
        }, {
            name: 'Тех.підтримка',
            route: ''
        }, {
            name: 'Створити',
            route: ''
        }];
    }
})();<|endoftext|>


<commit_before>var fs = require('fs-extra');
var gpio = require('rpi-gpio');
var SPI = require('spi');
var config = require('nconf');
var async = require("async");
var leds = require("./modules/leds.js");
var audio = require("./modules/mic.js");
var PythonShell = require('python-shell');
var tempSensor = require("./modules/am2302.js");
var gasSensors = require("./modules/gasSensors.js");
var usbDevices = require("./modules/usbDevices.js");
var mainInterval;
var mainLoopTime = 60000;
var timolo;
// NOTE: options for setting up pi-timolo
var timoloOptions = {
  mode: 'json',
  scriptPath: '/home/pi/pi-timolo'
};

config.use('file', { file: './config/default.json' });

// var faultStatus = {
//   "AM2302":true,
// "ext1":true,
// "ext2":true,
// "ext3":true,
// "wlan0":true,
// "wlan1":true,
// "imei":true,
// "iccid":true,
// "mic":true,
// "MQ7":true,
// "MQ135":true,
// "Camera":true,
// "Ethernet":true
// }
// NOTE: setup LEDS
leds.setup(gpio);

///////////////////// EVENTS /////////////////////////
// NOTE: register events from gas sensors
gasSensors.events.on('data', function(sensorData) {
  //console.log('gasSensors have data');
  console.log(JSON.stringify(sensorData));
})
audio.events.on('data',function(audioData){
  console.log(JSON.stringify(audioData));
})
// NOTE: register timolo message event
timolo.on('message', function (message) {
  // received a message sent from the Python script (a simple "print" statement)
  console.log("Timolo " + message.hasOwnProperty('timolo'));
  console.log("Motion " + message.hasOwnProperty('motion'));
  console.log("Timelapse " + message.hasOwnProperty('timelapse'));
  console.log(message);
});
timolo.on('error', function (message) {
  console.error(message);
});
timolo.on('close', function (message) {
  console.log(message);
});
//////////////////////////////////////////////////////

//NOTE: Empty timolo directories
fs.emptyDir('/home/pi/pi-timolo/motion', function (err) {
  if (!err) console.log('success!')
})
fs.emptyDir('/home/pi/pi-timolo/timelapse', function (err) {
  if (!err) console.log('success!')
})

async.series({
    am2302: function(callback){
      // NOTE: setup tempSensor
      tempSensor.setup(gpio,function(err){
        if(err){
          console.log("AM2302 failed to initialize");
        }else{
          leds.setFaultStatus("AM2302",true);
          //console.log("tempSensor ready");
          callback(null, true);
        }
      });
    },
    ext: function(callback){
        callback(null, false);
    },
    usb: function(callback){
      usbDevices.deviceIds(function(err,results){
        if(err){
          console.error(err);
          callback(null,false);
        }else{
          //console.log(JSON.stringify(results));
          callback(null, results);
        }
      });
    },
    mic: function(callback){
      audio.setup(SPI,function(status){
        callback(null, status);
      })
    },
    gas: function(callback){
        // NOTE: setup gas sensor
        gasSensors.setup(gpio,SPI,function(result){
          //console.log("waiting for gas sensors");
          callback(null, result);
        });
    },
    camera: function(callback){
      // NOTE: create timolo instance
        timolo = new PythonShell('pi-timolo.py',options);
        timolo.on('message', function (message) {
          if(message.hasOwnProperty('timolo')){
            callback(null, true);
          }
        }
        timolo.on('error', function (message) {
          //console.error(message);
          callback(null, false);
        });
    },
    ethernet: function(callback){
        callback(null, false);
    }
},
function(err, results) {
    // results is now equal to: {am2302: 1, ext: 2...}
    if(err) console.error(err);
    console.log(JSON.stringify(results));
});

// usbDevices.deviceIds(function(err,results){
//   if(err){
//     console.error(err);
//   }else{
//     console.log(JSON.stringify(results));
//   }
// });

function on_exit(){
     console.log('Process Exit');
     //pfio.deinit();
     //monitor.stop();
     //rfid.kill("SIGINT");
     process.exit(0)
 }

 process.on('SIGINT',on_exit);

// NOTE: setup main loop interval
mainInterval = setInterval(mainLoop,mainLoopTime);

// NOTE: function that runs when the main interval expires
function mainLoop(){
  var tempReading = tempSensor.read();
  console.log("Temp: "+tempReading.temperature.toFixed(1) + " Humidity: "+tempReading.humidity.toFixed(1));
}
<commit_msg>updated junctionbox with timolo<commit_after>var fs = require('fs-extra');
var gpio = require('rpi-gpio');
var SPI = require('spi');
var config = require('nconf');
var async = require("async");
var leds = require("./modules/leds.js");
var audio = require("./modules/mic.js");
var PythonShell = require('python-shell');
var tempSensor = require("./modules/am2302.js");
var gasSensors = require("./modules/gasSensors.js");
var usbDevices = require("./modules/usbDevices.js");
var mainInterval;
var mainLoopTime = 60000;
var timolo;
// NOTE: options for setting up pi-timolo
var timoloOptions = {
  mode: 'json',
  scriptPath: '/home/pi/pi-timolo'
};

config.use('file', { file: './config/default.json' });

// var faultStatus = {
//   "AM2302":true,
// "ext1":true,
// "ext2":true,
// "ext3":true,
// "wlan0":true,
// "wlan1":true,
// "imei":true,
// "iccid":true,
// "mic":true,
// "MQ7":true,
// "MQ135":true,
// "Camera":true,
// "Ethernet":true
// }
// NOTE: setup LEDS
leds.setup(gpio);

///////////////////// EVENTS /////////////////////////
// NOTE: register events from gas sensors
gasSensors.events.on('data', function(sensorData) {
  //console.log('gasSensors have data');
  console.log(JSON.stringify(sensorData));
})
audio.events.on('data',function(audioData){
  console.log(JSON.stringify(audioData));
})
// NOTE: register timolo message event
timolo.on('message', function (message) {
  // received a message sent from the Python script (a simple "print" statement)
  console.log("Timolo " + message.hasOwnProperty('timolo'));
  console.log("Motion " + message.hasOwnProperty('motion'));
  console.log("Timelapse " + message.hasOwnProperty('timelapse'));
  console.log(message);
});
timolo.on('error', function (message) {
  console.error(message);
});
timolo.on('close', function (message) {
  console.log(message);
});
//////////////////////////////////////////////////////

//NOTE: Empty timolo directories
fs.emptyDir('/home/pi/pi-timolo/motion', function (err) {
  if (!err) console.log('success!')
})
fs.emptyDir('/home/pi/pi-timolo/timelapse', function (err) {
  if (!err) console.log('success!')
})

async.series({
    am2302: function(callback){
      // NOTE: setup tempSensor
      tempSensor.setup(gpio,function(err){
        if(err){
          console.log("AM2302 failed to initialize");
        }else{
          leds.setFaultStatus("AM2302",true);
          //console.log("tempSensor ready");
          callback(null, true);
        }
      });
    },
    ext: function(callback){
        callback(null, false);
    },
    usb: function(callback){
      usbDevices.deviceIds(function(err,results){
        if(err){
          console.error(err);
          callback(null,false);
        }else{
          //console.log(JSON.stringify(results));
          callback(null, results);
        }
      });
    },
    mic: function(callback){
      audio.setup(SPI,function(status){
        callback(null, status);
      })
    },
    gas: function(callback){
        // NOTE: setup gas sensor
        gasSensors.setup(gpio,SPI,function(result){
          //console.log("waiting for gas sensors");
          callback(null, result);
        });
    },
    camera: function(callback){
      // NOTE: create timolo instance
        timolo = new PythonShell('pi-timolo.py',options);
        timolo.on('message', function (message) {
          if(message.hasOwnProperty('timolo')){
            callback(null, true);
          }
        });
        timolo.on('error', function (message) {
          //console.error(message);
          callback(null, false);
        });
    },
    ethernet: function(callback){
        callback(null, false);
    }
},
function(err, results) {
    // results is now equal to: {am2302: 1, ext: 2...}
    if(err) console.error(err);
    console.log(JSON.stringify(results));
});

// usbDevices.deviceIds(function(err,results){
//   if(err){
//     console.error(err);
//   }else{
//     console.log(JSON.stringify(results));
//   }
// });

function on_exit(){
     console.log('Process Exit');
     //pfio.deinit();
     //monitor.stop();
     //rfid.kill("SIGINT");
     process.exit(0)
 }

 process.on('SIGINT',on_exit);

// NOTE: setup main loop interval
mainInterval = setInterval(mainLoop,mainLoopTime);

// NOTE: function that runs when the main interval expires
function mainLoop(){
  var tempReading = tempSensor.read();
  console.log("Temp: "+tempReading.temperature.toFixed(1) + " Humidity: "+tempReading.humidity.toFixed(1));
}
<|endoftext|>