<commit_before>'use strict';

/**
 * @module main
 */

/* core module */
var util = require('util');

/* local modules */
var tools = require('./tools.js');
var Request = require('./request.js');

/**
 * Constructs a Request object for wrapping your own HTTP method / functionality
 *
 * @param {module:request~options} options The options Object taken by the {@link module:request~Request} constructor
 * @returns {module:request~Request} A new instance of the {@link module:request~Request} class
 */
exports.createHttpClient = function(options) {
	return new Request(options);
};

/**
 * HTTP GET method wrapper
 *
 * @param {module:request~options} options The options Object taken by the {@link Request} constructor, filtered by {@link module:tools.shortHand}. options.method = 'GET' and it can not be overridden
 * @param {module:main~callback} callback Completion callback
 */
exports.get = function(options, file, callback) {
	if (!callback) {
		callback = file;
		file = false;
	}

	options = tools.shortHand(options, 'get');
	var request = new Request(options);
	tools.checkCallback(callback, request.options.url);

	request.send(function(err, res) {
		if (err) {
			callback(err);
			return;
		}

		if (options.stream === true) {
			callback(null, request.stdResult());
			return;
		}

		switch (file) {
			case false:
				// buffer
				request.saveBuffer(function(err) {
					if (err) {
						callback(err);
						return;
					}

					callback(null, request.stdResult());
				});
				break;

			case null:
				// simulate writing to /dev/null, carefully under node.js v0.10
				callback(null, request.stdResult());
				res.response.resume();
				break;

			default:
				// save to file
				if (typeof file !== 'string') {
					throw tools.formatError('Expecting a file path for saving the object from URL: %s.', options.url);
				}

				request.saveFile(file, function(err) {
					if (err) {
						callback(err);
						return;
					}

					callback(null, request.stdResult());
				});
				break;
		}
	});
};

/**
 * HTTP HEAD method wrapper
 *
 * @param {module:request~options} options The options Object taken by the {@link Request} constructor, filtered by {@link module:tools.shortHand}. options.method = 'HEAD' and it can not be overridden
 * @param {module:main~callback} callback Completion callback
 */
exports.head = function(options, callback) {
	options = tools.shortHand(options, 'head');
	var request = new Request(options);
	tools.checkCallback(callback, request.options.url);

	request.send(function(err, res) {
		if (err) {
			callback(err);
			return;
		}

		callback(null, request.stdResult());
		res.response.resume();
	});
};

// documentation section

/**
 * Describes the callback passed to each HTTP method wrapper
 *
 * @callback module:main~callback
 * @param {module:request~stdError} error The standard error or *null* on success
 * @param {module:request~stdResult} result The standard result object if error is null
 */
<commit_msg>Implemented the setMaxSockets method.<commit_after>'use strict';

/**
 * @module main
 */

/* core modules */
var util = require('util');
var http = require('http');

/* local modules */
var tools = require('./tools.js');
var Request = require('./request.js');

/**
 * Constructs a Request object for wrapping your own HTTP method / functionality
 *
 * @param {module:request~options} options The options Object taken by the {@link module:request~Request} constructor
 * @returns {module:request~Request} A new instance of the {@link module:request~Request} class
 */
exports.createHttpClient = function(options) {
	return new Request(options);
};

/**
 * HTTP GET method wrapper
 *
 * @param {module:request~options} options The options Object taken by the {@link Request} constructor, filtered by {@link module:tools.shortHand}. options.method = 'GET' and it can not be overridden
 * @param {module:main~callback} callback Completion callback
 */
exports.get = function(options, file, callback) {
	if (!callback) {
		callback = file;
		file = false;
	}

	options = tools.shortHand(options, 'get');
	var request = new Request(options);
	tools.checkCallback(callback, request.options.url);

	request.send(function(err, res) {
		if (err) {
			callback(err);
			return;
		}

		if (options.stream === true) {
			callback(null, request.stdResult());
			return;
		}

		switch (file) {
			case false:
				// buffer
				request.saveBuffer(function(err) {
					if (err) {
						callback(err);
						return;
					}

					callback(null, request.stdResult());
				});
				break;

			case null:
				// simulate writing to /dev/null, carefully under node.js v0.10
				callback(null, request.stdResult());
				res.response.resume();
				break;

			default:
				// save to file
				if (typeof file !== 'string') {
					throw tools.formatError('Expecting a file path for saving the object from URL: %s.', options.url);
				}

				request.saveFile(file, function(err) {
					if (err) {
						callback(err);
						return;
					}

					callback(null, request.stdResult());
				});
				break;
		}
	});
};

/**
 * HTTP HEAD method wrapper
 *
 * @param {module:request~options} options The options Object taken by the {@link Request} constructor, filtered by {@link module:tools.shortHand}. options.method = 'HEAD' and it can not be overridden
 * @param {module:main~callback} callback Completion callback
 */
exports.head = function(options, callback) {
	options = tools.shortHand(options, 'head');
	var request = new Request(options);
	tools.checkCallback(callback, request.options.url);

	request.send(function(err, res) {
		if (err) {
			callback(err);
			return;
		}

		callback(null, request.stdResult());
		res.response.resume();
	});
};

/**
 * Sets the http.Agent.defaultMaxSockets value
 *
 * @param {Number} value
 */
exports.setMaxSockets = function (value) {
	value = tools.absInt(value);
	if ( ! value) { // fallback to the default
		value = 5;
	}
	http.Agent.defaultMaxSockets = value;
};

// documentation section

/**
 * Describes the callback passed to each HTTP method wrapper
 *
 * @callback module:main~callback
 * @param {module:request~stdError} error The standard error or *null* on success
 * @param {module:request~stdResult} result The standard result object if error is null
 */
<|endoftext|>


<commit_before>import { LOCATION_CHANGE } from '../src/actions'

describe('Example Test', () => {
  it('should pass', () => {
    expect(LOCATION_CHANGE).toEqual('@@router/LOCATION_CHANGE')
  })
})
<commit_msg>Remove sample test<commit_after><|endoftext|>


<commit_before>var noop = function () {};
var return_false = function () { return false; };
var return_true = function () { return true; };

set_global('document', {
    location: {}, // we need this to load compose.js
});

set_global('page_params', {
    use_websockets: false,
});

set_global('$', global.make_zjquery());

set_global('compose_pm_pill', {
});

zrequire('people');
zrequire('compose_ui');
zrequire('compose');
zrequire('util');
zrequire('compose_state');
zrequire('compose_actions');

set_global('document', 'document-stub');

var start = compose_actions.start;
var cancel = compose_actions.cancel;
var get_focus_area = compose_actions._get_focus_area;
var respond_to_message = compose_actions.respond_to_message;
var reply_with_mention = compose_actions.reply_with_mention;
var quote_and_reply = compose_actions.quote_and_reply;

var compose_state = global.compose_state;

compose_state.recipient = (function () {
    var recipient;

    return function (arg) {
        if (arg === undefined) {
            return recipient;
        }

        recipient = arg;
    };
}());

set_global('reload_state', {
    is_in_progress: return_false,
});

set_global('notifications', {
    clear_compose_notifications: noop,
});

set_global('compose_fade', {
    clear_compose: noop,
});

set_global('drafts', {
    update_draft: noop,
});

set_global('resize', {
    resize_bottom_whitespace: noop,
});

set_global('narrow_state', {
    set_compose_defaults: noop,
});

set_global('unread_ops', {
    notify_server_message_read: noop,
});

set_global('common', {
    status_classes: 'status_classes',
});

function stub_selected_message(msg) {
    set_global('current_msg_list', {
        selected_message: function () {
            return msg;
        },
    });
}

function stub_channel_get(success_value) {
    set_global('channel', {
        get: function (opts) {
            opts.success(success_value);
        },
    });
}

function assert_visible(sel) {
    assert($(sel).visible());
}

function assert_hidden(sel) {
    assert(!$(sel).visible());
}

run_test('initial_state', () => {
    assert.equal(compose_state.composing(), false);
    assert.equal(compose_state.get_message_type(), false);
    assert.equal(compose_state.has_message_content(), false);
});

run_test('start', () => {
    compose_actions.autosize_message_content = noop;
    compose_actions.expand_compose_box = noop;
    compose_actions.set_focus = noop;
    compose_actions.complete_starting_tasks = noop;
    compose_actions.blur_textarea = noop;
    compose_actions.clear_textarea = noop;

    // Start stream message
    global.narrow_state.set_compose_defaults = function () {
        var opts = {};
        opts.stream = 'stream1';
        opts.subject = 'topic1';
        return opts;
    };

    var opts = {};
    start('stream', opts);

    assert_visible('#stream-message');
    assert_hidden('#private-message');

    assert.equal($('#stream').val(), 'stream1');
    assert.equal($('#subject').val(), 'topic1');
    assert.equal(compose_state.get_message_type(), 'stream');
    assert(compose_state.composing());

    // Start PM
    global.narrow_state.set_compose_defaults = function () {
        var opts = {};
        opts.private_message_recipient = 'foo@example.com';
        return opts;
    };

    opts = {
        content: 'hello',
    };

    $('#compose-textarea').trigger = noop;
    start('private', opts);

    assert_hidden('#stream-message');
    assert_visible('#private-message');

    assert.equal(compose_state.recipient(), 'foo@example.com');
    assert.equal($('#compose-textarea').val(), 'hello');
    assert.equal(compose_state.get_message_type(), 'private');
    assert(compose_state.composing());

    // Cancel compose.
    var pill_cleared;

    compose_pm_pill.clear = function () {
        pill_cleared = true;
    };

    assert_hidden('#compose_controls');
    cancel();
    assert(pill_cleared);
    assert_visible('#compose_controls');
    assert_hidden('#private-message');
    assert(!compose_state.composing());
});

run_test('respond_to_message', () => {
    // Test PM
    var person = {
        user_id: 22,
        email: 'alice@example.com',
        full_name: 'Alice',
    };
    people.add_in_realm(person);

    var msg = {
        type: 'private',
        sender_id: person.user_id,
    };
    stub_selected_message(msg);

    var opts = {
        reply_type: 'personal',
    };

    respond_to_message(opts);
    assert.equal(compose_state.recipient(), 'alice@example.com');

    // Test stream
    msg = {
        type: 'stream',
        stream: 'devel',
        subject: 'python',
        reply_to: 'bob', // compose.start needs this for dubious reasons
    };
    stub_selected_message(msg);

    opts = {
    };

    respond_to_message(opts);
    assert.equal($('#stream').val(), 'devel');
});

run_test('reply_with_mention', () => {
    var msg = {
        type: 'stream',
        stream: 'devel',
        subject: 'python',
        reply_to: 'bob', // compose.start needs this for dubious reasons
        sender_full_name: 'Bob Roberts',
        sender_id: 40,
    };
    stub_selected_message(msg);

    var syntax_to_insert;
    compose_ui.insert_syntax_and_focus = function (syntax) {
        syntax_to_insert = syntax;
    };

    var opts = {
    };

    reply_with_mention(opts);
    assert.equal($('#stream').val(), 'devel');
    assert.equal(syntax_to_insert, '@**Bob Roberts**');
    assert(compose_state.has_message_content());

    // Test for extended mention syntax
    var bob_1 = {
        user_id: 30,
        email: 'bob1@example.com',
        full_name: 'Bob Roberts',
    };
    people.add_in_realm(bob_1);
    var bob_2 = {
        user_id: 40,
        email: 'bob2@example.com',
        full_name: 'Bob Roberts',
    };
    people.add_in_realm(bob_2);

    reply_with_mention(opts);
    assert.equal($('#stream').val(), 'devel');
    assert.equal(syntax_to_insert, '@**Bob Roberts|40**');
    assert(compose_state.has_message_content());
});

run_test('quote_and_reply', () => {
    var msg = {
        type: 'stream',
        stream: 'devel',
        subject: 'python',
        reply_to: 'bob',
        sender_full_name: 'Bob Roberts',
        sender_id: 40,
    };
    stub_selected_message(msg);
    stub_channel_get({ raw_content: 'Testing.' });

    current_msg_list.selected_id = function () {
        return 100;
    };

    compose_ui.insert_syntax_and_focus = function (syntax) {
        assert.equal(syntax, '[Quoting…]\n');
    };

    compose_ui.replace_syntax = function (syntax, replacement) {
        assert.equal(syntax, '[Quoting…]');
        assert.equal(replacement, 'Testing.');
    };

    var opts = {
        reply_type: 'personal',
    };

    quote_and_reply(opts);
});

run_test('get_focus_area', () => {
    assert.equal(get_focus_area('private', {}), 'private_message_recipient');
    assert.equal(get_focus_area('private', {
        private_message_recipient: 'bob@example.com'}), 'compose-textarea');
    assert.equal(get_focus_area('stream', {}), 'stream');
    assert.equal(get_focus_area('stream', {stream: 'fun'}),
                 'subject');
    assert.equal(get_focus_area('stream', {stream: 'fun',
                                           subject: 'more'}),
                 'compose-textarea');
    assert.equal(get_focus_area('stream', {stream: 'fun',
                                           subject: 'more',
                                           trigger: 'new topic button'}),
                 'subject');
});

run_test('focus_in_empty_compose', () => {
    $('#compose-textarea').is = function (attr) {
        assert.equal(attr, ':focus');
        return $('#compose-textarea').is_focused;
    };

    compose_state.composing = return_true;
    $('#compose-textarea').val('');
    $('#compose-textarea').focus();
    assert(compose_state.focus_in_empty_compose());

    compose_state.composing = return_false;
    assert(!compose_state.focus_in_empty_compose());

    $('#compose-textarea').val('foo');
    assert(!compose_state.focus_in_empty_compose());

    $('#compose-textarea').blur();
    assert(!compose_state.focus_in_empty_compose());
});

run_test('on_narrow', () => {
    var cancel_called = false;
    compose_actions.cancel = function () {
        cancel_called = true;
    };
    compose_actions.on_narrow({
        force_close: true,
    });
    assert(cancel_called);

    var on_topic_narrow_called = false;
    compose_actions.on_topic_narrow = function () {
        on_topic_narrow_called = true;
    };
    narrow_state.narrowed_by_topic_reply = function () {
        return true;
    };
    compose_actions.on_narrow({
        force_close: false,
    });
    assert(on_topic_narrow_called);

    var update_message_list_called = false;
    narrow_state.narrowed_by_topic_reply = function () {
        return false;
    };
    compose_fade.update_message_list = function () {
        update_message_list_called = true;
    };
    compose_state.has_message_content = function () {
        return true;
    };
    compose_actions.on_narrow({
        force_close: false,
    });
    assert(update_message_list_called);

    compose_state.has_message_content = function () {
        return false;
    };
    var start_called = false;
    compose_actions.start = function () {
        start_called = true;
    };
    narrow_state.narrowed_by_pm_reply = function () {
        return true;
    };
    compose_actions.on_narrow({
        force_close: false,
        trigger: 'not-search',
        private_message_recipient: 'not@empty.com',
    });
    assert(start_called);

    start_called = false;
    compose_actions.on_narrow({
        force_close: false,
        trigger: 'search',
        private_message_recipient: '',
    });
    assert(!start_called);

    narrow_state.narrowed_by_pm_reply = function () {
        return false;
    };
    cancel_called = false;
    compose_actions.on_narrow({
        force_close: false,
    });
    assert(cancel_called);
});
<commit_msg>node: Fix a compose_actions test.<commit_after>var noop = function () {};
var return_false = function () { return false; };
var return_true = function () { return true; };

set_global('document', {
    location: {}, // we need this to load compose.js
});

set_global('page_params', {
    use_websockets: false,
});

set_global('$', global.make_zjquery());

set_global('compose_pm_pill', {
});

zrequire('people');
zrequire('compose_ui');
zrequire('compose');
zrequire('util');
zrequire('compose_state');
zrequire('compose_actions');

set_global('document', 'document-stub');

var start = compose_actions.start;
var cancel = compose_actions.cancel;
var get_focus_area = compose_actions._get_focus_area;
var respond_to_message = compose_actions.respond_to_message;
var reply_with_mention = compose_actions.reply_with_mention;
var quote_and_reply = compose_actions.quote_and_reply;

var compose_state = global.compose_state;

compose_state.recipient = (function () {
    var recipient;

    return function (arg) {
        if (arg === undefined) {
            return recipient;
        }

        recipient = arg;
    };
}());

set_global('reload_state', {
    is_in_progress: return_false,
});

set_global('notifications', {
    clear_compose_notifications: noop,
});

set_global('compose_fade', {
    clear_compose: noop,
});

set_global('drafts', {
    update_draft: noop,
});

set_global('resize', {
    resize_bottom_whitespace: noop,
});

set_global('narrow_state', {
    set_compose_defaults: noop,
});

set_global('unread_ops', {
    notify_server_message_read: noop,
});

set_global('common', {
    status_classes: 'status_classes',
});

function stub_selected_message(msg) {
    set_global('current_msg_list', {
        selected_message: function () {
            return msg;
        },
    });
}

function stub_channel_get(success_value) {
    set_global('channel', {
        get: function (opts) {
            opts.success(success_value);
        },
    });
}

function assert_visible(sel) {
    assert($(sel).visible());
}

function assert_hidden(sel) {
    assert(!$(sel).visible());
}

run_test('initial_state', () => {
    assert.equal(compose_state.composing(), false);
    assert.equal(compose_state.get_message_type(), false);
    assert.equal(compose_state.has_message_content(), false);
});

run_test('start', () => {
    compose_actions.autosize_message_content = noop;
    compose_actions.expand_compose_box = noop;
    compose_actions.set_focus = noop;
    compose_actions.complete_starting_tasks = noop;
    compose_actions.blur_textarea = noop;
    compose_actions.clear_textarea = noop;

    // Start stream message
    global.narrow_state.set_compose_defaults = function () {
        var opts = {};
        opts.stream = 'stream1';
        opts.subject = 'topic1';
        return opts;
    };

    var opts = {};
    start('stream', opts);

    assert_visible('#stream-message');
    assert_hidden('#private-message');

    assert.equal($('#stream').val(), 'stream1');
    assert.equal($('#subject').val(), 'topic1');
    assert.equal(compose_state.get_message_type(), 'stream');
    assert(compose_state.composing());

    // Start PM
    global.narrow_state.set_compose_defaults = function () {
        var opts = {};
        opts.private_message_recipient = 'foo@example.com';
        return opts;
    };

    opts = {
        content: 'hello',
    };

    $('#compose-textarea').trigger = noop;
    start('private', opts);

    assert_hidden('#stream-message');
    assert_visible('#private-message');

    assert.equal(compose_state.recipient(), 'foo@example.com');
    assert.equal($('#compose-textarea').val(), 'hello');
    assert.equal(compose_state.get_message_type(), 'private');
    assert(compose_state.composing());

    // Cancel compose.
    var pill_cleared;

    compose_pm_pill.clear = function () {
        pill_cleared = true;
    };

    assert_hidden('#compose_controls');
    cancel();
    assert(pill_cleared);
    assert_visible('#compose_controls');
    assert_hidden('#private-message');
    assert(!compose_state.composing());
});

run_test('respond_to_message', () => {
    // Test PM
    var person = {
        user_id: 22,
        email: 'alice@example.com',
        full_name: 'Alice',
    };
    people.add_in_realm(person);

    var msg = {
        type: 'private',
        sender_id: person.user_id,
    };
    stub_selected_message(msg);

    var opts = {
        reply_type: 'personal',
    };

    respond_to_message(opts);
    assert.equal(compose_state.recipient(), 'alice@example.com');

    // Test stream
    msg = {
        type: 'stream',
        stream: 'devel',
        subject: 'python',
        reply_to: 'bob', // compose.start needs this for dubious reasons
    };
    stub_selected_message(msg);

    opts = {
    };

    respond_to_message(opts);
    assert.equal($('#stream').val(), 'devel');
});

run_test('reply_with_mention', () => {
    var msg = {
        type: 'stream',
        stream: 'devel',
        subject: 'python',
        reply_to: 'bob', // compose.start needs this for dubious reasons
        sender_full_name: 'Bob Roberts',
        sender_id: 40,
    };
    stub_selected_message(msg);

    var syntax_to_insert;
    compose_ui.insert_syntax_and_focus = function (syntax) {
        syntax_to_insert = syntax;
    };

    var opts = {
    };

    reply_with_mention(opts);
    assert.equal($('#stream').val(), 'devel');
    assert.equal(syntax_to_insert, '@**Bob Roberts**');
    assert(compose_state.has_message_content());

    // Test for extended mention syntax
    var bob_1 = {
        user_id: 30,
        email: 'bob1@example.com',
        full_name: 'Bob Roberts',
    };
    people.add_in_realm(bob_1);
    var bob_2 = {
        user_id: 40,
        email: 'bob2@example.com',
        full_name: 'Bob Roberts',
    };
    people.add_in_realm(bob_2);

    reply_with_mention(opts);
    assert.equal($('#stream').val(), 'devel');
    assert.equal(syntax_to_insert, '@**Bob Roberts|40**');
    assert(compose_state.has_message_content());
});

run_test('quote_and_reply', () => {
    var msg = {
        type: 'stream',
        stream: 'devel',
        subject: 'python',
        reply_to: 'bob',
        sender_full_name: 'Bob Roberts',
        sender_id: 40,
    };
    stub_selected_message(msg);
    stub_channel_get({ raw_content: 'Testing.' });

    current_msg_list.selected_id = function () {
        return 100;
    };

    compose_ui.insert_syntax_and_focus = function (syntax) {
        assert.equal(syntax, '[Quoting…]\n');
    };

    compose_ui.replace_syntax = function (syntax, replacement) {
        assert.equal(syntax, '[Quoting…]');
        assert.equal(replacement, '```quote\nTesting.\n```');
    };

    var opts = {
        reply_type: 'personal',
    };

    quote_and_reply(opts);
});

run_test('get_focus_area', () => {
    assert.equal(get_focus_area('private', {}), 'private_message_recipient');
    assert.equal(get_focus_area('private', {
        private_message_recipient: 'bob@example.com'}), 'compose-textarea');
    assert.equal(get_focus_area('stream', {}), 'stream');
    assert.equal(get_focus_area('stream', {stream: 'fun'}),
                 'subject');
    assert.equal(get_focus_area('stream', {stream: 'fun',
                                           subject: 'more'}),
                 'compose-textarea');
    assert.equal(get_focus_area('stream', {stream: 'fun',
                                           subject: 'more',
                                           trigger: 'new topic button'}),
                 'subject');
});

run_test('focus_in_empty_compose', () => {
    $('#compose-textarea').is = function (attr) {
        assert.equal(attr, ':focus');
        return $('#compose-textarea').is_focused;
    };

    compose_state.composing = return_true;
    $('#compose-textarea').val('');
    $('#compose-textarea').focus();
    assert(compose_state.focus_in_empty_compose());

    compose_state.composing = return_false;
    assert(!compose_state.focus_in_empty_compose());

    $('#compose-textarea').val('foo');
    assert(!compose_state.focus_in_empty_compose());

    $('#compose-textarea').blur();
    assert(!compose_state.focus_in_empty_compose());
});

run_test('on_narrow', () => {
    var cancel_called = false;
    compose_actions.cancel = function () {
        cancel_called = true;
    };
    compose_actions.on_narrow({
        force_close: true,
    });
    assert(cancel_called);

    var on_topic_narrow_called = false;
    compose_actions.on_topic_narrow = function () {
        on_topic_narrow_called = true;
    };
    narrow_state.narrowed_by_topic_reply = function () {
        return true;
    };
    compose_actions.on_narrow({
        force_close: false,
    });
    assert(on_topic_narrow_called);

    var update_message_list_called = false;
    narrow_state.narrowed_by_topic_reply = function () {
        return false;
    };
    compose_fade.update_message_list = function () {
        update_message_list_called = true;
    };
    compose_state.has_message_content = function () {
        return true;
    };
    compose_actions.on_narrow({
        force_close: false,
    });
    assert(update_message_list_called);

    compose_state.has_message_content = function () {
        return false;
    };
    var start_called = false;
    compose_actions.start = function () {
        start_called = true;
    };
    narrow_state.narrowed_by_pm_reply = function () {
        return true;
    };
    compose_actions.on_narrow({
        force_close: false,
        trigger: 'not-search',
        private_message_recipient: 'not@empty.com',
    });
    assert(start_called);

    start_called = false;
    compose_actions.on_narrow({
        force_close: false,
        trigger: 'search',
        private_message_recipient: '',
    });
    assert(!start_called);

    narrow_state.narrowed_by_pm_reply = function () {
        return false;
    };
    cancel_called = false;
    compose_actions.on_narrow({
        force_close: false,
    });
    assert(cancel_called);
});
<|endoftext|>


<commit_before>import aws from 'aws-sdk';
import Bluebird from 'bluebird';

import { Vpc } from '../resource';
import { createTagMap } from '../tags';
import { SlackNotification } from '../notification';

function loadEc2Instances(region, ec2, vpcId) {
  return ec2.describeInstancesAsync({
    Filters: [
      { Name: 'vpc-id', Values: [vpcId] }
    ],
    MaxResults: 5
  })
    .get('Reservations')
    .reduce((acc, res) => acc.concat(res.Instances), []);
}

function loadVpcs(region, ec2) {
  return ec2.describeVpcsAsync({
    Filters: [
      { Name: 'isDefault', Values: ['false'] }
    ]
  })
    .get('Vpcs')
    .map(vpc => new Vpc(region, vpc.VpcId, createTagMap(vpc.Tags)));
}

class EmptyVpc {
  run() {
    const region = aws.config.region;

    const ec2 = new aws.EC2({ apiVersion: '2014-10-01' });
    Bluebird.promisifyAll(Object.getPrototypeOf(ec2));

    const notification = new SlackNotification(process.env.SLACK_WEBHOOK_URL);

    return loadVpcs(region, ec2)
      .map(vpc => {
        return loadEc2Instances(region, ec2, vpc.id)
          .then(instances => {
            return { vpc, count: instances.length };
          });
      })
      .filter(({ vpc, count }) => count === 0)
      .map(({ vpc, count }) => notification.error(vpc, 'No instances present in VPC.'));
  }
}

export default EmptyVpc;
<commit_msg>Remove max results limit on ec2 instance list<commit_after>import aws from 'aws-sdk';
import Bluebird from 'bluebird';

import { Vpc } from '../resource';
import { createTagMap } from '../tags';
import { SlackNotification } from '../notification';

function loadEc2Instances(region, ec2, vpcId) {
  return ec2.describeInstancesAsync({
    Filters: [
      { Name: 'vpc-id', Values: [vpcId] }
    ]
  })
    .get('Reservations')
    .reduce((acc, res) => acc.concat(res.Instances), []);
}

function loadVpcs(region, ec2) {
  return ec2.describeVpcsAsync({
    Filters: [
      { Name: 'isDefault', Values: ['false'] }
    ]
  })
    .get('Vpcs')
    .map(vpc => new Vpc(region, vpc.VpcId, createTagMap(vpc.Tags)));
}

class EmptyVpc {
  run() {
    const region = aws.config.region;

    const ec2 = new aws.EC2({ apiVersion: '2014-10-01' });
    Bluebird.promisifyAll(Object.getPrototypeOf(ec2));

    const notification = new SlackNotification(process.env.SLACK_WEBHOOK_URL);

    return loadVpcs(region, ec2)
      .map(vpc => {
        return loadEc2Instances(region, ec2, vpc.id)
          .then(instances => {
            return { vpc, count: instances.length };
          });
      })
      .filter(({ vpc, count }) => count === 0)
      .map(({ vpc, count }) => notification.error(vpc, 'No instances present in VPC.'));
  }
}

export default EmptyVpc;
<|endoftext|>


<commit_before>var resolve = require('../');
var request = require('request');
var assert = require('assert');

function verify(done, query, expectedURL) {
  resolve(query, function(err, res) {
    assert.ifError(err);
    assert.equal(res.url, expectedURL);

    request(res.url, {
      method: 'HEAD'
    }, function(badUrl) {
      if (badUrl) {
        return done(new Error('The URL `' + res.url + '` returned: ' + badUrl.message));
      }
      done();
    });
  });
}

describe('mongodb-download-url', function() {
  // - http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-2.4.14.tgz
  // + http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-linux_64-2.4.14.tgz
  describe('linux', function() {
    it('should resolve 2.4.14', function(done) {
      var query = {
        version: '2.4.14',
        platform: 'linux',
        bits: 64
      };
      verify(done, query,
        'http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-2.4.14.tgz');
    });

    it('should resolve 2.6.11', function(done) {
      var query = {
        version: '2.6.11',
        platform: 'linux',
        bits: 64
      };
      verify(done, query,
        'http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-2.6.11.tgz');
    });

    it('should resolve 3.1.9', function(done) {
      var query = {
        version: '3.1.9',
        platform: 'linux',
        bits: 64
      };
      verify(done, query,
        'http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.1.9.tgz');
    });

    it('should resolve 3.1.9 enterprise', function(done) {
      var query = {
        version: '3.1.9',
        platform: 'linux',
        distro: 'ubuntu1404',
        enterprise: true,
        bits: 64
      };
      verify(done, query,
        'http://downloads.mongodb.com/linux/mongodb-linux-x86_64'
        + '-enterprise-ubuntu1404-3.1.9.tgz');
    });

    it('should resolve 3.0.7 (32-bit)', function(done) {
      var query = {
        version: '3.0.7',
        platform: 'linux',
        bits: 32
      };
      verify(done, query,
        'http://fastdl.mongodb.org/linux/mongodb-linux-i686-3.0.7.tgz');
    });
  });

  describe('windows', function() {
    it('should resolve 3.1.9', function(done) {
      var query = {
        version: '3.1.9',
        platform: 'win32',
        bits: 64
      };
      verify(done, query,
        'http://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-ssl-3.1.9.zip');
    });
    it('should resolve 3.1.19 enterprise', function(done) {
      var query = {
        version: '3.1.9',
        platform: 'win32',
        enterprise: true,
        bits: 64
      };
      verify(done, query,
        'http://downloads.mongodb.com/win32/'
        + 'mongodb-win32-x86_64-enterprise-windows-64-3.1.9.zip');
    });
    it('should resolve 2.6.11', function(done) {
      var query = {
        version: '2.6.11',
        platform: 'win32',
        bits: 64
      };
      verify(done, query,
        'http://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-2.6.11.zip');
    });
    it('should resolve 3.0.7 (32-bit)', function(done) {
      var query = {
        version: '3.0.7',
        platform: 'win32',
        bits: 32
      };
      verify(done, query,
        'http://fastdl.mongodb.org/win32/mongodb-win32-i386-3.0.7.zip');
    });
  });

  describe('osx', function() {
    it('should resolve 3.1.19 enterprise', function(done) {
      var query = {
        version: '3.1.9',
        platform: 'osx',
        enterprise: true,
        bits: 64
      };
      verify(done, query,
        'http://downloads.mongodb.com/osx/mongodb-osx-x86_64-enterprise-3.1.9.tgz');
    });
  });

  describe('evergreen', function() {
    it('should resolve a git commit sha1', function(done) {
      var sha = '610765fdb94eebf612bd0172ec081ccc21110103';
      var query = {
        version: sha,
        platform: 'win32',
        bits: 64,
        debug: true
      };
      resolve(query, function(err, res) {
        assert.ifError(err);
        assert.equal(res.url,
          'https://s3.amazonaws.com/mciuploads/mongodb-mongo-master/'
          + 'windows_64_2k8_debug/610765fdb94eebf612bd0172ec081ccc21110103/binaries'
          + '/binaries-mongodb_mongo_master_windows_64_2k8_debug_610765fdb94eebf'
          + '612bd0172ec081ccc21110103_15_07_20_20_04_03.zip'
        );
        done();
      });
    });
  });

  describe('version aliases', function() {
    it('should resolve `stable`', function(done) {
      var query = {
        version: 'stable'
      };
      resolve(query, function(err, res) {
        assert.ifError(err);
        assert(res.version);
        assert(res.url);
        done();
      });
    });

    it('should resolve `unstable`', function(done) {
      var query = {
        version: 'unstable'
      };
      resolve(query, function(err, res) {
        assert.ifError(err);
        assert(res.version);
        assert(res.url);
        done();
      });
    });

    it('should resolve `latest`', function(done) {
      var query = {
        version: 'latest'
      };
      resolve(query, function(err, res) {
        assert.ifError(err);
        assert(res.version);
        assert(res.url);
        done();
      });
    });
  });

  describe('options', function() {
    it('should handle nulls', function() {
      assert.doesNotThrow(function() {
        resolve.options();
      });
    });

    it('should default version to `stable`', function() {
      assert.equal(resolve.options().version, 'stable');
    });

    it('should use the MONGODB_VERSION environment variable for version', function() {
      process.env.MONGODB_VERSION = '2.6.11';
      var res = resolve.options();
      delete process.env.MONGODB_VERSION;

      assert.equal(res.version, '2.6.11');
    });
  });
});
<commit_msg>:green_heart: Use https for downloads<commit_after>var resolve = require('../');
var request = require('request');
var assert = require('assert');

function verify(done, query, expectedURL) {
  resolve(query, function(err, res) {
    assert.ifError(err);
    assert.equal(res.url, expectedURL);

    request(res.url, {
      method: 'HEAD'
    }, function(badUrl) {
      if (badUrl) {
        return done(new Error('The URL `' + res.url + '` returned: ' + badUrl.message));
      }
      done();
    });
  });
}

describe('mongodb-download-url', function() {
  // - https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-2.4.14.tgz
  // + https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-linux_64-2.4.14.tgz
  describe('linux', function() {
    it('should resolve 2.4.14', function(done) {
      var query = {
        version: '2.4.14',
        platform: 'linux',
        bits: 64
      };
      verify(done, query,
        'https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-2.4.14.tgz');
    });

    it('should resolve 2.6.11', function(done) {
      var query = {
        version: '2.6.11',
        platform: 'linux',
        bits: 64
      };
      verify(done, query,
        'https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-2.6.11.tgz');
    });

    it('should resolve 3.1.9', function(done) {
      var query = {
        version: '3.1.9',
        platform: 'linux',
        bits: 64
      };
      verify(done, query,
        'https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.1.9.tgz');
    });

    it('should resolve 3.1.9 enterprise', function(done) {
      var query = {
        version: '3.1.9',
        platform: 'linux',
        distro: 'ubuntu1404',
        enterprise: true,
        bits: 64
      };
      verify(done, query,
        'https://downloads.mongodb.com/linux/mongodb-linux-x86_64'
        + '-enterprise-ubuntu1404-3.1.9.tgz');
    });

    it('should resolve 3.0.7 (32-bit)', function(done) {
      var query = {
        version: '3.0.7',
        platform: 'linux',
        bits: 32
      };
      verify(done, query,
        'https://fastdl.mongodb.org/linux/mongodb-linux-i686-3.0.7.tgz');
    });
  });

  describe('windows', function() {
    it('should resolve 3.1.9', function(done) {
      var query = {
        version: '3.1.9',
        platform: 'win32',
        bits: 64
      };
      verify(done, query,
        'https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-ssl-3.1.9.zip');
    });
    it('should resolve 3.1.19 enterprise', function(done) {
      var query = {
        version: '3.1.9',
        platform: 'win32',
        enterprise: true,
        bits: 64
      };
      verify(done, query,
        'https://downloads.mongodb.com/win32/'
        + 'mongodb-win32-x86_64-enterprise-windows-64-3.1.9.zip');
    });
    it('should resolve 2.6.11', function(done) {
      var query = {
        version: '2.6.11',
        platform: 'win32',
        bits: 64
      };
      verify(done, query,
        'https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-2.6.11.zip');
    });
    it('should resolve 3.0.7 (32-bit)', function(done) {
      var query = {
        version: '3.0.7',
        platform: 'win32',
        bits: 32
      };
      verify(done, query,
        'https://fastdl.mongodb.org/win32/mongodb-win32-i386-3.0.7.zip');
    });
  });

  describe('osx', function() {
    it('should resolve 3.1.19 enterprise', function(done) {
      var query = {
        version: '3.1.9',
        platform: 'osx',
        enterprise: true,
        bits: 64
      };
      verify(done, query,
        'https://downloads.mongodb.com/osx/mongodb-osx-x86_64-enterprise-3.1.9.tgz');
    });
  });
  // NOTE (imlucas): This is pretty unused as far as I know...
  describe.skip('evergreen', function() {
    it('should resolve a git commit sha1', function(done) {
      var sha = '610765fdb94eebf612bd0172ec081ccc21110103';
      var query = {
        version: sha,
        platform: 'win32',
        bits: 64,
        debug: true
      };
      resolve(query, function(err, res) {
        assert.ifError(err);
        assert.equal(res.url,
          'https://s3.amazonaws.com/mciuploads/mongodb-mongo-master/'
          + 'windows_64_2k8_debug/610765fdb94eebf612bd0172ec081ccc21110103/binaries'
          + '/binaries-mongodb_mongo_master_windows_64_2k8_debug_610765fdb94eebf'
          + '612bd0172ec081ccc21110103_15_07_20_20_04_03.zip'
        );
        done();
      });
    });
  });

  describe('version aliases', function() {
    it('should resolve `stable`', function(done) {
      var query = {
        version: 'stable'
      };
      resolve(query, function(err, res) {
        assert.ifError(err);
        assert(res.version);
        assert(res.url);
        done();
      });
    });

    it('should resolve `unstable`', function(done) {
      var query = {
        version: 'unstable'
      };
      resolve(query, function(err, res) {
        assert.ifError(err);
        assert(res.version);
        assert(res.url);
        done();
      });
    });

    it('should resolve `latest`', function(done) {
      var query = {
        version: 'latest'
      };
      resolve(query, function(err, res) {
        assert.ifError(err);
        assert(res.version);
        assert(res.url);
        done();
      });
    });
  });

  describe('options', function() {
    it('should handle nulls', function() {
      assert.doesNotThrow(function() {
        resolve.options();
      });
    });

    it('should default version to `stable`', function() {
      assert.equal(resolve.options().version, 'stable');
    });

    it('should use the MONGODB_VERSION environment variable for version', function() {
      process.env.MONGODB_VERSION = '2.6.11';
      var res = resolve.options();
      delete process.env.MONGODB_VERSION;

      assert.equal(res.version, '2.6.11');
    });
  });
});
<|endoftext|>


<commit_before>"use strict";

const {strict: assert} = require("assert");

const {mock_esm, set_global, zrequire} = require("../zjsunit/namespace");
const {run_test} = require("../zjsunit/test");

mock_esm("../../static/js/resize", {
    resize_stream_filters_container: () => {},
});

const all_messages_data = mock_esm("../../static/js/all_messages_data");
const channel = mock_esm("../../static/js/channel");
const compose_actions = mock_esm("../../static/js/compose_actions");
const compose_closed_ui = mock_esm("../../static/js/compose_closed_ui");
const hashchange = mock_esm("../../static/js/hashchange");
const message_fetch = mock_esm("../../static/js/message_fetch");
const message_list = mock_esm("../../static/js/message_list", {
    set_narrowed(value) {
        message_list.narrowed = value;
    },
});
const message_lists = mock_esm("../../static/js/message_lists", {
    home: {},
    current: {},
    set_current(msg_list) {
        message_lists.current = msg_list;
    },
});
const message_scroll = mock_esm("../../static/js/message_scroll");
const message_view_header = mock_esm("../../static/js/message_view_header");
const notifications = mock_esm("../../static/js/notifications");
const search = mock_esm("../../static/js/search");
const stream_list = mock_esm("../../static/js/stream_list");
const top_left_corner = mock_esm("../../static/js/top_left_corner");
const typing_events = mock_esm("../../static/js/typing_events");
const ui_util = mock_esm("../../static/js/ui_util");
const unread_ops = mock_esm("../../static/js/unread_ops");
mock_esm("../../static/js/recent_topics_util", {
    is_visible: () => {},
});

//
// We have strange hacks in narrow.activate to sleep 0
// seconds.
set_global("setTimeout", (f, t) => {
    assert.equal(t, 0);
    f();
});

mock_esm("../../static/js/muted_topics", {
    is_topic_muted: () => false,
});

const util = zrequire("util");
const narrow_state = zrequire("narrow_state");
const stream_data = zrequire("stream_data");
const narrow = zrequire("narrow");

const denmark = {
    subscribed: false,
    color: "blue",
    name: "Denmark",
    stream_id: 1,
    is_muted: true,
};
stream_data.add_sub(denmark);

function test_helper() {
    let events = [];

    function stub(module, func_name) {
        module[func_name] = () => {
            events.push([module, func_name]);
        };
    }

    stub(compose_actions, "on_narrow");
    stub(compose_closed_ui, "update_reply_recipient_label");
    stub(hashchange, "save_narrow");
    stub(message_scroll, "hide_indicators");
    stub(message_scroll, "show_loading_older");
    stub(message_scroll, "hide_top_of_narrow_notices");
    stub(notifications, "clear_compose_notifications");
    stub(notifications, "redraw_title");
    stub(search, "update_button_visibility");
    stub(stream_list, "handle_narrow_activated");
    stub(message_view_header, "initialize");
    stub(top_left_corner, "handle_narrow_activated");
    stub(typing_events, "render_notifications_for_narrow");
    stub(ui_util, "change_tab_to");
    stub(unread_ops, "process_visible");
    stub(compose_closed_ui, "update_buttons_for_stream");
    stub(compose_closed_ui, "update_buttons_for_private");

    return {
        clear: () => {
            events = [];
        },
        push_event: (event) => {
            events.push(event);
        },
        assert_events: (expected_events) => {
            assert.deepEqual(expected_events, events);
        },
    };
}

function stub_message_list() {
    message_list.MessageList = function (opts) {
        this.data = opts.data;
        this.view = {
            set_message_offset(offset) {
                this.offset = offset;
            },
        };

        return this;
    };

    message_list.MessageList.prototype = {
        get(msg_id) {
            return this.data.get(msg_id);
        },

        empty() {
            return this.data.empty();
        },

        select_id(msg_id) {
            this.selected_id = msg_id;
        },
    };
}

run_test("basics", () => {
    stub_message_list();

    const helper = test_helper();
    const terms = [{operator: "stream", operand: "Denmark"}];

    const selected_id = 1000;

    const selected_message = {
        id: selected_id,
        type: "stream",
        stream_id: denmark.stream_id,
        topic: "whatever",
    };

    const messages = [selected_message];

    const row = {
        length: 1,
        offset: () => ({top: 25}),
    };

    message_lists.current.selected_id = () => -1;
    message_lists.current.get_row = () => row;

    all_messages_data.all_messages_data = {
        all_messages: () => messages,
        get: (msg_id) => {
            assert.equal(msg_id, selected_id);
            return selected_message;
        },
        fetch_status: {
            has_found_newest: () => true,
        },
        empty: () => false,
        first: () => ({id: 900}),
        last: () => ({id: 1100}),
    };

    let cont;

    message_fetch.load_messages_for_narrow = (opts) => {
        cont = opts.cont;

        assert.deepEqual(opts, {
            cont: opts.cont,
            anchor: 1000,
        });
    };

    narrow.activate(terms, {
        then_select_id: selected_id,
    });

    assert.equal(message_list.narrowed.selected_id, selected_id);
    assert.equal(message_list.narrowed.view.offset, 25);
    assert.equal(narrow_state.narrowed_to_pms(), false);

    helper.assert_events([
        [notifications, "clear_compose_notifications"],
        [notifications, "redraw_title"],
        [message_scroll, "hide_top_of_narrow_notices"],
        [message_scroll, "hide_indicators"],
        [ui_util, "change_tab_to"],
        [unread_ops, "process_visible"],
        [hashchange, "save_narrow"],
        [compose_closed_ui, "update_buttons_for_stream"],
        [compose_closed_ui, "update_reply_recipient_label"],
        [search, "update_button_visibility"],
        [compose_actions, "on_narrow"],
        [top_left_corner, "handle_narrow_activated"],
        [stream_list, "handle_narrow_activated"],
        [typing_events, "render_notifications_for_narrow"],
        [message_view_header, "initialize"],
    ]);

    message_lists.current.selected_id = () => -1;
    message_lists.current.get_row = () => row;
    util.sorted_ids = () => [];

    narrow.activate([{operator: "is", operand: "private"}], {
        then_select_id: selected_id,
    });

    assert.equal(narrow_state.narrowed_to_pms(), true);

    channel.post = (opts) => {
        assert.equal(opts.url, "/json/report/narrow_times");
        helper.push_event("report narrow times");
    };

    helper.clear();
    cont();
    helper.assert_events(["report narrow times"]);
});
<commit_msg>narrow_activate_test: Reorder helper.assert to be (actual, expected).<commit_after>"use strict";

const {strict: assert} = require("assert");

const {mock_esm, set_global, zrequire} = require("../zjsunit/namespace");
const {run_test} = require("../zjsunit/test");

mock_esm("../../static/js/resize", {
    resize_stream_filters_container: () => {},
});

const all_messages_data = mock_esm("../../static/js/all_messages_data");
const channel = mock_esm("../../static/js/channel");
const compose_actions = mock_esm("../../static/js/compose_actions");
const compose_closed_ui = mock_esm("../../static/js/compose_closed_ui");
const hashchange = mock_esm("../../static/js/hashchange");
const message_fetch = mock_esm("../../static/js/message_fetch");
const message_list = mock_esm("../../static/js/message_list", {
    set_narrowed(value) {
        message_list.narrowed = value;
    },
});
const message_lists = mock_esm("../../static/js/message_lists", {
    home: {},
    current: {},
    set_current(msg_list) {
        message_lists.current = msg_list;
    },
});
const message_scroll = mock_esm("../../static/js/message_scroll");
const message_view_header = mock_esm("../../static/js/message_view_header");
const notifications = mock_esm("../../static/js/notifications");
const search = mock_esm("../../static/js/search");
const stream_list = mock_esm("../../static/js/stream_list");
const top_left_corner = mock_esm("../../static/js/top_left_corner");
const typing_events = mock_esm("../../static/js/typing_events");
const ui_util = mock_esm("../../static/js/ui_util");
const unread_ops = mock_esm("../../static/js/unread_ops");
mock_esm("../../static/js/recent_topics_util", {
    is_visible: () => {},
});

//
// We have strange hacks in narrow.activate to sleep 0
// seconds.
set_global("setTimeout", (f, t) => {
    assert.equal(t, 0);
    f();
});

mock_esm("../../static/js/muted_topics", {
    is_topic_muted: () => false,
});

const util = zrequire("util");
const narrow_state = zrequire("narrow_state");
const stream_data = zrequire("stream_data");
const narrow = zrequire("narrow");

const denmark = {
    subscribed: false,
    color: "blue",
    name: "Denmark",
    stream_id: 1,
    is_muted: true,
};
stream_data.add_sub(denmark);

function test_helper() {
    let events = [];

    function stub(module, func_name) {
        module[func_name] = () => {
            events.push([module, func_name]);
        };
    }

    stub(compose_actions, "on_narrow");
    stub(compose_closed_ui, "update_reply_recipient_label");
    stub(hashchange, "save_narrow");
    stub(message_scroll, "hide_indicators");
    stub(message_scroll, "show_loading_older");
    stub(message_scroll, "hide_top_of_narrow_notices");
    stub(notifications, "clear_compose_notifications");
    stub(notifications, "redraw_title");
    stub(search, "update_button_visibility");
    stub(stream_list, "handle_narrow_activated");
    stub(message_view_header, "initialize");
    stub(top_left_corner, "handle_narrow_activated");
    stub(typing_events, "render_notifications_for_narrow");
    stub(ui_util, "change_tab_to");
    stub(unread_ops, "process_visible");
    stub(compose_closed_ui, "update_buttons_for_stream");
    stub(compose_closed_ui, "update_buttons_for_private");

    return {
        clear: () => {
            events = [];
        },
        push_event: (event) => {
            events.push(event);
        },
        assert_events: (expected_events) => {
            assert.deepEqual(events, expected_events);
        },
    };
}

function stub_message_list() {
    message_list.MessageList = function (opts) {
        this.data = opts.data;
        this.view = {
            set_message_offset(offset) {
                this.offset = offset;
            },
        };

        return this;
    };

    message_list.MessageList.prototype = {
        get(msg_id) {
            return this.data.get(msg_id);
        },

        empty() {
            return this.data.empty();
        },

        select_id(msg_id) {
            this.selected_id = msg_id;
        },
    };
}

run_test("basics", () => {
    stub_message_list();

    const helper = test_helper();
    const terms = [{operator: "stream", operand: "Denmark"}];

    const selected_id = 1000;

    const selected_message = {
        id: selected_id,
        type: "stream",
        stream_id: denmark.stream_id,
        topic: "whatever",
    };

    const messages = [selected_message];

    const row = {
        length: 1,
        offset: () => ({top: 25}),
    };

    message_lists.current.selected_id = () => -1;
    message_lists.current.get_row = () => row;

    all_messages_data.all_messages_data = {
        all_messages: () => messages,
        get: (msg_id) => {
            assert.equal(msg_id, selected_id);
            return selected_message;
        },
        fetch_status: {
            has_found_newest: () => true,
        },
        empty: () => false,
        first: () => ({id: 900}),
        last: () => ({id: 1100}),
    };

    let cont;

    message_fetch.load_messages_for_narrow = (opts) => {
        cont = opts.cont;

        assert.deepEqual(opts, {
            cont: opts.cont,
            anchor: 1000,
        });
    };

    narrow.activate(terms, {
        then_select_id: selected_id,
    });

    assert.equal(message_list.narrowed.selected_id, selected_id);
    assert.equal(message_list.narrowed.view.offset, 25);
    assert.equal(narrow_state.narrowed_to_pms(), false);

    helper.assert_events([
        [notifications, "clear_compose_notifications"],
        [notifications, "redraw_title"],
        [message_scroll, "hide_top_of_narrow_notices"],
        [message_scroll, "hide_indicators"],
        [ui_util, "change_tab_to"],
        [unread_ops, "process_visible"],
        [hashchange, "save_narrow"],
        [compose_closed_ui, "update_buttons_for_stream"],
        [compose_closed_ui, "update_reply_recipient_label"],
        [search, "update_button_visibility"],
        [compose_actions, "on_narrow"],
        [top_left_corner, "handle_narrow_activated"],
        [stream_list, "handle_narrow_activated"],
        [typing_events, "render_notifications_for_narrow"],
        [message_view_header, "initialize"],
    ]);

    message_lists.current.selected_id = () => -1;
    message_lists.current.get_row = () => row;
    util.sorted_ids = () => [];

    narrow.activate([{operator: "is", operand: "private"}], {
        then_select_id: selected_id,
    });

    assert.equal(narrow_state.narrowed_to_pms(), true);

    channel.post = (opts) => {
        assert.equal(opts.url, "/json/report/narrow_times");
        helper.push_event("report narrow times");
    };

    helper.clear();
    cont();
    helper.assert_events(["report narrow times"]);
});
<|endoftext|>


<commit_before>/**
 * @fileoverview Ensure that variable, function, parameter and declerative expression names follow mixedCase notation
 * @author Raghav Dua <duaraghav8@gmail.com>
 */

'use strict';

module.exports = {

	verify: function (context) {

		var mixedCaseRegEx = /^_?[a-z]+[a-zA-Z]*$/;
		var similarNodes = [
			'FunctionDeclaration',
			'ModifierDeclaration',
			'ModifierName'
		];

		function report (node, name) {
			context.report ({
				node: node,
				message: '\'' + name + '\' doesn\'t follow the mixedCase notation'
			});
		}

		similarNodes.forEach (function (event) {
			context.on (event, function (emitted) {
				var node = emitted.node;

				//a constructor (function with name same as it parent contract/library) is exception to mixedCase Rule
				if (
					emitted.exit ||
					(
						node.type === 'FunctionDeclaration' &&
						(node.parent.type === 'ContractStatement' || node.parent.type === 'LibraryStatement') &&
						node.parent.name === node.name
					)
				) {
					return;
				}

				if (!mixedCaseRegEx.test (node.name)) {
					report (node, node.name);
				}
			});
		});

		context.on ('VariableDeclarator', function (emitted) {
			var node = emitted.node;

			if (emitted.exit) {
				return;
			}

			if (!mixedCaseRegEx.test (node.id.name)) {
				context.report ({
					node: node,
					message: 'Identifier name \'' + node.id.name + '\' doesn\'t follow the mixedCase notation'
				});
			}
		});

		context.on ('DeclarativeExpression', function (emitted) {
			var node = emitted.node;

			if (emitted.exit) {
				return;
			}

			if (!node.is_constant && !mixedCaseRegEx.test (node.name)) {
				report (node, node.name);
			}
		});

		context.on ('InformalParameter', function (emitted) {
			var node = emitted.node;

			if (emitted.exit) {
				return;
			}

			if (!mixedCaseRegEx.test (node.id)) {
				report (node, node.id);
			}
		});

	}

};<commit_msg>bug fix in misedcase - allow numbers<commit_after>/**
 * @fileoverview Ensure that variable, function, parameter and declerative expression names follow mixedCase notation
 * @author Raghav Dua <duaraghav8@gmail.com>
 */

'use strict';

module.exports = {

	verify: function (context) {

		var mixedCaseRegEx = /^_?[a-z][a-zA-Z0-9]*$/;
		var similarNodes = [
			'FunctionDeclaration',
			'ModifierDeclaration',
			'ModifierName'
		];

		function report (node, name) {
			context.report ({
				node: node,
				message: '\'' + name + '\' doesn\'t follow the mixedCase notation'
			});
		}

		similarNodes.forEach (function (event) {
			context.on (event, function (emitted) {
				var node = emitted.node;

				//a constructor (function with name same as it parent contract/library) is exception to mixedCase Rule
				if (
					emitted.exit ||
					(
						node.type === 'FunctionDeclaration' &&
						(node.parent.type === 'ContractStatement' || node.parent.type === 'LibraryStatement') &&
						node.parent.name === node.name
					)
				) {
					return;
				}

				if (!mixedCaseRegEx.test (node.name)) {
					report (node, node.name);
				}
			});
		});

		context.on ('VariableDeclarator', function (emitted) {
			var node = emitted.node;

			if (emitted.exit) {
				return;
			}

			if (!mixedCaseRegEx.test (node.id.name)) {
				context.report ({
					node: node,
					message: 'Identifier name \'' + node.id.name + '\' doesn\'t follow the mixedCase notation'
				});
			}
		});

		context.on ('DeclarativeExpression', function (emitted) {
			var node = emitted.node;

			if (emitted.exit) {
				return;
			}

			if (!node.is_constant && !mixedCaseRegEx.test (node.name)) {
				report (node, node.name);
			}
		});

		context.on ('InformalParameter', function (emitted) {
			var node = emitted.node;

			if (emitted.exit) {
				return;
			}

			if (!mixedCaseRegEx.test (node.id)) {
				report (node, node.id);
			}
		});

	}

};<|endoftext|>


<commit_before>// Firefox Add-on Requires
var self = require('sdk/self'),
    buttons = require('sdk/ui/button/action'),
    panels = require('sdk/panel'),
    Request = require('sdk/request').Request,
    tmr = require('sdk/timers'),
    notifications = require('sdk/notifications'),
    tabs = require('sdk/tabs'),
    _ = require('sdk/l10n').get,
    ss = require('sdk/simple-storage'),
    platform = require("sdk/system").platform;

// API Urls
var streamAPI = 'https://api.twitch.tv/kraken/streams/',
    gameAPI = 'https://api.twitch.tv/kraken/games/top',
    followingPre = 'https://api.twitch.tv/kraken/users/',
    followingSuff = '/follows/channels',
    featuredAPI = 'https://api.twitch.tv/kraken/streams/featured',
    searchAPI = 'https://api.twitch.tv/kraken/search/streams';

var isFirst = true,
    followingNames = [],
    liveFollowings = [],
    newLiveFollowings = [],
    intervalID;

// Creating an empty settings locale storage if it is not set yet.
if (!ss.storage.settings)
    ss.storage.settings = {};

// Executes after extension loads.
exports.main = function(options, callbacks) {

    // Setting first settings
    if ((options.loadReason == "install" || options.loadReason == "upgrade") && Object.keys(ss.storage.settings).length == 0) {
        setStorageItem('notification', true);
        setStorageItem('notifySound', true);
        setStorageItem('open', 1);
        setStorageItem('notifySoundRing', 'Chord.mp3');
    }

    // Localization variables
    var viewers = ' ' + _('viewers'),
        channels = ' ' + _('channels'),
        playing = _('playing'),
        signIn = _('sign_in'),
        signOut = _('sign_out'),
        noStreams = _('no_streams'),
        searchMessage = _('search_message');

    // Action Button Initialize
    var button = buttons.ActionButton({
        id: 'twitch-live',
        label: 'Twitch Live',
        icon: {
            '16': './icons/twitch-icon-32.png',
            '32': './icons/twitch-icon-32.png',
            '64': './icons/twitch-icon-64.png',
            '128': './icons/twitch-icon-128.png'
        },
        onClick: handleClick
    });

    // Panel Initialize
    var panel = panels.Panel({
        contentURL: self.data.url('panel.html'),
        width: 400,
        height: 555
    });

    // Action Button Click Handler
    function handleClick(state) {
        panel.show({
            position: button
        });
    }

    /* Storage helpers */
    function getStorageItem(item) {
        return ss.storage.settings[item];
    }

    function setStorageItem(item, val) {
        ss.storage.settings[item] = val;
    }

    function deleteStorageItem(item) {
        delete ss.storage.settings[item];
    }

    function include(arr, obj) {
        return (arr.indexOf(obj) != -1);
    }

    /**
     * Port to get online following channels.
     * Send all followed channels to printFollowing() function for API request.
     */
    panel.port.on('getFollowings', function() {
        isFirst = true;

        if (followingNames.length > 0) {
            for (var i = 0; i < followingNames.length; i++) {
                if (i == followingNames.length - 1) {
                    printFollowing(followingNames[i], true);
                } else {
                    printFollowing(followingNames[i]);
                }
            }
        } else {
            panel.port.emit('noFollowingStream', noStreams);
        }
    });

    /**
     * Get followed channels one by one and send a API request.
     * If channels if online return port for channel information.
     */
    function printFollowing(name, isLast) {
        var apiRequest = Request ({
            url: streamAPI + encodeURIComponent(name),
            headers: {
                'Cache-control': 'no-cache'
            },
            onComplete: function(response) {
                if (response.json.stream != null) {
                    if (isFirst === true) {
                        isFirst = false;
                    }
                    panel.port.emit('followResponse', response.json, viewers, playing);
                }

                // If there is no online channel, then it give a warning
                if (isFirst == true && isLast == true) {
                    panel.port.emit('noFollowingStream', noStreams);
                }
            }
        });

        apiRequest.get();
    }

    /**
     * Port to get top 50 games.
     * Return a port for game informations.
     */
    panel.port.on('printGames', function() {
        var apiRequest = Request ({
            url: gameAPI,
            content: {
                limit: 50
            },
            headers: {
                'Cache-control': 'no-cache'
            },
            onComplete: function(response) {
                panel.port.emit('gameResponse', response.json, viewers, channels);
            }
        });

        apiRequest.get();
    });

    /**
     * Port to get top 50 streams by popularity.
     * Return a port for stream informations.
     */
    panel.port.on('printStreams', function() {
        var apiRequest = Request ({
            url: streamAPI,
            content: {
                limit: 50
            },
            headers: {
                'Cache-control': 'no-cache'
            },
            onComplete: function(response) {
                panel.port.emit('streamResponse', response.json, viewers, playing);
            }
        });

        apiRequest.get();
    });

    /**
     * Port to get top 50 streams by game. This port is used for second page of the game tab.
     * Return a port for stream informations.
     */
    panel.port.on('getStreamsByGame', function(gameName) {
        var apiRequest = Request ({
            url: streamAPI,
            content: {
                game : gameName,
                limit : 50
            },
            headers: {
                'Cache-control': 'no-cache'
            },
            onComplete: function(response) {
                panel.port.emit('streamByGameResponse', response.json, viewers, playing);
            }
        });

        apiRequest.get();
    });

    /**
     * Port to get top 50 featured streams.
     * Return a port for stream informations.
     */
    panel.port.on('getFeatured', function() {
        var apiRequest = Request({
            url: featuredAPI,
            content: {
                limit: 50
            },
            headers: {
                'Cache-control': 'no-cache'
            },
            onComplete: function(response) {
                panel.port.emit('featuredResponse', response.json, viewers, playing);
            }
        });

        apiRequest.get();
    });

    /**
     * Port to get search result by query.
     * Return a port for search result
     */
    panel.port.on('search', function(query) {
        var apiRequest = Request({
            url: searchAPI,
            content: {
                q: encodeURIComponent(query)
            },
            headers: {
                'Cache-control': 'no-cache'
            },
            onComplete: function(response) {
                panel.port.emit('searchResponse', response.json, viewers, playing);
            }
        });

        apiRequest.get();
    });

    /**
     * Call initializeNotify() for initialize notifications.
     */
    panel.port.on('initialize', function() {
        initializeNotify();
    });

    /**
     * Get followers and initialize notifications.
     * Notifications send in every 5 minutes.
     */
    function initializeNotify() {
        var username = getStorageItem('twitchName');

        if (username != undefined && username != '') {
            followingCheck(username, function() {
                // Firstly we are initializing a postnotify and then setting it to do that for 5mins(300000 ms) repeatedly.
                postNotify();
                intervalID = tmr.setInterval(postNotify, 300000); // 5 * 60 * 100
            });
        }
    }

    /**
     * Send API request to get all followers.
     * Used in initialize port and for refresh the followers.
     */
    function followingCheck(username, callback) {
        if (username != undefined) {
            var followUrl = followingPre + encodeURIComponent(username) + followingSuff;

            var apiRequest = Request ({
                url: followUrl,
                content: {
                    limit: 500
                },
                headers: {
                    'Cache-control': 'no-cache'
                },
                onComplete: function(response) {
                    if (response.json.follows != undefined) {
                        for (var i = 0; i < response.json.follows.length; i++) {
                            followingNames[i] = response.json.follows[i].channel.name;
                        }

                        // If callback parameter is filled, execute it.
                        if (callback && typeof(callback) === 'function') {
                            callback();
                        }
                    }
                }
            });

            apiRequest.get();
        };
    }

    /**
     * Execute in every 5 minutes and check for the new online streamers.
     * If there is online streamer then send it to notify function to show notify.
     */
    function postNotify() {
        var a = 0;
        var index = 0;
        var streamersText = '';
        var isLiveEmpty = liveFollowings.length == 0;
        var lastUrl = '';

        if (followingNames.length > 0) {
            for (var i = 0; i < followingNames.length; i++) {
                var apiRequest = Request ({
                    url: streamAPI + encodeURIComponent(followingNames[i]),
                    headers: {
                        'Cache-control': 'no-cache'
                    },
                    onComplete: function(response) {

                        // If live followigs empty, then here executes, otherwise goes to else for comparison
                        if (isLiveEmpty) {
                            if (response.json.stream != undefined) {
                                if (response.json.stream.channel.display_name !== undefined) {
                                    liveFollowings[a++] = response.json.stream.channel.display_name;
                                    lastUrl = response.json.stream.channel.url;
                                }
                            }

                            index++;
                            if (index == followingNames.length) {
                                streamersText = liveFollowings.join(', ');
                                streamersText += ' ' + _('now_online');

                                notify(streamersText, a, false, lastUrl);
                            }

                        } else {
                            if (response.json.stream != undefined) {
                                if (response.json.stream.channel.display_name !== undefined) {
                                    newLiveFollowings[a++] = response.json.stream.channel.display_name;
                                    if (!include(liveFollowings, response.json.stream.channel.display_name))
                                        lastUrl = response.json.stream.channel.url;
                                }
                            }

                            index++;
                            if (index == followingNames.length) {
                                var nowOnlineCount = 0;

                                for (var j = 0; j < newLiveFollowings.length; j++) {
                                    if (!include(liveFollowings, newLiveFollowings[j])) {
                                        streamersText += newLiveFollowings[j] + ', ';
                                        nowOnlineCount++;
                                    }
                                }

                                if (nowOnlineCount != 0) {
                                    streamersText = streamersText.slice(0, -2); // to delete the last ', ' characters.
                                    streamersText += ' ' + _('now_online');
                                    notify(streamersText, nowOnlineCount, true, lastUrl);
                                }
                            }
                        }

                    }
                });

                apiRequest.get();
            }
        }

    }

    /**
     * Get notify text count and show notification with these.
     * If there is one online streamer then show different
     */
    function notify(ntext, count, newLive, lastUrl) {
        if (count == 1) {
            notifications.notify({
                title: ntext,
                text: _('click_to_go'),
                iconURL: './icons/twitch-icon-128.png',
                onClick: function() {
                    openLink(lastUrl, true);
                }
            });
        } else if (count > 1) {
            notifications.notify({
                title: count + ' ' + _('streamers_online'),
                text: ntext,
                iconURL: './icons/twitch-icon-128.png',
                onClick: function() {
                    openLink('http://www.twitch.tv/directory/following', false);
                }
            });
        }

        // Play audio if OS is Windows
        if (platform == 'winnt' && getStorageItem('notifySound') == true) {
            panel.port.emit('playSound', getStorageItem('notifySoundRing'));
        }

        // If newlivefollowings is not empty, pass it's content to main array and empty it.
        if (newLive) {
            liveFollowings = [];
            liveFollowings = newLiveFollowings;
            newLiveFollowings = [];
        };
    }

    /**
     * Port to call clearTimer function for clear timer.
     */
    panel.port.on('clearTimer', function() {
        clearTimer();
    });

    /**
     * Clear timer and empty the follower lists.
     */
    function clearTimer() {
        tmr.clearInterval(intervalID);
        liveFollowings = [];
        newLiveFollowings = [];
    }

    /**
     * Port for login page localization.
     */
    panel.port.on('loginPage', function() {
        var locale = { signIn: signIn, passSign: _('pass_sign'), welcomeMsg: _('welcome_msg'), username: _('username') };
        panel.port.emit('loginPageResponse', locale);
    });

    /**
     * Port for sign in/out localization.
     */
    panel.port.on('getSignInOut', function() {

        if (getStorageItem('twitchName') == undefined) {
            panel.port.emit('getSignInOutResponse', signIn);
        } else {
            panel.port.emit('getSignInOutResponse', signOut);
        }

    });

    /**
     * Port for sign out localization.
     */
    panel.port.on('getLoadCheck', function() {
        panel.port.emit('getLoadCheckResponse', signOut);
    });

    /**
     * Port for search page beginning message localization.
     */
    panel.port.on('searchMessage', function() {
        panel.port.emit('searchMessageResponse', searchMessage);
    });

    /**
     * Port for setting localizations and values.
     */
    panel.port.on('getSettings', function(isLogged) {
        var settingsLocale = {
            refreshBtn: _('refresh_fl_btn'),
            refreshMsg: _('refresh_followed'),
            help: _('donate'),
            createdBy: _('created_by'),
            notification: getStorageItem('notification'),
            notifySound: getStorageItem('notifySound'),
            open: getStorageItem('open'),
            notifySoundRing: getStorageItem('notifySoundRing'),
            showNotifications: _('show_notifications'),
            playSound: _('play_sound'),
            openStreams: _('open_streams'),
            newTab: _('new_tab'),
            newWindow: _('new_window'),
            popout: _('popout'),
            notificationSound: _('new_tab'),
            newTab: _('new_tab'),
            notificationSound: _('notification_sound')
        };

        if (isLogged) {
            settingsLocale.logMsg = _('logged_as');
            settingsLocale.logInOut = signOut;
            panel.port.emit('settingsResponse', settingsLocale);
        } else {
            settingsLocale.logMsg = _('not_logged_yet');
            settingsLocale.logInOut = signIn;
            panel.port.emit('settingsResponse', settingsLocale);
        }
    });

    panel.port.on('changeSetting', function (setting, value) {
        setStorageItem(setting, value);

        if (setting == 'notification') {
            if (value == true) {
                initializeNotify();
            } else {
                clearTimer();
            }
        }
    });

    /**
     * Port for refresh followings.
     */
    panel.port.on('refreshFollowings', function() {
        followingCheck(getStorageItem('twitchName'));
    });

    /**
     * Port for Open Url and hide the panel.
     */
    panel.port.on('openPage', function(url) {
        openLink(url, true)
    });

    /**
     * Open Link depend on which open type selected in settings.
     */
    function openLink(url, isStream) {
        var openType = getStorageItem('open');

        if (openType == 2) {
            tabs.open({
              url: url,
              inNewWindow: true
            });
        } else if (openType == 3 && isStream) {
            url = url + '/popout';
            tabs.open(url);
        } else {
            tabs.open(url);
        }

        panel.hide();
    }

    // Set Simple Storage Item
    panel.port.on('setStorage', function(key, value) {
        setStorageItem(key, value);
    });

    // Get Simple Storage Item
    panel.port.on('getStorage', function(key) {
        panel.port.emit('getStorageResponse', getStorageItem(key));
    });

    // Delete Simple Storage Item
    panel.port.on('deleteStorage', function(key) {
        deleteStorageItem(key)
    });
};
<commit_msg>Requests are Changed<commit_after>// Firefox Add-on Requires
var self = require('sdk/self'),
    buttons = require('sdk/ui/button/action'),
    panels = require('sdk/panel'),
    Request = require('sdk/request').Request,
    tmr = require('sdk/timers'),
    notifications = require('sdk/notifications'),
    tabs = require('sdk/tabs'),
    _ = require('sdk/l10n').get,
    ss = require('sdk/simple-storage'),
    platform = require("sdk/system").platform;

// API Urls
var streamAPI = 'https://api.twitch.tv/kraken/streams/',
    gameAPI = 'https://api.twitch.tv/kraken/games/top',
    followingPre = 'https://api.twitch.tv/kraken/users/',
    followingSuff = '/follows/channels',
    featuredAPI = 'https://api.twitch.tv/kraken/streams/featured',
    searchAPI = 'https://api.twitch.tv/kraken/search/streams';

var isFirst = true,
    followingNames = [],
    liveFollowings = [],
    newLiveFollowings = [],
    intervalID;

// Creating an empty settings locale storage if it is not set yet.
if (!ss.storage.settings)
    ss.storage.settings = {};

// Executes after extension loads.
exports.main = function(options, callbacks) {

    // Setting first settings
    if ((options.loadReason == "install" || options.loadReason == "upgrade") && Object.keys(ss.storage.settings).length == 0) {
        setStorageItem('notification', true);
        setStorageItem('notifySound', true);
        setStorageItem('open', 1);
        setStorageItem('notifySoundRing', 'Chord.mp3');
    }

    // Localization variables
    var viewers = ' ' + _('viewers'),
        channels = ' ' + _('channels'),
        playing = _('playing'),
        signIn = _('sign_in'),
        signOut = _('sign_out'),
        noStreams = _('no_streams'),
        searchMessage = _('search_message');

    // Action Button Initialize
    var button = buttons.ActionButton({
        id: 'twitch-live',
        label: 'Twitch Live',
        icon: {
            '16': './icons/twitch-icon-32.png',
            '32': './icons/twitch-icon-32.png',
            '64': './icons/twitch-icon-64.png',
            '128': './icons/twitch-icon-128.png'
        },
        onClick: handleClick
    });

    // Panel Initialize
    var panel = panels.Panel({
        contentURL: self.data.url('panel.html'),
        width: 400,
        height: 555
    });

    // Action Button Click Handler
    function handleClick(state) {
        panel.show({
            position: button
        });
    }

    /* Storage helpers */
    function getStorageItem(item) {
        return ss.storage.settings[item];
    }

    function setStorageItem(item, val) {
        ss.storage.settings[item] = val;
    }

    function deleteStorageItem(item) {
        delete ss.storage.settings[item];
    }

    function include(arr, obj) {
        return (arr.indexOf(obj) != -1);
    }

    /**
     * Port to get online following channels.
     * Send all followed channels to printFollowing() function for API request.
     */
    panel.port.on('getFollowings', function() {
        isFirst = true;

        if (followingNames.length > 0) {
            for (var i = 0; i < followingNames.length; i++) {
                if (i == followingNames.length - 1) {
                    printFollowing(followingNames[i], true);
                } else {
                    printFollowing(followingNames[i]);
                }
            }
        } else {
            panel.port.emit('noFollowingStream', noStreams);
        }
    });

    /**
     * Get followed channels one by one and send a API request.
     * If channels if online return port for channel information.
     */
    function printFollowing(name, isLast) {
        Request ({
            url: streamAPI + encodeURIComponent(name),
            headers: {
                'Cache-control': 'no-cache'
            },
            onComplete: function(response) {
                if (response.json.stream != null) {
                    if (isFirst === true) {
                        isFirst = false;
                    }
                    panel.port.emit('followResponse', response.json, viewers, playing);
                }

                // If there is no online channel, then it give a warning
                if (isFirst == true && isLast == true) {
                    panel.port.emit('noFollowingStream', noStreams);
                }
            }
        }).get();
    }

    /**
     * Port to get top 50 games.
     * Return a port for game informations.
     */
    panel.port.on('printGames', function() {
        Request ({
            url: gameAPI,
            content: {
                limit: 50
            },
            headers: {
                'Cache-control': 'no-cache'
            },
            onComplete: function(response) {
                panel.port.emit('gameResponse', response.json, viewers, channels);
            }
        }).get();
    });

    /**
     * Port to get top 50 streams by popularity.
     * Return a port for stream informations.
     */
    panel.port.on('printStreams', function() {
        Request ({
            url: streamAPI,
            content: {
                limit: 50
            },
            headers: {
                'Cache-control': 'no-cache'
            },
            onComplete: function(response) {
                panel.port.emit('streamResponse', response.json, viewers, playing);
            }
        }).get();
    });

    /**
     * Port to get top 50 streams by game. This port is used for second page of the game tab.
     * Return a port for stream informations.
     */
    panel.port.on('getStreamsByGame', function(gameName) {
        Request ({
            url: streamAPI,
            content: {
                game : gameName,
                limit : 50
            },
            headers: {
                'Cache-control': 'no-cache'
            },
            onComplete: function(response) {
                panel.port.emit('streamByGameResponse', response.json, viewers, playing);
            }
        }).get();
    });

    /**
     * Port to get top 50 featured streams.
     * Return a port for stream informations.
     */
    panel.port.on('getFeatured', function() {
        Request ({
            url: featuredAPI,
            content: {
                limit: 50
            },
            headers: {
                'Cache-control': 'no-cache'
            },
            onComplete: function(response) {
                panel.port.emit('featuredResponse', response.json, viewers, playing);
            }
        }).get();
    });

    /**
     * Port to get search result by query.
     * Return a port for search result
     */
    panel.port.on('search', function(query) {
        Request ({
            url: searchAPI,
            content: {
                q: encodeURIComponent(query)
            },
            headers: {
                'Cache-control': 'no-cache'
            },
            onComplete: function(response) {
                panel.port.emit('searchResponse', response.json, viewers, playing);
            }
        }).get();
    });

    /**
     * Call initializeNotify() for initialize notifications.
     */
    panel.port.on('initialize', function() {
        initializeNotify();
    });

    /**
     * Get followers and initialize notifications.
     * Notifications send in every 5 minutes.
     */
    function initializeNotify() {
        var username = getStorageItem('twitchName');

        if (username != undefined && username != '') {
            followingCheck(username, function() {
                // Firstly we are initializing a postnotify and then setting it to do that for 5mins(300000 ms) repeatedly.
                postNotify();
                intervalID = tmr.setInterval(postNotify, 300000); // 5 * 60 * 100
            });
        }
    }

    /**
     * Send API request to get all followers.
     * Used in initialize port and for refresh the followers.
     */
    function followingCheck(username, callback) {
        if (username != undefined) {
            var followUrl = followingPre + encodeURIComponent(username) + followingSuff;

            Request ({
                url: followUrl,
                content: {
                    limit: 500
                },
                headers: {
                    'Cache-control': 'no-cache'
                },
                onComplete: function(response) {
                    if (response.json.follows != undefined) {
                        for (var i = 0; i < response.json.follows.length; i++) {
                            followingNames[i] = response.json.follows[i].channel.name;
                        }

                        // If callback parameter is filled, execute it.
                        if (callback && typeof(callback) === 'function') {
                            callback();
                        }
                    }
                }
            }).get();
        };
    }

    /**
     * Execute in every 5 minutes and check for the new online streamers.
     * If there is online streamer then send it to notify function to show notify.
     */
    function postNotify() {
        var a = 0;
        var index = 0;
        var streamersText = '';
        var isLiveEmpty = liveFollowings.length == 0;
        var lastUrl = '';

        if (followingNames.length > 0) {
            for (var i = 0; i < followingNames.length; i++) {
                Request ({
                    url: streamAPI + encodeURIComponent(followingNames[i]),
                    headers: {
                        'Cache-control': 'no-cache'
                    },
                    onComplete: function(response) {

                        // If live followigs empty, then here executes, otherwise goes to else for comparison
                        if (isLiveEmpty) {
                            if (response.json.stream != undefined) {
                                if (response.json.stream.channel.display_name !== undefined) {
                                    liveFollowings[a++] = response.json.stream.channel.display_name;
                                    lastUrl = response.json.stream.channel.url;
                                }
                            }

                            index++;
                            if (index == followingNames.length) {
                                streamersText = liveFollowings.join(', ');
                                streamersText += ' ' + _('now_online');

                                notify(streamersText, a, false, lastUrl);
                            }

                        } else {
                            if (response.json.stream != undefined) {
                                if (response.json.stream.channel.display_name !== undefined) {
                                    newLiveFollowings[a++] = response.json.stream.channel.display_name;
                                    if (!include(liveFollowings, response.json.stream.channel.display_name))
                                        lastUrl = response.json.stream.channel.url;
                                }
                            }

                            index++;
                            if (index == followingNames.length) {
                                var nowOnlineCount = 0;

                                for (var j = 0; j < newLiveFollowings.length; j++) {
                                    if (!include(liveFollowings, newLiveFollowings[j])) {
                                        streamersText += newLiveFollowings[j] + ', ';
                                        nowOnlineCount++;
                                    }
                                }

                                if (nowOnlineCount != 0) {
                                    streamersText = streamersText.slice(0, -2); // to delete the last ', ' characters.
                                    streamersText += ' ' + _('now_online');
                                    notify(streamersText, nowOnlineCount, true, lastUrl);
                                }
                            }
                        }

                    }
                }).get();
            }
        }

    }

    /**
     * Get notify text count and show notification with these.
     * If there is one online streamer then show different
     */
    function notify(ntext, count, newLive, lastUrl) {
        if (count == 1) {
            notifications.notify({
                title: ntext,
                text: _('click_to_go'),
                iconURL: './icons/twitch-icon-128.png',
                onClick: function() {
                    openLink(lastUrl, true);
                }
            });
        } else if (count > 1) {
            notifications.notify({
                title: count + ' ' + _('streamers_online'),
                text: ntext,
                iconURL: './icons/twitch-icon-128.png',
                onClick: function() {
                    openLink('http://www.twitch.tv/directory/following', false);
                }
            });
        }

        // Play audio if OS is Windows
        if (platform == 'winnt' && getStorageItem('notifySound') == true) {
            panel.port.emit('playSound', getStorageItem('notifySoundRing'));
        }

        // If newlivefollowings is not empty, pass it's content to main array and empty it.
        if (newLive) {
            liveFollowings = [];
            liveFollowings = newLiveFollowings;
            newLiveFollowings = [];
        };
    }

    /**
     * Port to call clearTimer function for clear timer.
     */
    panel.port.on('clearTimer', function() {
        clearTimer();
    });

    /**
     * Clear timer and empty the follower lists.
     */
    function clearTimer() {
        tmr.clearInterval(intervalID);
        liveFollowings = [];
        newLiveFollowings = [];
    }

    /**
     * Port for login page localization.
     */
    panel.port.on('loginPage', function() {
        var locale = { signIn: signIn, passSign: _('pass_sign'), welcomeMsg: _('welcome_msg'), username: _('username') };
        panel.port.emit('loginPageResponse', locale);
    });

    /**
     * Port for sign in/out localization.
     */
    panel.port.on('getSignInOut', function() {

        if (getStorageItem('twitchName') == undefined) {
            panel.port.emit('getSignInOutResponse', signIn);
        } else {
            panel.port.emit('getSignInOutResponse', signOut);
        }

    });

    /**
     * Port for sign out localization.
     */
    panel.port.on('getLoadCheck', function() {
        panel.port.emit('getLoadCheckResponse', signOut);
    });

    /**
     * Port for search page beginning message localization.
     */
    panel.port.on('searchMessage', function() {
        panel.port.emit('searchMessageResponse', searchMessage);
    });

    /**
     * Port for setting localizations and values.
     */
    panel.port.on('getSettings', function(isLogged) {
        var settingsLocale = {
            refreshBtn: _('refresh_fl_btn'),
            refreshMsg: _('refresh_followed'),
            help: _('donate'),
            createdBy: _('created_by'),
            notification: getStorageItem('notification'),
            notifySound: getStorageItem('notifySound'),
            open: getStorageItem('open'),
            notifySoundRing: getStorageItem('notifySoundRing'),
            showNotifications: _('show_notifications'),
            playSound: _('play_sound'),
            openStreams: _('open_streams'),
            newTab: _('new_tab'),
            newWindow: _('new_window'),
            popout: _('popout'),
            notificationSound: _('new_tab'),
            newTab: _('new_tab'),
            notificationSound: _('notification_sound')
        };

        if (isLogged) {
            settingsLocale.logMsg = _('logged_as');
            settingsLocale.logInOut = signOut;
            panel.port.emit('settingsResponse', settingsLocale);
        } else {
            settingsLocale.logMsg = _('not_logged_yet');
            settingsLocale.logInOut = signIn;
            panel.port.emit('settingsResponse', settingsLocale);
        }
    });

    panel.port.on('changeSetting', function (setting, value) {
        setStorageItem(setting, value);

        if (setting == 'notification') {
            if (value == true) {
                initializeNotify();
            } else {
                clearTimer();
            }
        }
    });

    /**
     * Port for refresh followings.
     */
    panel.port.on('refreshFollowings', function() {
        followingCheck(getStorageItem('twitchName'));
    });

    /**
     * Port for Open Url and hide the panel.
     */
    panel.port.on('openPage', function(url) {
        openLink(url, true)
    });

    /**
     * Open Link depend on which open type selected in settings.
     */
    function openLink(url, isStream) {
        var openType = getStorageItem('open');

        if (openType == 2) {
            tabs.open({
              url: url,
              inNewWindow: true
            });
        } else if (openType == 3 && isStream) {
            url = url + '/popout';
            tabs.open(url);
        } else {
            tabs.open(url);
        }

        panel.hide();
    }

    // Set Simple Storage Item
    panel.port.on('setStorage', function(key, value) {
        setStorageItem(key, value);
    });

    // Get Simple Storage Item
    panel.port.on('getStorage', function(key) {
        panel.port.emit('getStorageResponse', getStorageItem(key));
    });

    // Delete Simple Storage Item
    panel.port.on('deleteStorage', function(key) {
        deleteStorageItem(key)
    });
};
<|endoftext|>


<commit_before>'use strict'

const id = 'subsystem'

const validSubsystems = [
  'benchmark'
, 'build'
, 'deps'
, 'doc'
, 'errors'
, 'etw'
, 'inspector'
, 'lib'
, 'meta'
, 'msi'
, 'node'
, 'n-api'
, 'perfctr'
, 'src'
, 'test'
, 'tools'
, 'win'

// core libs
, 'assert'
, 'async_wrap'
, 'buffer'
, 'child_process'
, 'cluster'
, 'console'
, 'constants'
, 'crypto'
, 'debugger'
, 'dgram'
, 'dns'
, 'domain'
, 'events'
, 'fs'
, 'http'
, 'https'
, 'http2'
, 'module'
, 'net'
, 'os'
, 'path'
, 'perf_hooks'
, 'process'
, 'punycode'
, 'querystring'
, 'readline'
, 'repl'
, 'stream'
, 'string_decoder'
, 'sys'
, 'timers'
, 'tls'
, 'tty'
, 'url'
, 'util'
, 'v8'
, 'vm'
, 'zlib'
]

module.exports = {
  id: id
, meta: {
    description: 'enforce subsystem validity'
  , recommended: true
  }
, defaults: {
    subsystems: validSubsystems
  }
, options: {
    subsystems: validSubsystems
  }
, validate: (context, rule) => {
    const subs = rule.options.subsystems
    const parsed = context.toJSON()
    if (!parsed.subsystems.length) {
      if (!parsed.release && !parsed.working) {
        // Missing subsystem
        context.report({
          id: id
        , message: 'Missing subsystem.'
        , string: parsed.title
        , line: 0
        , column: 0
        , level: 'fail'
        , wanted: subs
        })
      } else {
        context.report({
          id: id
        , message: 'Release commits do not have subsystems'
        , string: ''
        , level: 'skip'
        })
      }
    } else {
      var failed = false
      for (const sub of parsed.subsystems) {
        if (!~subs.indexOf(sub)) {
          failed = true
          // invalid subsystem
          const column = parsed.title.indexOf(sub)
          context.report({
            id: id
          , message: `Invalid subsystem: "${sub}"`
          , string: parsed.title
          , line: 0
          , column: column
          , level: 'fail'
          , wanted: subs
          })
        }
      }

      if (!failed) {
        context.report({
          id: id
        , message: 'valid subsystems'
        , string: parsed.subsystems.join(',')
        , level: 'pass'
        })
      }
    }
  }
}
<commit_msg>async_wrap -> async_hooks (#17)<commit_after>'use strict'

const id = 'subsystem'

const validSubsystems = [
  'benchmark'
, 'build'
, 'deps'
, 'doc'
, 'errors'
, 'etw'
, 'inspector'
, 'lib'
, 'meta'
, 'msi'
, 'node'
, 'n-api'
, 'perfctr'
, 'src'
, 'test'
, 'tools'
, 'win'

// core libs
, 'assert'
, 'async_hooks'
, 'buffer'
, 'child_process'
, 'cluster'
, 'console'
, 'constants'
, 'crypto'
, 'debugger'
, 'dgram'
, 'dns'
, 'domain'
, 'events'
, 'fs'
, 'http'
, 'https'
, 'http2'
, 'module'
, 'net'
, 'os'
, 'path'
, 'perf_hooks'
, 'process'
, 'punycode'
, 'querystring'
, 'readline'
, 'repl'
, 'stream'
, 'string_decoder'
, 'sys'
, 'timers'
, 'tls'
, 'tty'
, 'url'
, 'util'
, 'v8'
, 'vm'
, 'zlib'
]

module.exports = {
  id: id
, meta: {
    description: 'enforce subsystem validity'
  , recommended: true
  }
, defaults: {
    subsystems: validSubsystems
  }
, options: {
    subsystems: validSubsystems
  }
, validate: (context, rule) => {
    const subs = rule.options.subsystems
    const parsed = context.toJSON()
    if (!parsed.subsystems.length) {
      if (!parsed.release && !parsed.working) {
        // Missing subsystem
        context.report({
          id: id
        , message: 'Missing subsystem.'
        , string: parsed.title
        , line: 0
        , column: 0
        , level: 'fail'
        , wanted: subs
        })
      } else {
        context.report({
          id: id
        , message: 'Release commits do not have subsystems'
        , string: ''
        , level: 'skip'
        })
      }
    } else {
      var failed = false
      for (const sub of parsed.subsystems) {
        if (!~subs.indexOf(sub)) {
          failed = true
          // invalid subsystem
          const column = parsed.title.indexOf(sub)
          context.report({
            id: id
          , message: `Invalid subsystem: "${sub}"`
          , string: parsed.title
          , line: 0
          , column: column
          , level: 'fail'
          , wanted: subs
          })
        }
      }

      if (!failed) {
        context.report({
          id: id
        , message: 'valid subsystems'
        , string: parsed.subsystems.join(',')
        , level: 'pass'
        })
      }
    }
  }
}
<|endoftext|>