<commit_before>function resize_main_div() {
    // Resize main_div to exactly take up remaining vertical space.
    var div = $('#main_div');
    div.height(Math.max(200, div.height() + $(window).height() - $('body').height()));
}
$(function () {
    resize_main_div();
    $(window).resize(resize_main_div);
    $('#zephyr-type-tabs a').on('shown', function (e) { resize_main_div(); });
});

$(function() {
    $('#zephyr-type-tabs a[href="#class-message"]').on('shown', function (e) {
        $('#class-message input:not(:hidden):first').focus().select();
    });
    $('#zephyr-type-tabs a[href="#personal-message"]').on('shown', function (e) {
        $('#personal-message input:not(:hidden):first').focus().select();
    });
});

$.ajaxSetup({
     beforeSend: function(xhr, settings) {
         function getCookie(name) {
             var cookieValue = null;
             if (document.cookie && document.cookie != '') {
                 var cookies = document.cookie.split(';');
                 for (var i = 0; i < cookies.length; i++) {
                     var cookie = jQuery.trim(cookies[i]);
                     // Does this cookie string begin with the name we want?
                 if (cookie.substring(0, name.length + 1) == (name + '=')) {
                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                     break;
                 }
             }
         }
         return cookieValue;
         }
         if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
             // Only send the token to relative URLs i.e. locally.
             xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
         }
     }
});

$(function() {
    var status_classes = 'alert-error alert-success alert-info';
    var send_status = $('#send-status');
    var buttons = $('#class-message, #personal-message').find('input[type="submit"]');

    var options = {
        beforeSubmit: function (form, _options) {
            send_status.removeClass(status_classes)
                       .addClass('alert-info')
                       .text('Sending')
                       .stop(true).fadeTo(0,1);
            buttons.attr('disabled', 'disabled');
        },
        success: function (resp, statusText, xhr, form) {
            form.find('textarea').val('');
            send_status.removeClass(status_classes)
                       .addClass('alert-success')
                       .text('Sent message')
                       .stop(true).fadeTo(0,1).delay(1000).fadeOut(1000);
            buttons.removeAttr('disabled');
        },
        error: function() {
            send_status.removeClass(status_classes)
                       .addClass('alert-error')
                       .html('Error sending message ')
                       .append($('')
                           .addClass('send-status-close').html('×')
                           .click(function () { send_status.stop(true).fadeOut(500); }))
                       .stop(true).fadeTo(0,1);

            buttons.removeAttr('disabled');
        }
    };

    send_status.hide();
    $("#class-message form").ajaxForm(options);
    $("#personal-message form").ajaxForm(options);
});

selected_tag = '
▶
'

var allow_hotkeys = true;

// NB: This just binds to current elements, and won't bind to elements
// created after ready() is called.

$(document).ready(function() {
    $('input, textarea, button').focus(function() {
          allow_hotkeys = false;
    });

    $('input, textarea, button').blur(function() {
          allow_hotkeys = true;
    });
});

var goto_pressed = false;

$(document).keydown(function(event) {
    if (allow_hotkeys) {

        if (event.keyCode == 38 || event.keyCode == 40) { // down or up arrow
            p = $("#selected");
            tr = $(p).closest("tr");
            td = $(p).closest("td");

            if (event.keyCode == 40) { // down arrow
                // There are probably more verbose but more efficient ways to do this.
                next_zephyr = tr.nextAll(":not(:hidden):first");
            } else { // up arrow
                next_zephyr = tr.prevAll(":not(:hidden):first");
            }
            if (next_zephyr.length != 0) { // We are not at the bottom or top of the zephyrs.
                next_zephyr.children("td:first").html(selected_tag);
                td.empty(); // Clear the previous arrow.
                $.post("update", {pointer: next_zephyr.attr("id")});

                if ($(next_zephyr).offset().top < $("#main_div").offset().top) {
                    $("#main_div").scrollTop($("#main_div").scrollTop() - 75);
                }

                if ($(next_zephyr).offset().top + $(next_zephyr).height() > $("#main_div").offset().top + $("#main_div").height()) {
                    $("#main_div").scrollTop($("#main_div").scrollTop() + 75);
                }
            }
        } else if (event.keyCode == 82) { // 'r' keypress, for responding to a zephyr
            var parent = $("#selected").parents("tr");
            var zephyr_class = parent.find("span.zephyr_class").text();
            var instance = parent.find("span.zephyr_instance").text();
            $("#class").val(zephyr_class);
            $("#instance").val(instance);
            $("#new_zephyr").focus();
            $("#new_zephyr").select();
            event.preventDefault();
        } else if (event.keyCode == 71) { // 'g' keypress, set trigger for "go to"
            goto_pressed = true;
            event.preventDefault();
        } else if (goto_pressed && event.keyCode == 67) { // 'c' keypress, for narrow-by-recipient
            var parent = $("#selected").parents("tr");
            var zephyr_class = parent.find("span.zephyr_class").text();
            narrow(zephyr_class, parent.attr("id"));
            event.preventDefault()
        } else if (goto_pressed && event.keyCode == 73) { // 'i' keypress, for narrow-by-instance
            var parent = $("#selected").parents("tr");
            var zephyr_class = parent.find("span.zephyr_class").text();
            var zephyr_instance = parent.find("span.zephyr_instance").text();
            narrow_instance(zephyr_class, zephyr_instance, parent.attr("id"));
            event.preventDefault()
        } else if (goto_pressed && event.keyCode == 80) { // 'p' keypress, for narrow-to-personals
            narrow_personals($("#selected").parents("tr").attr("id"));
            event.preventDefault();
        } else if (goto_pressed && event.keyCode == 65) { // 'a' keypress, for unnarrow
            unhide();
            event.preventDefault();
        }

        if (event.keyCode != 71) { // not 'g'
            goto_pressed = false;
        }

    } else if (event.keyCode == 27) { // Esc pressed
        $('input, textarea, button').blur();
        event.preventDefault();
    }
});

function scroll_to_zephyr(target_zephyr, old_offset) {
    // target_zephyr is an id.
    // old_offset is how far from the top of the scroll area the
    // zephyr was before any narrowing or unnarrowing happened.
    var height_above_zephyr = 0;
    $("#table tr:lt(" + $("#" + target_zephyr).index() + ")").each(function() {
        if (!$(this).is(":hidden")) {
            height_above_zephyr += $(this).height();
        }
    });
    $("#main_div").scrollTop(height_above_zephyr + old_offset);
}

function hide_personals() {
    $("span.zephyr_personal_recipient").each(
        function() {
            $(this).parents("tr").hide();
        }
    );
}

function narrow_personals(target_zephyr) {
    var old_top = $("#main_div").offset().top - $("#" + target_zephyr).offset().top;

    $("span.zephyr_personal_recipient").each(
        function() {
            $(this).parents("tr").show();
        }
    );
    $("span.zephyr_class").each(
        function() {
            $(this).parents("tr").hide();
        }
    );

    $("#selected").closest("td").empty();
    $("#" + target_zephyr).children("td:first").html(selected_tag);
    $.post("update", {pointer: target_zephyr});
    scroll_to_zephyr(target_zephyr, old_top);

    $("#unhide").removeAttr("disabled");
    $("#narrow_indicator").html("Showing personals");
}

function narrow(class_name, target_zephyr) {
    // We want the zephyr on which the narrow happened to stay in the same place if possible.
    var old_top = $("#main_div").offset().top - $("#" + target_zephyr).offset().top;
    $("span.zephyr_class").each(
        function() {
            if ($(this).text() != class_name) {
                $(this).parents("tr").hide();
            } else {
                // If you've narrowed on an instance and then click on the class, that should unhide the other instances on that class.
                $(this).parents("tr").show();
	    }
        }
    );
    hide_personals();
    $("#selected").closest("td").empty();
    $("#" + target_zephyr).children("td:first").html(selected_tag);
    $.post("update", {pointer: target_zephyr});

    // Try to keep the zephyr in the same place on the screen after narrowing.
    scroll_to_zephyr(target_zephyr, old_top);

    $("#unhide").removeAttr("disabled");
    $("#narrow_indicator").html("Showing " + class_name + "");
}

function narrow_instance(class_name, instance, target_zephyr) {
    var old_top = $("#main_div").offset().top - $("#" + target_zephyr).offset().top;
    $("tr").each(
        function() {
            if (($(this).find("span.zephyr_class").text() != class_name) ||
		($(this).find("span.zephyr_instance").text() != instance)) {
                $(this).hide();
	    }
        }
    );
    hide_personals();
    $("#selected").closest("td").empty();
    $("#" + target_zephyr).children("td:first").html(selected_tag);
    $.post("update", {pointer: target_zephyr});

    // Try to keep the zephyr in the same place on the screen after narrowing.
    scroll_to_zephyr(target_zephyr, old_top);

    $("#unhide").removeAttr("disabled");
    $("#narrow_indicator").html("Showing " + class_name
      + " " + instance + "");
}

function prepare_personal(username) {
    $('#zephyr-type-tabs a[href="#personal-message"]').tab('show');
    $("#recipient").val(username);
    $("#new_personal_zephyr").focus();
}

function unhide() {
    $("tr").show();

    p = $("#selected");
    tr = $(p).closest("tr");
    scroll_to_zephyr(tr.attr("id"), 0);

    $("#unhide").attr("disabled", "disabled");
    $("#narrow_indicator").html("");
}

function newline2br(content) {
    return content.replace(/\n/g, '
');
}

function add_message(index, zephyr) {
    var zephyr_para = $('
');
    var new_label = function (text, classes, on_click) {
        zephyr_para.append($('')
            .text(text)
            .addClass('label zephyr_label_clickable ' + classes)
            .click(on_click));
        zephyr_para.append(' ');
    };

    if (zephyr.type == 'class') {
        new_label(zephyr.display_recipient, 'zephyr_class',
            function (e) { narrow(zephyr.display_recipient, zephyr.id); });
        new_label(zephyr.instance, 'zephyr_instance',
            function (e) { narrow_instance(zephyr.display_recipient,
                                           zephyr.instance, zephyr.id); });
    } else {
        new_label(zephyr.display_recipient, 'zephyr_personal_recipient',
            function (e) { narrow_personals(zephyr.id); });
        zephyr_para.append('← ');
    }

    new_label(zephyr.sender, 'zephyr_sender',
             function (e) { prepare_personal(zephyr.sender); });

    zephyr_para.append('
' + newline2br(zephyr.content));

    $('#table tr:last').after($('
')
        .attr('id', zephyr.id)
        .append('

	')
        .append($('').append(zephyr_para)));
}

$(function() {
  $(initial_zephyr_json).each(add_message);
});

function get_updates_longpoll(data) {
    if (data && data.zephyrs) {
	$.each(data.zephyrs, add_message);
    }
    var last_received = $("tr:last").attr("id");
    $.post("get_updates_longpoll",
	   {last_received: last_received},
	    function(data) {
		get_updates_longpoll(data);
	    }, "json");
}

$(document).ready(function() {
    get_updates_longpoll()
});

<commit_msg>Correctly handle 'r' for personals.<commit_after>function resize_main_div() {
    // Resize main_div to exactly take up remaining vertical space.
    var div = $('#main_div');
    div.height(Math.max(200, div.height() + $(window).height() - $('body').height()));
}
$(function () {
    resize_main_div();
    $(window).resize(resize_main_div);
    $('#zephyr-type-tabs a').on('shown', function (e) { resize_main_div(); });
});

$(function() {
    $('#zephyr-type-tabs a[href="#class-message"]').on('shown', function (e) {
        $('#class-message input:not(:hidden):first').focus().select();
    });
    $('#zephyr-type-tabs a[href="#personal-message"]').on('shown', function (e) {
        $('#personal-message input:not(:hidden):first').focus().select();
    });
});

$.ajaxSetup({
     beforeSend: function(xhr, settings) {
         function getCookie(name) {
             var cookieValue = null;
             if (document.cookie && document.cookie != '') {
                 var cookies = document.cookie.split(';');
                 for (var i = 0; i < cookies.length; i++) {
                     var cookie = jQuery.trim(cookies[i]);
                     // Does this cookie string begin with the name we want?
                 if (cookie.substring(0, name.length + 1) == (name + '=')) {
                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                     break;
                 }
             }
         }
         return cookieValue;
         }
         if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
             // Only send the token to relative URLs i.e. locally.
             xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
         }
     }
});

$(function() {
    var status_classes = 'alert-error alert-success alert-info';
    var send_status = $('#send-status');
    var buttons = $('#class-message, #personal-message').find('input[type="submit"]');

    var options = {
        beforeSubmit: function (form, _options) {
            send_status.removeClass(status_classes)
                       .addClass('alert-info')
                       .text('Sending')
                       .stop(true).fadeTo(0,1);
            buttons.attr('disabled', 'disabled');
        },
        success: function (resp, statusText, xhr, form) {
            form.find('textarea').val('');
            send_status.removeClass(status_classes)
                       .addClass('alert-success')
                       .text('Sent message')
                       .stop(true).fadeTo(0,1).delay(1000).fadeOut(1000);
            buttons.removeAttr('disabled');
        },
        error: function() {
            send_status.removeClass(status_classes)
                       .addClass('alert-error')
                       .html('Error sending message ')
                       .append($('')
                           .addClass('send-status-close').html('×')
                           .click(function () { send_status.stop(true).fadeOut(500); }))
                       .stop(true).fadeTo(0,1);

            buttons.removeAttr('disabled');
        }
    };

    send_status.hide();
    $("#class-message form").ajaxForm(options);
    $("#personal-message form").ajaxForm(options);
});

selected_tag = '
▶
'

var allow_hotkeys = true;

// NB: This just binds to current elements, and won't bind to elements
// created after ready() is called.

$(document).ready(function() {
    $('input, textarea, button').focus(function() {
          allow_hotkeys = false;
    });

    $('input, textarea, button').blur(function() {
          allow_hotkeys = true;
    });
});

var goto_pressed = false;

$(document).keydown(function(event) {
    if (allow_hotkeys) {

        if (event.keyCode == 38 || event.keyCode == 40) { // down or up arrow
            p = $("#selected");
            tr = $(p).closest("tr");
            td = $(p).closest("td");

            if (event.keyCode == 40) { // down arrow
                // There are probably more verbose but more efficient ways to do this.
                next_zephyr = tr.nextAll(":not(:hidden):first");
            } else { // up arrow
                next_zephyr = tr.prevAll(":not(:hidden):first");
            }
            if (next_zephyr.length != 0) { // We are not at the bottom or top of the zephyrs.
                next_zephyr.children("td:first").html(selected_tag);
                td.empty(); // Clear the previous arrow.
                $.post("update", {pointer: next_zephyr.attr("id")});

                if ($(next_zephyr).offset().top < $("#main_div").offset().top) {
                    $("#main_div").scrollTop($("#main_div").scrollTop() - 75);
                }

                if ($(next_zephyr).offset().top + $(next_zephyr).height() > $("#main_div").offset().top + $("#main_div").height()) {
                    $("#main_div").scrollTop($("#main_div").scrollTop() + 75);
                }
            }
        } else if (event.keyCode == 82) { // 'r' keypress, for responding to a zephyr
            var parent = $("#selected").parents("tr");
            var zephyr_class = parent.find("span.zephyr_class").text();
            var instance = parent.find("span.zephyr_instance").text();
            if (zephyr_class != '') {
                $('#zephyr-type-tabs a[href="#class-message"]').tab('show');
                $("#class").val(zephyr_class);
                $("#instance").val(instance);
                $("#new_zephyr").focus();
                $("#new_zephyr").select();
            } else { // No instance, must be a personal
                prepare_personal(parent.find("span.zephyr_sender").text());
                $("#new_personal_zephyr").focus();
                $("#new_personal_zephyr").select();
            }
            event.preventDefault();
        } else if (event.keyCode == 71) { // 'g' keypress, set trigger for "go to"
            goto_pressed = true;
            event.preventDefault();
        } else if (goto_pressed && event.keyCode == 67) { // 'c' keypress, for narrow-by-recipient
            var parent = $("#selected").parents("tr");
            var zephyr_class = parent.find("span.zephyr_class").text();
            narrow(zephyr_class, parent.attr("id"));
            event.preventDefault()
        } else if (goto_pressed && event.keyCode == 73) { // 'i' keypress, for narrow-by-instance
            var parent = $("#selected").parents("tr");
            var zephyr_class = parent.find("span.zephyr_class").text();
            var zephyr_instance = parent.find("span.zephyr_instance").text();
            narrow_instance(zephyr_class, zephyr_instance, parent.attr("id"));
            event.preventDefault()
        } else if (goto_pressed && event.keyCode == 80) { // 'p' keypress, for narrow-to-personals
            narrow_personals($("#selected").parents("tr").attr("id"));
            event.preventDefault();
        } else if (goto_pressed && event.keyCode == 65) { // 'a' keypress, for unnarrow
            unhide();
            event.preventDefault();
        }

        if (event.keyCode != 71) { // not 'g'
            goto_pressed = false;
        }

    } else if (event.keyCode == 27) { // Esc pressed
        $('input, textarea, button').blur();
        event.preventDefault();
    }
});

function scroll_to_zephyr(target_zephyr, old_offset) {
    // target_zephyr is an id.
    // old_offset is how far from the top of the scroll area the
    // zephyr was before any narrowing or unnarrowing happened.
    var height_above_zephyr = 0;
    $("#table tr:lt(" + $("#" + target_zephyr).index() + ")").each(function() {
        if (!$(this).is(":hidden")) {
            height_above_zephyr += $(this).height();
        }
    });
    $("#main_div").scrollTop(height_above_zephyr + old_offset);
}

function hide_personals() {
    $("span.zephyr_personal_recipient").each(
        function() {
            $(this).parents("tr").hide();
        }
    );
}

function narrow_personals(target_zephyr) {
    var old_top = $("#main_div").offset().top - $("#" + target_zephyr).offset().top;

    $("span.zephyr_personal_recipient").each(
        function() {
            $(this).parents("tr").show();
        }
    );
    $("span.zephyr_class").each(
        function() {
            $(this).parents("tr").hide();
        }
    );

    $("#selected").closest("td").empty();
    $("#" + target_zephyr).children("td:first").html(selected_tag);
    $.post("update", {pointer: target_zephyr});
    scroll_to_zephyr(target_zephyr, old_top);

    $("#unhide").removeAttr("disabled");
    $("#narrow_indicator").html("Showing personals");
}

function narrow(class_name, target_zephyr) {
    // We want the zephyr on which the narrow happened to stay in the same place if possible.
    var old_top = $("#main_div").offset().top - $("#" + target_zephyr).offset().top;
    $("span.zephyr_class").each(
        function() {
            if ($(this).text() != class_name) {
                $(this).parents("tr").hide();
            } else {
                // If you've narrowed on an instance and then click on the class, that should unhide the other instances on that class.
                $(this).parents("tr").show();
	    }
        }
    );
    hide_personals();
    $("#selected").closest("td").empty();
    $("#" + target_zephyr).children("td:first").html(selected_tag);
    $.post("update", {pointer: target_zephyr});

    // Try to keep the zephyr in the same place on the screen after narrowing.
    scroll_to_zephyr(target_zephyr, old_top);

    $("#unhide").removeAttr("disabled");
    $("#narrow_indicator").html("Showing " + class_name + "");
}

function narrow_instance(class_name, instance, target_zephyr) {
    var old_top = $("#main_div").offset().top - $("#" + target_zephyr).offset().top;
    $("tr").each(
        function() {
            if (($(this).find("span.zephyr_class").text() != class_name) ||
		($(this).find("span.zephyr_instance").text() != instance)) {
                $(this).hide();
	    }
        }
    );
    hide_personals();
    $("#selected").closest("td").empty();
    $("#" + target_zephyr).children("td:first").html(selected_tag);
    $.post("update", {pointer: target_zephyr});

    // Try to keep the zephyr in the same place on the screen after narrowing.
    scroll_to_zephyr(target_zephyr, old_top);

    $("#unhide").removeAttr("disabled");
    $("#narrow_indicator").html("Showing " + class_name
      + " " + instance + "");
}

function prepare_personal(username) {
    $('#zephyr-type-tabs a[href="#personal-message"]').tab('show');
    $("#recipient").val(username);
    $("#new_personal_zephyr").focus();
}

function unhide() {
    $("tr").show();

    p = $("#selected");
    tr = $(p).closest("tr");
    scroll_to_zephyr(tr.attr("id"), 0);

    $("#unhide").attr("disabled", "disabled");
    $("#narrow_indicator").html("");
}

function newline2br(content) {
    return content.replace(/\n/g, '
');
}

function add_message(index, zephyr) {
    var zephyr_para = $('
');
    var new_label = function (text, classes, on_click) {
        zephyr_para.append($('')
            .text(text)
            .addClass('label zephyr_label_clickable ' + classes)
            .click(on_click));
        zephyr_para.append(' ');
    };

    if (zephyr.type == 'class') {
        new_label(zephyr.display_recipient, 'zephyr_class',
            function (e) { narrow(zephyr.display_recipient, zephyr.id); });
        new_label(zephyr.instance, 'zephyr_instance',
            function (e) { narrow_instance(zephyr.display_recipient,
                                           zephyr.instance, zephyr.id); });
    } else {
        new_label(zephyr.display_recipient, 'zephyr_personal_recipient',
            function (e) { narrow_personals(zephyr.id); });
        zephyr_para.append('← ');
    }

    new_label(zephyr.sender, 'zephyr_sender',
             function (e) { prepare_personal(zephyr.sender); });

    zephyr_para.append('
' + newline2br(zephyr.content));

    $('#table tr:last').after($('
')
        .attr('id', zephyr.id)
        .append('

	')
        .append($('').append(zephyr_para)));
}

$(function() {
  $(initial_zephyr_json).each(add_message);
});

function get_updates_longpoll(data) {
    if (data && data.zephyrs) {
	$.each(data.zephyrs, add_message);
    }
    var last_received = $("tr:last").attr("id");
    $.post("get_updates_longpoll",
	   {last_received: last_received},
	    function(data) {
		get_updates_longpoll(data);
	    }, "json");
}

$(document).ready(function() {
    get_updates_longpoll()
});

<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');

var app = express();

app.get('/', function(req, res) {
	res.send('Hello World!');
});

app.use(express.static(path.join(__dirname, 'html')));

var server = app.listen(3000, function() {
	var host = server.address().address;
	var port = server.address().port;

	console.log('Example app listening at http://%s:%s', host, port);
});
<commit_msg>troubleshooting for heroku<commit_after>var express = require('express');
var path = require('path');

var app = express();

app.set('port', (process.env.PORT || 5000));

app.get('/', function(req, res) {
	res.send('Hello World!');
});

app.use(express.static(path.join(__dirname, 'html')));

// var server = app.listen(3000, function() {
// 	var host = server.address().address;
// 	var port = server.address().port;

// 	console.log('Example app listening at http://%s:%s', host, port);
// });

app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'));
});
<|endoftext|>


<commit_before>/*
	Copyright 2015, Google, Inc.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/
var express = require('express'),
	app = express(),
	http = require('http').Server(app),
	io = require('socket.io')(http),
	redis = require('redis').createClient(),
	session = require('express-session'),
	sharedsession = require("express-socket.io-session"),
	RedisStore = require('connect-redis')(session),
	google = require('googleapis'),
	OAuth2 = google.auth.OAuth2,
	user = google.oauth2('v2');

//Set up Google OAuth
var GOOGLE_CLIENT_ID = "PASTE YOUR CLIENT ID HERE", //See Readme to learn how to get this
	GOOGLE_CLIENT_SECRET = "PASTE YOUR CLIENT SECRET HERE", //See Readme to learn how to get this
	GOOGLE_REDIRECT_URL = "http://localhost:3000/auth/google/callback",
	oauth2Client = new OAuth2(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REDIRECT_URL),
	url = oauth2Client.generateAuthUrl({
		access_type: 'online',
		scope: 'https://www.googleapis.com/auth/userinfo.profile'
	});

//Treat the public directory as the root directory, and statically serve them
app.use('/', express.static(__dirname + '/public'));
app.set('views', __dirname + '/public');

//Use session to store user data with Redis
var ShoutChatSession = session({
	store: new RedisStore({
		client: redis
	}),
	secret: 'keyboard cat',
	resave: false,
	saveUninitialized: true
});

//Set up sessions for both http and sockets
app.use(ShoutChatSession);
io.use(sharedsession(ShoutChatSession));

//Callback function after the Google Auth is done
app.get('/auth/google/callback', function(req, res) {
	if (req.query.code) {
		oauth2Client.getToken(req.query.code, function(err, tokens) {
			if (err) {
				console.log("Auth Error - " + err);
				res.redirect('/');
			} else {
				//Use the returned token to authenticate the user
				oauth2Client.setCredentials(tokens);
				//Get the user's name and store it in the session
				user.userinfo.get({
					userId: 'me',
					auth: oauth2Client
				}, function(err, profile) {
					if (err) {
						console.log("Auth Error - " + err);
					} else {
						//If everything was successful, then store the user's name in session
						req.session.sender = profile.name;
					}
					res.redirect('/');
				});
			}
		});
	} else {
		console.log("Auth Error" - req.query)
	}
})

io.on('connection', function(socket) {

	//If user has a valid session, then tell them they are allowed to send messages
	if (socket.handshake.session) {
		if (socket.handshake.session.sender) {
			socket.emit('auth_set');
		}
	}

	//Enable the Google Auth button click
	//A different way to do this may be to use a template and inject the url into the template
	//However, I want to keep both implementations the same
	socket.on('get_google_auth', function(msg) {
		socket.emit('google_auth', url);
	});

	//Get the last 1000 messages and send them to the client
	redis.lrange('messages', 0, 1000, function(error, msgs) {
		msgs.forEach(function(msg) {
			socket.emit('child_added', JSON.parse(msg));
		});
	});

	//If the client sends us a new message, process it
	socket.on('new_message', function(msg) {
		//Make sure the client has a valid session
		if (socket.handshake.session) {
			if (socket.handshake.session.sender) {
				//Update the sender name using our session variable
				msg.sender = socket.handshake.session.sender;
				//Push the message to everyone else
				io.sockets.emit('child_added', msg);
				//Add the message to Redis
				redis.rpush('messages', JSON.stringify(msg));
				//Trim Redis so we only store the last 1000 messages (optional)
				redis.ltrim('messages', 0, 1000);
			}
		} else {
			//If the session is invalid, decline the message
			socket.emit('child_added', {
				sender: "",
				msg: "Failed to send message, please log in",
				lat: 0,
				lng: 0,
				location: ""
			})
		}
	})
});

http.listen(3000, '127.0.0.1');
<commit_msg>Allow node to work on production server<commit_after>/*
	Copyright 2015, Google, Inc.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/
var express = require('express'),
	app = express(),
	http = require('http').Server(app),
	io = require('socket.io')(http),
	redis = require('redis').createClient(),
	session = require('express-session'),
	sharedsession = require("express-socket.io-session"),
	RedisStore = require('connect-redis')(session),
	google = require('googleapis'),
	OAuth2 = google.auth.OAuth2,
	user = google.oauth2('v2');

//Set up Google OAuth
var GOOGLE_CLIENT_ID = "PASTE YOUR CLIENT ID HERE", //See Readme to learn how to get this
	GOOGLE_CLIENT_SECRET = "PASTE YOUR CLIENT SECRET HERE", //See Readme to learn how to get this
	GOOGLE_REDIRECT_URL = "http://localhost:3000/auth/google/callback",
	oauth2Client = new OAuth2(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REDIRECT_URL),
	url = oauth2Client.generateAuthUrl({
		access_type: 'online',
		scope: 'https://www.googleapis.com/auth/userinfo.profile'
	});

//Treat the public directory as the root directory, and statically serve them
app.use('/', express.static(__dirname + '/public'));
app.set('views', __dirname + '/public');

//Use session to store user data with Redis
var ShoutChatSession = session({
	store: new RedisStore({
		client: redis
	}),
	secret: 'keyboard cat',
	resave: false,
	saveUninitialized: true
});

//Set up sessions for both http and sockets
app.use(ShoutChatSession);
io.use(sharedsession(ShoutChatSession));

//Callback function after the Google Auth is done
app.get('/auth/google/callback', function(req, res) {
	if (req.query.code) {
		oauth2Client.getToken(req.query.code, function(err, tokens) {
			if (err) {
				console.log("Auth Error - " + err);
				res.redirect('/');
			} else {
				//Use the returned token to authenticate the user
				oauth2Client.setCredentials(tokens);
				//Get the user's name and store it in the session
				user.userinfo.get({
					userId: 'me',
					auth: oauth2Client
				}, function(err, profile) {
					if (err) {
						console.log("Auth Error - " + err);
					} else {
						//If everything was successful, then store the user's name in session
						req.session.sender = profile.name;
					}
					res.redirect('/');
				});
			}
		});
	} else {
		console.log("Auth Error" - req.query)
	}
})

io.on('connection', function(socket) {

	//If user has a valid session, then tell them they are allowed to send messages
	if (socket.handshake.session) {
		if (socket.handshake.session.sender) {
			socket.emit('auth_set');
		}
	}

	//Enable the Google Auth button click
	//A different way to do this may be to use a template and inject the url into the template
	//However, I want to keep both implementations the same
	socket.on('get_google_auth', function(msg) {
		socket.emit('google_auth', url);
	});

	//Get the last 1000 messages and send them to the client
	redis.lrange('messages', 0, 1000, function(error, msgs) {
		msgs.forEach(function(msg) {
			socket.emit('child_added', JSON.parse(msg));
		});
	});

	//If the client sends us a new message, process it
	socket.on('new_message', function(msg) {
		//Make sure the client has a valid session
		if (socket.handshake.session) {
			if (socket.handshake.session.sender) {
				//Update the sender name using our session variable
				msg.sender = socket.handshake.session.sender;
				//Push the message to everyone else
				io.sockets.emit('child_added', msg);
				//Add the message to Redis
				redis.rpush('messages', JSON.stringify(msg));
				//Trim Redis so we only store the last 1000 messages (optional)
				redis.ltrim('messages', 0, 1000);
			}
		} else {
			//If the session is invalid, decline the message
			socket.emit('child_added', {
				sender: "",
				msg: "Failed to send message, please log in",
				lat: 0,
				lng: 0,
				location: ""
			})
		}
	})
});

http.listen(3000);
<|endoftext|>


<commit_before>let epsilon = 1E-9;

onmessage = function(e){
  let start = Date.now();
  let nodes = e.data.nodes, links = e.data.links, dm = e.data.matrix;
  let n = nodes.length, m = links.length;
  for(let j = 0; j < m; j++){
    links[j].nn = false;
  }
  for(let i = 0; i < n; i++){
    let minDist = Number.MAX_VALUE;
    let targets = [];
    for(let j = 0; j < i; j++){
      if(!dm[i][j]){
        postMessage('Error');
        close();
      }
      if(Math.abs(dm[i][j] - minDist) < epsilon){
        targets.push(nodes[j].id);
      } else if(dm[i][j] < minDist){
        minDist = dm[i][j];
        targets = [nodes[j].id];
      }
    }
    for(let j = 0; j < m; j++){
      let l = links[j];
      if((l.source === nodes[i].id & targets.includes(l.target)) |
         (l.target === nodes[i].id & targets.includes(l.source))){
        l.nn = true;
      }
    }
  }
  console.log('NN Compute time: ', ((Date.now()-start)/1000).toLocaleString(), 's');
  start = Date.now();
  var encoder = new TextEncoder();
  links = encoder.encode(JSON.stringify(links)).buffer;
  postMessage({links: links, start: start}, [links]);
  close();
};
<commit_msg>Removed an incorrect error handler<commit_after>let epsilon = 1E-9;

onmessage = function(e){
  let start = Date.now();
  let nodes = e.data.nodes, links = e.data.links, dm = e.data.matrix;
  let n = nodes.length, m = links.length;
  for(let j = 0; j < m; j++){
    links[j].nn = false;
  }
  for(let i = 0; i < n; i++){
    let minDist = Number.MAX_VALUE;
    let targets = [];
    for(let j = 0; j < i; j++){
      if(Math.abs(dm[i][j] - minDist) < epsilon){
        targets.push(nodes[j].id);
      } else if(dm[i][j] < minDist){
        minDist = dm[i][j];
        targets = [nodes[j].id];
      }
    }
    for(let j = 0; j < m; j++){
      let l = links[j];
      if((l.source === nodes[i].id & targets.includes(l.target)) |
         (l.target === nodes[i].id & targets.includes(l.source))){
        l.nn = true;
      }
    }
  }
  console.log('NN Compute time: ', ((Date.now()-start)/1000).toLocaleString(), 's');
  start = Date.now();
  var encoder = new TextEncoder();
  links = encoder.encode(JSON.stringify(links)).buffer;
  postMessage({links: links, start: start}, [links]);
  close();
};
<|endoftext|>


<commit_before>import * as life from '../src/modules/life';

describe('life', function() {
  var bullet;
  var attackReceived;
  var player;
  var lifeText;

  beforeEach(function(){

    bullet = {
      kill: function() {}
    };

    player = {
      kill: function() {}
    };

    lifeText = {
    	text: "Lives: 3"
    }

    spyOn(bullet,'kill');
    spyOn(player,'kill');
  });

  it('resets the life to 3', function(){
    life.reduce(player, bullet);
    life.count(lifeText)
    expect(life.get()).toEqual(2);
    life.reset();
    expect(life.get()).toEqual(3);
  });
});

  // it('kills bullet and enemy', function(){
  //   score.update(bullet, enemy);
  //   expect(bullet.kill).toHaveBeenCalled();
  //   expect(enemy.kill).toHaveBeenCalled();
  //   score.reset();
  // });

  // it('increases the score', function(){
  //   score.update(bullet, enemy);
  //   expect(score.get()).toEqual(scoreIncrease);
  //   score.reset();
  // });

// var attackReceived = false;
// var lives = 3;

// export function reduce(player, bullet){
// 	attackReceived = true;
// 	bullet.kill();
// 	if (lives < 1){
// 		player.kill();
// 	}
// };

// export function count(lifeText) {
// 	if (attackReceived){
// 		lives -= 1;
// 		lifeText.text = 'Lives: ' + lives;
// 		attackReceived = false;
// 	}
// };

// export function get(){
// 	return lives;
// }

// export function reset(){
// 	lives = 3;
// 	attackReceived = false;
// }
<commit_msg>Life module tested<commit_after>import * as life from '../src/modules/life';

describe('life', function() {
  var bullet;
  var attackReceived;
  var player;
  var lifeText;

  beforeEach(function(){

    bullet = {
      kill: function() {}
    };

    player = {
      kill: function() {}
    };

    lifeText = {
    	text: "Lives: 3"
    }

    spyOn(bullet,'kill');
    spyOn(player,'kill');
  });

  it('resets the life to 3', function(){
    life.reduce(player, bullet);
    life.count(lifeText)
    expect(life.get()).toEqual(2);
    life.reset();
    expect(life.get()).toEqual(3);
  });

    it('reduce life to 0', function(){
    	for(var i = 0; i < 3; i++)
    	{
    	life.reduce(player, bullet);
    	life.count(lifeText);
  		}
    expect(life.get()).toEqual(0);
  });

  it('kills the player when life is 0', function(){
    	for(var i = 0; i < 3; i++)
    	{
    	life.reduce(player, bullet);
    	life.count(lifeText);
  		}
    expect(player.kill).toHaveBeenCalled();
  });
});
<|endoftext|>


<commit_before>function resize_main_div() {
    // Resize main_div to exactly take up remaining vertical space.
    var div = $('#main_div');
    div.height(Math.max(200, div.height() + $(window).height() - $('body').height()));
}
$(function () {
    resize_main_div();
    $(window).resize(resize_main_div);
    $('#zephyr-type-tabs a').on('shown', function (e) { resize_main_div(); });
});

$(function() {
    $('#zephyr-type-tabs a[href="#class-message"]').on('shown', function (e) {
        $('#class-message input:not(:hidden):first').focus().select();
    });
    $('#zephyr-type-tabs a[href="#personal-message"]').on('shown', function (e) {
        $('#personal-message input:not(:hidden):first').focus().select();
    });
});

$.ajaxSetup({
     beforeSend: function(xhr, settings) {
         function getCookie(name) {
             var cookieValue = null;
             if (document.cookie && document.cookie != '') {
                 var cookies = document.cookie.split(';');
                 for (var i = 0; i < cookies.length; i++) {
                     var cookie = jQuery.trim(cookies[i]);
                     // Does this cookie string begin with the name we want?
                 if (cookie.substring(0, name.length + 1) == (name + '=')) {
                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                     break;
                 }
             }
         }
         return cookieValue;
         }
         if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
             // Only send the token to relative URLs i.e. locally.
             xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
         }
     }
});

$(function() {
    var status_classes = 'alert-error alert-success alert-info';
    var send_status = $('#send-status');
    var buttons = $('#class-message, #personal-message').find('input[type="submit"]');

    var options = {
        beforeSubmit: function (form, _options) {
            send_status.removeClass(status_classes)
                       .addClass('alert-info')
                       .text('Sending')
                       .stop(true).fadeTo(0,1);
            buttons.attr('disabled', 'disabled');
        },
        success: function (resp, statusText, xhr, form) {
            form.find('textarea').val('');
            send_status.removeClass(status_classes)
                       .addClass('alert-success')
                       .text('Sent message')
                       .stop(true).fadeTo(0,1).delay(1000).fadeOut(1000);
            buttons.removeAttr('disabled');
        },
        error: function() {
            send_status.removeClass(status_classes)
                       .addClass('alert-error')
                       .html('Error sending message ')
                       .append($('')
                           .addClass('send-status-close').html('×')
                           .click(function () { send_status.stop(true).fadeOut(500); }))
                       .stop(true).fadeTo(0,1);

            buttons.removeAttr('disabled');
        }
    };

    send_status.hide();
    $("#class-message form").ajaxForm(options);
    $("#personal-message form").ajaxForm(options);
});

selected_tag = '
▶
'

var allow_hotkeys = true;

// NB: This just binds to current elements, and won't bind to elements
// created after ready() is called.

$(document).ready(function() {
    $('input, textarea, button').focus(function() {
          allow_hotkeys = false;
    });

    $('input, textarea, button').blur(function() {
          allow_hotkeys = true;
    });
});

var goto_pressed = false;

$(document).keydown(function(event) {
    if (allow_hotkeys) {

        if (event.keyCode == 38 || event.keyCode == 40) { // down or up arrow
            p = $("#selected");
            tr = $(p).closest("tr");
            td = $(p).closest("td");

            if (event.keyCode == 40) { // down arrow
                // There are probably more verbose but more efficient ways to do this.
                next_zephyr = tr.nextAll(":not(:hidden):first");
            } else { // up arrow
                next_zephyr = tr.prevAll(":not(:hidden):first");
            }
            if (next_zephyr.length != 0) { // We are not at the bottom or top of the zephyrs.
                next_zephyr.children("td:first").html(selected_tag);
                td.empty(); // Clear the previous arrow.
                $.post("update", {pointer: next_zephyr.attr("id")});

                if ($(next_zephyr).offset().top < $("#main_div").offset().top) {
                    $("#main_div").scrollTop($("#main_div").scrollTop() - 75);
                }

                if ($(next_zephyr).offset().top + $(next_zephyr).height() > $("#main_div").offset().top + $("#main_div").height()) {
                    $("#main_div").scrollTop($("#main_div").scrollTop() + 75);
                }
            }
        } else if (event.keyCode == 82) { // 'r' keypress, for responding to a zephyr
            var parent = $("#selected").parents("tr");
            var zephyr_class = parent.find("span.zephyr_class").text();
            var instance = parent.find("span.zephyr_instance").text();
            $("#class").val(zephyr_class);
            $("#instance").val(instance);
            $("#new_zephyr").focus();
            event.preventDefault();
        } else if (event.keyCode == 71) { // 'g' keypress, set trigger for "go to"
            goto_pressed = true;
            event.preventDefault();
        } else if (goto_pressed && event.keyCode == 67) { // 'c' keypress, for narrow-by-recipient
            var parent = $("#selected").parents("tr");
            var zephyr_class = parent.find("span.zephyr_class").text();
            narrow(zephyr_class, parent.attr("id"));
            event.preventDefault()
        } else if (goto_pressed && event.keyCode == 73) { // 'i' keypress, for narrow-by-instance
            var parent = $("#selected").parents("tr");
            var zephyr_class = parent.find("span.zephyr_class").text();
            var zephyr_instance = parent.find("span.zephyr_instance").text();
            narrow_instance(zephyr_class, zephyr_instance, parent.attr("id"));
            event.preventDefault()
        } else if (goto_pressed && event.keyCode == 80) { // 'p' keypress, for narrow-to-personals
            narrow_personals($("#selected").parents("tr").attr("id"));
            event.preventDefault();
        } else if (goto_pressed && event.keyCode == 65) { // 'a' keypress, for unnarrow
            unhide();
            event.preventDefault();
        }

        if (event.keyCode != 71) { // not 'g'
            goto_pressed = false;
        }

    } else if (event.keyCode == 27) { // Esc pressed
        $('input, textarea, button').blur();
        event.preventDefault();
    }
});

function scroll_to_zephyr(target_zephyr, old_offset) {
    // target_zephyr is an id.
    // old_offset is how far from the top of the scroll area the
    // zephyr was before any narrowing or unnarrowing happened.
    var height_above_zephyr = 0;
    $("#table tr:lt(" + $("#" + target_zephyr).index() + ")").each(function() {
        if (!$(this).is(":hidden")) {
            height_above_zephyr += $(this).height();
        }
    });
    $("#main_div").scrollTop(height_above_zephyr + old_offset);
}

function hide_personals() {
    $("span.zephyr_personal_recipient").each(
        function() {
            $(this).parents("tr").hide();
        }
    );
}

function narrow_personals(target_zephyr) {
    var old_top = $("#main_div").offset().top - $("#" + target_zephyr).offset().top;

    $("span.zephyr_personal_recipient").each(
        function() {
            $(this).parents("tr").show();
        }
    );
    $("span.zephyr_class").each(
        function() {
            $(this).parents("tr").hide();
        }
    );

    $("#selected").closest("td").empty();
    $("#" + target_zephyr).children("td:first").html(selected_tag);
    $.post("update", {pointer: target_zephyr});
    scroll_to_zephyr(target_zephyr, old_top);

    $("#unhide").removeAttr("disabled");
    $("#narrow_indicator").html("Showing personals");
}

function narrow(class_name, target_zephyr) {
    // We want the zephyr on which the narrow happened to stay in the same place if possible.
    var old_top = $("#main_div").offset().top - $("#" + target_zephyr).offset().top;
    $("span.zephyr_class").each(
        function() {
            if ($(this).text() != class_name) {
                $(this).parents("tr").hide();
            } else {
                // If you've narrowed on an instance and then click on the class, that should unhide the other instances on that class.
                $(this).parents("tr").show();
	    }
        }
    );
    hide_personals();
    $("#selected").closest("td").empty();
    $("#" + target_zephyr).children("td:first").html(selected_tag);
    $.post("update", {pointer: target_zephyr});

    // Try to keep the zephyr in the same place on the screen after narrowing.
    scroll_to_zephyr(target_zephyr, old_top);

    $("#unhide").removeAttr("disabled");
    $("#narrow_indicator").html("Showing " + class_name + "");
}

function narrow_instance(class_name, instance, target_zephyr) {
    var old_top = $("#main_div").offset().top - $("#" + target_zephyr).offset().top;
    $("tr").each(
        function() {
            if (($(this).find("span.zephyr_class").text() != class_name) ||
		($(this).find("span.zephyr_instance").text() != instance)) {
                $(this).hide();
	    }
        }
    );
    hide_personals();
    $("#selected").closest("td").empty();
    $("#" + target_zephyr).children("td:first").html(selected_tag);
    $.post("update", {pointer: target_zephyr});

    // Try to keep the zephyr in the same place on the screen after narrowing.
    scroll_to_zephyr(target_zephyr, old_top);

    $("#unhide").removeAttr("disabled");
    $("#narrow_indicator").html("Showing " + class_name
      + " " + instance + "");
}

function prepare_personal(username) {
    $('#zephyr-type-tabs a[href="#personal-message"]').tab('show');
    $("#recipient").val(username);
    $("#new_personal_zephyr").focus();
}

function unhide() {
    $("tr").show();

    p = $("#selected");
    tr = $(p).closest("tr");
    scroll_to_zephyr(tr.attr("id"), 0);

    $("#unhide").attr("disabled", "disabled");
    $("#narrow_indicator").html("");
}

function newline2br(content) {
    return content.replace(/\n/g, '
');
}

function add_message(index, zephyr) {
    var zephyr_para = $('
');
    var new_label = function (text, classes, on_click) {
        zephyr_para.append($('')
            .text(text)
            .addClass('label zephyr_label_clickable ' + classes)
            .click(on_click));
        zephyr_para.append(' ');
    };

    if (zephyr.type == 'class') {
        new_label(zephyr.display_recipient, 'zephyr_class',
            function (e) { narrow(zephyr.display_recipient, zephyr.id); });
        new_label(zephyr.instance, 'zephyr_instance',
            function (e) { narrow_instance(zephyr.display_recipient,
                                           zephyr.instance, zephyr.id); });
    } else {
        new_label(zephyr.display_recipient, 'zephyr_personal_recipient',
            function (e) { narrow_personals(zephyr.id); });
        zephyr_para.append('← ');
    }

    new_label(zephyr.sender, 'zephyr_sender',
             function (e) { prepare_personal(zephyr.sender); });

    zephyr_para.append('
' + newline2br(zephyr.content));

    $('#table tr:last').after($('
')
        .attr('id', zephyr.id)
        .append('

	')
        .append($('').append(zephyr_para)));
}

$(function() {
  $(initial_zephyr_json).each(add_message);
});

function get_updates_longpoll(data) {
    if (data && data.zephyrs) {
	$.each(data.zephyrs, add_message);
    }
    var last_received = $("tr:last").attr("id");
    $.post("get_updates_longpoll",
	   {last_received: last_received},
	    function(data) {
		get_updates_longpoll(data);
	    }, "json");
}

$(document).ready(function() {
    get_updates_longpoll()
});

<commit_msg>Select the value of "content" when replying to a zephyr.<commit_after>function resize_main_div() {
    // Resize main_div to exactly take up remaining vertical space.
    var div = $('#main_div');
    div.height(Math.max(200, div.height() + $(window).height() - $('body').height()));
}
$(function () {
    resize_main_div();
    $(window).resize(resize_main_div);
    $('#zephyr-type-tabs a').on('shown', function (e) { resize_main_div(); });
});

$(function() {
    $('#zephyr-type-tabs a[href="#class-message"]').on('shown', function (e) {
        $('#class-message input:not(:hidden):first').focus().select();
    });
    $('#zephyr-type-tabs a[href="#personal-message"]').on('shown', function (e) {
        $('#personal-message input:not(:hidden):first').focus().select();
    });
});

$.ajaxSetup({
     beforeSend: function(xhr, settings) {
         function getCookie(name) {
             var cookieValue = null;
             if (document.cookie && document.cookie != '') {
                 var cookies = document.cookie.split(';');
                 for (var i = 0; i < cookies.length; i++) {
                     var cookie = jQuery.trim(cookies[i]);
                     // Does this cookie string begin with the name we want?
                 if (cookie.substring(0, name.length + 1) == (name + '=')) {
                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                     break;
                 }
             }
         }
         return cookieValue;
         }
         if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
             // Only send the token to relative URLs i.e. locally.
             xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
         }
     }
});

$(function() {
    var status_classes = 'alert-error alert-success alert-info';
    var send_status = $('#send-status');
    var buttons = $('#class-message, #personal-message').find('input[type="submit"]');

    var options = {
        beforeSubmit: function (form, _options) {
            send_status.removeClass(status_classes)
                       .addClass('alert-info')
                       .text('Sending')
                       .stop(true).fadeTo(0,1);
            buttons.attr('disabled', 'disabled');
        },
        success: function (resp, statusText, xhr, form) {
            form.find('textarea').val('');
            send_status.removeClass(status_classes)
                       .addClass('alert-success')
                       .text('Sent message')
                       .stop(true).fadeTo(0,1).delay(1000).fadeOut(1000);
            buttons.removeAttr('disabled');
        },
        error: function() {
            send_status.removeClass(status_classes)
                       .addClass('alert-error')
                       .html('Error sending message ')
                       .append($('')
                           .addClass('send-status-close').html('×')
                           .click(function () { send_status.stop(true).fadeOut(500); }))
                       .stop(true).fadeTo(0,1);

            buttons.removeAttr('disabled');
        }
    };

    send_status.hide();
    $("#class-message form").ajaxForm(options);
    $("#personal-message form").ajaxForm(options);
});

selected_tag = '
▶
'

var allow_hotkeys = true;

// NB: This just binds to current elements, and won't bind to elements
// created after ready() is called.

$(document).ready(function() {
    $('input, textarea, button').focus(function() {
          allow_hotkeys = false;
    });

    $('input, textarea, button').blur(function() {
          allow_hotkeys = true;
    });
});

var goto_pressed = false;

$(document).keydown(function(event) {
    if (allow_hotkeys) {

        if (event.keyCode == 38 || event.keyCode == 40) { // down or up arrow
            p = $("#selected");
            tr = $(p).closest("tr");
            td = $(p).closest("td");

            if (event.keyCode == 40) { // down arrow
                // There are probably more verbose but more efficient ways to do this.
                next_zephyr = tr.nextAll(":not(:hidden):first");
            } else { // up arrow
                next_zephyr = tr.prevAll(":not(:hidden):first");
            }
            if (next_zephyr.length != 0) { // We are not at the bottom or top of the zephyrs.
                next_zephyr.children("td:first").html(selected_tag);
                td.empty(); // Clear the previous arrow.
                $.post("update", {pointer: next_zephyr.attr("id")});

                if ($(next_zephyr).offset().top < $("#main_div").offset().top) {
                    $("#main_div").scrollTop($("#main_div").scrollTop() - 75);
                }

                if ($(next_zephyr).offset().top + $(next_zephyr).height() > $("#main_div").offset().top + $("#main_div").height()) {
                    $("#main_div").scrollTop($("#main_div").scrollTop() + 75);
                }
            }
        } else if (event.keyCode == 82) { // 'r' keypress, for responding to a zephyr
            var parent = $("#selected").parents("tr");
            var zephyr_class = parent.find("span.zephyr_class").text();
            var instance = parent.find("span.zephyr_instance").text();
            $("#class").val(zephyr_class);
            $("#instance").val(instance);
            $("#new_zephyr").focus();
            $("#new_zephyr").select();
            event.preventDefault();
        } else if (event.keyCode == 71) { // 'g' keypress, set trigger for "go to"
            goto_pressed = true;
            event.preventDefault();
        } else if (goto_pressed && event.keyCode == 67) { // 'c' keypress, for narrow-by-recipient
            var parent = $("#selected").parents("tr");
            var zephyr_class = parent.find("span.zephyr_class").text();
            narrow(zephyr_class, parent.attr("id"));
            event.preventDefault()
        } else if (goto_pressed && event.keyCode == 73) { // 'i' keypress, for narrow-by-instance
            var parent = $("#selected").parents("tr");
            var zephyr_class = parent.find("span.zephyr_class").text();
            var zephyr_instance = parent.find("span.zephyr_instance").text();
            narrow_instance(zephyr_class, zephyr_instance, parent.attr("id"));
            event.preventDefault()
        } else if (goto_pressed && event.keyCode == 80) { // 'p' keypress, for narrow-to-personals
            narrow_personals($("#selected").parents("tr").attr("id"));
            event.preventDefault();
        } else if (goto_pressed && event.keyCode == 65) { // 'a' keypress, for unnarrow
            unhide();
            event.preventDefault();
        }

        if (event.keyCode != 71) { // not 'g'
            goto_pressed = false;
        }

    } else if (event.keyCode == 27) { // Esc pressed
        $('input, textarea, button').blur();
        event.preventDefault();
    }
});

function scroll_to_zephyr(target_zephyr, old_offset) {
    // target_zephyr is an id.
    // old_offset is how far from the top of the scroll area the
    // zephyr was before any narrowing or unnarrowing happened.
    var height_above_zephyr = 0;
    $("#table tr:lt(" + $("#" + target_zephyr).index() + ")").each(function() {
        if (!$(this).is(":hidden")) {
            height_above_zephyr += $(this).height();
        }
    });
    $("#main_div").scrollTop(height_above_zephyr + old_offset);
}

function hide_personals() {
    $("span.zephyr_personal_recipient").each(
        function() {
            $(this).parents("tr").hide();
        }
    );
}

function narrow_personals(target_zephyr) {
    var old_top = $("#main_div").offset().top - $("#" + target_zephyr).offset().top;

    $("span.zephyr_personal_recipient").each(
        function() {
            $(this).parents("tr").show();
        }
    );
    $("span.zephyr_class").each(
        function() {
            $(this).parents("tr").hide();
        }
    );

    $("#selected").closest("td").empty();
    $("#" + target_zephyr).children("td:first").html(selected_tag);
    $.post("update", {pointer: target_zephyr});
    scroll_to_zephyr(target_zephyr, old_top);

    $("#unhide").removeAttr("disabled");
    $("#narrow_indicator").html("Showing personals");
}

function narrow(class_name, target_zephyr) {
    // We want the zephyr on which the narrow happened to stay in the same place if possible.
    var old_top = $("#main_div").offset().top - $("#" + target_zephyr).offset().top;
    $("span.zephyr_class").each(
        function() {
            if ($(this).text() != class_name) {
                $(this).parents("tr").hide();
            } else {
                // If you've narrowed on an instance and then click on the class, that should unhide the other instances on that class.
                $(this).parents("tr").show();
	    }
        }
    );
    hide_personals();
    $("#selected").closest("td").empty();
    $("#" + target_zephyr).children("td:first").html(selected_tag);
    $.post("update", {pointer: target_zephyr});

    // Try to keep the zephyr in the same place on the screen after narrowing.
    scroll_to_zephyr(target_zephyr, old_top);

    $("#unhide").removeAttr("disabled");
    $("#narrow_indicator").html("Showing " + class_name + "");
}

function narrow_instance(class_name, instance, target_zephyr) {
    var old_top = $("#main_div").offset().top - $("#" + target_zephyr).offset().top;
    $("tr").each(
        function() {
            if (($(this).find("span.zephyr_class").text() != class_name) ||
		($(this).find("span.zephyr_instance").text() != instance)) {
                $(this).hide();
	    }
        }
    );
    hide_personals();
    $("#selected").closest("td").empty();
    $("#" + target_zephyr).children("td:first").html(selected_tag);
    $.post("update", {pointer: target_zephyr});

    // Try to keep the zephyr in the same place on the screen after narrowing.
    scroll_to_zephyr(target_zephyr, old_top);

    $("#unhide").removeAttr("disabled");
    $("#narrow_indicator").html("Showing " + class_name
      + " " + instance + "");
}

function prepare_personal(username) {
    $('#zephyr-type-tabs a[href="#personal-message"]').tab('show');
    $("#recipient").val(username);
    $("#new_personal_zephyr").focus();
}

function unhide() {
    $("tr").show();

    p = $("#selected");
    tr = $(p).closest("tr");
    scroll_to_zephyr(tr.attr("id"), 0);

    $("#unhide").attr("disabled", "disabled");
    $("#narrow_indicator").html("");
}

function newline2br(content) {
    return content.replace(/\n/g, '
');
}

function add_message(index, zephyr) {
    var zephyr_para = $('
');
    var new_label = function (text, classes, on_click) {
        zephyr_para.append($('')
            .text(text)
            .addClass('label zephyr_label_clickable ' + classes)
            .click(on_click));
        zephyr_para.append(' ');
    };

    if (zephyr.type == 'class') {
        new_label(zephyr.display_recipient, 'zephyr_class',
            function (e) { narrow(zephyr.display_recipient, zephyr.id); });
        new_label(zephyr.instance, 'zephyr_instance',
            function (e) { narrow_instance(zephyr.display_recipient,
                                           zephyr.instance, zephyr.id); });
    } else {
        new_label(zephyr.display_recipient, 'zephyr_personal_recipient',
            function (e) { narrow_personals(zephyr.id); });
        zephyr_para.append('← ');
    }

    new_label(zephyr.sender, 'zephyr_sender',
             function (e) { prepare_personal(zephyr.sender); });

    zephyr_para.append('
' + newline2br(zephyr.content));

    $('#table tr:last').after($('
')
        .attr('id', zephyr.id)
        .append('

	')
        .append($('').append(zephyr_para)));
}

$(function() {
  $(initial_zephyr_json).each(add_message);
});

function get_updates_longpoll(data) {
    if (data && data.zephyrs) {
	$.each(data.zephyrs, add_message);
    }
    var last_received = $("tr:last").attr("id");
    $.post("get_updates_longpoll",
	   {last_received: last_received},
	    function(data) {
		get_updates_longpoll(data);
	    }, "json");
}

$(document).ready(function() {
    get_updates_longpoll()
});

<|endoftext|>


<commit_before>var faye = require('faye'),
    debug = require('debug')('openframe:apiserver:pubsub');

// Note: the 'app' arg is called 'app' elsewhere in loopback
module.exports = function(app) {
    debug('instantiating pubsub module');

    var ps_protocol = app.get('pubsub_protocol'),
        ps_host = app.get('pubsub_host'),
        ps_port = app.get('pubsub_port'),
        ps_path = app.get('pubsub_path'),
        ps_url = ps_protocol + '://' + ps_host + ':' + ps_port + ps_path;

    // Once the loopback app has started, connect to the PubSub server
    app.on('started', function() {
        // add a pubsub client for the API app
        app.pubsub = new faye.Client(ps_url);

        // handlers for pubsub connection events
        app.pubsub.on('transport:down', function() {
            // the pubsub client is offline
            debug('pubsub client offline');
        });

        // handlers for pubsub connection events
        app.pubsub.on('transport:up', function() {
            // the pubsub client is online
            debug('pubsub client online');
        });

        // listen for all /frame/connected events, update the Frame
        app.pubsub.subscribe('/frame/connected', function(frame_id) {
            // update frame status
            debug('frame %s connected', frame_id);
            app.models.Frame.findById(frame_id, function(err, frame) {
                if (err) {
                    debug(err);
                    return;
                }
                frame.connected = true;
                frame.save();
            });
        });

        // listen for all /frame/disconnected events, update the Frame
        app.pubsub.subscribe('/frame/disconnected', function(frame_id) {
            debug('frame %s disconnected', frame_id);
            // update frame status
            app.models.Frame.findById(frame_id, function(err, frame) {
                if (err) {
                    debug(err);
                    return;
                }
                frame.connected = false;
                frame.save();
            });
        });
    });
};

<commit_msg>Catch unknown frame connect/disconnect<commit_after>var faye = require('faye'),
    debug = require('debug')('openframe:apiserver:pubsub');

// Note: the 'app' arg is called 'app' elsewhere in loopback
module.exports = function(app) {
    debug('instantiating pubsub module');

    var ps_protocol = app.get('pubsub_protocol'),
        ps_host = app.get('pubsub_host'),
        ps_port = app.get('pubsub_port'),
        ps_path = app.get('pubsub_path'),
        ps_url = ps_protocol + '://' + ps_host + ':' + ps_port + ps_path;

    // Once the loopback app has started, connect to the PubSub server
    app.on('started', function() {
        // add a pubsub client for the API app
        app.pubsub = new faye.Client(ps_url);

        // handlers for pubsub connection events
        app.pubsub.on('transport:down', function() {
            // the pubsub client is offline
            debug('pubsub client offline');
        });

        // handlers for pubsub connection events
        app.pubsub.on('transport:up', function() {
            // the pubsub client is online
            debug('pubsub client online');
        });

        // listen for all /frame/connected events, update the Frame
        app.pubsub.subscribe('/frame/connected', function(frame_id) {
            // update frame status
            debug('frame %s connected', frame_id);
            app.models.Frame.findById(frame_id, function(err, frame) {
                if (err) {
                    debug(err);
                    return;
                }
                if (frame === null) {
                    debug('Unknown frame connected.');
                    return;
                }
                frame.connected = true;
                frame.save();
            });
        });

        // listen for all /frame/disconnected events, update the Frame
        app.pubsub.subscribe('/frame/disconnected', function(frame_id) {
            debug('frame %s disconnected', frame_id);
            // update frame status
            app.models.Frame.findById(frame_id, function(err, frame) {
                if (err) {
                    debug(err);
                    return;
                }
                if (frame === null) {
                    debug('Unknown frame disconnected.');
                    return;
                }
                frame.connected = false;
                frame.save();
            });
        });
    });
};

<|endoftext|>


<commit_before>// Copyright 2010 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Event Types.
 *
 */

goog.provide('goog.events.EventType');

goog.require('goog.userAgent');

/**
 * Constants for event names.
 * @enum {string}
 */
goog.events.EventType = {
  // Mouse events
  CLICK: 'click',
  DBLCLICK: 'dblclick',
  MOUSEDOWN: 'mousedown',
  MOUSEUP: 'mouseup',
  MOUSEOVER: 'mouseover',
  MOUSEOUT: 'mouseout',
  MOUSEMOVE: 'mousemove',
  SELECTSTART: 'selectstart', // IE, Safari, Chrome

  // Key events
  KEYPRESS: 'keypress',
  KEYDOWN: 'keydown',
  KEYUP: 'keyup',

  // Focus
  BLUR: 'blur',
  FOCUS: 'focus',
  DEACTIVATE: 'deactivate', // IE only
  // NOTE: The following two events are not stable in cross-browser usage.
  //     WebKit and Opera implement DOMFocusIn/Out.
  //     IE implements focusin/out.
  //     Gecko implements neither see bug at
  //     https://bugzilla.mozilla.org/show_bug.cgi?id=396927.
  // The DOM Events Level 3 Draft deprecates DOMFocusIn in favor of focusin:
  //     http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html
  // You can use FOCUS in Capture phase until implementations converge.
  FOCUSIN: goog.userAgent.IE ? 'focusin' : 'DOMFocusIn',
  FOCUSOUT: goog.userAgent.IE ? 'focusout' : 'DOMFocusOut',

  // Forms
  CHANGE: 'change',
  SELECT: 'select',
  SUBMIT: 'submit',
  INPUT: 'input',
  PROPERTYCHANGE: 'propertychange', // IE only

  // Drag and drop
  DRAGSTART: 'dragstart',
  DRAGENTER: 'dragenter',
  DRAGOVER: 'dragover',
  DRAGLEAVE: 'dragleave',
  DROP: 'drop',

  // WebKit touch events.
  TOUCHSTART: 'touchstart',
  TOUCHMOVE: 'touchmove',
  TOUCHEND: 'touchend',
  TOUCHCANCEL: 'touchcancel',

  // Misc
  CONTEXTMENU: 'contextmenu',
  ERROR: 'error',
  HELP: 'help',
  LOAD: 'load',
  LOSECAPTURE: 'losecapture',
  READYSTATECHANGE: 'readystatechange',
  RESIZE: 'resize',
  SCROLL: 'scroll',
  UNLOAD: 'unload',

  // HTML 5 History events
  // See http://www.w3.org/TR/html5/history.html#event-definitions
  HASHCHANGE: 'hashchange',
  PAGEHIDE: 'pagehide',
  PAGESHOW: 'pageshow',
  POPSTATE: 'popstate',

  // Copy and Paste
  COPY: 'copy',
  PASTE: 'paste',
  CUT: 'cut',

  // HTML 5 worker events
  MESSAGE: 'message',
  CONNECT: 'connect'
};
<commit_msg><commit_after>// Copyright 2010 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Event Types.
 *
 */

goog.provide('goog.events.EventType');

goog.require('goog.userAgent');

/**
 * Constants for event names.
 * @enum {string}
 */
goog.events.EventType = {
  // Mouse events
  CLICK: 'click',
  DBLCLICK: 'dblclick',
  MOUSEDOWN: 'mousedown',
  MOUSEUP: 'mouseup',
  MOUSEOVER: 'mouseover',
  MOUSEOUT: 'mouseout',
  MOUSEMOVE: 'mousemove',
  SELECTSTART: 'selectstart', // IE, Safari, Chrome

  // Key events
  KEYPRESS: 'keypress',
  KEYDOWN: 'keydown',
  KEYUP: 'keyup',

  // Focus
  BLUR: 'blur',
  FOCUS: 'focus',
  DEACTIVATE: 'deactivate', // IE only
  // NOTE: The following two events are not stable in cross-browser usage.
  //     WebKit and Opera implement DOMFocusIn/Out.
  //     IE implements focusin/out.
  //     Gecko implements neither see bug at
  //     https://bugzilla.mozilla.org/show_bug.cgi?id=396927.
  // The DOM Events Level 3 Draft deprecates DOMFocusIn in favor of focusin:
  //     http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html
  // You can use FOCUS in Capture phase until implementations converge.
  FOCUSIN: goog.userAgent.IE ? 'focusin' : 'DOMFocusIn',
  FOCUSOUT: goog.userAgent.IE ? 'focusout' : 'DOMFocusOut',

  // Forms
  CHANGE: 'change',
  SELECT: 'select',
  SUBMIT: 'submit',
  INPUT: 'input',
  PROPERTYCHANGE: 'propertychange', // IE only

  // Drag and drop
  DRAGSTART: 'dragstart',
  DRAGENTER: 'dragenter',
  DRAGOVER: 'dragover',
  DRAGLEAVE: 'dragleave',
  DROP: 'drop',

  // WebKit touch events.
  TOUCHSTART: 'touchstart',
  TOUCHMOVE: 'touchmove',
  TOUCHEND: 'touchend',
  TOUCHCANCEL: 'touchcancel',

  // Misc
  CONTEXTMENU: 'contextmenu',
  ERROR: 'error',
  HELP: 'help',
  LOAD: 'load',
  LOSECAPTURE: 'losecapture',
  READYSTATECHANGE: 'readystatechange',
  RESIZE: 'resize',
  SCROLL: 'scroll',
  UNLOAD: 'unload',

  // HTML 5 History events
  // See http://www.w3.org/TR/html5/history.html#event-definitions
  HASHCHANGE: 'hashchange',
  PAGEHIDE: 'pagehide',
  PAGESHOW: 'pageshow',
  POPSTATE: 'popstate',

  // Copy and Paste
  // Support is limited. Make sure it works on your favorite browser
  // before using.
  // http://www.quirksmode.org/dom/events/cutcopypaste.html
  COPY: 'copy',
  PASTE: 'paste',
  CUT: 'cut',
  BEFORECOPY: 'beforecopy',
  BEFORECUT: 'beforecut',
  BEFOREPASTE: 'beforepaste',

  // HTML 5 worker events
  MESSAGE: 'message',
  CONNECT: 'connect'
};
<|endoftext|>


<commit_before>/*
  MIT License,
  Copyright (c) 2015, Richard Rodger and other contributors.
  Copyright (c) 2010-2014, Richard Rodger.
*/

'use strict'

var Assert = require('assert')
var Lab = require('lab')
var Seneca = require('seneca')
var Shared = require('seneca-store-test')

var lab = exports.lab = Lab.script()
var describe = lab.describe
var it = lab.it

var seneca = Seneca({
  log: 'silent',
  default_plugins: {'mem-store': false}
})
seneca.use({name: '..', tag: '1'})

var senecaMerge = Seneca({
  log: 'silent'
})
senecaMerge.use({name: '..', tag: '1', merge: false })

describe('mem-store tests', function () {
  Shared.basictest({
    seneca: seneca,
    senecaMerge: senecaMerge,
    script: lab
  })

  it('export-native', function (done) {
    Assert.ok(seneca.export('mem-store/1/native'))
    done()
  })

  it('custom-test', function (done) {
    seneca.options({errhandler: done})

    var ent = seneca.make('foo', {id$: '0', q: 1})

    ent.save$(function (err) {
      Assert.ok(null === err)

      seneca.act('role:mem-store, cmd:export', function (err, exported) {
        var expected =
              '{"undefined":{"foo":{"0":{"entity$":"-/-/foo","q":1,"id":"0"}}}}'

        Assert.ok(null === err)
        Assert.equal(exported.json, expected)

        var data = JSON.parse(exported.json)
        data['undefined']['foo']['1'] = { 'entity$': '-/-/foo', 'val': 2, 'id': '1' }

        seneca.act(
          'role:mem-store, cmd:import',
          {json: JSON.stringify(data)},
          function (err) {
            Assert.ok(null === err)

            seneca.make('foo').load$('1', function (err, foo) {
              Assert.ok(null === err)
              Assert.equal(2, foo.val)

              done()
            })
          })
      })
    })
  })
})
<commit_msg>add tests for sort and limit<commit_after>/*
  MIT License,
  Copyright (c) 2015, Richard Rodger and other contributors.
  Copyright (c) 2010-2014, Richard Rodger.
*/

'use strict'

var Assert = require('assert')
var Lab = require('lab')
var Seneca = require('seneca')
var Shared = require('seneca-store-test')

var lab = exports.lab = Lab.script()
var describe = lab.describe
var it = lab.it

var seneca = Seneca({
  log: 'silent',
  default_plugins: {'mem-store': false}
})
seneca.use({name: '..', tag: '1'})

var senecaMerge = Seneca({
  log: 'silent'
})
senecaMerge.use({name: '..', tag: '1', merge: false })

describe('mem-store tests', function () {
  Shared.basictest({
    seneca: seneca,
    senecaMerge: senecaMerge,
    script: lab
  })

  Shared.limitstest({
    seneca: seneca,
    script: lab
  })

  Shared.sorttest({
    seneca: seneca,
    script: lab
  })

  it('export-native', function (done) {
    Assert.ok(seneca.export('mem-store/1/native'))
    done()
  })

  it('custom-test', function (done) {
    seneca.options({errhandler: done})

    var ent = seneca.make('foo', {id$: '0', q: 1})

    ent.save$(function (err) {
      Assert.ok(null === err)

      seneca.act('role:mem-store, cmd:export', function (err, exported) {
        var expected =
              '{"undefined":{"foo":{"0":{"entity$":"-/-/foo","q":1,"id":"0"}}}}'

        Assert.ok(null === err)
        Assert.equal(exported.json, expected)

        var data = JSON.parse(exported.json)
        data['undefined']['foo']['1'] = { 'entity$': '-/-/foo', 'val': 2, 'id': '1' }

        seneca.act(
          'role:mem-store, cmd:import',
          {json: JSON.stringify(data)},
          function (err) {
            Assert.ok(null === err)

            seneca.make('foo').load$('1', function (err, foo) {
              Assert.ok(null === err)
              Assert.equal(2, foo.val)

              done()
            })
          })
      })
    })
  })
})
<|endoftext|>


<commit_before>// Initial Version from Chris1284
// Modifications for 2.2 klausw	4.7.2016
// Modifications for 2.4 mario stephan	2.12.2016
// data-get			all|today|tomorrow
// data-start		none|notoday|notomorrow		(only for data-get="all" -> dont show Entrys from today or today and tomorrow)
// data-max			number how much Entries are maximal listed
// data-color		Text color
// data-detail		Array of details that should be shown default: ["bdate", "btime", "summary", "location"]
// data-showempty	show Text for "no Date" default: true

/* global ftui:true, Modul_widget:true */

var Modul_calview = function () {

    var readings = [];

    function init() {

        me.elements = $('div[data-type="' + me.widgetname + '"]', me.area);
        me.elements.each(function (index) {
            var elem = $(this);
            // Standardwerte fuer Parameter
            elem.initData('max', 10);
            elem.initData('get', 'STATE');
            elem.initData('start', 'all');
            elem.initData('color', '');
            elem.initData('detail', ["bdate", "btime", "summary", "location"]);
            elem.initData('showempty', 'true');

            var device = $(this).data('device');
            console.log("device: " + device + " get: " + $(this).data('get') + " max: " + $(this).data('max'));
            var num;
            var value;
            elem.initData('c-term', 'c-term');
            elem.initData('c-today', 'c-today');
            elem.initData('c-tomorrow', 'c-tomorrow');
            if ($(this).data('get') == 'today' || $(this).data('get') == 'tomorrow' || $(this).data('get') == 'all') {
                value = $(this).data('max');
                var wann = $(this).data('get');
                //elem.initData('c-'+wann, 'c-'+wann);
                if (wann == "all") {
                    wann = "term";
                }
                me.addReading(elem, 'c-' + wann);
                console.log("c-" + wann + ": " + elem.getReading('c-' + wann).val);
                if (wann == "term") {
                    wann = "t";
                }
                for (var i = 1; i <= value; i++) {
                    num = "00" + i;
                    num = num.slice(-3);
                    elem.data('detail').forEach(function (wert) {
                        elem.initData(wann + '_' + num + '_' + wert, wann + '_' + num + '_' + wert);
                        me.addReading(elem, wann + '_' + num + '_' + wert);
                        console.log(wann + '_' + num + '_' + wert + ': ' + elem.getReading(wann + '_' + num + '_' + wert).val);
                    });
                }
            }
        });
    }

    function update(dev, par) {
        var deviceElements;
        var text;
        var num;
        var ct;
        if (dev == '*') {
            deviceElements = me.elements;
        } else {
            deviceElements = me.elements.filter('div[data-device="' + dev + '"]');
        }

        deviceElements.each(function (index) {
            var elem = $(this);
            var get = elem.data('get');
            var color = elem.data('color');
            elem.css("color", ftui.getStyle('.' + color, 'color') || color);
            if (elem.data('get') == 'STATE') {
                var value = elem.getReading('get').val;
                if (ftui.isValid(value)) {
                    elem.html("
" + value + "
");
                }
            } else if (elem.data('get') == 'today' || elem.data('get') == 'tomorrow' || elem.data('get') == 'all') {
                text = "";
                var beginn = 1;
                var zeitrahmen = {
                    "today": "Heute ",
                    "tomorrow": "Morgen ",
                    "all": ""
                };
                var wann = elem.data('get');
                ct = elem.getReading('c-' + wann).val;

                if (elem.data('get') == 'all') {
                    wann = "t";
                    ct = elem.getReading('c-term').val;
                    if (elem.data('start') == "notoday") {
                        beginn = 1 + parseInt(elem.getReading('c-today').val);
                    } else if (elem.data('start') == "notomorrow") {
                        beginn = 1 + parseInt(elem.getReading('c-today').val) + parseInt(elem.getReading('c-tomorrow').val);
                    }
                }
                if (ct === 0) {
                    if (elem.data('showempty') == "true") {
                        text += "
" + zeitrahmen[wann] + "keine Termine
";
                    }
                } else {
                    if (ct > elem.data('max')) {
                        ct = elem.data('max');
                    }
                    for (var i = beginn; i <= ct; i++) {
                        num = "00" + i;
                        num = num.slice(-3);
                        text += "
";
                        elem.data('detail').forEach(function (spalte) {
                            if (typeof elem.getReading(wann + '_' + num + '_' + spalte).val !== "undefined") {
                                text += "
" + elem.getReading(wann + '_' + num + '_' + spalte).val + "
";
                            }
                        });
                        text += "
";
                    }
                }
                elem.html(text);
            }
        });
    }

    var me = $.extend(new Modul_widget(), {
        widgetname: 'calview',
        init: init,
        update: update,
    });

    return me;
};<commit_msg>current version<commit_after>// Initial Version from Chris1284
// Modifications for 2.2 klausw	4.7.2016
// Modifications for 2.4 mario stephan	2.12.2016
// Modifications for 2.6 chris1284 08.12.2016 - Ursprüngliche Darstellung wieder hergestellt
// Modifications for 2.8 chris1284 28.12.2016 - widget an aktuelle calview angepasst
// data-get			all|today|tomorrow
// data-start		none|notoday|notomorrow		(only for data-get="all" -> dont show Entrys from today or today and tomorrow)
// data-max			number how much Entries are maximal listed
// data-color		Text color
// data-detail		Array of details that should be shown default: ["bdate", "btime", "summary", "location"]
// data-showempty	show Text for "no Date" default: true

/* global ftui:true, Modul_widget:true */

var Modul_calview = function () {

    var readings = [];

    function init() {

        me.elements = $('div[data-type="' + me.widgetname + '"]', me.area);
        me.elements.each(function (index) {
            var elem = $(this);
            // Standardwerte fuer Parameter
            elem.initData('max', 10);
            elem.initData('get', 'STATE');
            elem.initData('start', 'all');
            elem.initData('color', '');
            elem.initData('detail', ["bdate", "btime", "summary", "location","edate","etime","source","age","description"]);
            elem.initData('showempty', 'true');

            var device = $(this).data('device');
            console.log("device: " + device + " get: " + $(this).data('get') + " max: " + $(this).data('max'));
            var num;
            var value;
            elem.initData('c-term', 'c-term');
            elem.initData('c-today', 'c-today');
            elem.initData('c-tomorrow', 'c-tomorrow');
            if ($(this).data('get') == 'today' || $(this).data('get') == 'tomorrow' || $(this).data('get') == 'all') {
                value = $(this).data('max');
                var wann = $(this).data('get');
                //elem.initData('c-'+wann, 'c-'+wann);
                if (wann == "all") {
                    wann = "term";
                }
                me.addReading(elem, 'c-' + wann);
                console.log("c-" + wann + ": " + elem.getReading('c-' + wann).val);
                if (wann == "term") {
                    wann = "t";
                }
                for (var i = 1; i <= value; i++) {
                    num = "00" + i;
                    num = num.slice(-3);
                    elem.data('detail').forEach(function (wert) {
                        elem.initData(wann + '_' + num + '_' + wert, wann + '_' + num + '_' + wert);
                        me.addReading(elem, wann + '_' + num + '_' + wert);
                        console.log(wann + '_' + num + '_' + wert + ': ' + elem.getReading(wann + '_' + num + '_' + wert).val);
                    });
                }
            }
        });
    }

    function update(dev, par) {
        var deviceElements;
        var text;
        var num;
        var ct;
        if (dev == '*') {
            deviceElements = me.elements;
        } else {
            deviceElements = me.elements.filter('div[data-device="' + dev + '"]');
        }

        deviceElements.each(function (index) {
            var elem = $(this);
            var get = elem.data('get');
            var color = elem.data('color');
            elem.css("color", ftui.getStyle('.' + color, 'color') || color);

			elem.getReading('c-term').val;
            elem.getReading('c-today').val;
            elem.getReading('c-tomorrow').val;

            if (elem.data('get') == 'STATE') {
                var value = elem.getReading('get').val;
                if (ftui.isValid(value)) {
                    elem.html("
" + value + "
");
                }
            } else if (elem.data('get') == 'today' || elem.data('get') == 'tomorrow' || elem.data('get') == 'all') {
                text = "";
                var beginn = 1;
                var zeitrahmen = {
					"today": "Heute ",
                    "tomorrow": "Morgen ",
                    "all": ""
                };
                var wann = elem.data('get');
                ct = elem.getReading('c-' + wann).val;

                if (elem.data('get') == 'all') {
                    wann = "t";
                    ct = elem.getReading('c-term').val;
                    if (elem.data('start') == "notoday") {
                        beginn = 1 + parseInt(elem.getReading('c-today').val);
                    } else if (elem.data('start') == "notomorrow") {
                        beginn = 1 + parseInt(elem.getReading('c-today').val) + parseInt(elem.getReading('c-tomorrow').val);
                    }
                }
                if (ct === 0) {
                    if (elem.data('showempty') == "true") {
                        text += "
" + zeitrahmen[wann] + "keine Termine
";
                    }
                } else {
                    if (ct > elem.data('max')) {
                        ct = elem.data('max');
                    }
                    for (var i = beginn; i <= ct; i++) {
                        num = "00" + i;
                        num = num.slice(-3);
								colcounter = elem.data('detail').length;
								elem.data('detail').forEach(function(spalte) {
									if ( typeof elem.getReading(wann+'_'+num+'_'+spalte).val != "undefined" ) {
										text += "
";
										text += "
" + elem.getReading(wann+'_'+num+'_'+spalte).val + "
";
										text += "
";
									}
								});
                    }
                }
                elem.html(text);
            }
        });
    }

    var me = $.extend(new Modul_widget(), {
        widgetname: 'calview',
        init: init,
        update: update,
    });

    return me;
};<|endoftext|>


<commit_before>// @flow weak
/* eslint-disable no-console */

import path from 'path'
import fse from 'fs-extra'

function copyFile(file) {
  const buildPath = path.resolve(__dirname, '../build/', path.basename(file))
  return new Promise(resolve => {
    fse.copy(file, buildPath, err => {
      if (err) {
        throw err
      }
      resolve()
    })
  }).then(() => console.log(`Copied ${file} to ${buildPath}`))
}

function copyTypes(src, dst) {
  const buildPath = path.resolve(__dirname, '../build/', dst)
  return new Promise(resolve => {
    fse.copy(src, buildPath, err => {
      if (err) {
        throw err
      }
      resolve()
    })
  }).then(() => console.log(`Copied ${src} to ${buildPath}`))
}

function createPackageFile() {
  return new Promise(resolve => {
    fse.readFile(
      path.resolve(__dirname, '../package.json'),
      'utf8',
      (err, data) => {
        if (err) {
          throw err
        }

        resolve(data)
      },
    )
  })
    .then(data => JSON.parse(data))
    .then(packageData => {
      const {
        version,
        contributors,
        description,
        keywords,
        repository,
        license,
        bugs,
        homepage,
        peerDependencies,
        dependencies,
      } = packageData

      const minimalPackage = {
        name: 'react-move',
        version,
        contributors,
        description,
        main: 'index.js',
        module: 'es/index.js',
        'jsnext:main': 'es/index.js',
        types: 'index.d.ts',
        keywords,
        repository,
        license,
        bugs,
        homepage,
        peerDependencies,
        dependencies,
      }

      return new Promise(resolve => {
        const buildPath = path.resolve(__dirname, '../build/package.json')
        const data = JSON.stringify(minimalPackage, null, 2)
        fse.writeFile(buildPath, data, err => {
          if (err) {
            throw err
          }
          console.log(`\nCreated package.json in ${buildPath}\n`)
          resolve()
        })
      })
    })
}

const files = ['README.md', 'LICENSE']

const types = [
  ['src/index.d.ts', 'index.d.ts'],
  ['src/core/index.d.ts', 'core/index.d.ts'],
  ['src/configAnimate/index.d.ts', 'configAnimate/index.d.ts'],
  ['src/configNodeGroup/index.d.ts', 'configNodeGroup/index.d.ts'],
]

Promise.all(files.map(file => copyFile(file)))
  .then(() => Promise.all(types.map(file => copyTypes(...file))))
  .then(() => createPackageFile())
<commit_msg>fix build<commit_after>// @flow weak
/* eslint-disable no-console */

import path from 'path'
import fse from 'fs-extra'

function copyFile(file) {
  const buildPath = path.resolve(__dirname, '../build/', path.basename(file))
  return new Promise(resolve => {
    fse.copy(file, buildPath, err => {
      if (err) {
        throw err
      }
      resolve()
    })
  }).then(() => console.log(`Copied ${file} to ${buildPath}`))
}

function copyTypes(src, dst) {
  const buildPath = path.resolve(__dirname, '../build/', dst)
  return new Promise(resolve => {
    fse.copy(src, buildPath, err => {
      if (err) {
        throw err
      }
      resolve()
    })
  }).then(() => console.log(`Copied ${src} to ${buildPath}`))
}

function createPackageFile() {
  return new Promise(resolve => {
    fse.readFile(
      path.resolve(__dirname, '../package.json'),
      'utf8',
      (err, data) => {
        if (err) {
          throw err
        }

        resolve(data)
      },
    )
  })
    .then(data => JSON.parse(data))
    .then(packageData => {
      const {
        version,
        contributors,
        description,
        keywords,
        repository,
        license,
        bugs,
        homepage,
        peerDependencies,
        dependencies,
      } = packageData

      const minimalPackage = {
        name: 'react-move',
        version,
        contributors,
        description,
        main: 'index.js',
        module: 'es/index.js',
        'jsnext:main': 'es/index.js',
        types: 'index.d.ts',
        keywords,
        repository,
        license,
        bugs,
        homepage,
        peerDependencies,
        dependencies,
      }

      return new Promise(resolve => {
        const buildPath = path.resolve(__dirname, '../build/package.json')
        const data = JSON.stringify(minimalPackage, null, 2)
        fse.writeFile(buildPath, data, err => {
          if (err) {
            throw err
          }
          console.log(`\nCreated package.json in ${buildPath}\n`)
          resolve()
        })
      })
    })
}

const files = ['README.md', 'LICENSE']

const types = [
  ['src/index.d.ts', 'index.d.ts'],
  ['src/core/index.d.ts', 'core/index.d.ts'],
  ['src/createAnimate/index.d.ts', 'createAnimate/index.d.ts'],
  ['src/createNodeGroup/index.d.ts', 'createNodeGroup/index.d.ts'],
]

Promise.all(files.map(file => copyFile(file)))
  .then(() => Promise.all(types.map(file => copyTypes(...file))))
  .then(() => createPackageFile())
<|endoftext|>


<commit_before>// ==UserScript==
// @name         Zoom show web link
// @description  Adds a link to the Zoom web client to the join page.
// @author       Stephen Jennings
// @namespace    http://jennings.io/
// @version      1.20200622.0
// @match        https://*.zoom.us/j/*
// @run-at       document-start
// ==/UserScript==

(function () {
  "use strict";

  function getMeetingIdFromLocation() {
    const { pathname } = location;
    const re = /\/j\/(\d+)/;
    const match = pathname.match(re);
    if (match) {
      return match[1];
    }
  }

  function getWebClientUrl(meetingId) {
    return `https://zoom.us/wc/join/${meetingId}`;
  }

  const id = setTimeout(() => {
    const meetingId = getMeetingIdFromLocation();
    const meetingUrl = getWebClientUrl(meetingId);

    const div = document.createElement("div");
    div.innerHTML = `Web client: <a href="${meetingUrl}">${meetingUrl}</a>`;

    const parentElement =
      document.querySelector("h3[role=presentation]") || document.body;
    parentElement.appendChild(div);
  }, 100);
})();
<commit_msg>zoom-show-web-link: retry a couple times before falling back<commit_after>// ==UserScript==
// @name         Zoom show web link
// @description  Adds a link to the Zoom web client to the join page.
// @author       Stephen Jennings
// @namespace    http://jennings.io/
// @version      1.20200622.0
// @match        https://*.zoom.us/j/*
// @run-at       document-start
// ==/UserScript==

(function() {
  "use strict";

  function getMeetingIdFromLocation() {
    const { pathname } = location;
    const re = /\/j\/(\d+)/;
    const match = pathname.match(re);
    if (match) {
      return match[1];
    }
  }

  function getWebClientUrl(meetingId) {
    return `https://zoom.us/wc/join/${meetingId}`;
  }

  let attempts = 4;
  const id = setInterval(() => {
    const meetingId = getMeetingIdFromLocation();
    const meetingUrl = getWebClientUrl(meetingId);

    const div = document.createElement("div");
    div.innerHTML = `Web client: <a href="${meetingUrl}">${meetingUrl}</a>`;

    const parentElement = document.querySelector("h3[role=presentation]");

    if (parentElement != null) {
      parentElement.appendChild(div);
      clearInterval(id);
    } else if (attempts-- <= 0) {
      document.body.appendChild(div);
      clearInterval(id);
    }
  }, 100);
})();
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright The Closure Library Authors.
 * SPDX-License-Identifier: Apache-2.0
 */

goog.provide('goog.promise.Resolver');

goog.requireType('goog.Promise');

/**
 * Resolver interface for promises. The resolver is a convenience interface that
 * bundles the promise and its associated resolve and reject functions together,
 * for cases where the resolver needs to be persisted internally.
 *
 * @interface
 * @template TYPE
 */
goog.promise.Resolver = function() {};

/**
 * The promise that created this resolver.
 * @type {!goog.Promise<TYPE>}
 */
goog.promise.Resolver.prototype.promise;

/**
 * Resolves this resolver with the specified value.
 * @type {function((TYPE|goog.Promise<TYPE>|Thenable)=)}
 */
goog.promise.Resolver.prototype.resolve;

/**
 * Rejects this resolver with the specified reason.
 * @type {function(*=): void}
 */
goog.promise.Resolver.prototype.reject;
<commit_msg>[Closure] Convert `goog.promise.Resolver` to `goog.module` and to ES6. RELNOTES: n/a<commit_after>/**
 * @license
 * Copyright The Closure Library Authors.
 * SPDX-License-Identifier: Apache-2.0
 */
goog.module('goog.promise.Resolver');
goog.module.declareLegacyNamespace();

const GoogPromise = goog.requireType('goog.Promise');
const Thenable = goog.requireType('goog.Thenable');

/**
 * Resolver interface for promises. The resolver is a convenience interface that
 * bundles the promise and its associated resolve and reject functions together,
 * for cases where the resolver needs to be persisted internally.
 * @template TYPE
 * @interface
 */
class Resolver {
  constructor() {
    /**
     * The promise that created this resolver.
     * @type {!GoogPromise<TYPE>}
     */
    this.promise;
    /**
     * Resolves this resolver with the specified value.
     * @type {function((TYPE|GoogPromise<TYPE>|Promise<TYPE>|IThenable|Thenable)=)}
     */
    this.resolve;
    /**
     * Rejects this resolver with the specified reason.
     * @type {function(*=): void}
     */
    this.reject;
  }
}

exports = Resolver;
<|endoftext|>


<commit_before>/* global describe, it */

var assert = require('assert')
var networks = require('../src/networks')

var HDNode = require('../src/hdnode')

var fixtures = require('./fixtures/network')

describe('networks', function () {
  fixtures.forEach(function (f) {
    var network = networks[f.network]

    Object.keys(f.bip32).forEach(function (name) {
      var extb58 = f.bip32[name]

      it(extb58 + ' auto-detects ' + f.network, function () {
        assert.strictEqual(HDNode.fromBase58(extb58).keyPair.network, network)
      })
    })
  })
})
<commit_msg>rm network auto-detection<commit_after><|endoftext|>