<commit_before>/// <reference path="../jquery-2.0.2.js" />
/// <reference path="persister.js" />

var ui = (function () {
    function drawLogInForm() {
        return '<fieldset id="login-user-container">' +
                    '<legend>Log In</legend>' +
                    'Nickname' +
                    '<input id="login-user-nickname" type="text" name="name" value="" placeholder="Enter your nickname" autofocus="true" />' +
                    'Password' +
                    '<input id="login-user-password" type="password" name="name" value="" placeholder="Enter your password" />' +
                    '<button id="button-log-in">Log In</button>' +
                    'Register now' +
                '</fieldset>';
    }

    function drawRegisterForm() {
        return '<fieldset id="register-user-container">' +
                    '<legend>Register</legend>' +
                    'Name' +
                    '<input id="register-user-name" type="text" name="name" value="" placeholder="Enter your first and last name" autofocus="true" />' +
                    'Nickname' +
                    '<input id="register-user-nickname" type="text" name="name" value="" placeholder="Enter your nickname" />' +
                    'Password' +
                    '<input id="register-user-password" type="password" name="name" value="" placeholder="Enter your password" />' +
                    'Password' +
                    '<input id="register-user-password-re" type="password" name="name" value="" placeholder="Confirm your password" />' +
                    'Back' +
                    '<button id="button-register">Register</button>' +
                '</fieldset>';
    }

    function drawLoggedInForm() {
        return '
' +
                    '
Hello, ' + localStorage.getItem('userNickname') + '
' +
                    '
Let\'s chat ...
' +
                    '<button id="button-logout">Log out</button>' +
                '
';
    }

    function drawUserInteraction() {
        return '

' +
               '

' +
               '

';
    }

    function showAppErrorMessage(message) {
        $('#error-messages').text(message);

        setTimeout(function () {
            $('#error-messages').text('');
        }, 15000);
    }

    function showErrorMessage(err) {
        $('#error-messages').text(err);

        setTimeout(function () {
            $('#error-messages').text('');
        }, 15000);
    }

    function showMessage(message) {
        $('#messages').text(message);

        setTimeout(function () {
            $('#messages').text('');
        }, 15000);
    }

    function clearErrorMessage() {
        $('#error-messages').text('');
    }

    function showOrHideElements(elementID) {
        if ($(elementID + '-list').hasClass('show')) {
            $(elementID + '-list').hide(1500);
            $(elementID + '-list').removeClass('show');
        }
        else {
            $(elementID + '-list').show(1500);
            $(elementID + '-list').addClass('show');
        }

        return false;
    }

    function drawListOfChats(myActiveChats, container, conatinerTitle, type) {
        $(container)
            .append($('
').attr('id', 'chats-' + type).text(conatinerTitle))
            .append($('
').attr({ 'id': 'chats-' + type + '-list', 'class': 'show' }));

        var elementsContainer = $(container + ' #' + 'chats-' + type + '-list');

        var currentUser = localStorage.getItem('userId');

        for (var i = 0; i < myActiveChats.length; i++) {
            var otherUser;
            var otherUserId;

            if (myActiveChats[i].User1.Id != currentUser) {
                otherUser = myActiveChats[i].User1.Name;
                otherUserId = myActiveChats[i].User1.Id;
            }
            else {
                otherUser = myActiveChats[i].User2.Name;
                otherUserId = myActiveChats[i].User1.Id;
            }

            var currentLi = $('
').attr({
                'data-chat-id': myActiveChats[i].Id,
                'data-chat-channel': myActiveChats[i].Channel,
                'data-user-id': otherUserId
            }).append($('').attr('href', '#').text(otherUser));

            elementsContainer.append(currentLi);
        }
    }

    function drawListOfUsers(users, container, conatinerTitle, type) {
        $(container)
            .append($('
').attr('id', 'users-' + type).text(conatinerTitle))
            .append($('
').attr({ 'id': 'users-' + type + '-list', 'class': 'show' }));

        var elementsContainer = $(container + ' #' + 'users-' + type + '-list');

        for (var i = 0; i < users.length; i++) {
            elementsContainer
                .append($('
').attr('data-user-id', users[i].Id).append($('').attr('href', '#').text(users[i].Name)));
        }
    }

    function drawSendMessageMenu(otherUserID, chatId) {
        return '
' +
                    '<input id="message-text" type="text" name="name" value="" placeholder="Message" />' +
                    '<button id="confirm-send" data-user-id="' + otherUserID + '" data-chat-id="' + chatId + '">Send</button>' +
                '
';
    }

    function drawMessages(data) {
        $('#current-chat-state').empty();
        var elementsContainer = $('#current-chat-state').append($('
'));
        elementsContainer = $('#current-chat-state ul')

        for (var i = 0; i < data.length; i++) {
            elementsContainer
                .append($('
').attr('data-owner-id', data[i].OwnerId).text(data[i].OwnerName + ': ' + data[i].Content));
        }
    }

    function drawSidebars(persister) {
        $('#left-side-bar').empty();
        $('#right-side-bar').empty();
        persister.chat.all(function (data) {
            drawListOfChats(data, '#left-side-bar', 'My active chats', 'active');
        });

        persister.user.all(function (data) {
            drawListOfUsers(data, '#right-side-bar', 'Users', 'user');
        });
    }

    return {
        drawLogIn: drawLogInForm,
        drawRegister: drawRegisterForm,
        drawLoggedIn: drawLoggedInForm,
        drawUserInteraction: drawUserInteraction,
        showAppErrorMessage: showAppErrorMessage,
        showErrorMessage: showErrorMessage,
        showMessage: showMessage,
        clearErrorMessage: clearErrorMessage,
        drawListOfChats: drawListOfChats,
        drawListOfUsers: drawListOfUsers,
        drawSendMessageMenu: drawSendMessageMenu,
        drawMessages: drawMessages,
        drawSidebars: drawSidebars,
        showOrHideElements: showOrHideElements
    };
}());<commit_msg>Fix in UI<commit_after>/// <reference path="../jquery-2.0.2.js" />
/// <reference path="persister.js" />

var ui = (function () {
    function drawLogInForm() {
        return '<fieldset id="login-user-container">' +
                    '<legend>Log In</legend>' +
                    'Nickname' +
                    '<input id="login-user-nickname" type="text" name="name" value="" placeholder="Enter your nickname" autofocus="true" />' +
                    'Password' +
                    '<input id="login-user-password" type="password" name="name" value="" placeholder="Enter your password" />' +
                    '<button id="button-log-in">Log In</button>' +
                    'Register now' +
                '</fieldset>';
    }

    function drawRegisterForm() {
        return '<fieldset id="register-user-container">' +
                    '<legend>Register</legend>' +
                    'Name' +
                    '<input id="register-user-name" type="text" name="name" value="" placeholder="Enter your first and last name" autofocus="true" />' +
                    'Nickname' +
                    '<input id="register-user-nickname" type="text" name="name" value="" placeholder="Enter your nickname" />' +
                    'Password' +
                    '<input id="register-user-password" type="password" name="name" value="" placeholder="Enter your password" />' +
                    'Password' +
                    '<input id="register-user-password-re" type="password" name="name" value="" placeholder="Confirm your password" />' +
                    'Back' +
                    '<button id="button-register">Register</button>' +
                '</fieldset>';
    }

    function drawLoggedInForm() {
        return '
' +
                    '
Hello, ' + localStorage.getItem('userNickname') + '
' +
                    '
Let\'s chat ...
' +
                    '<button id="button-logout">Log out</button>' +
                '
';
    }

    function drawUserInteraction() {
        return '

' +
               '

' +
               '

';
    }

    function showAppErrorMessage(message) {
        $('#error-messages').text(message);

        setTimeout(function () {
            $('#error-messages').text('');
        }, 15000);
    }

    function showErrorMessage(err) {
        $('#error-messages').text(err);

        setTimeout(function () {
            $('#error-messages').text('');
        }, 15000);
    }

    function showMessage(message) {
        $('#messages').text(message);

        setTimeout(function () {
            $('#messages').text('');
        }, 15000);
    }

    function clearErrorMessage() {
        $('#error-messages').text('');
    }

    function showOrHideElements(elementID) {
        if ($(elementID + '-list').hasClass('show')) {
            $(elementID + '-list').hide(1500);
            $(elementID + '-list').removeClass('show');
        }
        else {
            $(elementID + '-list').show(1500);
            $(elementID + '-list').addClass('show');
        }

        return false;
    }

    function drawListOfChats(myActiveChats, container, conatinerTitle, type) {
        $(container)
            .append($('
').attr('id', 'chats-' + type).text(conatinerTitle))
            .append($('
').attr({ 'id': 'chats-' + type + '-list', 'class': 'show' }));

        var elementsContainer = $(container + ' #' + 'chats-' + type + '-list');

        var currentUser = localStorage.getItem('userId');

        for (var i = 0; i < myActiveChats.length; i++) {
            var otherUser;
            var otherUserId;

            if (myActiveChats[i].User1.Id != currentUser) {
                otherUser = myActiveChats[i].User1.Name;
                otherUserId = myActiveChats[i].User1.Id;
            }
            else {
                otherUser = myActiveChats[i].User2.Name;
                otherUserId = myActiveChats[i].User2.Id;
            }

            var currentLi = $('
').attr({
                'data-chat-id': myActiveChats[i].Id,
                'data-chat-channel': myActiveChats[i].Channel,
                'data-user-id': otherUserId
            }).append($('').attr('href', '#').text(otherUser));

            elementsContainer.append(currentLi);
        }
    }

    function drawListOfUsers(users, container, conatinerTitle, type) {
        $(container)
            .append($('
').attr('id', 'users-' + type).text(conatinerTitle))
            .append($('
').attr({ 'id': 'users-' + type + '-list', 'class': 'show' }));

        var elementsContainer = $(container + ' #' + 'users-' + type + '-list');

        for (var i = 0; i < users.length; i++) {
            elementsContainer
                .append($('
').attr('data-user-id', users[i].Id).append($('').attr('href', '#').text(users[i].Name)));
        }
    }

    function drawSendMessageMenu(otherUserID, chatId) {
        return '
' +
                    '<input id="message-text" type="text" name="name" value="" placeholder="Message" />' +
                    '<button id="confirm-send" data-user-id="' + otherUserID + '" data-chat-id="' + chatId + '">Send</button>' +
                '
';
    }

    function drawMessages(data) {
        $('#current-chat-state').empty();
        var elementsContainer = $('#current-chat-state').append($('
'));
        elementsContainer = $('#current-chat-state ul')

        for (var i = 0; i < data.length; i++) {
            elementsContainer
                .append($('
').attr('data-owner-id', data[i].OwnerId).text(data[i].OwnerName + ': ' + data[i].Content));
        }
    }

    function drawSidebars(persister) {
        $('#left-side-bar').empty();
        $('#right-side-bar').empty();
        persister.chat.all(function (data) {
            drawListOfChats(data, '#left-side-bar', 'My active chats', 'active');
        });

        persister.user.all(function (data) {
            drawListOfUsers(data, '#right-side-bar', 'Users', 'user');
        });
    }

    return {
        drawLogIn: drawLogInForm,
        drawRegister: drawRegisterForm,
        drawLoggedIn: drawLoggedInForm,
        drawUserInteraction: drawUserInteraction,
        showAppErrorMessage: showAppErrorMessage,
        showErrorMessage: showErrorMessage,
        showMessage: showMessage,
        clearErrorMessage: clearErrorMessage,
        drawListOfChats: drawListOfChats,
        drawListOfUsers: drawListOfUsers,
        drawSendMessageMenu: drawSendMessageMenu,
        drawMessages: drawMessages,
        drawSidebars: drawSidebars,
        showOrHideElements: showOrHideElements
    };
}());<|endoftext|>


<commit_before>/*
 Glue JavaScript code to startup ACE editor and submit text
 pbv, 2018
 */

/* start up the editor */
function startAceEditor(id) {
    var editor = ace.edit(id);
    var size = window.localStorage.getItem('fontsize');
    if (size == null)
	size = "16";
    editor.setFontSize(parseInt(size));
    return editor;
}

function changeFontSize(id, delta) {
    var size = editor.getFontSize() + delta;
    if (size < 8)
	size = 8;
    else if (size > 40)
	size = 40;
    editor.setFontSize(size);
    window.localStorage.setItem('fontsize',size);
}

/* set the editing mode by file path extension
*/

function setAceEditorModeExt(editor, path) {
    var modelist = ace.require("ace/ext/modelist");
    var mode = modelist.getModeForPath(path).mode;
    editor.getSession().setMode(mode);
}

/* read a local file
 */
function readFile(editor, browserId) {
    if (window.File && window.FileReader && window.FileList && window.Blob) {
        // Get the file object
	var filesSelected = document.getElementById(browserId).files;
	if(filesSelected.length > 0) {
            var fileTobeRead = filesSelected[0];
            var fileReader = new FileReader();
            fileReader.onload = function (e) {
		editor.setValue(fileReader.result);
		editor.moveCursorTo(0,0);
            }
            fileReader.readAsText(fileTobeRead);
	    return fileTobeRead.name;
	}
    }
}

function submitListener(editor, codeId) {
    var textarea = document.getElementById(codeId);
    textarea.value = editor.session.getValue();
}

function fileListener(editor, fileBrowserId, langSelectorId) {
    var filename = readFile(editor, fileBrowserId);
    for(var i = 0; i<languageExtensions.length; i++)  {
	if ( filename.endsWith(languageExtensions[i]) ) {
	    var input = document.getElementById(langSelectorId);
	    editor.session.setMode(languageModes[i]);
	    input.selectedIndex = i;
	    break;
	}
    }
}

<commit_msg>ensure ACE editor uses soft tabs<commit_after>/*
 Glue JavaScript code to startup ACE editor and submit text
 pbv, 2018
 */

/* start up the editor */
function startAceEditor(id) {
    var editor = ace.edit(id);
    var size = window.localStorage.getItem('fontsize');
    if (size == null)
	size = "16";
    editor.setFontSize(parseInt(size));
    editor.getSession().setUseSoftTabs(true);
    return editor;
}

function changeFontSize(id, delta) {
    var size = editor.getFontSize() + delta;
    if (size < 8)
	size = 8;
    else if (size > 40)
	size = 40;
    editor.setFontSize(size);
    window.localStorage.setItem('fontsize',size);
}

/* set the editing mode by file path extension
*/

function setAceEditorModeExt(editor, path) {
    var modelist = ace.require("ace/ext/modelist");
    var mode = modelist.getModeForPath(path).mode;
    editor.getSession().setMode(mode);
    editor.getSession().setUseSoftTabs(true);
}

/* read a local file
 */
function readFile(editor, browserId) {
    if (window.File && window.FileReader && window.FileList && window.Blob) {
        // Get the file object
	var filesSelected = document.getElementById(browserId).files;
	if(filesSelected.length > 0) {
            var fileTobeRead = filesSelected[0];
            var fileReader = new FileReader();
            fileReader.onload = function (e) {
		editor.setValue(fileReader.result);
		editor.moveCursorTo(0,0);
		editor.getSession().setUseSoftTabs(true);
            }
            fileReader.readAsText(fileTobeRead);
	    return fileTobeRead.name;
	}
    }
}

function submitListener(editor, codeId) {
    var textarea = document.getElementById(codeId);
    textarea.value = editor.session.getValue();
}

function fileListener(editor, fileBrowserId, langSelectorId) {
    var filename = readFile(editor, fileBrowserId);
    for(var i = 0; i<languageExtensions.length; i++)  {
	if ( filename.endsWith(languageExtensions[i]) ) {
	    var input = document.getElementById(langSelectorId);
	    editor.session.setMode(languageModes[i]);
	    input.selectedIndex = i;
	    break;
	}
    }
}

<|endoftext|>


<commit_before>function calCalculator(){
  var age = document.getElementById('age').value;
  var height = document.getElementById('height').value;
  var weight = document.getElementById('weight').value;
  var sex = document.getElementById('sex').value;
  if  (age === '' || weight === '' || height === '' || sex === '') {
    document.getElementById('output').innerHTML= 'Missing factor!';
  }

  else {
    //turn inputs into usable data
    age = parseInt(age, 10);
    height = parseInt(height, 10);
    weight = parseInt(weight, 10);

    //declare values for following "Harris-Benedict" equation
    var recCalories;
    var percentage;
    var calsInPSL = 375; /*there are 375 calories in a large whole milk
    Peet's Pumpkin Spice Latte*/

      if (sex === 'F' || sex === 'f') {
        recCalories = Math.floor(1.375 * ((447.593 + (9.247 * weight) +
        (3.098 *height)) - (4.330 * age)));
      }

      else if (sex === 'M' || sex === 'm') {
        recCalories = Math.floor(1.375 * ((88.362 + (13.397 * weight) +
        (4.799 * height)) - (5.677 * age)));
      }

      percentage = Math.floor(100 * (calsInPSL / recCalories));
      document.getElementById('output').innerHTML= 'You are about to consume ' +
      percentage + '%  of your daily recommended ' + recCalories + ' calories!';
    }
  }<commit_msg>redoing because of github ick that I need to figure out<commit_after>function calCalculator(){
  var age = document.getElementById('age').value;
  var height = document.getElementById('height').value;
  var weight = document.getElementById('weight').value;
  var sex = document.getElementById('sex').value;
  if  (age === '' || weight === '' || height === '' || sex === '') {
    document.getElementById('output').innerHTML= 'Missing factor!';
  }

  else {
    //turn inputs into usable data
    age = parseInt(age, 10);
    height = parseInt(height, 10);
    weight = parseInt(weight, 10);

    //declare values for following "Harris-Benedict" equation
    var recCalories;
    var percentage;
    var calsInPSL = 435; /*there are 435 calories in a large whole milk
    Peet's Pumpkin Spice Latte*/

      if (sex === 'F' || sex === 'f') {
        recCalories = Math.floor(1.375 * ((447.593 + (9.247 * weight) +
        (3.098 *height)) - (4.330 * age)));
      }

      else if (sex === 'M' || sex === 'm') {
        recCalories = Math.floor(1.375 * ((88.362 + (13.397 * weight) +
        (4.799 * height)) - (5.677 * age)));
      }

      percentage = Math.floor(100 * (calsInPSL / recCalories));
      document.getElementById('output').innerHTML= 'You are about to consume ' +
      percentage + '%  of your daily recommended ' + recCalories + ' calories!';
    }
  }<|endoftext|>


<commit_before>var xmlHttpRequest;
var startws; // ゲームの開始ボタンを押すまでのWebSocket変数
var updatews = null; // ゲームプレイ中のWebSocket変数
var myName; // 自分のuser名
var userList;
var playerFlag; // 書き手かどうかの判別
var startButtonJson;
var LOCATION = "localhost:8080/isp2";
// School: "ecl.info.kindai.ac.jp/16/isp2/warup/servlet/B17";
// "localhost:8080/isp2";

// 読み込み時に呼び出される
function init() {
    // サーブレットからユーザ名を取得
    sendToStartServlet();

    // 開始ボタンのEventListener
    document.getElementById("start_button").addEventListener("click", function() {
        updatews.send(startButtonJson);
    }, false);

    // 送信ボタンのEventListener
    document.getElementById("send_button").addEventListener("click", function() {
        // textBoxについての設定
            // 絵のタイトル未入力の際の動作
            var drawWord = document.getElementById("word");
            if (!drawWord.value) {
                alert("絵の名前を入力してください");
                return;
            }

            // textformに日本語のみが入力されているかの判定
            if (!(drawWord.value.match(/^[\u3040-\u309F]+$/)) && !drawWord.value.match(/ー/)) {
                alert("平仮名のみで入力してください");
                return;
            }
            var lastWord = drawWord.value.slice(-1);
            if (lastWord.match(/ん/)) {
                alert("勝手にしりとりを終わらせないでください");
                return;
            }

        // 画像->base64データに変換
        var data = canvas.toDataURL("image/jpeg");
        // alert(data);

        // 画像送信用
        // json = {"playerName":"myName","userList":[],"imgName":"絵の名前","img":"絵のデータ"}
        var json = "{\"playerName\": \"" + myName + "\",\"userList\":[],\"imgName\": \"drawWord.value\",\"img\": \"" + data + "\"}";

        // 画像データ送信用のupdatewsを受け取ってから送信する
        updatews.send(json);

        // 画面クリア
        clearCanvas();

    }, false);

}

/* xmlHttpRequestをStartに送る/受取はcheckStartRequest */
function sendToStartServlet() {
    // ここで開始ボタンを無効化
    // <未実装>
    var url = "start";
    xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.onreadystatechange = checkStartRequest;
    xmlHttpRequest.open("GET", url, true);
    xmlHttpRequest.send(null);
}

/* xmlHttpRequestの受取/受け取った自分の名前をsendToStartWebSocketに送信 */
function checkStartRequest() {
    // 開始ボタンのレスポンス処理部分
    if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
        // 返信データの処理
        var response = JSON.parse(xmlHttpRequest.responseText);
        myName = response.userName;
        // StartWebSocketに送信
        sendToStartWebSocket(myName);
    }
}

/* startwsで自分の名前を送信/参加者を受取/参加者リストに表示/参加を確認できたらsendToUpdateWebSocketへの接続を行う */
function sendToStartWebSocket(userName) {
    startws = new WebSocket('ws://' + LOCATION + '/project/drawwordchain/startbroadcast');

    startws.onopen = function() {
        startws.send(userName);
    };

    startws.onmessage = function(receive) {
        userList = (receive.data).split(",");
        console.log("startwsのonmessage");
        var userAreaElement = document.getElementById("user_name");

        // データの削除
        while (userAreaElement.lastChild) {
            userAreaElement.removeChild(userAreaElement.lastChild);
        }

        // プレイヤーの挿入
        userList.forEach(function(user) {
            console.log("userList: "+user);
            var userElement = document.createElement("div");
            userElement.appendChild(document.createTextNode(user));
            userAreaElement.appendChild(userElement);
        });

        // StartWebSocketにデータを送信
        sendToUpdateWebSocket();
    };
}

/* updatewsで自分の名前と参加者リストを送信/ */
function sendToUpdateWebSocket() {

    if(updatews === null) {
        updatews = new WebSocket('ws://' + LOCATION + '/project/drawwordchain/updatebroadcast');
    }

    /* 接続時にユーザリストと自分の名前をパック */
    updatews.onopen = function() {
        // userListJson = a", "b", "c"
        var userListJson = "";

        for (var i = 0; i < userList.length; i++) {
            userListJson += "\"" + userList[i] + "\"";
            if (i == userList.length - 1) {} else {
                userListJson += ",";
            }
        }

        // json = {"playerName":"myName","userList":["test","test2"],"imgName":"","img":""}
        startButtonJson = "{\"playerName\": \"" + myName + "\",\"userList\":[" + userListJson + "],\"imgName\": \"\",\"img\": \"\"}";

        // ここで開始ボタンを有効化
        // <未実装>
    };

    /* プレイヤー名と最初の文字を受取 */
    updatews.onmessage = function(receive) {
        console.log("updatewsのonmessage");
        // receive.data = {"playerName" : "Name", "firstChar" : "文字"}
        var response = JSON.parse(receive.data);
        //firstCharをplay_displayの最初に表示
        var firstChar = response.firstChar;
        var playerName = response.playerName;

        //初めの文字を表示
        var element = document.createElement('p');
        element.style.cssText = "font-size:100pt;" + "display:table-cell;" + "vertical-align:middle;";
        element.appendChild(document.createTextNode("[" + firstChar + "]"));
        document.getElementById("pict_display").appendChild(element);

        //矢印を表示
        var arrow = document.createElement('p');
        arrow.style.cssText = "display:table-cell;" + "vertical-align:middle;" + "font-size:100px;" + "color:white;";
        var arrowText = document.createTextNode("→");
        arrow.appendChild(arrowText);
        document.getElementById('pict_display').appendChild(arrow);

        // 以下やること
        // 開始ボタンを無効にする
        // playerFlagをtrueにする．

        // 動作しないためチェックしてください
        // element.appendChild(document.createTextNode(playerName));
        // document.getElementById("pict_display").appendChild(element);

        //startwsを切断
        console.log("startwsの切断");
        startws.close(1000);

        // send_buttonを押したときのみに更新してしまうため，他のプレイヤーが受信できない問題
        // updatews.onmessageの更新/imgデータの受取
        updatews.onmessage = function(receive) {
            console.log("更新後のupdatewsのonmessage");
            var response = JSON.parse(receive.data);
            var imgData = response.img;
            var img = new Image();
            img.src = imgData;
            img.width = 250;
            img.height = 250;

            console.log(response.img);

            var newImg = document.createElement('p');
            newImg.style.cssText = "display:table-cell;" + "vertical-align:middle;" + "border: 1px solid black;";
            newImg.appendChild(img);
            document.getElementById('pict_display').appendChild(newImg);
            //画像と画像の間に矢印
            var arrow = document.createElement('p');
            arrow.style.cssText = "display:table-cell;" + "vertical-align:middle;" + "font-size:100px;" + "color:white;";
            var arrowText = document.createTextNode("→");
            arrow.appendChild(arrowText);
            document.getElementById('pict_display').appendChild(arrow);
        };

        // データを受け取ったときに現在の落書きを削除
        clearCanvas();

    };
}

function clearCanvas() {
    ctx.beginPath();
    ctx.fillStyle = "#f5f5f5";
    ctx.globalAlpha = 1.0;
    ctx.fillRect(0, 0, 500, 500);
}

// ページ読み込み時
window.addEventListener("load", function() {
    init(); // 初期化用メソッド
}, false);

// // ページ終了時
window.addEventListener("beforeunload", function() {
    startws.close(1000);
    updatews.close(1000);
}, false);
<commit_msg>現在のプレイヤー名を表示するようにmain.jsをいじった<commit_after>var xmlHttpRequest;
var startws; // ゲームの開始ボタンを押すまでのWebSocket変数
var updatews = null; // ゲームプレイ中のWebSocket変数
var myName; // 自分のuser名
var userList;
var playerFlag; // 書き手かどうかの判別
var startButtonJson;
var LOCATION = "localhost:8080/isp2";
// School: "ecl.info.kindai.ac.jp/16/isp2/warup/servlet/B17";
// "localhost:8080/isp2";

// 読み込み時に呼び出される
function init() {
    // サーブレットからユーザ名を取得
    sendToStartServlet();

    // 開始ボタンのEventListener
    document.getElementById("start_button").addEventListener("click", function() {
        updatews.send(startButtonJson);
    }, false);

    // 送信ボタンのEventListener
    document.getElementById("send_button").addEventListener("click", function() {
        // textBoxについての設定
            // 絵のタイトル未入力の際の動作
            var drawWord = document.getElementById("word");
            if (!drawWord.value) {
                alert("絵の名前を入力してください");
                return;
            }

            // textformに日本語のみが入力されているかの判定
            if (!(drawWord.value.match(/^[\u3040-\u309F]+$/)) && !drawWord.value.match(/ー/)) {
                alert("平仮名のみで入力してください");
                return;
            }
            var lastWord = drawWord.value.slice(-1);
            if (lastWord.match(/ん/)) {
                alert("勝手にしりとりを終わらせないでください");
                return;
            }

        // 画像->base64データに変換
        var data = canvas.toDataURL("image/jpeg");
        // alert(data);

        // 画像送信用
        // json = {"playerName":"myName","userList":[],"imgName":"絵の名前","img":"絵のデータ"}
        var json = "{\"playerName\": \"" + myName + "\",\"userList\":[],\"imgName\": \"drawWord.value\",\"img\": \"" + data + "\"}";

        // 画像データ送信用のupdatewsを受け取ってから送信する
        updatews.send(json);

        // 画面クリア
        clearCanvas();

    }, false);

}

/* xmlHttpRequestをStartに送る/受取はcheckStartRequest */
function sendToStartServlet() {
    // ここで開始ボタンを無効化
    // <未実装>
    var url = "start";
    xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.onreadystatechange = checkStartRequest;
    xmlHttpRequest.open("GET", url, true);
    xmlHttpRequest.send(null);
}

/* xmlHttpRequestの受取/受け取った自分の名前をsendToStartWebSocketに送信 */
function checkStartRequest() {
    // 開始ボタンのレスポンス処理部分
    if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
        // 返信データの処理
        var response = JSON.parse(xmlHttpRequest.responseText);
        myName = response.userName;
        // StartWebSocketに送信
        sendToStartWebSocket(myName);
    }
}

/* startwsで自分の名前を送信/参加者を受取/参加者リストに表示/参加を確認できたらsendToUpdateWebSocketへの接続を行う */
function sendToStartWebSocket(userName) {
    startws = new WebSocket('ws://' + LOCATION + '/project/drawwordchain/startbroadcast');

    startws.onopen = function() {
        startws.send(userName);
    };

    startws.onmessage = function(receive) {
        userList = (receive.data).split(",");
        console.log("startwsのonmessage");
        var userAreaElement = document.getElementById("user_name");

        // データの削除
        while (userAreaElement.lastChild) {
            userAreaElement.removeChild(userAreaElement.lastChild);
        }

        // プレイヤーの挿入
        userList.forEach(function(user) {
            console.log("userList: "+user);
            var userElement = document.createElement("div");
            userElement.appendChild(document.createTextNode(user));
            userAreaElement.appendChild(userElement);
        });

        // StartWebSocketにデータを送信
        sendToUpdateWebSocket();
    };
}

/* updatewsで自分の名前と参加者リストを送信/ */
function sendToUpdateWebSocket() {

    if(updatews === null) {
        updatews = new WebSocket('ws://' + LOCATION + '/project/drawwordchain/updatebroadcast');
    }

    /* 接続時にユーザリストと自分の名前をパック */
    updatews.onopen = function() {
        // userListJson = a", "b", "c"
        var userListJson = "";

        for (var i = 0; i < userList.length; i++) {
            userListJson += "\"" + userList[i] + "\"";
            if (i == userList.length - 1) {} else {
                userListJson += ",";
            }
        }

        // json = {"playerName":"myName","userList":["test","test2"],"imgName":"","img":""}
        startButtonJson = "{\"playerName\": \"" + myName + "\",\"userList\":[" + userListJson + "],\"imgName\": \"\",\"img\": \"\"}";

        // ここで開始ボタンを有効化
        // <未実装>
    };

    /* プレイヤー名と最初の文字を受取 */
    updatews.onmessage = function(receive) {
        console.log("updatewsのonmessage");
        // receive.data = {"playerName" : "Name", "firstChar" : "文字"}
        var response = JSON.parse(receive.data);
        //firstCharをplay_displayの最初に表示
        var firstChar = response.firstChar;
        var playerName = response.playerName;

        //初めの文字を表示
        var element = document.createElement('p');
        element.style.cssText = "font-size:100pt;" + "display:table-cell;" + "vertical-align:middle;";
        element.appendChild(document.createTextNode("[" + firstChar + "]"));
        document.getElementById("pict_display").appendChild(element);

        //矢印を表示
        var arrow = document.createElement('p');
        arrow.style.cssText = "display:table-cell;" + "vertical-align:middle;" + "font-size:100px;" + "color:white;";
        var arrowText = document.createTextNode("→");
        arrow.appendChild(arrowText);
        document.getElementById('pict_display').appendChild(arrow);

        //現在のプレイヤー名を表示
        document.getElementById('now_draw_user').innerHTML=playerName;

        // 以下やること
        // 開始ボタンを無効にする
        // playerFlagをtrueにする．

        //startwsを切断
        console.log("startwsの切断");
        startws.close(1000);

        // send_buttonを押したときのみに更新してしまうため，他のプレイヤーが受信できない問題
        // updatews.onmessageの更新/imgデータの受取
        updatews.onmessage = function(receive) {
            console.log("更新後のupdatewsのonmessage");
            var response = JSON.parse(receive.data);
            var imgData = response.img;
            var img = new Image();
            img.src = imgData;
            img.width = 250;
            img.height = 250;

            console.log(response.img);

            var newImg = document.createElement('p');
            newImg.style.cssText = "display:table-cell;" + "vertical-align:middle;" + "border: 1px solid black;";
            newImg.appendChild(img);
            document.getElementById('pict_display').appendChild(newImg);
            //画像と画像の間に矢印
            var arrow = document.createElement('p');
            arrow.style.cssText = "display:table-cell;" + "vertical-align:middle;" + "font-size:100px;" + "color:white;";
            var arrowText = document.createTextNode("→");
            arrow.appendChild(arrowText);
            document.getElementById('pict_display').appendChild(arrow);
        };

        // データを受け取ったときに現在の落書きを削除
        clearCanvas();

    };
}

function clearCanvas() {
    ctx.beginPath();
    ctx.fillStyle = "#f5f5f5";
    ctx.globalAlpha = 1.0;
    ctx.fillRect(0, 0, 500, 500);
}

// ページ読み込み時
window.addEventListener("load", function() {
    init(); // 初期化用メソッド
}, false);

// // ページ終了時
window.addEventListener("beforeunload", function() {
    startws.close(1000);
    updatews.close(1000);
}, false);
<|endoftext|>


<commit_before>var xmlHttpRequest;
var ws;
var myName;
var LOCATION = "localhost:8080/isp2";
//School: LOCATION = "ecl.info.kindai.ac.jp/16/isp2/warup/servlet/B17/";

function checkStartRequest() {
    // 開始ボタンのレスポンス処理部分
    if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
        receiveStartResponse();
    }
}

// 返信データの処理
function receiveStartResponse() {
    var response = JSON.parse(xmlHttpRequest.responseText);
    myName = response.userName;
    console.log(myName);
    if (!myName) {
        alert("プレイヤー名を入力してからアクセスしてください");
        location.replace('index.html');
    }
    sendToStartWebSocket(myName);
}

function sendToStartWebSocket(userName) {
    ws = new WebSocket('ws://'+ LOCATION +'/project/drawwordchain/startbroadcast');
    ws.onopen = function() {
        ws.send(userName);
    };

    ws.onmessage = function(receive) {
        var userList = (receive.data).split(",");

        var userAreaElement =  document.getElementById("user_area");

        // データの削除
        while (userAreaElement.lastChild) {
            userAreaElement.removeChild(userAreaElement.lastChild);
        }

        // プレイヤーの挿入
        userList.forEach(function(user) {
            var userElement = document.createElement("div");
            userAreaElement.appendChild(userElement);
            userElement.innerHTML = user;
        });
	};
}

function sendToStartServlet() {
    var url = "start";
    xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.onreadystatechange = checkStartRequest;
    xmlHttpRequest.open("GET", url, true);
    xmlHttpRequest.send(null);
}

// ページ読み込み時
window.addEventListener("load", function() {

    sendToStartServlet();

	// 開始ボタンのEventListener
    document.getElementById("start_button").addEventListener("click", function() {
    }, false);

	// 送信ボタンのEventListener
	document.getElementById("send_button").addEventListener("click", function() {
        //絵のタイトル未入力の際の動作
        if(!document.getElementById("word").value){
             alert("絵の名前を入力してください");
             return;
        }
        //textformに日本語のみが入力されているかの判定
        for(var i=0;i<document.getElementById("word").value.length;i++){
          if(!(document.getElementById("word").value.match(/^[\u3040-\u309F]+$/))){
            alert("平仮名のみで入力してください");
            return;
          }
        }

        //プレイヤー名の中に絵のタイトルを表示(一時的なもの)
        var userName = document.getElementById("user_name");
        userName.innerHTML= document.getElementById("word").value;

        // 画像->base64データに変換
            var data = canvas.toDataURL("image/jpeg");
            // alert(data);

            var img = new Image();
            img.src = data;
            img.width = 250;
            img.height = 250;
            document.getElementById('pict_display').appendChild(img);
            //がめんクリア
            ctx.beginPath();
            ctx.fillStyle = "#f5f5f5";
            ctx.globalAlpha = 1.0;
            ctx.fillRect(0, 0, 500, 500);

            //
            // var image = new Image();
            // image.src = data;
            // image.onload = function() {
            //   ctx2.drawImage(image, 0, 0);
            // }

    		// 画像送信の記述なし
        }, false);

}, false);

// ページ終了時
window.addEventListener("beforeunload", function() {

}, false);

////以下メモ用
// var userAreaElement = document.getElementById("user_area");
//
// while (userAreaElement.lastChild) {
//     userAreaElement.removeChild(userAreaElement.lastChild);
// }
//
// var userElement = document.createElement("span");
// userAreaElement.appendChild(userElement);
// userElement.innerHTML = response.userName;
// userAreaElement.appendChild(document.createElement("br"));

// userListを返した場合の処理
// for (var i = 0; i < response.userList.length; i++) {
//     var userElement = document.createElement("span");
//     userAreaElement.appendChild(userElement);
//     userElement.innerHTML = "user" + (i + 1) + ":" + response.userList[i];
//     userAreaElement.appendChild(document.createElement("br"));
// }
<commit_msg>絵のタイトルが「ん」で終了する場合注意喚起を行うmain.jsに追加<commit_after>var xmlHttpRequest;
var ws;
var myName;
var LOCATION = "localhost:8080/isp2";
//School: LOCATION = "ecl.info.kindai.ac.jp/16/isp2/warup/servlet/B17/";

function checkStartRequest() {
    // 開始ボタンのレスポンス処理部分
    if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
        receiveStartResponse();
    }
}

// 返信データの処理
function receiveStartResponse() {
    var response = JSON.parse(xmlHttpRequest.responseText);
    myName = response.userName;
    console.log(myName);
    if (!myName) {
        alert("プレイヤー名を入力してからアクセスしてください");
        location.replace('index.html');
    }
    sendToStartWebSocket(myName);
}

function sendToStartWebSocket(userName) {
    ws = new WebSocket('ws://'+ LOCATION +'/project/drawwordchain/startbroadcast');
    ws.onopen = function() {
        ws.send(userName);
    };

    ws.onmessage = function(receive) {
        var userList = (receive.data).split(",");

        var userAreaElement =  document.getElementById("user_area");

        // データの削除
        while (userAreaElement.lastChild) {
            userAreaElement.removeChild(userAreaElement.lastChild);
        }

        // プレイヤーの挿入
        userList.forEach(function(user) {
            var userElement = document.createElement("div");
            userAreaElement.appendChild(userElement);
            userElement.innerHTML = user;
        });
	};
}

function sendToStartServlet() {
    var url = "start";
    xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.onreadystatechange = checkStartRequest;
    xmlHttpRequest.open("GET", url, true);
    xmlHttpRequest.send(null);
}

// ページ読み込み時
window.addEventListener("load", function() {

    sendToStartServlet();

	// 開始ボタンのEventListener
    document.getElementById("start_button").addEventListener("click", function() {
    }, false);

	// 送信ボタンのEventListener
	document.getElementById("send_button").addEventListener("click", function() {
        //絵のタイトル未入力の際の動作
        var drawWord = document.getElementById("word");
        if(!drawWord.value){
             alert("絵の名前を入力してください");
             return;
        }
        //textformに日本語のみが入力されているかの判定
        // for(var i=0;i<drawWord.value.length;i++){
          if(!(drawWord.value.match(/^[\u3040-\u309F]+$/))){
            alert("平仮名のみで入力してください");
            return;
          }
          var lastWord = drawWord.value.slice(-1);
          if(lastWord.match(/ん/)){
            alert("勝手にしりとりを終わらせないでください");
            return;
          }
        // }

        //プレイヤー名の中に絵のタイトルを表示(一時的なもの)
        var userName = document.getElementById("user_name");
        userName.innerHTML= drawWord.value;

        // 画像->base64データに変換
            var data = canvas.toDataURL("image/jpeg");
            // alert(data);

            var img = new Image();
            img.src = data;
            img.width = 250;
            img.height = 250;
            document.getElementById('pict_display').appendChild(img);
            //がめんクリア
            ctx.beginPath();
            ctx.fillStyle = "#f5f5f5";
            ctx.globalAlpha = 1.0;
            ctx.fillRect(0, 0, 500, 500);

            //
            // var image = new Image();
            // image.src = data;
            // image.onload = function() {
            //   ctx2.drawImage(image, 0, 0);
            // }

    		// 画像送信の記述なし
        }, false);

}, false);

// ページ終了時
window.addEventListener("beforeunload", function() {

}, false);

////以下メモ用
// var userAreaElement = document.getElementById("user_area");
//
// while (userAreaElement.lastChild) {
//     userAreaElement.removeChild(userAreaElement.lastChild);
// }
//
// var userElement = document.createElement("span");
// userAreaElement.appendChild(userElement);
// userElement.innerHTML = response.userName;
// userAreaElement.appendChild(document.createElement("br"));

// userListを返した場合の処理
// for (var i = 0; i < response.userList.length; i++) {
//     var userElement = document.createElement("span");
//     userAreaElement.appendChild(userElement);
//     userElement.innerHTML = "user" + (i + 1) + ":" + response.userList[i];
//     userAreaElement.appendChild(document.createElement("br"));
// }
<|endoftext|>


<commit_before>
function move_map_to_location () {
    var project = projects[location.hash.slice(1)];
    var centre = L.latLng(project.centre[0], project.centre[1]);
    console.log(project);
    map.panTo(centre, 11);
}

window.onhashchange = move_map_to_location;

// Get projects and update map location:
var projects = {}
$.getJSON('/locations.json', function (json) {
    $.each(json.locations, function (index, project) {
        var project_link = '
' + project.human_readable_name + '
';
        $('#locations').append(project_link);
        projects[project.name] = project;
    });
    move_map_to_location();
});
<commit_msg>Cleaned up projects JS.<commit_after>function move_map_to_location () {
    var project = projects[location.hash.slice(1)];
    var centre = L.latLng(project.centre[0], project.centre[1]);
    map.panTo(centre, 11);
}

// Get projects and update map location once loaded:
var projects = {}
$.getJSON('/locations.json', function (json) {
    $.each(json.locations, function (index, project) {
        var project_link = '
' + project.human_readable_name + '
';
        $('#locations').append(project_link);
        projects[project.name] = project;
    });
    move_map_to_location();
});

// Update map location when location-hash changes:
window.onhashchange = move_map_to_location;
<|endoftext|>


<commit_before>var referral = (function () {

var exports = {};

var placeholder_invitees = ['guglielmo@marconi.com',
                            'heinrich@hertz.com',
                            'nikola@tesla.com',
                            'samuel@morse.com',
                            'claude@shannon.com',
                            'thomas@edison.com',
                            'hedy@lamarr.com',
                            'grace@hopper.com',
                            'martha@coston.com',
                            'ada@lovelace.com',
                            'hanna@hammarstrom.com',
                            'hertha@ayrton.com'
                           ];

var last_granted;
var last_used;
exports.update_state = function (granted, used) {
    if (last_granted === granted && last_used === used) {
        return;
    }

    last_granted = granted;
    last_used = used;

    if (granted <= 0) {
        $("#share-the-love").hide();
    } else {
        $("#referral-form input").attr('placeholder', _.shuffle(placeholder_invitees).pop());
        $("#invite-hearts").empty();
        var i;
        for (i = 0; i < used; i++) {
            $("#invite-hearts").append($('<i class="icon-vector-heart"> </i>'));
        }

        var invites_left = Math.max(0, granted - used);
        for (i = 0; i < invites_left; i++) {
            $("#invite-hearts").append($('<i class="icon-vector-heart-empty"> </i>'));
        }
        $(".invite-count").text(invites_left);
        if (invites_left === 1) {
            $(".invite-count-is-plural").hide();
        } else {
            $(".invite-count-is-plural").show();
        }

        if (invites_left > 0) {
            $(".still-have-invites").show();
            $(".no-more-invites").hide();
        } else {
            $(".still-have-invites").hide();
            $(".no-more-invites").show();
        }

        if (used > 0) {
            $("#encouraging-invite-message").hide();
        }

        $("#share-the-love").show();
    }

    ui.resize_page_components();
};

function show_and_fade_elem(elem) {
    elem.stop();
    elem.css({opacity: 100});
    elem.show().delay(4000).fadeOut(1000, ui.resize_page_components);
}

$(function () {
    $("#referral-form").validate({
        errorClass: 'text-error',
        submitHandler: function () {
            $.ajax({
                type: "POST",
                url: "/json/refer_friend",
                dataType: "json",
                data: { email: $("#referral-form input").val() },
                error: function () {
                    // We ignore errors from the server because
                    // they're unlikely and we'll get an email either
                    // way
                }
            });

            show_and_fade_elem($("#tell-a-friend-success"));
            $("#referral-form input").val('');
            exports.update_state(last_granted, last_used + 1);
        }
    });

    exports.update_state(page_params.referrals.granted, page_params.referrals.used);
});

return exports;
}());
<commit_msg>referral: Only show "no more invites" message when you first deplete your invites<commit_after>var referral = (function () {

var exports = {};

var placeholder_invitees = ['guglielmo@marconi.com',
                            'heinrich@hertz.com',
                            'nikola@tesla.com',
                            'samuel@morse.com',
                            'claude@shannon.com',
                            'thomas@edison.com',
                            'hedy@lamarr.com',
                            'grace@hopper.com',
                            'martha@coston.com',
                            'ada@lovelace.com',
                            'hanna@hammarstrom.com',
                            'hertha@ayrton.com'
                           ];

var last_granted;
var last_used;
var ever_had_invites = false;
exports.update_state = function (granted, used) {
    if (last_granted === granted && last_used === used) {
        return;
    }

    last_granted = granted;
    last_used = used;

    if (granted <= 0) {
        $("#share-the-love").hide();
    } else {
        $("#referral-form input").attr('placeholder', _.shuffle(placeholder_invitees).pop());
        $("#invite-hearts").empty();
        var i;
        for (i = 0; i < used; i++) {
            $("#invite-hearts").append($('<i class="icon-vector-heart"> </i>'));
        }

        var invites_left = Math.max(0, granted - used);
        for (i = 0; i < invites_left; i++) {
            $("#invite-hearts").append($('<i class="icon-vector-heart-empty"> </i>'));
        }
        $(".invite-count").text(invites_left);
        if (invites_left === 1) {
            $(".invite-count-is-plural").hide();
        } else {
            $(".invite-count-is-plural").show();
        }

        if (invites_left > 0) {
            ever_had_invites = true;
            $(".still-have-invites").show();
            $(".no-more-invites").hide();
        } else {
            $(".still-have-invites").hide();
            if (ever_had_invites) {
                $(".no-more-invites").show();
            }
        }

        if (used > 0) {
            $("#encouraging-invite-message").hide();
        }

        $("#share-the-love").show();
    }

    ui.resize_page_components();
};

function show_and_fade_elem(elem) {
    elem.stop();
    elem.css({opacity: 100});
    elem.show().delay(4000).fadeOut(1000, ui.resize_page_components);
}

$(function () {
    $("#referral-form").validate({
        errorClass: 'text-error',
        submitHandler: function () {
            $.ajax({
                type: "POST",
                url: "/json/refer_friend",
                dataType: "json",
                data: { email: $("#referral-form input").val() },
                error: function () {
                    // We ignore errors from the server because
                    // they're unlikely and we'll get an email either
                    // way
                }
            });

            show_and_fade_elem($("#tell-a-friend-success"));
            $("#referral-form input").val('');
            exports.update_state(last_granted, last_used + 1);
        }
    });

    exports.update_state(page_params.referrals.granted, page_params.referrals.used);
});

return exports;
}());
<|endoftext|>


<commit_before>function position_map_box() {
    var $html = $('html');
    var oxfordshire_right;
    if ($html.hasClass('ie6') || $html.hasClass('ie7')) {
        oxfordshire_right = '-480px';
    } else {
        oxfordshire_right = '0em';
    }

    var map_box_width = 464;
    var map_box_height = 464;
    // Do the same as CSS (in case resized from mobile).
    $('#map_box').prependTo('.content').css({
        zIndex: 1, position: 'absolute',
        top: '1em', left: '', right: oxfordshire_right, bottom: '',
        width: map_box_width + 'px', height: map_box_height +'px',
        margin: 0
    });
    if($('#map_box').length) {
        if (! $('#occ-map-instructions').length) {
            $('#map_box').after("

" +
                "Click on a pin and then on the “details” link to see an individual report detail.

");
        }
        var mb_y = $('#map_box').position().top + map_box_height ;
        $('#occ-map-instructions').show().css({
            left: '',
            right: oxfordshire_right,
            bottom: '',
            top: mb_y +'px',
            width: map_box_width
        });
    }

}

function map_fix() {}
var slide_wards_down = 1;
<commit_msg>Specify width/height units in position_map<commit_after>function position_map_box() {
    var $html = $('html');
    var oxfordshire_right;
    if ($html.hasClass('ie6') || $html.hasClass('ie7')) {
        oxfordshire_right = '-480px';
    } else {
        oxfordshire_right = '0em';
    }

    var map_box_width = "464px";
    var map_box_height = "464px";
    // Do the same as CSS (in case resized from mobile).
    $('#map_box').prependTo('.content').css({
        zIndex: 1, position: 'absolute',
        top: '1em', left: '', right: oxfordshire_right, bottom: '',
        width: map_box_width, height: map_box_height,
        margin: 0
    });
    if($('#map_box').length) {
        if (! $('#occ-map-instructions').length) {
            $('#map_box').after("

" +
                "Click on a pin and then on the “details” link to see an individual report detail.

");
        }
        var mb_y = $('#map_box').position().top + parseInt(map_box_height, 10) ;
        $('#occ-map-instructions').show().css({
            left: '',
            right: oxfordshire_right,
            bottom: '',
            top: mb_y +'px',
            width: map_box_width
        });
    }

}

function map_fix() {}
var slide_wards_down = 1;
<|endoftext|>


<commit_before>function position_map_box() {
    var $html = $('html');
    var oxfordshire_right;
    if ($html.hasClass('ie6') || $html.hasClass('ie7')) {
        oxfordshire_right = '-480px';
    } else {
        oxfordshire_right = '0em';
    }

    var map_box_width = 464;
    var map_box_height = 464;
    // Do the same as CSS (in case resized from mobile).
    $('#map_box').prependTo('.content').css({
        zIndex: 1, position: 'absolute',
        top: '1em', left: '', right: oxfordshire_right, bottom: '',
        width: map_box_width + 'px', height: map_box_height +'px',
        margin: 0
    });

}

function map_fix() {}
var slide_wards_down = 1;
<commit_msg>add Oxfordshire 'click on pin' message (fixed bad js)<commit_after>function position_map_box() {
    var $html = $('html');
    var oxfordshire_right;
    if ($html.hasClass('ie6') || $html.hasClass('ie7')) {
        oxfordshire_right = '-480px';
    } else {
        oxfordshire_right = '0em';
    }

    var map_box_width = 464;
    var map_box_height = 464;
    // Do the same as CSS (in case resized from mobile).
    $('#map_box').prependTo('.content').css({
        zIndex: 1, position: 'absolute',
        top: '1em', left: '', right: oxfordshire_right, bottom: '',
        width: map_box_width + 'px', height: map_box_height +'px',
        margin: 0
    });
    if($('#map_box').length) {
        if (! $('#occ-map-instructions').length) {
            $('#map_box').after("

" +
                "Click on a pin and then on the “details” link to see an individual report detail.

");
        }
        var mb_y = $('#map_box').position().top + map_box_height ;
        $('#occ-map-instructions').show().css({
            left: '',
            right: oxfordshire_right,
            bottom: '',
            top: mb_y +'px',
            width: map_box_width
        });
    }

}

function map_fix() {}
var slide_wards_down = 1;

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @constructor
 * @extends {WebInspector.TimelineOverviewBase}
 * @param {!WebInspector.TimelineModel} model
 */
WebInspector.TimelineEventOverview = function(model)
{
    WebInspector.TimelineOverviewBase.call(this, model);
    this.element.id = "timeline-overview-events";

    this._fillStyles = {};
    var categories = WebInspector.TimelineUIUtils.categories();
    for (var category in categories) {
        this._fillStyles[category] = categories[category].fillColorStop1;
        categories[category].addEventListener(WebInspector.TimelineCategory.Events.VisibilityChanged, this._onCategoryVisibilityChanged, this);
    }

    this._disabledCategoryFillStyle = "hsl(0, 0%, 67%)";
}

/** @const */
WebInspector.TimelineEventOverview._stripHeight = 10;
/** @const */
WebInspector.TimelineEventOverview._maxNetworkStripHeight = 32;

WebInspector.TimelineEventOverview.prototype = {
    /**
     * @override
     */
    dispose: function()
    {
        var categories = WebInspector.TimelineUIUtils.categories();
        for (var category in categories)
            categories[category].removeEventListener(WebInspector.TimelineCategory.Events.VisibilityChanged, this._onCategoryVisibilityChanged, this);
    },

    /**
     * @override
     */
    update: function()
    {
        var /** @const */ padding = 2;
        this.resetCanvas();
        var threads = this._model.virtualThreads();
        var mainThreadEvents = this._model.mainThreadEvents();
        var estimatedHeight = padding + 3 * WebInspector.TimelineEventOverview._stripHeight;
        estimatedHeight += padding + WebInspector.TimelineEventOverview._maxNetworkStripHeight;
        this._canvas.height = estimatedHeight * window.devicePixelRatio;
        this._canvas.style.height = estimatedHeight + "px";
        var position = padding;
        if (Runtime.experiments.isEnabled("networkRequestsOnTimeline")) {
            position += this._drawNetwork(mainThreadEvents, position);
            position += padding;
        }
        this._drawEvents(mainThreadEvents, position);
        position += WebInspector.TimelineEventOverview._stripHeight;
        for (var thread of threads.filter(function(thread) { return !thread.isWorker(); }))
            this._drawEvents(thread.events, position);
        position += WebInspector.TimelineEventOverview._stripHeight;
        var workersHeight = 0;
        for (var thread of threads.filter(function(thread) { return thread.isWorker(); }))
            workersHeight = Math.max(workersHeight, this._drawEvents(thread.events, position));
        position += workersHeight;
        this.element.style.flexBasis = position + "px";
    },

    /**
     * @param {!Array.<!WebInspector.TracingModel.Event>} events
     * @param {number} position
     * @return {number}
     */
    _drawNetwork: function(events, position)
    {
        var /** @const */ maxBandHeight = 4;
        var bandsCount = WebInspector.TimelineUIUtils.calculateNetworkBandsCount(events);
        var bandInterval = Math.min(maxBandHeight, WebInspector.TimelineEventOverview._maxNetworkStripHeight / (bandsCount || 1));
        var bandHeight = Math.ceil(bandInterval);
        var timeOffset = this._model.minimumRecordTime();
        var timeSpan = this._model.maximumRecordTime() - timeOffset;
        var canvasWidth = this._canvas.width;
        var scale = canvasWidth / timeSpan;
        var loadingCategory = WebInspector.TimelineUIUtils.categories()["loading"];
        var waitingColor = loadingCategory.backgroundColor;
        var processingColor = loadingCategory.fillColorStop1;

        /**
         * @param {number} band
         * @param {number} startTime
         * @param {number} endTime
         * @param {?WebInspector.TracingModel.Event} event
         * @this {WebInspector.TimelineEventOverview}
         */
        function drawBar(band, startTime, endTime, event)
        {
            var start = Number.constrain((startTime - timeOffset) * scale, 0, canvasWidth);
            var end = Number.constrain((endTime - timeOffset) * scale, 0, canvasWidth);
            var color = !event ||
                event.name === WebInspector.TimelineModel.RecordType.ResourceReceiveResponse ||
                event.name === WebInspector.TimelineModel.RecordType.ResourceSendRequest ? waitingColor : processingColor;
            this._renderBar(Math.floor(start), Math.ceil(end), Math.floor(position + band * bandInterval), bandHeight, color);
        }

        WebInspector.TimelineUIUtils.iterateNetworkRequestsInRoundRobin(events, bandsCount, drawBar.bind(this));
        return Math.ceil(bandInterval * bandsCount);
    },

    /**
     * @param {!Array.<!WebInspector.TracingModel.Event>} events
     * @param {number} position
     * @return {number}
     */
    _drawEvents: function(events, position)
    {
        var /** @const */ padding = 1;
        var stripHeight = WebInspector.TimelineEventOverview._stripHeight;
        var visualHeight = stripHeight - padding;
        var timeOffset = this._model.minimumRecordTime();
        var timeSpan = this._model.maximumRecordTime() - timeOffset;
        var scale = this._canvas.width / timeSpan;
        var ditherer = new WebInspector.Dithering();
        var categoryStack = [];
        var lastX = 0;
        var drawn = false;

        /**
         * @param {!WebInspector.TimelineCategory} category
         * @return {string}
         * @this {WebInspector.TimelineEventOverview}
         */
        function categoryColor(category)
        {
            return category.hidden ? this._disabledCategoryFillStyle : this._fillStyles[category.name];
        }

        /**
         * @param {!WebInspector.TracingModel.Event} e
         * @this {WebInspector.TimelineEventOverview}
         */
        function onEventStart(e)
        {
            var pos = (e.startTime - timeOffset) * scale;
            if (categoryStack.length) {
                var category = categoryStack.peekLast();
                var bar = ditherer.appendInterval(category, lastX, pos);
                if (bar) {
                    this._renderBar(bar.start, bar.end, position, visualHeight, categoryColor.call(this, category));
                    drawn = true;
                }
            }
            categoryStack.push(WebInspector.TimelineUIUtils.eventStyle(e).category);
            lastX = pos;
        }

        /**
         * @param {!WebInspector.TracingModel.Event} e
         * @this {WebInspector.TimelineEventOverview}
         */
        function onEventEnd(e)
        {
            var category = categoryStack.pop();
            var pos = (e.endTime - timeOffset) * scale;
            var bar = ditherer.appendInterval(category, lastX, pos);
            if (bar) {
                this._renderBar(bar.start, bar.end, position, visualHeight, categoryColor.call(this, category));
                drawn = true;
            }
            lastX = pos;
        }

        WebInspector.TimelineModel.forEachEvent(events, onEventStart.bind(this), onEventEnd.bind(this));
        return drawn ? stripHeight : 0;
    },

    _onCategoryVisibilityChanged: function()
    {
        this.update();
    },

    /**
     * @param {number} begin
     * @param {number} end
     * @param {number} position
     * @param {number} height
     * @param {string} color
     */
    _renderBar: function(begin, end, position, height, color)
    {
        var x = begin;
        var y = position * window.devicePixelRatio;
        var width = end - begin;
        this._context.fillStyle = color;
        this._context.fillRect(x, y, width, height * window.devicePixelRatio);
    },

    __proto__: WebInspector.TimelineOverviewBase.prototype
}

/**
 * @constructor
 * @template T
 */
WebInspector.Dithering = function()
{
    /** @type {!Map.<?T,number>} */
    this._groupError = new Map();
    this._position = 0;
    this._lastReportedPosition = 0;
}

WebInspector.Dithering.prototype = {
    /**
     * @param {!T} group
     * @param {number} start
     * @param {number} end
     * @return {?{start: number, end: number}}
     * @template T
     */
    appendInterval: function(group, start, end)
    {
        this._innerAppend(null, start); // Append an empty space before.
        return this._innerAppend(group, end); // Append the interval itself.
    },

    /**
     * @param {?T} group
     * @param {number} position
     * @return {?{start: number, end: number}}
     * @template T
     */
    _innerAppend: function(group, position)
    {
        if (position < this._position)
            return null;
        var result = null;
        var length = position - this._position;
        length += this._groupError.get(group) || 0;
        if (length >= 1) {
            if (!group)
                length -= this._distributeExtraAmount(length - 1);
            var newReportedPosition = this._lastReportedPosition + Math.floor(length);
            result = { start: this._lastReportedPosition, end: newReportedPosition };
            this._lastReportedPosition = newReportedPosition;
            length %= 1;
        }
        this._groupError.set(group, length);
        this._position = position;
        return result;
    },

    /**
     * @param {number} amount
     * @return {number}
     */
    _distributeExtraAmount: function(amount)
    {
        var canConsume = 0;
        for (var g of this._groupError.keys()) {
            if (g)
                canConsume += 1 - this._groupError.get(g);
        }
        var toDistribute = Math.min(amount, canConsume);
        if (toDistribute <= 0)
            return 0;
        var ratio = toDistribute / canConsume;
        for (var g of this._groupError.keys()) {
            if (!g)
                continue;
            var value = this._groupError.get(g);
            value += (1 - value) * ratio;
            this._groupError.set(g, value);
        }
        return toDistribute;
    }
}
<commit_msg>DevTools: Move network activity on timeline overview out of experiment<commit_after>/*
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @constructor
 * @extends {WebInspector.TimelineOverviewBase}
 * @param {!WebInspector.TimelineModel} model
 */
WebInspector.TimelineEventOverview = function(model)
{
    WebInspector.TimelineOverviewBase.call(this, model);
    this.element.id = "timeline-overview-events";

    this._fillStyles = {};
    var categories = WebInspector.TimelineUIUtils.categories();
    for (var category in categories) {
        this._fillStyles[category] = categories[category].fillColorStop1;
        categories[category].addEventListener(WebInspector.TimelineCategory.Events.VisibilityChanged, this._onCategoryVisibilityChanged, this);
    }

    this._disabledCategoryFillStyle = "hsl(0, 0%, 67%)";
}

/** @const */
WebInspector.TimelineEventOverview._stripHeight = 10;
/** @const */
WebInspector.TimelineEventOverview._maxNetworkStripHeight = 32;

WebInspector.TimelineEventOverview.prototype = {
    /**
     * @override
     */
    dispose: function()
    {
        var categories = WebInspector.TimelineUIUtils.categories();
        for (var category in categories)
            categories[category].removeEventListener(WebInspector.TimelineCategory.Events.VisibilityChanged, this._onCategoryVisibilityChanged, this);
    },

    /**
     * @override
     */
    update: function()
    {
        var /** @const */ padding = 2;
        this.resetCanvas();
        var threads = this._model.virtualThreads();
        var mainThreadEvents = this._model.mainThreadEvents();
        var estimatedHeight = padding + 3 * WebInspector.TimelineEventOverview._stripHeight;
        estimatedHeight += padding + WebInspector.TimelineEventOverview._maxNetworkStripHeight;
        this._canvas.height = estimatedHeight * window.devicePixelRatio;
        this._canvas.style.height = estimatedHeight + "px";
        var position = padding;
        position += this._drawNetwork(mainThreadEvents, position);
        position += padding;
        this._drawEvents(mainThreadEvents, position);
        position += WebInspector.TimelineEventOverview._stripHeight;
        for (var thread of threads.filter(function(thread) { return !thread.isWorker(); }))
            this._drawEvents(thread.events, position);
        position += WebInspector.TimelineEventOverview._stripHeight;
        var workersHeight = 0;
        for (var thread of threads.filter(function(thread) { return thread.isWorker(); }))
            workersHeight = Math.max(workersHeight, this._drawEvents(thread.events, position));
        position += workersHeight;
        this.element.style.flexBasis = position + "px";
    },

    /**
     * @param {!Array.<!WebInspector.TracingModel.Event>} events
     * @param {number} position
     * @return {number}
     */
    _drawNetwork: function(events, position)
    {
        var /** @const */ maxBandHeight = 4;
        var bandsCount = WebInspector.TimelineUIUtils.calculateNetworkBandsCount(events);
        var bandInterval = Math.min(maxBandHeight, WebInspector.TimelineEventOverview._maxNetworkStripHeight / (bandsCount || 1));
        var bandHeight = Math.ceil(bandInterval);
        var timeOffset = this._model.minimumRecordTime();
        var timeSpan = this._model.maximumRecordTime() - timeOffset;
        var canvasWidth = this._canvas.width;
        var scale = canvasWidth / timeSpan;
        var loadingCategory = WebInspector.TimelineUIUtils.categories()["loading"];
        var waitingColor = loadingCategory.backgroundColor;
        var processingColor = loadingCategory.fillColorStop1;

        /**
         * @param {number} band
         * @param {number} startTime
         * @param {number} endTime
         * @param {?WebInspector.TracingModel.Event} event
         * @this {WebInspector.TimelineEventOverview}
         */
        function drawBar(band, startTime, endTime, event)
        {
            var start = Number.constrain((startTime - timeOffset) * scale, 0, canvasWidth);
            var end = Number.constrain((endTime - timeOffset) * scale, 0, canvasWidth);
            var color = !event ||
                event.name === WebInspector.TimelineModel.RecordType.ResourceReceiveResponse ||
                event.name === WebInspector.TimelineModel.RecordType.ResourceSendRequest ? waitingColor : processingColor;
            this._renderBar(Math.floor(start), Math.ceil(end), Math.floor(position + band * bandInterval), bandHeight, color);
        }

        WebInspector.TimelineUIUtils.iterateNetworkRequestsInRoundRobin(events, bandsCount, drawBar.bind(this));
        return Math.ceil(bandInterval * bandsCount);
    },

    /**
     * @param {!Array.<!WebInspector.TracingModel.Event>} events
     * @param {number} position
     * @return {number}
     */
    _drawEvents: function(events, position)
    {
        var /** @const */ padding = 1;
        var stripHeight = WebInspector.TimelineEventOverview._stripHeight;
        var visualHeight = stripHeight - padding;
        var timeOffset = this._model.minimumRecordTime();
        var timeSpan = this._model.maximumRecordTime() - timeOffset;
        var scale = this._canvas.width / timeSpan;
        var ditherer = new WebInspector.Dithering();
        var categoryStack = [];
        var lastX = 0;
        var drawn = false;

        /**
         * @param {!WebInspector.TimelineCategory} category
         * @return {string}
         * @this {WebInspector.TimelineEventOverview}
         */
        function categoryColor(category)
        {
            return category.hidden ? this._disabledCategoryFillStyle : this._fillStyles[category.name];
        }

        /**
         * @param {!WebInspector.TracingModel.Event} e
         * @this {WebInspector.TimelineEventOverview}
         */
        function onEventStart(e)
        {
            var pos = (e.startTime - timeOffset) * scale;
            if (categoryStack.length) {
                var category = categoryStack.peekLast();
                var bar = ditherer.appendInterval(category, lastX, pos);
                if (bar) {
                    this._renderBar(bar.start, bar.end, position, visualHeight, categoryColor.call(this, category));
                    drawn = true;
                }
            }
            categoryStack.push(WebInspector.TimelineUIUtils.eventStyle(e).category);
            lastX = pos;
        }

        /**
         * @param {!WebInspector.TracingModel.Event} e
         * @this {WebInspector.TimelineEventOverview}
         */
        function onEventEnd(e)
        {
            var category = categoryStack.pop();
            var pos = (e.endTime - timeOffset) * scale;
            var bar = ditherer.appendInterval(category, lastX, pos);
            if (bar) {
                this._renderBar(bar.start, bar.end, position, visualHeight, categoryColor.call(this, category));
                drawn = true;
            }
            lastX = pos;
        }

        WebInspector.TimelineModel.forEachEvent(events, onEventStart.bind(this), onEventEnd.bind(this));
        return drawn ? stripHeight : 0;
    },

    _onCategoryVisibilityChanged: function()
    {
        this.update();
    },

    /**
     * @param {number} begin
     * @param {number} end
     * @param {number} position
     * @param {number} height
     * @param {string} color
     */
    _renderBar: function(begin, end, position, height, color)
    {
        var x = begin;
        var y = position * window.devicePixelRatio;
        var width = end - begin;
        this._context.fillStyle = color;
        this._context.fillRect(x, y, width, height * window.devicePixelRatio);
    },

    __proto__: WebInspector.TimelineOverviewBase.prototype
}

/**
 * @constructor
 * @template T
 */
WebInspector.Dithering = function()
{
    /** @type {!Map.<?T,number>} */
    this._groupError = new Map();
    this._position = 0;
    this._lastReportedPosition = 0;
}

WebInspector.Dithering.prototype = {
    /**
     * @param {!T} group
     * @param {number} start
     * @param {number} end
     * @return {?{start: number, end: number}}
     * @template T
     */
    appendInterval: function(group, start, end)
    {
        this._innerAppend(null, start); // Append an empty space before.
        return this._innerAppend(group, end); // Append the interval itself.
    },

    /**
     * @param {?T} group
     * @param {number} position
     * @return {?{start: number, end: number}}
     * @template T
     */
    _innerAppend: function(group, position)
    {
        if (position < this._position)
            return null;
        var result = null;
        var length = position - this._position;
        length += this._groupError.get(group) || 0;
        if (length >= 1) {
            if (!group)
                length -= this._distributeExtraAmount(length - 1);
            var newReportedPosition = this._lastReportedPosition + Math.floor(length);
            result = { start: this._lastReportedPosition, end: newReportedPosition };
            this._lastReportedPosition = newReportedPosition;
            length %= 1;
        }
        this._groupError.set(group, length);
        this._position = position;
        return result;
    },

    /**
     * @param {number} amount
     * @return {number}
     */
    _distributeExtraAmount: function(amount)
    {
        var canConsume = 0;
        for (var g of this._groupError.keys()) {
            if (g)
                canConsume += 1 - this._groupError.get(g);
        }
        var toDistribute = Math.min(amount, canConsume);
        if (toDistribute <= 0)
            return 0;
        var ratio = toDistribute / canConsume;
        for (var g of this._groupError.keys()) {
            if (!g)
                continue;
            var value = this._groupError.get(g);
            value += (1 - value) * ratio;
            this._groupError.set(g, value);
        }
        return toDistribute;
    }
}
<|endoftext|>


<commit_before>var core_daemons = [
	{
		"name": "aggregator",
		"port": 4070,
		"versions": {
			"1": {
				"buildMasterIndex": []
			}
		}
	}
];

var core_daemon_grpconf = [
	{
		"daemonConfigGroup": "tansa",
		"daemon": "aggregator",
		"status": 1,
		"interval": 100,
		"type":"interval",
		"jobs": {
			"buildMasterIndex": {
				"type": "global", // "tenant" || "global"
				"serviceConfig": {"mike": "tormoss"}, //if global
				"tenantExtKeys": [] //if tenant
			}
		}
	},
	{
		"daemonConfigGroup": "tormoss",
		"daemon": "aggregator",
		"status": 1,
		"interval": 100,
		"type":"interval",
		"jobs": {
			"mtMW": {
				"type": "tenant", // "tenant" || "global"
				"serviceConfig": {}, //if global
				"tenantExtKeys": ["aa39b5490c4a4ed0e56d7ec1232a428f771e8bb83cfcee16de14f735d0f5da587d5968ec4f785e38570902fd24e0b522b46cb171872d1ea038e88328e7d973ff47d9392f72b2d49566209eb88eb60aed8534a965cf30072c39565bd8d72f68ac"] //if tenant
			}
		}
	}
];

<commit_msg>added provision for section 04 in composer documentation for daemon<commit_after>var core_daemons = [
	{
		"name": "aggregator",
		"port": 4070,
		"versions": {
			"1": {
				"buildMasterIndex": []
			}
		}
	}
];

var core_daemon_grpconf = [
	{
		"daemonConfigGroup": "tansa",
		"daemon": "aggregator",
		"status": 1,
		"interval": 100,
		"type":"interval",
		"jobs": {
			"buildMasterIndex": {
				"type": "global", // "tenant" || "global"
				"serviceConfig": {"mike": "tormoss"}, //if global
				"tenantExtKeys": [] //if tenant
			}
		}
	},
	{
		"daemonConfigGroup": "tormoss",
		"daemon": "aggregator",
		"status": 1,
		"interval": 100,
		"type":"interval",
		"jobs": {
			"mtMW": {
				"type": "tenant", // "tenant" || "global"
				"serviceConfig": {}, //if global
				"tenantExtKeys": ["aa39b5490c4a4ed0e56d7ec1232a428f771e8bb83cfcee16de14f735d0f5da587d5968ec4f785e38570902fd24e0b522b46cb171872d1ea038e88328e7d973ff47d9392f72b2d49566209eb88eb60aed8534a965cf30072c39565bd8d72f68ac"] //if tenant
			}
		}
	},
	{
		"daemonConfigGroup": "catalog",
		"daemon": "composerDaemon",
		"status": 1,
		"interval": 100,
		"type": "interval",
		"jobs": {
			"insertRecords": {
				"type": "global",
				"serviceConfig": {},
				"tenantExtKeys": []
			}
		}
	}
];

<|endoftext|>


<commit_before>export default class CommandHandler {

  constructor() {
    this.history = [];
    this.maxHistorySize = 300;
  }

  addToHistory(cmdName) {;
    this.history.push(cmdName);
    if (this.history.length > this.maxHistorySize)
      this.history.splice(0, this.history.length - this.maxHistorySize);
  }

  exec(commandOrName, morph, args, count, evt) {
    // commandOrName can be
    // 1. a string, naming a command in morphs.commands
    // 2. a spec object like {command: "cmd name", args: {...}, handlesCount: BOOL, }
    // 3. a proper command object {name: STRING, exec: FUNCTION, ....}

    var name, command;

    if (!commandOrName) return null;

    if (typeof commandOrName === "string") name = commandOrName;
    if (typeof commandOrName.command === "string") name = commandOrName.command;

    if (commandOrName.exec) {
      command = commandOrName;
      name = command.name;
    }

    if (!command) command = morph.commands.find(ea => ea.name === name);

    if (!command) {
      console.warn(`Cannot find command ${name}`);
      return null;
    }

    name && this.addToHistory(name);

    var world = morph.world(), result;

    if (command && typeof command.exec === "function") {
        try {
          result = command.exec(morph, args, command.handlesCount ? count : undefined, evt);
        } catch(err) {
          result = err;
          var msg = `Error in interactive command ${name}: ${err.stack || err}`;
          world ? world.logError(msg) : console.error(msg);
        }
    }

    // to not swallow errors
    if (result && typeof result.catch === "function") {
      result.catch(err => {
        var msg = `Error in interactive command ${name}: ${err.stack || err}`;
        world ? world.logError(msg) : console.error(msg);
        throw err;
      });
    }

    // handle count by repeating command
    if (result && typeof count === "number" && count > 1 && !command.handlesCount) {
      return typeof result.then === "function" ?
        result.then(() => this.exec(command, morph, args, count-1, evt)) :
        this.exec(command, morph, args, count-1, evt);
    }

    return result;
  }

}
<commit_msg>command handler records more of cmd history<commit_after>import { obj, arr } from "lively.lang";

function printArg(x) {
  return obj.inspect(x, {maxDepth: 1}).replace(/\n/g, "").replace(/\s+/g, " ");
}

export default class CommandHandler {

  constructor() {
    this.history = [];
    this.maxHistorySize = 300;
  }

  addToHistory(cmdName) {
    this.history.push(cmdName);
    if (this.history.length > this.maxHistorySize)
      this.history.splice(0, this.history.length - this.maxHistorySize);
  }

  printHistory() {
    return this.history.map(({name, target: {string: targetName}, args, count}) =>
      `${name} ${args ? printArg(args) : ""}${typeof count === "number" ? ` x${count}` : ""} ${targetName}`)
        .join("\n");
  }

  exec(commandOrName, morph, args, count, evt, afterExecFn) {
    // commandOrName can be
    // 1. a string, naming a command in morphs.commands
    // 2. a spec object like {command: "cmd name", args: {...}, handlesCount: BOOL, }
    // 3. a proper command object {name: STRING, exec: FUNCTION, ....}

    var name, command;

    if (!commandOrName) return null;

    if (typeof commandOrName === "string") name = commandOrName;
    if (typeof commandOrName.command === "string") name = commandOrName.command;

    if (commandOrName.exec) {
      command = commandOrName;
      name = command.name;
    }

    if (!command) command = morph.commands.find(ea => ea.name === name);

    if (!command) {
      console.warn(`Cannot find command ${name}`);
      return null;
    }

    name && this.addToHistory({name, target: {string: String(morph), id: morph.id}, args, count, time: Date.now()});

    var world = morph.world(), result;

    if (command && typeof command.exec === "function") {
        try {
          result = command.exec(morph, args, command.handlesCount ? count : undefined, evt);
        } catch(err) {
          result = err;
          var msg = `Error in interactive command ${name}: ${err.stack || err}`;
          world ? world.logError(msg) : console.error(msg);
        }
    }

    // to not swallow errors
    if (result && typeof result.catch === "function") {
      result.catch(err => {
        var msg = `Error in interactive command ${name}: ${err.stack || err}`;
        world ? world.logError(msg) : console.error(msg);
        throw err;
      });
    }

    // handle count by repeating command
    if (result && typeof count === "number" && count > 1 && !command.handlesCount) {
      result = typeof result.then === "function" ?
        result.then(() => this.exec(command, morph, args, count-1, evt, null)) :
        this.exec(command, morph, args, count-1, evt, null);
    }

    if (result && typeof afterExecFn === "function") {
      typeof result.then === "function" ?
        result.then(result => afterExecFn(result, command, morph, args, count, evt)) :
        afterExecFn(result, command, morph, args, count, evt);
    }

    return result;
  }

}
<|endoftext|>


<commit_before>Module.register("trafficincidents", {

  defaults: {
    baseUrl: "http://www.mapquestapi.com/traffic/v2/incidents?key=",
    CK: "0MfvxPkvBhP7qwk0n7uNKAxVZzlSBXkQ",
    TL: "40.77",
    TR: "-73.92",
    BL: "40.67",
    BR: "-74.02"
  },

  getHeader: function(){
    return this.data.header //This is gonna be added in config.js file
  },

  getTranslations: function(){
    return false;
  },

  start: function(){

    Log.info("Starting module: " + this.name);

    moment.locale(config.language);

    this.fullDescription = null; // fullDesc
    this.incidents = [];

    this.sendSocketNotification("TRAFFIC_REQUEST");
    this.loaded = false;
  },

  getDom: function(){

    var div = document.createElement("div")
    div.className = "traffic-display"

    var ol = document.createElement("ol");

    for(i=0; i < this.incidents.length; i++){
      var li = document.createElement("li");

        li.className = "traffic-incident-" + i;
        li.innerHTML = this.incidents[i];
        ol.appendChild(li);
    }
    div.appendChild(ol);
    return div;
  },

  notificationReceived: function(notification){
    var notArr = notification.split(" ");
    if(notArr.includes("traffic")){
      this.sendSocketNotification("NEED_UPDATES", this.defaults);
      this.show();
    }else{
      this.hide();
    }
  },

  socketNotificationReceived: function(notification, payload){
    Log.log("This is for testing");
    if(notification === "TRAFFIC_ALERTS"){
      var parsedData = payload;
      if(parsedData["incidents"].length === 0){
        this.incidents.push("There are no alerts for traffic in the nearby area")
      }else if(parsedData["incidents"].length < 5){
        for(i=0; i < parsedData["incidents"].length; i++){
          this.incidents.push(parsedData["incidents"][i]["shortDesc"])
      }}else{
        for(i=0; i<5; i++){
          this.incidents.push(parsedData["incidents"][i]["shortDesc"])
        }
      }
      this.updateDom(0);
      this.incidents = []
    }
  },

});
<commit_msg>Add class name to ordered list element.<commit_after>Module.register("trafficincidents", {

  defaults: {
    baseUrl: "http://www.mapquestapi.com/traffic/v2/incidents?key=",
    CK: "0MfvxPkvBhP7qwk0n7uNKAxVZzlSBXkQ",
    TL: "40.77",
    TR: "-73.92",
    BL: "40.67",
    BR: "-74.02"
  },

  getHeader: function(){
    return this.data.header //This is gonna be added in config.js file
  },

  getTranslations: function(){
    return false;
  },

  start: function(){

    Log.info("Starting module: " + this.name);

    moment.locale(config.language);

    this.fullDescription = null; // fullDesc
    this.incidents = [];

    this.sendSocketNotification("TRAFFIC_REQUEST");
    this.loaded = false;
  },

  getDom: function(){

    var div = document.createElement("div")
    div.className = "traffic-display"

    var ol = document.createElement("ol");
    ol.className = "traffic-incidents"

    for(i=0; i < this.incidents.length; i++){
      var li = document.createElement("li");

        li.className = "traffic-incident-" + i;
        li.innerHTML = this.incidents[i];
        ol.appendChild(li);
    }
    div.appendChild(ol);
    return div;
  },

  notificationReceived: function(notification){
    var notArr = notification.split(" ");
    if(notArr.includes("traffic")){
      this.sendSocketNotification("NEED_UPDATES", this.defaults);
      this.show();
    }else{
      this.hide();
    }
  },

  socketNotificationReceived: function(notification, payload){
    Log.log("This is for testing");
    if(notification === "TRAFFIC_ALERTS"){
      var parsedData = payload;
      if(parsedData["incidents"].length === 0){
        this.incidents.push("There are no alerts for traffic in the nearby area")
      }else if(parsedData["incidents"].length < 5){
        for(i=0; i < parsedData["incidents"].length; i++){
          this.incidents.push(parsedData["incidents"][i]["shortDesc"])
      }}else{
        for(i=0; i<5; i++){
          this.incidents.push(parsedData["incidents"][i]["shortDesc"])
        }
      }
      this.updateDom(0);
      this.incidents = []
    }
  },

});
<|endoftext|>


<commit_before>import React, { PropTypes, Component } from 'react';
import TimeUtils from '../utils/TimeUtils';
import ImageUtils from '../utils/ImageUtils';
import { Link } from 'react-router';
import ImageWithFallback from './ImageWithFallback';

export default class Speech extends Component {
    static propTypes = {
        speech: PropTypes.object.isRequired,
        showTime: PropTypes.bool,
        showContextLink: PropTypes.bool,
    };

    state = { useFallbackImage: false };

    render() {
        let speech = this.props.speech;
        let timestamp = TimeUtils.timestampForHit(speech);
        let title = speech.title;

        if (speech.party) {
            title = `${title}, ${speech.party}`;
        }

        if (this.props.showTime) {
            timestamp = `${timestamp} ${TimeUtils.formatHitTime(speech)}`;
        }

        if (speech.name === 'Presidenten' && speech.presidents.length === 1) {
            var president = speech.presidents[0];

            speech.name = president.name;
            speech.external_id = president.external_id; // eslint-disable-line
        }

        return (

                                <Link
                                    to={`/speeches/${speech.transcript}/${
                                        speech.order
                                    }`}>
                                    {timestamp}
                                </Link>

                                {speech.name}

{title}

                                <Link
                                    to={`https://stortinget.no/no/Saker-og-publikasjoner/Publikasjoner/Referater/Stortinget/${
                                        speech.session
                                    }/${speech.transcript}/`}>
                                    Referat hos Stortinget
                                </Link>

                        {this.props.showContextLink !== false && (

                                    <Link
                                        to={`/speeches/${speech.transcript}/${
                                            speech.order
                                        }`}>
                                        Innlegget i kontekst
                                    </Link>

                        )}

                        <ImageWithFallback
                            className="img-responsive"
                            src={ImageUtils.personImageFor(speech.external_id)}
                            alt={speech.name}
                            height={180}
                            fallbackSrc={ImageUtils.fallbackImage()}
                        />

                            {this.paragraphsFrom(speech)}

        );
    }

    paragraphsFrom(speech) {
        let text = speech.highlight ? speech.highlight.text.join('\n') : speech.text;

        return text.split('\n').map((fragment, i) => {
            fragment = fragment.replace(/<\/mark>(\s*)/g, '$1');

            return
;
        });
    }
}
<commit_msg>Fix extenal link<commit_after>import React, { PropTypes, Component } from 'react';
import TimeUtils from '../utils/TimeUtils';
import ImageUtils from '../utils/ImageUtils';
import { Link } from 'react-router';
import ImageWithFallback from './ImageWithFallback';

export default class Speech extends Component {
    static propTypes = {
        speech: PropTypes.object.isRequired,
        showTime: PropTypes.bool,
        showContextLink: PropTypes.bool,
    };

    state = { useFallbackImage: false };

    render() {
        let speech = this.props.speech;
        let timestamp = TimeUtils.timestampForHit(speech);
        let title = speech.title;

        if (speech.party) {
            title = `${title}, ${speech.party}`;
        }

        if (this.props.showTime) {
            timestamp = `${timestamp} ${TimeUtils.formatHitTime(speech)}`;
        }

        if (speech.name === 'Presidenten' && speech.presidents.length === 1) {
            var president = speech.presidents[0];

            speech.name = president.name;
            speech.external_id = president.external_id; // eslint-disable-line
        }

        return (

                                <Link
                                    to={`/speeches/${speech.transcript}/${
                                        speech.order
                                    }`}>
                                    {timestamp}
                                </Link>

                                {speech.name}

{title}

                                    Referat hos Stortinget

                        {this.props.showContextLink !== false && (

                                    <Link
                                        to={`/speeches/${speech.transcript}/${
                                            speech.order
                                        }`}>
                                        Innlegget i kontekst
                                    </Link>

                        )}

                        <ImageWithFallback
                            className="img-responsive"
                            src={ImageUtils.personImageFor(speech.external_id)}
                            alt={speech.name}
                            height={180}
                            fallbackSrc={ImageUtils.fallbackImage()}
                        />

                            {this.paragraphsFrom(speech)}

        );
    }

    paragraphsFrom(speech) {
        let text = speech.highlight ? speech.highlight.text.join('\n') : speech.text;

        return text.split('\n').map((fragment, i) => {
            fragment = fragment.replace(/<\/mark>(\s*)/g, '$1');

            return
;
        });
    }
}
<|endoftext|>