<commit_before>$(".peering").css("width", "39%");
$(".final_note").css("width", "24%");

//chrome.extension.sendMessage({type: "getTime" });

$(".peering ul:even a").each(function(){

	var remove = $(this).parent().parent().prev().find("a").last();
	$(this).text($(this).text().replace("noter le groupe " + remove.text(), "noter"));
	var link = $(this);
	var text = link.text().replace("devez noter ", "");
	if (text != "avez donné la note" && text != "devez noter")
	{
		$.ajax({
			url: "https://dashboard.42.fr/crawler/pull/" + text + "/",
			dataType: "json",
			success: function(result){
				link.after(' (' + result.last_host.replace(".42.fr", "") + ")");
			},
			error: function(result){
				link.after(' (Logged out)');
			}
		});
	}
});

$(".peering ul:odd a[title]").each(function(){

	var link = $(this);
	$.ajax({
		url: "https://dashboard.42.fr/crawler/pull/" + link.text() + "/",
		dataType: "json",
		success: function(result){
			link.after(' (' + result.last_host.replace(".42.fr", "") + ")");
		},
		error: function(result){
			link.after(' (Logged out)');
		}
	});
});

$(document).on('DOMNodeInserted', function(e) {

	var that = e.target.firstChild;
	$('.ncompletion').css("height", "");
	if (that && that.className == "col1 login")
	{
		$('.ncompletion').css("width", "400px");
		var text = that.innerText;
		var magic = text.match(/^.*\((.*)\)/);
		$.ajax({
			url: "https://dashboard.42.fr/crawler/pull/" + magic[1] + "/",
			dataType: "json",
			success: function(result)
			{
				$(that).html(text + ' (' + result.last_host.replace(".42.fr", "") + ")");
			},
			error: function(){
				$(that).html(text + ' (x)');
			}
		});
	}
});
<commit_msg>changes<commit_after>$(".peering").css("width", "39%");
$(".final_note").css("width", "24%");

//chrome.extension.sendMessage({type: "getTime" });

$(".peering ul:even a").each(function(){

	var remove = $(this).parent().parent().prev().find("a").last();
	$(this).text($(this).text().replace("noter le groupe " + remove.text(), "noter"));
	var link = $(this);
	var text = link.text().replace("devez noter ", "");
	if (text != "avez donné la note" && text != "devez noter")
	{
		$.ajax({
			url: "https://dashboard.42.fr/crawler/pull/" + text + "/",
			dataType: "json",
			success: function(result){
				link.after(' (' + result.last_host.replace(".42.fr", "") + ")");
			},
			error: function(result){
				link.after(' (Logged out)');
			}
		});
	}
});

$(".peering ul:odd a[title]").each(function(){

	var link = $(this);
	$.ajax({
		url: "https://dashboard.42.fr/crawler/pull/" + link.text() + "/",
		dataType: "json",
		success: function(result){
			link.after(' (' + result.last_host.replace(".42.fr", "") + ")");
		},
		error: function(result){
			link.after(' (Logged out)');
		}
	});
});

$(document).on('DOMNodeInserted', function(e) {

	var that = e.target.firstChild;
	$('.ncompletion').css("height", "");
	$('.ncompletion').css("max-height", "300px");
	if (that && that.className == "col1 login")
	{
		$('.ncompletion').css("width", "400px");
		var text = that.innerText;
		var magic = text.match(/^.*\((.*)\)/);
		$.ajax({
			url: "https://dashboard.42.fr/crawler/pull/" + magic[1] + "/",
			dataType: "json",
			success: function(result)
			{
				$(that).html(text + ' (' + result.last_host.replace(".42.fr", "") + ")");
			},
			error: function(){
				$(that).html(text + ' (x)');
			}
		});
	}
});
<|endoftext|>


<commit_before>/*
 * Licensed to Cloudkick, Inc ('Cloudkick') under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * Cloudkick licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var path = require('path');

var CommandParser = require('util/command_parser').CommandParser;

var COMMANDS_PATH = path.join(__dirname, 'data/commands');

var GLOBAL_COMMANDS = ['hello'];
var NORMAL_COMMANDS = {
  'services': ['list', 'restart']
}

var parser = new CommandParser(COMMANDS_PATH, GLOBAL_COMMANDS, NORMAL_COMMANDS);
parser.banner = 'moo';

exports['test initialization'] = function(assert, beforeExit) {
  assert.equal(parser.global_commands, GLOBAL_COMMANDS);
  assert.equal(parser.normal_commands, NORMAL_COMMANDS);
  assert.equal(parser.banner, 'moo');
};

exports['test exception is thrown on invalid command'] = function(assert, beforeExit) {
  var n = 0;

  try {
    parser.parse(['bin', 'file', 'invalid command']);
  }
  catch (error) {
    n++;
    assert.match(error.message, /invalid command/i)
  }

  beforeExit(function() {
    assert.equal(1, n, 'Exceptions thrown');
  });
};

exports['test exception is thrown on invalid number of arguments'] = function(assert, beforeExit) {
  var n = 0;

  try {
    parser.parse(['bin', 'file', 'services', 'list', 'arg1', 'arg2']);
  }
  catch (error) {
    n++;
    assert.match(error.message, /invalid number of arguments/i);
  }

  beforeExit(function() {
    assert.equal(1, n, 'Exceptions thrown');
  });
};

exports['test global command'] = function(assert, beforeExit) {
  var value = parser.parse(['bin', 'file', 'hello']);

  assert.match(value, /hello world/i);
};

exports['test command services list'] = function(assert, beforeExit) {
  var value1 = parser.parse(['bin', 'file', 'services', 'list']);
  var value2 = parser.parse(['bin', 'file', 'services', 'list', 'server1']);

  assert.match(value1, /listing services for all servers/i);
  assert.match(value2, /listing services for server server1/i)
};
<commit_msg>Some more tests for command parser<commit_after>/*
 * Licensed to Cloudkick, Inc ('Cloudkick') under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * Cloudkick licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var path = require('path');

var CommandParser = require('util/command_parser').CommandParser;

var COMMANDS_PATH = path.join(__dirname, 'data/commands');

var GLOBAL_COMMANDS = ['hello'];
var NORMAL_COMMANDS = {
  'services': ['list', 'restart']
}

var stdout_data = [];
global.process.stdout.write = function (string) {
  stdout_data.push(string);
};

var parser = new CommandParser(COMMANDS_PATH, GLOBAL_COMMANDS, NORMAL_COMMANDS);
parser.banner = 'moo';

exports['test initialization'] = function(assert, beforeExit) {
  assert.equal(parser.global_commands, GLOBAL_COMMANDS);
  assert.equal(parser.normal_commands, NORMAL_COMMANDS);
  assert.equal(parser.banner, 'moo');
};

exports['test exception is thrown on invalid command'] = function(assert, beforeExit) {
  var n = 0;

  try {
    parser.parse(['bin', 'file', 'invalid command']);
  }
  catch (error) {
    n++;
    assert.match(error.message, /invalid command/i)
  }

  beforeExit(function() {
    assert.equal(1, n, 'Exceptions thrown');
  });
};

exports['test exception is thrown on invalid number of arguments'] = function(assert, beforeExit) {
  var n = 0;

  try {
    parser.parse(['bin', 'file', 'services', 'list', 'arg1', 'arg2']);
  }
  catch (error) {
    n++;
    assert.match(error.message, /invalid number of arguments/i);
  }

  beforeExit(function() {
    assert.equal(1, n, 'Exceptions thrown');
  });
};

exports['test global help'] = function(assert, beforeExit) {
  stdout_data = [];

  assert.equal(stdout_data.length, 0);
  parser.parse(['bin', 'file', 'help']);
  assert.match(stdout_data.join(''), /.*available commands.*/i)
};

exports['test command help'] = function(assert, beforeExit) {
  stdout_data = [];

  assert.equal(stdout_data.length, 0);
  parser.parse(['bin', 'file', 'help', 'services']);
  assert.match(stdout_data.join(''), /.*available sub-commands for command.*/i)

  beforeExit(function() {
    stdout_data = [];
  });
};

exports['test sub-command help'] = function(assert, beforeExit) {
  stdout_data = [];

  assert.equal(stdout_data.length, 0);
  parser.parse(['bin', 'file', 'help', 'services', 'list']);
  assert.match(stdout_data.join(''), /.*help for services list.*/i)

  beforeExit(function() {
    stdout_data = [];
  });
};
exports['test global command'] = function(assert, beforeExit) {
  var value = parser.parse(['bin', 'file', 'hello']);

  assert.match(value, /hello world/i);
};

exports['test command services list'] = function(assert, beforeExit) {
  var value1 = parser.parse(['bin', 'file', 'services', 'list']);
  var value2 = parser.parse(['bin', 'file', 'services', 'list', 'server1']);

  assert.match(value1, /listing services for all servers/i);
  assert.match(value2, /listing services for server server1/i)
};
<|endoftext|>


<commit_before>/**
 *  @module Crysyan-Core
 */
(function($load) {
    'use strict';
    if (typeof $load==="undefined") $load=true;
    // jquery
    if (!window.$) {
        var jQuery = window.parent.$ || window.jQuery;
        if (!jQuery) {
            throw new Error("Crysyan requires 'jQuery'");
        } else {
            window.$ = jQuery;
        }
    }
    var jsLoadCache = [];
    // map to Cache  the view instances
    var viewCacheMap = {};
   // Parameters parsed from href
    var hrefRequestArgs = {};

    /**
     * Simple dynamically load JS file in serial
     *
     * @param {Array|string} filePaths  the path of js file
     * @param {function} callback  will be called  after all files been completely loaded
     */
    function requireSeries(filePaths, callback) {
        var headElement = document.getElementsByTagName("head").item(0) || document.documentElement;
        if (typeof filePaths === "string") {
            filePaths = [filePaths];
        }
        if (typeof filePaths !== "object") {
            return;
        }
        var recursiveLoad = function(i) {
            if (i >= filePaths.length) {
                if (typeof callback === "function") callback();
                return;
            }
            // if the file has been loaded
            // if (jsLoadCache.hasOwnProperty(filePaths[i])) {
            //     recursiveLoad(i + 1);
            // }
            var script = document.createElement("script");
            script.src = filePaths[i];
            script.type = "text/javascript";
            script.onload = script.onreadystatechange = function() {
                // !/*@cc_on!@*/0 not IE
                if (! /*@cc_on!@*/ 0 || this.readyState == "loaded" || this.readyState == "complete") {
                    // remove the 'script' tag  after loading the js file is complete
                    this.onload = this.onreadystatechange = null;
                    this.parentNode.removeChild(this);
                    // jsLoadCache[filePaths[i]] = 1;
                    if (i < filePaths.length) {
                        recursiveLoad(i + 1);
                    }
                }
            };
            headElement.appendChild(script);
        };
        recursiveLoad(0);
    }

    (function getRequest() {
        // get from URL string after '?'
        var url = decodeURI(location.search);
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                hrefRequestArgs[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
            }
        }
    })();
    //
    var widgetinit = function(callback) {
        var widgetBasePath = "../js/widget/";
        var widgetIconPath = "../img/";
        var widgetsLoad = [];
        var widgets = CrysyanWidgetConfig.widgets;
        for (var attr in widgets) {
            if (widgets[attr].hasOwnProperty("jsFile") && typeof widgets[attr].jsFile === "string" && widgets[attr].jsFile !== "") {
                widgetsLoad.push(widgetBasePath + widgets[attr].jsFile);
            }
            if (widgets[attr].hasOwnProperty("icon")) {
                widgets[attr].icon = widgetIconPath + widgets[attr].icon;
            }
        }
        if ($load) {
            requireSeries(widgetsLoad, callback);
        } else {
            callback();
        }
    };
    //
    var init = function() {
        widgetinit(function() {
            var config = JSON.parse(hrefRequestArgs.config);
            var view = new CrysyanView(config).init();
            viewCacheMap["default"] = view;
        });
    };
    if ($load) {
        // load file（Pseudo module）
        var baseLoadPath = "../js/";
        requireSeries([
            baseLoadPath + "util.js",
            baseLoadPath + "config.js",
            baseLoadPath + "widget.js",
            baseLoadPath + "canvas.js",
            baseLoadPath + "view.js",
        ], init);
    } else {
        init();
    }
    var Crysyan = {
        getView: function(name) {
            if (typeof name === "undefined" || name === "") name = "default";
            return viewCacheMap[name];
        }
    };
    window.Crysyan = Crysyan;
})(CrysyanFlag);
<commit_msg>fix bug : CrysyanFlag is undefined<commit_after>/**
 *  @module Crysyan-Core
 */
(function($load) {
    'use strict';
    if (typeof $load==="undefined") $load=true;
    // jquery
    if (!window.$) {
        var jQuery = window.parent.$ || window.jQuery;
        if (!jQuery) {
            throw new Error("Crysyan requires 'jQuery'");
        } else {
            window.$ = jQuery;
        }
    }
    var jsLoadCache = [];
    // map to Cache  the view instances
    var viewCacheMap = {};
   // Parameters parsed from href
    var hrefRequestArgs = {};

    /**
     * Simple dynamically load JS file in serial
     *
     * @param {Array|string} filePaths  the path of js file
     * @param {function} callback  will be called  after all files been completely loaded
     */
    function requireSeries(filePaths, callback) {
        var headElement = document.getElementsByTagName("head").item(0) || document.documentElement;
        if (typeof filePaths === "string") {
            filePaths = [filePaths];
        }
        if (typeof filePaths !== "object") {
            return;
        }
        var recursiveLoad = function(i) {
            if (i >= filePaths.length) {
                if (typeof callback === "function") callback();
                return;
            }
            // if the file has been loaded
            // if (jsLoadCache.hasOwnProperty(filePaths[i])) {
            //     recursiveLoad(i + 1);
            // }
            var script = document.createElement("script");
            script.src = filePaths[i];
            script.type = "text/javascript";
            script.onload = script.onreadystatechange = function() {
                // !/*@cc_on!@*/0 not IE
                if (! /*@cc_on!@*/ 0 || this.readyState == "loaded" || this.readyState == "complete") {
                    // remove the 'script' tag  after loading the js file is complete
                    this.onload = this.onreadystatechange = null;
                    this.parentNode.removeChild(this);
                    // jsLoadCache[filePaths[i]] = 1;
                    if (i < filePaths.length) {
                        recursiveLoad(i + 1);
                    }
                }
            };
            headElement.appendChild(script);
        };
        recursiveLoad(0);
    }

    (function getRequest() {
        // get from URL string after '?'
        var url = decodeURI(location.search);
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                hrefRequestArgs[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
            }
        }
    })();
    //
    var widgetinit = function(callback) {
        var widgetBasePath = "../js/widget/";
        var widgetIconPath = "../img/";
        var widgetsLoad = [];
        var widgets = CrysyanWidgetConfig.widgets;
        for (var attr in widgets) {
            if (widgets[attr].hasOwnProperty("jsFile") && typeof widgets[attr].jsFile === "string" && widgets[attr].jsFile !== "") {
                widgetsLoad.push(widgetBasePath + widgets[attr].jsFile);
            }
            if (widgets[attr].hasOwnProperty("icon")) {
                widgets[attr].icon = widgetIconPath + widgets[attr].icon;
            }
        }
        if ($load) {
            requireSeries(widgetsLoad, callback);
        } else {
            callback();
        }
    };
    //
    var init = function() {
        widgetinit(function() {
            var config = JSON.parse(hrefRequestArgs.config);
            var view = new CrysyanView(config).init();
            viewCacheMap["default"] = view;
        });
    };
    if ($load) {
        // load file（Pseudo module）
        var baseLoadPath = "../js/";
        requireSeries([
            baseLoadPath + "util.js",
            baseLoadPath + "config.js",
            baseLoadPath + "widget.js",
            baseLoadPath + "canvas.js",
            baseLoadPath + "view.js",
        ], init);
    } else {
        init();
    }
    var Crysyan = {
        getView: function(name) {
            if (typeof name === "undefined" || name === "") name = "default";
            return viewCacheMap[name];
        }
    };
    window.Crysyan = Crysyan;
})(typeof CrysyanFlag==="undefined"? true:CrysyanFlag);
<|endoftext|>


<commit_before>
/** small helper singleton object
 *  displays log output under map
 *
 */
var logger = (function (){
    var outel = document.getElementById("debug");
    outel.innerHTML="logger output";
    return {
        log: function(str){
                outel.innerHTML=str.toString();
            }
    };
})();

var osmLayer = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA"',
    maxNativeZoom: 19,
    maxZoom: 22
});

var PNKLayer = L.tileLayer('http://tiles.prahounakole.cz/{z}/{x}/{y}.png', {
    attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA"',
    maxNativeZoom: 18,
    maxZoom: 22
});

var MTBMapLayer = L.tileLayer('http://tile.mtbmap.cz/mtbmap_tiles/{z}/{x}/{y}.png', {
    attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA"',
    maxNativeZoom: 18,
    maxZoom: 22
});

var cuzkOrtofotoLayer = L.tileLayer.wms("http://geoportal.cuzk.cz/WMS_ORTOFOTO_PUB/service.svc/get", {
    layers: 'GR_ORTFOTORGB',
    format: 'image/jpeg',
    attribution: "© ČÚZK",
    version: "1.1.1",
    crs: L.CRS.EPSG3857,
    maxZoom: 22
});

var waymarkedTrailsCyclingLayer = L.tileLayer('http://tile.waymarkedtrails.org/cycling/{z}/{x}/{y}.png', {
    attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA"',
    maxNativeZoom: 17,
    maxZoom: 22
});

var waymarkedTrailsHikingLayer = L.tileLayer('http://tile.waymarkedtrails.org/hiking/{z}/{x}/{y}.png', {
    attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA"',
    maxNativeZoom: 17,
    maxZoom: 22
});

var llmap = L.map('llmap', {
    center: [50.0648527,14.518207],
    zoom: 10,
    layers: [osmLayer]
});

L.control.layers({
    "ČÚZK Ortofoto": cuzkOrtofotoLayer,
    "Openstreetmap": osmLayer,
    "Prahou na kole": PNKLayer,
    "MTB Mapa": MTBMapLayer
},
{
    "Waymarked Trails Cycling": waymarkedTrailsCyclingLayer,
    "Waymarked Trails Hiking": waymarkedTrailsHikingLayer
},
{collapsed:true
}).addTo(llmap);

L.control.scale({
    imperial: false
}).addTo(llmap);

/************** mapy.cz *****************/

var stred = SMap.Coords.fromWGS84(14.518207,50.0648527);
var mapa = new SMap(JAK.gel("mapycz"), stred, 8);

mapa.addDefaultLayer(SMap.DEF_TURIST).enable();
mapa.addDefaultLayer(SMap.DEF_BIKE).enable();
mapa.addDefaultLayer(SMap.DEF_TRAIL).enable();

var markerLayer = new SMap.Layer.Marker();
mapa.addLayer(markerLayer);
markerLayer.enable();

var marker = new SMap.Marker(SMap.Coords.fromWGS84(0,0), "myMarker",{});
markerLayer.addMarker(marker);

logger.log("All up and running");

/**
 * Move event listener for Lefalet map
 * @param {MouseEvent} e
 * @returns {undefined} nothing
 */
function moveSMmapFromLlmap(e){
    var latlon = llmap.getCenter();
    var zoom = llmap.getZoom();
    logger.log(latlon.toString()+zoom.toString());
    mapa.setCenterZoom(SMap.Coords.fromWGS84(latlon.lng,latlon.lat), zoom-2);
};
llmap.on('move',moveSMmapFromLlmap);
llmap.on('zoomend',moveSMmapFromLlmap);

function copyMousePositionFromLlmap(e){
    var latlon = e.latlng;
    logger.log(latlon);

    marker.setCoords(SMap.Coords.fromWGS84(latlon.lng,latlon.lat));

};
llmap.on('mousemove',copyMousePositionFromLlmap);

<commit_msg>small linting fixes<commit_after>
/** small helper singleton object
 *  displays log output under map
 *
 */
var logger = (function (){
    var outel = document.getElementById("debug");
    outel.innerHTML="logger output";
    return {
        log: function(str){
                outel.innerHTML=str.toString();
            }
    };
})();

var osmLayer = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA"',
    maxNativeZoom: 19,
    maxZoom: 22
});

var PNKLayer = L.tileLayer('http://tiles.prahounakole.cz/{z}/{x}/{y}.png', {
    attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA"',
    maxNativeZoom: 18,
    maxZoom: 22
});

var MTBMapLayer = L.tileLayer('http://tile.mtbmap.cz/mtbmap_tiles/{z}/{x}/{y}.png', {
    attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA"',
    maxNativeZoom: 18,
    maxZoom: 22
});

var cuzkOrtofotoLayer = L.tileLayer.wms("http://geoportal.cuzk.cz/WMS_ORTOFOTO_PUB/service.svc/get", {
    layers: 'GR_ORTFOTORGB',
    format: 'image/jpeg',
    attribution: "© ČÚZK",
    version: "1.1.1",
    crs: L.CRS.EPSG3857,
    maxZoom: 22
});

var waymarkedTrailsCyclingLayer = L.tileLayer('http://tile.waymarkedtrails.org/cycling/{z}/{x}/{y}.png', {
    attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA"',
    maxNativeZoom: 17,
    maxZoom: 22
});

var waymarkedTrailsHikingLayer = L.tileLayer('http://tile.waymarkedtrails.org/hiking/{z}/{x}/{y}.png', {
    attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA"',
    maxNativeZoom: 17,
    maxZoom: 22
});

var llmap = L.map('llmap', {
    center: [50.0648527,14.518207],
    zoom: 10,
    layers: [osmLayer]
});

L.control.layers({
    "ČÚZK Ortofoto": cuzkOrtofotoLayer,
    "Openstreetmap": osmLayer,
    "Prahou na kole": PNKLayer,
    "MTB Mapa": MTBMapLayer
},
{
    "Waymarked Trails Cycling": waymarkedTrailsCyclingLayer,
    "Waymarked Trails Hiking": waymarkedTrailsHikingLayer
},
{collapsed:true
}).addTo(llmap);

L.control.scale({
    imperial: false
}).addTo(llmap);

/************** mapy.cz *****************/

var stred = SMap.Coords.fromWGS84(14.518207,50.0648527);
var mapa = new SMap(JAK.gel("mapycz"), stred, 8);

mapa.addDefaultLayer(SMap.DEF_TURIST).enable();
mapa.addDefaultLayer(SMap.DEF_BIKE).enable();
mapa.addDefaultLayer(SMap.DEF_TRAIL).enable();

var markerLayer = new SMap.Layer.Marker();
mapa.addLayer(markerLayer);
markerLayer.enable();

var marker = new SMap.Marker(SMap.Coords.fromWGS84(0,0), "myMarker",{});
markerLayer.addMarker(marker);

logger.log("All up and running");

/**
 * Move event listener for Lefalet map
 * @param {MouseEvent} e
 * @returns {undefined} nothing
 */
function moveSMmapFromLlmap(e){
    var latlon = llmap.getCenter();
    var zoom = llmap.getZoom();
    logger.log(latlon.toString()+zoom.toString());
    mapa.setCenterZoom(SMap.Coords.fromWGS84(latlon.lng,latlon.lat), zoom-2);
}

llmap.on('move',moveSMmapFromLlmap);
llmap.on('zoomend',moveSMmapFromLlmap);

function copyMousePositionFromLlmap(e){
    var latlon = e.latlng;
    logger.log(latlon);

    marker.setCoords(SMap.Coords.fromWGS84(latlon.lng,latlon.lat));

}

llmap.on('mousemove',copyMousePositionFromLlmap);

<|endoftext|>


<commit_before>const {Rule} = require('./Rule');
const page = require('../lib/page');
const Utils = require('../utils');

/**
 * A summary of a Rule in card format
 * @constructor
 * @param {Gateway} gateway - global Gateway with which to communicate
 * @param {Element} elt - element into which to put the card
 * @param {String} id - unique identifier of the rule card
 * @param {RuleDescription} desc - rule description to represent
 */
function RuleCard(gateway, elt, id, desc) {
  this.elt = elt;
  this.id = id;
  this.rule = new Rule(gateway, desc);

  let checked = this.rule.enabled ? 'checked' : '';
  if (!this.rule.valid()) {
    checked = '';
    this.elt.classList.add('invalid');
  }

  this.elt.innerHTML = `

      <input class="rule-edit-button" type="button" value="Edit Rule"/>

Are you sure you want to remove this rule permanently?

        <input class="rule-delete-cancel-button" type="button"
               value="Cancel"/>
        <input class="rule-delete-confirm-button" type="button"
               value="Remove Rule"/>

${Utils.escapeHtml(this.rule.name)}

${Utils.escapeHtml(this.rule.toHumanDescription())}

    <form class="rule-switch switch">
      <input type="checkbox" id="rule-switch-${Utils.escapeHtml(id)}"
             class="switch-checkbox" ${checked}/>

    </form>
  `;

  this.onEditButtonClick = this.onEditButtonClick.bind(this);
  this.onDeleteButtonClick = this.onDeleteButtonClick.bind(this);
  this.onDeleteCancelClick = this.onDeleteCancelClick.bind(this);
  this.onDeleteConfirmClick = this.onDeleteConfirmClick.bind(this);
  this.onEnabledCheckboxChange = this.onEnabledCheckboxChange.bind(this);

  this.editButton = this.elt.querySelector('.rule-edit-button');
  this.editButton.addEventListener('click', this.onEditButtonClick);

  this.deleteButton = this.elt.querySelector('.rule-delete-button');
  this.deleteButton.addEventListener('click', this.onDeleteButtonClick);
  this.deleteCancel = this.elt.querySelector('.rule-delete-cancel-button');
  this.deleteCancel.addEventListener('click', this.onDeleteCancelClick);
  this.deleteConfirm = this.elt.querySelector('.rule-delete-confirm-button');
  this.deleteConfirm.addEventListener('click', this.onDeleteConfirmClick);

  this.enabledCheckbox = this.elt.querySelector('.switch-checkbox');
  this.enabledCheckbox.addEventListener('change', this.onEnabledCheckboxChange);

  this.editOverlay = this.elt.querySelector('.rule-edit-overlay');
}

RuleCard.prototype.onEditButtonClick = function() {
  page(`/rules/${encodeURIComponent(this.rule.id)}`);
};

RuleCard.prototype.onDeleteButtonClick = function() {
  this.editOverlay.classList.add('delete');
};

RuleCard.prototype.onDeleteCancelClick = function() {
  this.editOverlay.classList.remove('delete');
};

RuleCard.prototype.onDeleteConfirmClick = function() {
  this.rule.delete();
  this.elt.parentNode.removeChild(this.elt);
};

RuleCard.prototype.onEnabledCheckboxChange = function() {
  if (this.enabledCheckbox.checked) {
    this.rule.enabled = true;
  } else {
    this.rule.enabled = false;
  }
  this.rule.update();
};

module.exports = RuleCard;
<commit_msg>Display [INVALID] before rule name<commit_after>const {Rule} = require('./Rule');
const page = require('../lib/page');
const Utils = require('../utils');

/**
 * A summary of a Rule in card format
 * @constructor
 * @param {Gateway} gateway - global Gateway with which to communicate
 * @param {Element} elt - element into which to put the card
 * @param {String} id - unique identifier of the rule card
 * @param {RuleDescription} desc - rule description to represent
 */
function RuleCard(gateway, elt, id, desc) {
  this.elt = elt;
  this.id = id;
  this.rule = new Rule(gateway, desc);

  let checked = this.rule.enabled ? 'checked' : '';
  let invalidWarning = '';
  if (!this.rule.valid()) {
    checked = '';
    invalidWarning = '[INVALID] ';
    this.elt.classList.add('invalid');
  }

  this.elt.innerHTML = `

      <input class="rule-edit-button" type="button" value="Edit Rule"/>

Are you sure you want to remove this rule permanently?

        <input class="rule-delete-cancel-button" type="button"
               value="Cancel"/>
        <input class="rule-delete-confirm-button" type="button"
               value="Remove Rule"/>

${invalidWarning}${Utils.escapeHtml(this.rule.name)}

${Utils.escapeHtml(this.rule.toHumanDescription())}

    <form class="rule-switch switch">
      <input type="checkbox" id="rule-switch-${Utils.escapeHtml(id)}"
             class="switch-checkbox" ${checked}/>

    </form>
  `;

  this.onEditButtonClick = this.onEditButtonClick.bind(this);
  this.onDeleteButtonClick = this.onDeleteButtonClick.bind(this);
  this.onDeleteCancelClick = this.onDeleteCancelClick.bind(this);
  this.onDeleteConfirmClick = this.onDeleteConfirmClick.bind(this);
  this.onEnabledCheckboxChange = this.onEnabledCheckboxChange.bind(this);

  this.editButton = this.elt.querySelector('.rule-edit-button');
  this.editButton.addEventListener('click', this.onEditButtonClick);

  this.deleteButton = this.elt.querySelector('.rule-delete-button');
  this.deleteButton.addEventListener('click', this.onDeleteButtonClick);
  this.deleteCancel = this.elt.querySelector('.rule-delete-cancel-button');
  this.deleteCancel.addEventListener('click', this.onDeleteCancelClick);
  this.deleteConfirm = this.elt.querySelector('.rule-delete-confirm-button');
  this.deleteConfirm.addEventListener('click', this.onDeleteConfirmClick);

  this.enabledCheckbox = this.elt.querySelector('.switch-checkbox');
  this.enabledCheckbox.addEventListener('change', this.onEnabledCheckboxChange);

  this.editOverlay = this.elt.querySelector('.rule-edit-overlay');
}

RuleCard.prototype.onEditButtonClick = function() {
  page(`/rules/${encodeURIComponent(this.rule.id)}`);
};

RuleCard.prototype.onDeleteButtonClick = function() {
  this.editOverlay.classList.add('delete');
};

RuleCard.prototype.onDeleteCancelClick = function() {
  this.editOverlay.classList.remove('delete');
};

RuleCard.prototype.onDeleteConfirmClick = function() {
  this.rule.delete();
  this.elt.parentNode.removeChild(this.elt);
};

RuleCard.prototype.onEnabledCheckboxChange = function() {
  if (this.enabledCheckbox.checked) {
    this.rule.enabled = true;
  } else {
    this.rule.enabled = false;
  }
  this.rule.update();
};

module.exports = RuleCard;
<|endoftext|>


<commit_before>/**
 * OpenEyes
 *
 * (C) Moorfields Eye Hospital NHS Foundation Trust, 2008-2011
 * (C) OpenEyes Foundation, 2011-2013
 * This file is part of OpenEyes.
 * OpenEyes is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 * OpenEyes is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License along with OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package OpenEyes
 * @link http://www.openeyes.org.uk
 * @author OpenEyes <info@openeyes.org.uk>
 * @copyright Copyright (c) 2008-2011, Moorfields Eye Hospital NHS Foundation Trust
 * @copyright Copyright (c) 2011-2013, OpenEyes Foundation
 * @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0
 */

var OpenEyes = window.OpenEyes || {};
OpenEyes.Dialog = OpenEyes.Dialog || {};

(function() {

	// Set the jQuery UI Dialog default options.
	$.extend($.ui.dialog.prototype.options, {
		dialogClass: 'dialog',
		show: 'fade'
	});

	var EventEmitter = OpenEyes.Util.EventEmitter;

	/**
	 * Dialog constructor.
	 * @name Dialog
	 * @constructor
	 * @example
	 * var dialog = new OpenEyes.Dialog({
	 *	 title: 'Title here',
	 *	 content: 'Here is some content.'
	 * });
	 * dialog.on('open', function() {
	 *	 console.log('The dialog is now open');
	 * });
	 * dialog.on('close', function() {
	 *	 console.log('The dialog is now closed.');
	 * });
	 * dialog.on('destroy', function() {
	 *	 console.log('The dialog has been destroyed.');
	 * });
	 * dialog.open();
	 */
	function Dialog(options) {

		EventEmitter.call(this);

		this.options = $.extend(true, {}, Dialog._defaultOptions, options);

		this.create();
		this.bindEvents();

		if (this.options.url) {
			this.loadContent();
		}
	}

	Dialog.inherits(EventEmitter);

	/**
	 * The default dialog options. Custom options will be merged with these.
	 * @name Dialog#_defaultOptions
	 * @property {object} _defaultOptions
	 * @private
	 */
	Dialog._defaultOptions = {
		content: '',
		destroyOnClose: true,
		url: null,
		data: null,
		id: null,
		autoOpen: false,
		title: '',
		modal: true,
		dialogClass: 'dialog',
		resizable: false,
		draggable: false,
		width: 400,
		height: 'auto',
		minHeight: 'auto',
		show: 'fade'
	};

	/**
	 * Creates and stores the dialog container, and creates a new jQuery UI
	 * instance on the container.
	 * @name Dialog#create
	 * @method
	 * @private
	 */
	Dialog.prototype.create = function() {

		// Create the dialog content div.
		this.content = $('<div />', { id: this.options.id });

		// Add default content (if any exists)
		this.setContent(this.options.content);

		// Create the jQuery UI dialog.
		this.content.dialog(this.options);

		// Store a reference to the jQuery UI dialog instance.
		this.instance = this.content.data('ui-dialog');
	};

	/**
	 * Add content to the dialog.
	 * @name Dialog#setContent
	 * @method
	 * @public
	 */
	Dialog.prototype.setContent = function(content) {
		this.content.html(content);
	};

	/**
	 * Binds common dialog event handlers.
	 * @name Dialog#create
	 * @method
	 * @private
	 */
	Dialog.prototype.bindEvents = function() {
		this.content.on({
			dialogclose: this.onDialogClose.bind(this),
			dialogopen: this.onDialogOpen.bind(this)
		});
	};

	/**
	 * Gets a script template from the DOM, compiles it using Mustache, and
	 * returns the HTML.
	 * @name Dialog#compileTemplate
	 * @method
	 * @private
	 * @param {object} options - An options object container the template selector and data.
	 * @returns {string}
	 */
	Dialog.prototype.compileTemplate = function(options) {

		var template = $(options.selector).html();

		if (!template) {
			throw new Error('Unable to compile dialog template. Template not found: ' + options.selector);
		}

		return Mustache.render(template, options.data || {});
	};

	/**
	 * Sets a 'loading' message and retrieves the dialog content via AJAX.
	 * @name Dialog#loadContent
	 * @method
	 * @private
	 */
	Dialog.prototype.loadContent = function() {

		this.content.addClass('loading');
		this.setTitle('Loading...');

		var xhr = $.ajax({
			url: this.options.url,
			data: this.options.data
		});

		xhr.done(this.onContentLoadSuccess.bind(this));
		xhr.fail(this.onContentLoadFail.bind(this));
		xhr.always(this.onContentLoad.bind(this));
	};

	/**
	 * Sets the dialog title.
	 * @name Dialog#setTitle
	 * @method
	 * @public
	 */
	Dialog.prototype.setTitle = function(title) {
		this.instance._setOption('title', title);
	};

	/**
	 * Repositions the dialog in the center of the page.
	 * @name Dialog#reposition
	 * @method
	 * @public
	 */
	Dialog.prototype.reposition = function() {
		this.instance._position(this.instance._position());
	};

	/**
	 * Opens (shows) the dialog.
	 * @name Dialog#open
	 * @method
	 * @public
	 */
	Dialog.prototype.open = function() {
		this.instance.open();
	};

	/**
	 * Closes (hides) the dialog.
	 * @name Dialog#close
	 * @method
	 * @public
	 */
	Dialog.prototype.close = function() {
		this.instance.close();
	};

	/**
	 * Destroys the dialog. Removes all elements from the DOM and detaches all
	 * event handlers.
	 * @name Dialog#destroy
	 * @method
	 * @public
	 */
	Dialog.prototype.destroy = function() {
		this.instance.destroy();
		this.content.remove();
		this.emit('destroy');
	};

	/** Event handlers */

	/**
	 * Emit the 'open' event after the dialog has opened.
	 * @name Dialog#onDialogOpen
	 * @method
	 * @private
	 */
	Dialog.prototype.onDialogOpen = function() {
		this.emit('open');
	};

	/**
	 * Emit the 'close' event after the dialog has closed, and optionally destroy
	 * the dialog.
	 * @name Dialog#onDialogClose
	 * @method
	 * @private
	 */
	Dialog.prototype.onDialogClose = function() {
		this.emit('close');
		if (this.options.destroyOnClose) {
			this.destroy();
		}
	};

	/**
	 * Content load handler. This method is always executed after the content
	 * request completes (whether there was an error or not), and is executed after
	 * any success or fail handlers. This method removes the loading state of the
	 * dialog, and repositions it in the center of the screen.
	 * @name Dialog#onContentLoad
	 * @method
	 * @private
	 */
	Dialog.prototype.onContentLoad = function() {
		// Remove loading state.
		this.content.removeClass('loading');
		// Reposition the dialog in the center of the screen.
		this.reposition();
	};

	/**
	 * Content load success handler. Sets the dialog content to be the response of
	 * the content request.
	 * @name Dialog#onContentLoadSuccess
	 * @method
	 * @private
	 */
	Dialog.prototype.onContentLoadSuccess = function(response) {
		// Set the dialog content.
		this.setTitle(this.options.title);
		this.setContent(response);
	};

	/**
	 * Content load fail handler. This method is executed if the content request
	 * fails, and shows an error message.
	 * @name Dialog#onContentLoadFail
	 * @method
	 * @private
	 */
	Dialog.prototype.onContentLoadFail = function() {
		// Show the error.
		this.setTitle('Error');
		this.setContent('Sorry, there was an error retrieving the content. Please try again.');
	};

	OpenEyes.Dialog = Dialog;

}());

(function() {

	var Dialog = OpenEyes.Dialog;

	/**
	 * AlertDialog constructor. The AlertDialog extends the base Dialog and provides
	 * an 'Ok' button for the user to click on.
	 * @name AlertDialog
	 * @constructor
	 * @extends Dialog
	 * @example
	 * var alert = new OpenEyes.Dialog.Alert({
	 *	 content: 'Here is some content.'
	 * });
	 * alert.open();
	 */
	function AlertDialog(options) {

		options = $.extend(true, {}, AlertDialog._defaultOptions, options);
		options.content = this.getContent(options);

		Dialog.call(this, options);
	}

	AlertDialog.inherits(Dialog);

	/**
	 * The default alert dialog options. These options will be merged into the
	 * default dialog options.
	 * @name AlertDialog#_defaultOptions
	 * @property {object] _defaultOptions
	 * @private
	 */
	AlertDialog._defaultOptions = {
		modal: true,
		width: 400,
		minHeight: 'auto',
		title: 'Alert',
		dialogClass: 'dialog alert'
	};

	/**
	 * Get the dialog content. Do some basic content formatting, then compile
	 * and return the alert dialog template.
	 * @name AlertDialog#getContent
	 * @method
	 * @private
	 * @param {string} content - The main alert dialog content to display.
	 * @returns {string}
	 */
	AlertDialog.prototype.getContent = function(options) {

		// Replace new line characters with html breaks
		options.content = (options.content || '').replace(/\n/g, '<br/>');

		// Compile the template, get the HTML
		return this.compileTemplate({
			selector: '#dialog-alert-template',
			data: {
				content: options.content
			}
		});
	};

	/**
	 * Bind events
	 * @name AlertDialog#bindEvents
	 * @method
	 * @private
	 */
	AlertDialog.prototype.bindEvents = function() {
		Dialog.prototype.bindEvents.apply(this, arguments);
		this.content.on('click', '.ok', this.onButtonClick.bind(this));
	};

	/** Event handlers */

	/**
	 * 'OK' button click handler. Simply close the dialog on click.
	 * @name AlertDialog#onButtonClick
	 * @method
	 * @private
	 */
	AlertDialog.prototype.onButtonClick = function() {
		this.close();
	};

	OpenEyes.Dialog.Alert = AlertDialog;

}());

(function() {

	var Dialog = OpenEyes.Dialog;

	/**
	 * ConfirmDialog constructor. The ConfirmDialog extends the base Dialog and provides
	 * an 'Ok' and 'Cancel' button for the user to click on.
	 * @name ConfirmDialog
	 * @constructor
	 * @extends Dialog
	 * @example
	 * var alert = new OpenEyes.Dialog.Confirm({
	 *	 content: 'Here is some content.'
	 * });
	 * alert.open();
	 */
	function ConfirmDialog(options) {

		options = $.extend(true, {}, ConfirmDialog._defaultOptions, options);
		options.content = this.getContent(options);

		Dialog.call(this, options);
	}

	ConfirmDialog.inherits(Dialog);

	/**
	 * The default confirm dialog options. These options will be merged into the
	 * default dialog options.
	 * @name ConfirmDialog#_defaultOptions
	 * @property {object} _defaultOptions - The default options.
	 * @private
	 */
	ConfirmDialog._defaultOptions = {
		modal: true,
		width: 400,
		minHeight: 'auto',
		title: 'Confirm',
		dialogClass: 'dialog confirm',
		okButton: 'OK',
		cancelButton: 'Cancel'
	};

	/**
	 * Get the dialog content. Do some basic content formatting, then compile
	 * and return the alert dialog template.
	 * @name ConfirmDialog#getContent
	 * @method
	 * @private
	 * @param {string} content - The main alert dialog content to display.
	 * @returns {string}
	 */
	ConfirmDialog.prototype.getContent = function(options) {
		// Compile the template, get the HTML
		return this.compileTemplate({
			selector: '#dialog-confirm-template',
			data: {
				content: options.content,
				okButton: options.okButton,
				cancelButton: options.cancelButton
			}
		});
	};

	/**
	 * Bind events
	 * @name ConfirmDialog#bindEvents
	 * @method
	 * @private
	 */
	ConfirmDialog.prototype.bindEvents = function() {
		Dialog.prototype.bindEvents.apply(this, arguments);
		this.content.on('click', '.ok', this.onOKButtonClick.bind(this));
		this.content.on('click', '.cancel', this.onCancelButtonClick.bind(this));
	};

	/** Event handlers */

	/**
	 * 'OK' button click handler. Simply close the dialog on click.
	 * @name ConfirmDialog#onButtonClick
	 * @method
	 * @private
	 */
	ConfirmDialog.prototype.onOKButtonClick = function() {
		this.close();
		this.emit('ok');
	};

	/**
	 * 'Cancel' button click handler. Simply close the dialog on click.
	 * @name ConfirmDialog#onButtonClick
	 * @method
	 * @private
	 */
	ConfirmDialog.prototype.onCancelButtonClick = function() {
		this.close();
		this.emit('cancel');
	};

	OpenEyes.Dialog.Confirm = ConfirmDialog;

}());<commit_msg>Updated the ConfirmDialog to support AJAX requests<commit_after>/**
 * OpenEyes
 *
 * (C) Moorfields Eye Hospital NHS Foundation Trust, 2008-2011
 * (C) OpenEyes Foundation, 2011-2013
 * This file is part of OpenEyes.
 * OpenEyes is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 * OpenEyes is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License along with OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package OpenEyes
 * @link http://www.openeyes.org.uk
 * @author OpenEyes <info@openeyes.org.uk>
 * @copyright Copyright (c) 2008-2011, Moorfields Eye Hospital NHS Foundation Trust
 * @copyright Copyright (c) 2011-2013, OpenEyes Foundation
 * @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0
 */

var OpenEyes = window.OpenEyes || {};
OpenEyes.Dialog = OpenEyes.Dialog || {};

(function() {

	// Set the jQuery UI Dialog default options.
	$.extend($.ui.dialog.prototype.options, {
		dialogClass: 'dialog',
		show: 'fade'
	});

	var EventEmitter = OpenEyes.Util.EventEmitter;

	/**
	 * Dialog constructor.
	 * @name Dialog
	 * @constructor
	 * @example
	 * var dialog = new OpenEyes.Dialog({
	 *	 title: 'Title here',
	 *	 content: 'Here is some content.'
	 * });
	 * dialog.on('open', function() {
	 *	 console.log('The dialog is now open');
	 * });
	 * dialog.on('close', function() {
	 *	 console.log('The dialog is now closed.');
	 * });
	 * dialog.on('destroy', function() {
	 *	 console.log('The dialog has been destroyed.');
	 * });
	 * dialog.open();
	 */
	function Dialog(options) {

		EventEmitter.call(this);

		this.options = $.extend(true, {}, Dialog._defaultOptions, options);

		this.create();
		this.bindEvents();

		if (this.options.url) {
			this.loadContent();
		}
	}

	Dialog.inherits(EventEmitter);

	/**
	 * The default dialog options. Custom options will be merged with these.
	 * @name Dialog#_defaultOptions
	 * @property {object} _defaultOptions
	 * @private
	 */
	Dialog._defaultOptions = {
		content: '',
		destroyOnClose: true,
		url: null,
		data: null,
		id: null,
		autoOpen: false,
		title: '',
		modal: true,
		dialogClass: 'dialog',
		resizable: false,
		draggable: false,
		width: 400,
		height: 'auto',
		minHeight: 'auto',
		show: 'fade'
	};

	/**
	 * Creates and stores the dialog container, and creates a new jQuery UI
	 * instance on the container.
	 * @name Dialog#create
	 * @method
	 * @private
	 */
	Dialog.prototype.create = function() {

		// Create the dialog content div.
		this.content = $('<div />', { id: this.options.id });

		// Add default content (if any exists)
		this.setContent(this.options.content);

		// Create the jQuery UI dialog.
		this.content.dialog(this.options);

		// Store a reference to the jQuery UI dialog instance.
		this.instance = this.content.data('ui-dialog');
	};

	/**
	 * Add content to the dialog.
	 * @name Dialog#setContent
	 * @method
	 * @public
	 */
	Dialog.prototype.setContent = function(content) {
		this.content.html(content);
	};

	/**
	 * Binds common dialog event handlers.
	 * @name Dialog#create
	 * @method
	 * @private
	 */
	Dialog.prototype.bindEvents = function() {
		this.content.on({
			dialogclose: this.onDialogClose.bind(this),
			dialogopen: this.onDialogOpen.bind(this)
		});
	};

	/**
	 * Gets a script template from the DOM, compiles it using Mustache, and
	 * returns the HTML.
	 * @name Dialog#compileTemplate
	 * @method
	 * @private
	 * @param {object} options - An options object container the template selector and data.
	 * @returns {string}
	 */
	Dialog.prototype.compileTemplate = function(options) {

		var template = $(options.selector).html();

		if (!template) {
			throw new Error('Unable to compile dialog template. Template not found: ' + options.selector);
		}

		return Mustache.render(template, options.data || {});
	};

	/**
	 * Sets a 'loading' message and retrieves the dialog content via AJAX.
	 * @name Dialog#loadContent
	 * @method
	 * @private
	 */
	Dialog.prototype.loadContent = function() {

		this.content.addClass('loading');
		this.setTitle('Loading...');

		var xhr = $.ajax({
			url: this.options.url,
			data: this.options.data
		});

		xhr.done(this.onContentLoadSuccess.bind(this));
		xhr.fail(this.onContentLoadFail.bind(this));
		xhr.always(this.onContentLoad.bind(this));
	};

	/**
	 * Sets the dialog title.
	 * @name Dialog#setTitle
	 * @method
	 * @public
	 */
	Dialog.prototype.setTitle = function(title) {
		this.instance._setOption('title', title);
	};

	/**
	 * Repositions the dialog in the center of the page.
	 * @name Dialog#reposition
	 * @method
	 * @public
	 */
	Dialog.prototype.reposition = function() {
		this.instance._position(this.instance._position());
	};

	/**
	 * Opens (shows) the dialog.
	 * @name Dialog#open
	 * @method
	 * @public
	 */
	Dialog.prototype.open = function() {
		this.instance.open();
	};

	/**
	 * Closes (hides) the dialog.
	 * @name Dialog#close
	 * @method
	 * @public
	 */
	Dialog.prototype.close = function() {
		this.instance.close();
	};

	/**
	 * Destroys the dialog. Removes all elements from the DOM and detaches all
	 * event handlers.
	 * @name Dialog#destroy
	 * @method
	 * @public
	 */
	Dialog.prototype.destroy = function() {
		this.instance.destroy();
		this.content.remove();
		this.emit('destroy');
	};

	/** Event handlers */

	/**
	 * Emit the 'open' event after the dialog has opened.
	 * @name Dialog#onDialogOpen
	 * @method
	 * @private
	 */
	Dialog.prototype.onDialogOpen = function() {
		this.emit('open');
	};

	/**
	 * Emit the 'close' event after the dialog has closed, and optionally destroy
	 * the dialog.
	 * @name Dialog#onDialogClose
	 * @method
	 * @private
	 */
	Dialog.prototype.onDialogClose = function() {
		this.emit('close');
		if (this.options.destroyOnClose) {
			this.destroy();
		}
	};

	/**
	 * Content load handler. This method is always executed after the content
	 * request completes (whether there was an error or not), and is executed after
	 * any success or fail handlers. This method removes the loading state of the
	 * dialog, and repositions it in the center of the screen.
	 * @name Dialog#onContentLoad
	 * @method
	 * @private
	 */
	Dialog.prototype.onContentLoad = function() {
		// Remove loading state.
		this.content.removeClass('loading');
		// Reposition the dialog in the center of the screen.
		this.reposition();
	};

	/**
	 * Content load success handler. Sets the dialog content to be the response of
	 * the content request.
	 * @name Dialog#onContentLoadSuccess
	 * @method
	 * @private
	 */
	Dialog.prototype.onContentLoadSuccess = function(response) {
		// Set the dialog content.
		this.setTitle(this.options.title);
		this.setContent(response);
	};

	/**
	 * Content load fail handler. This method is executed if the content request
	 * fails, and shows an error message.
	 * @name Dialog#onContentLoadFail
	 * @method
	 * @private
	 */
	Dialog.prototype.onContentLoadFail = function() {
		// Show the error.
		this.setTitle('Error');
		this.setContent('Sorry, there was an error retrieving the content. Please try again.');
	};

	OpenEyes.Dialog = Dialog;

}());

(function() {

	var Dialog = OpenEyes.Dialog;

	/**
	 * AlertDialog constructor. The AlertDialog extends the base Dialog and provides
	 * an 'Ok' button for the user to click on.
	 * @name AlertDialog
	 * @constructor
	 * @extends Dialog
	 * @example
	 * var alert = new OpenEyes.Dialog.Alert({
	 *	 content: 'Here is some content.'
	 * });
	 * alert.open();
	 */
	function AlertDialog(options) {

		options = $.extend(true, {}, AlertDialog._defaultOptions, options);
		options.content = this.getContent(options);

		Dialog.call(this, options);
	}

	AlertDialog.inherits(Dialog);

	/**
	 * The default alert dialog options. These options will be merged into the
	 * default dialog options.
	 * @name AlertDialog#_defaultOptions
	 * @property {object] _defaultOptions
	 * @private
	 */
	AlertDialog._defaultOptions = {
		modal: true,
		width: 400,
		minHeight: 'auto',
		title: 'Alert',
		dialogClass: 'dialog alert'
	};

	/**
	 * Get the dialog content. Do some basic content formatting, then compile
	 * and return the alert dialog template.
	 * @name AlertDialog#getContent
	 * @method
	 * @private
	 * @param {string} content - The main alert dialog content to display.
	 * @returns {string}
	 */
	AlertDialog.prototype.getContent = function(options) {

		// Replace new line characters with html breaks
		options.content = (options.content || '').replace(/\n/g, '<br/>');

		// Compile the template, get the HTML
		return this.compileTemplate({
			selector: '#dialog-alert-template',
			data: {
				content: options.content
			}
		});
	};

	/**
	 * Bind events
	 * @name AlertDialog#bindEvents
	 * @method
	 * @private
	 */
	AlertDialog.prototype.bindEvents = function() {
		Dialog.prototype.bindEvents.apply(this, arguments);
		this.content.on('click', '.ok', this.onButtonClick.bind(this));
	};

	/** Event handlers */

	/**
	 * 'OK' button click handler. Simply close the dialog on click.
	 * @name AlertDialog#onButtonClick
	 * @method
	 * @private
	 */
	AlertDialog.prototype.onButtonClick = function() {
		this.close();
	};

	OpenEyes.Dialog.Alert = AlertDialog;

}());

(function() {

	var Dialog = OpenEyes.Dialog;

	/**
	 * ConfirmDialog constructor. The ConfirmDialog extends the base Dialog and provides
	 * an 'Ok' and 'Cancel' button for the user to click on.
	 * @name ConfirmDialog
	 * @constructor
	 * @extends Dialog
	 * @example
	 * var alert = new OpenEyes.Dialog.Confirm({
	 *	 content: 'Here is some content.'
	 * });
	 * alert.open();
	 */
	function ConfirmDialog(options) {

		options = $.extend(true, {}, ConfirmDialog._defaultOptions, options);
		options.content = !options.url ? this.getContent(options) : '';

		Dialog.call(this, options);
	}

	ConfirmDialog.inherits(Dialog);

	/**
	 * The default confirm dialog options. These options will be merged into the
	 * default dialog options.
	 * @name ConfirmDialog#_defaultOptions
	 * @property {object} _defaultOptions - The default options.
	 * @private
	 */
	ConfirmDialog._defaultOptions = {
		modal: true,
		width: 400,
		minHeight: 'auto',
		title: 'Confirm',
		dialogClass: 'dialog confirm',
		okButton: 'OK',
		cancelButton: 'Cancel'
	};

	/**
	 * Get the dialog content. Do some basic content formatting, then compile
	 * and return the alert dialog template.
	 * @name ConfirmDialog#getContent
	 * @method
	 * @private
	 * @param {string} content - The main alert dialog content to display.
	 * @returns {string}
	 */
	ConfirmDialog.prototype.getContent = function(options) {
		// Compile the template, get the HTML
		return this.compileTemplate({
			selector: '#dialog-confirm-template',
			data: {
				content: options.content,
				okButton: options.okButton,
				cancelButton: options.cancelButton
			}
		});
	};

	/**
	 * Bind events
	 * @name ConfirmDialog#bindEvents
	 * @method
	 * @private
	 */
	ConfirmDialog.prototype.bindEvents = function() {
		Dialog.prototype.bindEvents.apply(this, arguments);
		this.content.on('click', '.ok', this.onOKButtonClick.bind(this));
		this.content.on('click', '.cancel', this.onCancelButtonClick.bind(this));
	};

	/** Event handlers */

	/**
	 * 'OK' button click handler. Simply close the dialog on click.
	 * @name ConfirmDialog#onButtonClick
	 * @method
	 * @private
	 */
	ConfirmDialog.prototype.onOKButtonClick = function() {
		this.close();
		this.emit('ok');
	};

	/**
	 * 'Cancel' button click handler. Simply close the dialog on click.
	 * @name ConfirmDialog#onButtonClick
	 * @method
	 * @private
	 */
	ConfirmDialog.prototype.onCancelButtonClick = function() {
		this.close();
		this.emit('cancel');
	};

	/**
	 * Content load success handler. Sets the dialog content to be the response of
	 * the content request.
	 * @name ConfirmDialog#onContentLoadSuccess
	 * @method
	 * @private
	 */
	ConfirmDialog.prototype.onContentLoadSuccess = function(response) {
		this.options.content = response;
		Dialog.prototype.onContentLoadSuccess.call(this, this.getContent(this.options));
	};

	OpenEyes.Dialog.Confirm = ConfirmDialog;
}());<|endoftext|>


<commit_before>var TaskView = Backbone.View.extend({
    tagName: 'li',
    className: 'task',

    events: {
        'keypress #task-name'         :   'close',
        'click #delete-task'          :   'delete'
    },

    template: _.template( $('#task-template').html() ),

    initialize: function() {
        this.listenTo(this.model, 'change:complete', this.updateComplete);
        this.listenTo(this.model, 'change', this.renderTitle);
        this.listenTo(this.model, 'change:expectations', this.model.logTasksAndExp);
        this.$el.collapsible();
    },

    render: function() {
        console.log('Render TaskView');

        this.$el.html( this.template( this.model.attributes ) );

        if (this.$el.children('#new-expectation').length === 0) {
            this.addExpectationsListView();
        }

        this.updateComplete('silent');

        this.model.logTasksAndExp();

        var self = this;
        _.defer(function() {
            self.$el.find('#new-expectation').focus();
        })
        return this;
    },

    renderTitle: function() {
        this.$el.children('#task-name').val(this.model.get('title'));
    },

    addExpectationsListView: function() {
        var view = new ExpectationsListView({ collection: this.model.expectations });
        this.$el.append( view.render().el );
    },

    updateComplete: function(ui) {
        if (this.model.get('complete')) {
            this.$el.children('.collapsible-header').addClass('complete');
            if (ui != 'silent') {
                //Materialize.toast("Congratulations, you completed a task!", 3000, 'rounded');
            };
        }
        else {
            this.$el.children('.collapsible-header').removeClass('complete');
        };
    },

    close: function() {
        this.$edit = this.$('#task-name');
        if ( event.which !== ENTER_KEY || !this.$edit.val().trim() ) {
            return;
        }

        this.model.editTitle(this.$edit.val());
        this.$el.find('#new-expectation').focus();
        Materialize.toast('Task updated to "' + this.model.get('title') + '"', 3000, 'rounded');

        this.model.logTasksAndExp();
    },

    delete: function() {
        this.model.delete();
        Materialize.toast("Task removed.", 3000, 'rounded');
    },

    edit: function() {
        this.$el.children('#task-name').addClass('hidden');
        this.$el.children('#edit-task').removeClass('hidden');

        this.$el.children('#edit-task').focus();
    }
});<commit_msg>Remove calls to logTasksAndExp().<commit_after>var TaskView = Backbone.View.extend({
    tagName: 'li',
    className: 'task',

    events: {
        'keypress #task-name'         :   'close',
        'click #delete-task'          :   'delete'
    },

    template: _.template( $('#task-template').html() ),

    initialize: function() {
        this.listenTo(this.model, 'change:complete', this.updateComplete);
        this.listenTo(this.model, 'change', this.renderTitle);
        this.$el.collapsible();
    },

    render: function() {
        console.log('Render TaskView');

        this.$el.html( this.template( this.model.attributes ) );

        if (this.$el.children('#new-expectation').length === 0) {
            this.addExpectationsListView();
        }

        this.updateComplete('silent');

        this.model.logTasksAndExp();

        var self = this;
        _.defer(function() {
            self.$el.find('#new-expectation').focus();
        })
        return this;
    },

    renderTitle: function() {
        this.$el.children('#task-name').val(this.model.get('title'));
    },

    addExpectationsListView: function() {
        var view = new ExpectationsListView({ collection: this.model.expectations });
        this.$el.append( view.render().el );
    },

    updateComplete: function(ui) {
        if (this.model.get('complete')) {
            this.$el.children('.collapsible-header').addClass('complete');
            if (ui != 'silent') {
                //Materialize.toast("Congratulations, you completed a task!", 3000, 'rounded');
            };
        }
        else {
            this.$el.children('.collapsible-header').removeClass('complete');
        };
    },

    close: function() {
        this.$edit = this.$('#task-name');
        if ( event.which !== ENTER_KEY || !this.$edit.val().trim() ) {
            return;
        }

        this.model.editTitle(this.$edit.val());
        this.$el.find('#new-expectation').focus();
        Materialize.toast('Task updated to "' + this.model.get('title') + '"', 3000, 'rounded');
    },

    delete: function() {
        this.model.delete();
        Materialize.toast("Task removed.", 3000, 'rounded');
    },

    edit: function() {
        this.$el.children('#task-name').addClass('hidden');
        this.$el.children('#edit-task').removeClass('hidden');

        this.$el.children('#edit-task').focus();
    }
});<|endoftext|>


<commit_before>Ext.ns("SymPy");

$.fn.reverse = [].reverse;

SymPy.NumberKeyCodes = {
    49: 1,
    50: 2, 51: 3,
    52: 4, 53: 5,
    54: 6, 55: 7,
    56: 8, 57: 9,
};

SymPy.NumberKeys = {
    49: true,
    50: true, 51: true,
    52: true, 53: true,
    54: true, 55: true,
    56: true, 57: true,
};

SymPy.Completer = Ext.extend(Ext.util.Observable, {
    inputEl: null,
    outputEl: null,
    completions: [],
    currentCompletion: 0,
    completionRowSize: 3,

    constructor: function(config, shell) {
        config = Ext.apply({}, config);
        this.inputEl = config.input;
        this.containerEl = $(config.container.dom);
        this.shell = shell;
        this.buttonState = {
            prev: false,
            next: false,
            expand: false,
        };
    },

    setup: function() {
        this.toolbarEl = this.containerEl.append(
            $("
", {class: 'sympy-live-completions-toolbar'})
            .append($("<button>▼</button>",
                      {id: 'sympy-live-completions-toggle'}))
            .append($("<button><</button>",
                      {class: 'disabled', id: 'sympy-live-completions-prev'}))
            .append($("<button>></button>",
                      {class: 'disabled', id: 'sympy-live-completions-next'}))
        ).children('div');
        this.expandEl = this.toolbarEl.children("button:nth(0)");
        this.prevEl = this.toolbarEl.children("button:nth(1)");
        this.nextEl = this.toolbarEl.children("button:nth(2)");
        this.expandEl.click($.proxy(function(e) {
            if (this.isButtonEnabled("expand")) {
                this.toggleAllCompletions();
            }
            this.shell.focus();
        }, this));
        this.nextEl.click($.proxy(function(event){
            if (this.isButtonEnabled("next")) {
                this.showNextGroup();
            }
            this.shell.focus();
        }, this));
        this.prevEl.click($.proxy(function(event){
            if (this.isButtonEnabled("prev")) {
                this.showPrevGroup();
            }
            this.shell.focus();
        }, this));
        this.outputEl = $("
", {class: 'sympy-live-completions'})
            .append($("Completions here"));
        this.containerEl.append(this.outputEl);
        this.disableButtons(["prev", "next", "expand"]);
    },

    complete: function(statement, selection) {
        if (statement === this.replaceText) {
            this.doComplete(this.completions[this.currentCompletion], true);
            return;
        }
        if (statement !== null) {

            // Get just the part to complete
            var start = 0;
            var end = selection.end;
            // Ugly loop, but it's simple and it works
            var regex = /:|"|'|\)|\(|\[|\]|\{|\}|\n|\s|\t/;
            for(var i = end - 1; i >= 0 ; i--){
                var c = statement[i];

                if (c.match(regex) !== null) {
                    start = i + 1;
                    break;
                }
            }

            this.replacePosition = [start, end];
            this.replaceText = statement;
            statement = statement.substring(start, end);

            var data = {
                session: this.shell.session || null,
                statement: statement
            };
            $.ajax((this.basePath || '') + '/complete', {
                type: 'POST',
                data: JSON.stringify(data),
                dataType: 'json',
                success: $.proxy(function(data, textStatus, xhr) {
                    this.completionSuccess(data);
                }, this),
                error: $.proxy(function(xhr, textStatus, error) {
                    this.completionError();
                }, this)
            });
        }
    },

    doComplete: function(completion, end) {
        var prefix = this.replaceText.substring(0, this.replacePosition[0]);
        var suffix = this.replaceText.substring(
            this.replacePosition[1],
            this.replaceText.length);
        this.shell.setValue(prefix + completion + suffix);
        this.shell.setSelection(prefix.length + completion.length);
        if(typeof end === "undefined" || end === true) {
            this.finishComplete();
        }
    },

    doNumberComplete: function(keyCode){
        if(!this.isNumberKey(keyCode)) {return;}
        var number = SymPy.NumberKeyCodes[keyCode];
        var index = this.currentCompletion + number - 1;
        if (index < this.completions.length){
            this.doComplete(this.completions[index]);
        }
    },

    finishComplete: function(){
        this.replaceText = null;
        this.replacePositon = null;
        this.completions = [];
        this.allCompletions = [];
        this.currentCompletion = 0;
        $(this.outputEl).html('');
        this.hideAllCompletions();
        this.disableButtons(["prev", "next", "expand"]);
    },

    completionSuccess: function(responseJSON) {
        this.shell.session = responseJSON['session'];
        var completions = responseJSON['completions'];
        this.outputEl.html('');
        if (responseJSON['prefix']){
            this.doComplete(responseJSON['prefix'], false);
        }

        if (completions.length === 1){
            this.doComplete(completions[0]);
        }
        else if(completions.length > 0){
            if ($.inArray(responseJSON['prefix'], completions) !== -1){
                completions = $.grep(
                    completions,
                    function(val) { return val != responseJSON['prefix']; });
            }
            for(var i = 0; i < completions.length; i++){
                var link = $("
<button>" + completions[i] + "</button>
");
                link.attr({id: this.getID(i)});
                link.appendTo(this.outputEl);
                link.click($.proxy(function(event){
                    this.doComplete($(event.currentTarget).text());
                }, this));
            }
            var padding = this.completionRowSize;
            padding -= (completions.length % this.completionRowSize);
            padding %= this.completionRowSize;
            for (var j = 0; j < padding; j++) {
                this.outputEl.append($("
<button class='padding'/>
"));
            }
            $("button.padding").html(" ");
            this.currentCompletion = 0;
            this.completions = completions;
            this.allCompletions = completions;
            if (completions.length > this.completionRowSize) {
                this.showAllCompletions();
                this.enableButtons(["expand", "next"]);
            }
            else {
                this.disableButtons(["expand", "prev", "next"]);
            }
        }
        else {
            this.finishComplete();
            this.outputEl.append($("
<No completions>",
                                   {class: 'sympy-live-completions-none'}));
        }
    },

    completionError: function() {
        this.outputEl.html('');
        this.outputEl.append($("
<Error getting completions>
"),
                             {class: 'sympy-live-completions-none'});
    },

    showNextGroup: function() {
        if (this.completions.length <= this.completionRowSize) {
            this.disableButton("next");
            return;
        }
        this.enableButton("prev");
        var id = (this.currentCompletion + this.completionRowSize);
        if (id >= this.completions.length - this.completionRowSize) {
            this.disableButton("next");
            id = this.completions.length - this.completionRowSize + 1;
            id += this.completions.length % this.completionRowSize;
        }
        $('#' + this.getID(id)).
            prevAll().
            reverse().
            appendTo(this.outputEl);
        this.currentCompletion = id;
        if (this.currentCompletion >= this.completions.length - 1) {
            this.currentCompletion = this.completions.length - 1;
            this.disableButton("next");
        }
        if (this.showingNumbers === true) {
            this.showNumbers();
        }
    },

    showPrevGroup: function() {
        if (this.completions.length <= this.completionRowSize ||
            this.currentCompletion == 0
           ) {
            this.disableButton("prev");
            return;
        }
        this.enableButton("next");
        $('#' + this.getID(this.currentCompletion)).
            nextAll().
            slice(-this.completionRowSize).
            prependTo(this.outputEl);
        this.currentCompletion -= this.completionRowSize;
        if (this.currentCompletion <= 0) {
            this.currentCompletion = 0;
            this.disableButton("prev");
        }
        if (this.showingNumbers === true) {
            this.showNumbers();
        }
    },

    toggleAllCompletions: function(event){
        if ($(".sympy-live-completions").hasClass("expanded")){
            this.hideAllCompletions();
        }
        else {
            this.showAllCompletions();
        }
    },

    showAllCompletions: function(event){
        height = Math.ceil(this.completions.length / this.completionRowSize) * 40;
        if(height > 160) {height = 160;}
        $(".sympy-live-completions").
            scrollTop(0).
            addClass("expanded").
            height(height);
        $(".sympy-live-completions-toolbar button:first").addClass("hidden");
    },

    hideAllCompletions: function(event){
        $(".sympy-live-completions-toolbar button:first").removeClass("hidden");
        $(".sympy-live-completions").scrollTop(0).
            removeClass("expanded").height(30);
    },

    showNumbers: function() {
        this.hideNumbers();
        this.showingNumbers = true;
        this.outputEl.children("li").slice(0, 9).addClass('counted');
    },

    hideNumbers: function() {
        this.outputEl.children("li").removeClass('counted');
        this.showingNumbers = false;
    },

    isButtonEnabled: function(button) {
        if (this.buttonState[button] === true) {
            return true;
        }
        return false;
    },

    enableButton: function(button) {
        this.buttonState[button] = true;
        // Not very nice but simple
        this[button + "El"].removeClass("disabled");
    },

    disableButton: function(button) {
        this.buttonState[button] = false;
        // Not very nice but simple
        this[button + "El"].addClass("disabled");
    },

    enableButtons: function(buttons) {
        $.map(buttons, $.proxy(this.enableButton, this));
    },

    disableButtons: function(buttons) {
        $.map(buttons, $.proxy(this.disableButton, this));
    },

    getID: function(index) {
        return "completion-" + index
    },

    isNumberKey: function(keyCode) {
        return SymPy.NumberKeys[keyCode] === true;
    }
});
<commit_msg>Fix bug where arrows appeared in mobile<commit_after>Ext.ns("SymPy");

$.fn.reverse = [].reverse;

SymPy.NumberKeyCodes = {
    49: 1,
    50: 2, 51: 3,
    52: 4, 53: 5,
    54: 6, 55: 7,
    56: 8, 57: 9,
};

SymPy.NumberKeys = {
    49: true,
    50: true, 51: true,
    52: true, 53: true,
    54: true, 55: true,
    56: true, 57: true,
};

SymPy.Completer = Ext.extend(Ext.util.Observable, {
    inputEl: null,
    outputEl: null,
    completions: [],
    currentCompletion: 0,
    completionRowSize: 3,

    constructor: function(config, shell) {
        config = Ext.apply({}, config);
        this.inputEl = config.input;
        this.containerEl = $(config.container.dom);
        this.shell = shell;
        this.buttonState = {
            prev: false,
            next: false,
            expand: false,
        };
    },

    setup: function() {
        this.toolbarEl = this.containerEl.append(
            $("
", {"class": 'sympy-live-completions-toolbar'})
                .append($("<button>▼</button>")
                        .attr({"id": 'sympy-live-completions-toggle'}))
                .append($("<button><</button>")
                        .attr({"class": 'disabled',
                               'id': 'sympy-live-completions-prev'}))
                .append($("<button>></button>")
                        .attr({"class": 'disabled',
                               "id": 'sympy-live-completions-next'}))
        ).children('div');
        this.expandEl = this.toolbarEl.children("button:nth(0)");
        this.prevEl = this.toolbarEl.children("button:nth(1)");
        this.nextEl = this.toolbarEl.children("button:nth(2)");
        this.expandEl.click($.proxy(function(e) {
            if (this.isButtonEnabled("expand")) {
                this.toggleAllCompletions();
            }
            this.shell.focus();
        }, this));
        this.nextEl.click($.proxy(function(event){
            if (this.isButtonEnabled("next")) {
                this.showNextGroup();
            }
            this.shell.focus();
        }, this));
        this.prevEl.click($.proxy(function(event){
            if (this.isButtonEnabled("prev")) {
                this.showPrevGroup();
            }
            this.shell.focus();
        }, this));
        this.outputEl = $("
", {class: 'sympy-live-completions'})
            .append($("Completions here"));
        this.containerEl.append(this.outputEl);
        this.disableButtons(["prev", "next", "expand"]);
    },

    complete: function(statement, selection) {
        if (statement === this.replaceText) {
            this.doComplete(this.completions[this.currentCompletion], true);
            return;
        }
        if (statement !== null) {

            // Get just the part to complete
            var start = 0;
            var end = selection.end;
            // Ugly loop, but it's simple and it works
            var regex = /:|"|'|\)|\(|\[|\]|\{|\}|\n|\s|\t/;
            for(var i = end - 1; i >= 0 ; i--){
                var c = statement[i];

                if (c.match(regex) !== null) {
                    start = i + 1;
                    break;
                }
            }

            this.replacePosition = [start, end];
            this.replaceText = statement;
            statement = statement.substring(start, end);

            var data = {
                session: this.shell.session || null,
                statement: statement
            };
            $.ajax((this.basePath || '') + '/complete', {
                type: 'POST',
                data: JSON.stringify(data),
                dataType: 'json',
                success: $.proxy(function(data, textStatus, xhr) {
                    this.completionSuccess(data);
                }, this),
                error: $.proxy(function(xhr, textStatus, error) {
                    this.completionError();
                }, this)
            });
        }
    },

    doComplete: function(completion, end) {
        var prefix = this.replaceText.substring(0, this.replacePosition[0]);
        var suffix = this.replaceText.substring(
            this.replacePosition[1],
            this.replaceText.length);
        this.shell.setValue(prefix + completion + suffix);
        this.shell.setSelection(prefix.length + completion.length);
        if(typeof end === "undefined" || end === true) {
            this.finishComplete();
        }
    },

    doNumberComplete: function(keyCode){
        if(!this.isNumberKey(keyCode)) {return;}
        var number = SymPy.NumberKeyCodes[keyCode];
        var index = this.currentCompletion + number - 1;
        if (index < this.completions.length){
            this.doComplete(this.completions[index]);
        }
    },

    finishComplete: function(){
        this.replaceText = null;
        this.replacePositon = null;
        this.completions = [];
        this.allCompletions = [];
        this.currentCompletion = 0;
        $(this.outputEl).html('');
        this.hideAllCompletions();
        this.disableButtons(["prev", "next", "expand"]);
    },

    completionSuccess: function(responseJSON) {
        this.shell.session = responseJSON['session'];
        var completions = responseJSON['completions'];
        this.outputEl.html('');
        if (responseJSON['prefix']){
            this.doComplete(responseJSON['prefix'], false);
        }

        if (completions.length === 1){
            this.doComplete(completions[0]);
        }
        else if(completions.length > 0){
            if ($.inArray(responseJSON['prefix'], completions) !== -1){
                completions = $.grep(
                    completions,
                    function(val) { return val != responseJSON['prefix']; });
            }
            for(var i = 0; i < completions.length; i++){
                var link = $("
<button>" + completions[i] + "</button>
");
                link.attr({id: this.getID(i)});
                link.appendTo(this.outputEl);
                link.click($.proxy(function(event){
                    this.doComplete($(event.currentTarget).text());
                }, this));
            }
            var padding = this.completionRowSize;
            padding -= (completions.length % this.completionRowSize);
            padding %= this.completionRowSize;
            for (var j = 0; j < padding; j++) {
                this.outputEl.append($("
<button class='padding'/>
"));
            }
            $("button.padding").html(" ");
            this.currentCompletion = 0;
            this.completions = completions;
            this.allCompletions = completions;
            if (completions.length > this.completionRowSize) {
                this.showAllCompletions();
                this.enableButtons(["expand", "next"]);
            }
            else {
                this.disableButtons(["expand", "prev", "next"]);
            }
        }
        else {
            this.finishComplete();
            this.outputEl.append($("
<No completions>",
                                   {class: 'sympy-live-completions-none'}));
        }
    },

    completionError: function() {
        this.outputEl.html('');
        this.outputEl.append($("
<Error getting completions>
"),
                             {class: 'sympy-live-completions-none'});
    },

    showNextGroup: function() {
        if (this.completions.length <= this.completionRowSize) {
            this.disableButton("next");
            return;
        }
        this.enableButton("prev");
        var id = (this.currentCompletion + this.completionRowSize);
        if (id >= this.completions.length - this.completionRowSize) {
            this.disableButton("next");
            id = this.completions.length - this.completionRowSize + 1;
            id += this.completions.length % this.completionRowSize;
        }
        $('#' + this.getID(id)).
            prevAll().
            reverse().
            appendTo(this.outputEl);
        this.currentCompletion = id;
        if (this.currentCompletion >= this.completions.length - 1) {
            this.currentCompletion = this.completions.length - 1;
            this.disableButton("next");
        }
        if (this.showingNumbers === true) {
            this.showNumbers();
        }
    },

    showPrevGroup: function() {
        if (this.completions.length <= this.completionRowSize ||
            this.currentCompletion == 0
           ) {
            this.disableButton("prev");
            return;
        }
        this.enableButton("next");
        $('#' + this.getID(this.currentCompletion)).
            nextAll().
            slice(-this.completionRowSize).
            prependTo(this.outputEl);
        this.currentCompletion -= this.completionRowSize;
        if (this.currentCompletion <= 0) {
            this.currentCompletion = 0;
            this.disableButton("prev");
        }
        if (this.showingNumbers === true) {
            this.showNumbers();
        }
    },

    toggleAllCompletions: function(event){
        if ($(".sympy-live-completions").hasClass("expanded")){
            this.hideAllCompletions();
        }
        else {
            this.showAllCompletions();
        }
    },

    showAllCompletions: function(event){
        height = Math.ceil(this.completions.length / this.completionRowSize) * 40;
        if(height > 160) {height = 160;}
        $(".sympy-live-completions").
            scrollTop(0).
            addClass("expanded").
            height(height);
        $(".sympy-live-completions-toolbar button:first").addClass("hidden");
    },

    hideAllCompletions: function(event){
        $(".sympy-live-completions-toolbar button:first").removeClass("hidden");
        $(".sympy-live-completions").scrollTop(0).
            removeClass("expanded").height(30);
    },

    showNumbers: function() {
        this.hideNumbers();
        this.showingNumbers = true;
        this.outputEl.children("li").slice(0, 9).addClass('counted');
    },

    hideNumbers: function() {
        this.outputEl.children("li").removeClass('counted');
        this.showingNumbers = false;
    },

    isButtonEnabled: function(button) {
        if (this.buttonState[button] === true) {
            return true;
        }
        return false;
    },

    enableButton: function(button) {
        this.buttonState[button] = true;
        // Not very nice but simple
        this[button + "El"].removeClass("disabled");
    },

    disableButton: function(button) {
        this.buttonState[button] = false;
        // Not very nice but simple
        this[button + "El"].addClass("disabled");
    },

    enableButtons: function(buttons) {
        $.map(buttons, $.proxy(this.enableButton, this));
    },

    disableButtons: function(buttons) {
        $.map(buttons, $.proxy(this.disableButton, this));
    },

    getID: function(index) {
        return "completion-" + index
    },

    isNumberKey: function(keyCode) {
        return SymPy.NumberKeys[keyCode] === true;
    }
});
<|endoftext|>


<commit_before>/* GalleryJS (https://github.com/Imdsm/GalleryJS)
 * Adam K Dean (Imdsm)
 * 08/07/2013 16:32
 */

$(function() {

	var $container = $('.items');

	// we use imagesLoaded here so that all images are downloaded
	// before isotope makes any width/height calculations.
	$container.imagesLoaded( function(){
		$container.isotope({
			itemSelector: '.item'
		});
	});

});<commit_msg>Bit of this, bit of that.<commit_after>/* GalleryJS (https://github.com/Imdsm/GalleryJS)
 * Adam K Dean (Imdsm)
 * 08/07/2013 16:32
 */

$(function() {

	var $container = $('.items');

	$container.isotope({ itemSelector: '.item' });

	//$newItems = $('
test
');
	//$container.isotope('insert', $newItems);

	// does not work with file:// on chrome/safari ...
	$.get('img/', function(data) {
		console.log(data);
	});
});<|endoftext|>


<commit_before>$(function(){
  // Ensure that the window has a unique name
  if ((window.name == null) || window.name == "") {
    var d = new Date();
    window.name = d.getTime();
  }

  // Follow tab's URL instead of loading its content via ajax
  $("#tabs").tabs();
  // Restore previously selected tab
  var selected_tab = $.cookie("ganglia-selected-tab-" + window.name);
  if ((selected_tab != null) && (selected_tab.length > 0)) {
    try {
      var tab_index = parseInt(selected_tab, 10);
      if (!isNaN(tab_index) && (tab_index >= 0)) {
        //alert("ganglia-selected-tab: " + tab_index);
        $("#tabs").tabs("select", tab_index);
        switch (tab_index) {
          case 2:
            getViewsContent();
            break;
          case 4:
            autoRotationChooser();
            break;
        }
      }
    } catch (err) {
      try {
          alert("Error(ganglia.js): Unable to select tab: " +
                tab_index + ". " + err.getDescription());
      } catch (err) {
          // If we can't even show the error, fail silently.
      }
    }
  }

  $("#tabs").bind("tabsselect", function(event, ui) {
    // Store selected tab in a session cookie
    $.cookie("ganglia-selected-tab-" + window.name, ui.index);
  });

  $( "#range_menu" ).buttonset();
  $( "#sort_menu" ).buttonset();

  jQuery('#metric-search input[name="q"]').liveSearch({url: 'search.php?q=', typeDelay: 500});

  $( "#search-field-q").keyup(function() {
    $.cookie("ganglia-search-field-q" + window.name, $(this).val());
  });

  var search_value = $.cookie("ganglia-search-field-q" + window.name);
  if (search_value != null && search_value.length > 0)
    $("#search-field-q").val(search_value);

  $( "#datepicker-cs" ).datepicker({
	  showOn: "button",
	  buttonImage: "img/calendar.gif",
	  buttonImageOnly: true
  });
  $( "#datepicker-ce" ).datepicker({
	  showOn: "button",
	  buttonImage: "img/calendar.gif",
	  buttonImageOnly: true
  });

  $( "#create-new-view-dialog" ).dialog({
    autoOpen: false,
    height: 200,
    width: 350,
    modal: true,
    close: function() {
      getViewsContent();
      $("#create-new-view-layer").toggle();
      $("#create-new-view-confirmation-layer").html("");
    }
  });

  $( "#metric-actions-dialog" ).dialog({
    autoOpen: false,
    height: 250,
    width: 450,
    modal: true
  });

});

function selectTab(tab_index) {
  $("#tabs").tabs("select", tab_index);
}

function viewId(view_name) {
  return "v_" + view_name.replace(/[^a-zA-Z0-9_]/g, "_");
}

function highlightSelectedView(view_name) {
  $("#navlist a").css('background-color', '#FFFFFF');
  $("#" + viewId(view_name)).css('background-color', 'rgb(238,238,238)');
}

function selectView(view_name) {
  highlightSelectedView(view_name);
  $.cookie('ganglia-selected-view-' + window.name, view_name);
  var range = $.cookie('ganglia-view-range-' + window.name);
  if (range == null)
    range = '1hour';
  getViewsContentJustGraphs(view_name, range, '', '');
}

function getViewsContent() {
  $.get('views.php', "" , function(data) {
    $("#tabs-views-content").html('');
    $("#tabs-views-content").html(data);
    $("#create_view_button")
      .button()
      .click(function() {
	$( "#create-new-view-dialog" ).dialog( "open" );
      });;
    $( "#view_range_chooser" ).buttonset();

    // Restore previously selected view
    var view_name = document.getElementById('view_name');
    var selected_view = $.cookie("ganglia-selected-view-" + window.name);
    if (selected_view != null) {
        view_name.value = selected_view;
	var range = $.cookie("ganglia-view-range-" + window.name);
	if (range == null)
          range = "hour";
	$("#view-range-"+range).click();
    } else
      view_name.value = "default";
    highlightSelectedView(view_name.value);
  });
  return false;
}

// This one avoids
function getViewsContentJustGraphs(viewName,range, cs, ce) {
    $("#view_graphs").html('');
    $.get('views.php', "view_name=" + viewName + "&just_graphs=1&r=" + range + "&cs=" + cs + "&ce=" + ce, function(data) {
	$("#view_graphs").html(data);
	document.getElementById('view_name').value = viewName;
     });
    return false;
}

function createView() {
  $("#create-new-view-confirmation-layer").html('');
  $.get('views.php', $("#create_view_form").serialize() , function(data) {
    $("#create-new-view-layer").toggle();
    $("#create-new-view-confirmation-layer").html(data);
  });
  return false;
}

function addItemToView() {
  $.get('views.php', $("#add_metric_to_view_form").serialize() + "&add_to_view=1" , function(data) {
      $("#metric-actions-dialog-content").html('');
      $("#metric-actions-dialog-content").html(data);
  });
  return false;
}
function metricActions(host_name,metric_name,type,graphargs) {
    $( "#metric-actions-dialog" ).dialog( "open" );
    $("#metric-actions-dialog-content").html('');
    $.get('actions.php', "action=show_views&host_name=" + host_name + "&metric_name=" + metric_name + "&type=" + type + graphargs, function(data) {
      $("#metric-actions-dialog-content").html(data);
     });
    return false;
}

function createAggregateGraph() {
  if ( $('#hreg').val() == "" ||  $('#metric_chooser').val() == "" ) {
      alert("Host regular expression and metric name can't be blank");
      return false;
  }
  $("#aggregate_graph_display").html('');
  $.get('graph_all_periods.php', $("#aggregate_graph_form").serialize() + "&aggregate=1&embed=1" , function(data) {
    $("#aggregate_graph_display").html(data);
  });
  return false;
}

function metricActionsAggregateGraph() {
    $( "#metric-actions-dialog" ).dialog( "open" );
    $("#metric-actions-dialog-content").html('');
    $.get('actions.php', "action=show_views&aggregate=1&" + $("#aggregate_graph_form").serialize(), function(data) {
      $("#metric-actions-dialog-content").html(data);
     });
    return false;
}

function autoRotationChooser() {
  $("#tabs-autorotation-chooser").html('');
  $.get('autorotation.php', "" , function(data) {
      $("#tabs-autorotation-chooser").html(data);
  });
}
function updateViewTimeRange() {
  alert("Not implemented yet");
}

function ganglia_submit(clearonly) {
  document.getElementById("datepicker-cs").value = "";
  document.getElementById("datepicker-ce").value = "";
  if (! clearonly)
    document.ganglia_form.submit();
}
<commit_msg>Remove a redundant call to getViewsContent when refreshing the Views tab<commit_after>$(function(){
  // Ensure that the window has a unique name
  if ((window.name == null) || window.name == "") {
    var d = new Date();
    window.name = d.getTime();
  }

  // Follow tab's URL instead of loading its content via ajax
  $("#tabs").tabs();
  // Restore previously selected tab
  var selected_tab = $.cookie("ganglia-selected-tab-" + window.name);
  if ((selected_tab != null) && (selected_tab.length > 0)) {
    try {
      var tab_index = parseInt(selected_tab, 10);
      if (!isNaN(tab_index) && (tab_index >= 0)) {
        //alert("ganglia-selected-tab: " + tab_index);
        $("#tabs").tabs("select", tab_index);
        switch (tab_index) {
          case 4:
            autoRotationChooser();
            break;
        }
      }
    } catch (err) {
      try {
          alert("Error(ganglia.js): Unable to select tab: " +
                tab_index + ". " + err.getDescription());
      } catch (err) {
          // If we can't even show the error, fail silently.
      }
    }
  }

  $("#tabs").bind("tabsselect", function(event, ui) {
    // Store selected tab in a session cookie
    $.cookie("ganglia-selected-tab-" + window.name, ui.index);
  });

  $( "#range_menu" ).buttonset();
  $( "#sort_menu" ).buttonset();

  jQuery('#metric-search input[name="q"]').liveSearch({url: 'search.php?q=', typeDelay: 500});

  $( "#search-field-q").keyup(function() {
    $.cookie("ganglia-search-field-q" + window.name, $(this).val());
  });

  var search_value = $.cookie("ganglia-search-field-q" + window.name);
  if (search_value != null && search_value.length > 0)
    $("#search-field-q").val(search_value);

  $( "#datepicker-cs" ).datepicker({
	  showOn: "button",
	  buttonImage: "img/calendar.gif",
	  buttonImageOnly: true
  });
  $( "#datepicker-ce" ).datepicker({
	  showOn: "button",
	  buttonImage: "img/calendar.gif",
	  buttonImageOnly: true
  });

  $( "#create-new-view-dialog" ).dialog({
    autoOpen: false,
    height: 200,
    width: 350,
    modal: true,
    close: function() {
      getViewsContent();
      $("#create-new-view-layer").toggle();
      $("#create-new-view-confirmation-layer").html("");
    }
  });

  $( "#metric-actions-dialog" ).dialog({
    autoOpen: false,
    height: 250,
    width: 450,
    modal: true
  });

});

function selectTab(tab_index) {
  $("#tabs").tabs("select", tab_index);
}

function viewId(view_name) {
  return "v_" + view_name.replace(/[^a-zA-Z0-9_]/g, "_");
}

function highlightSelectedView(view_name) {
  $("#navlist a").css('background-color', '#FFFFFF');
  $("#" + viewId(view_name)).css('background-color', 'rgb(238,238,238)');
}

function selectView(view_name) {
  highlightSelectedView(view_name);
  $.cookie('ganglia-selected-view-' + window.name, view_name);
  var range = $.cookie('ganglia-view-range-' + window.name);
  if (range == null)
    range = '1hour';
  getViewsContentJustGraphs(view_name, range, '', '');
}

function getViewsContent() {
  $.get('views.php', "" , function(data) {
    $("#tabs-views-content").html('');
    $("#tabs-views-content").html(data);
    $("#create_view_button")
      .button()
      .click(function() {
	$( "#create-new-view-dialog" ).dialog( "open" );
      });;
    $( "#view_range_chooser" ).buttonset();

    // Restore previously selected view
    var view_name = document.getElementById('view_name');
    var selected_view = $.cookie("ganglia-selected-view-" + window.name);
    if (selected_view != null) {
        view_name.value = selected_view;
	var range = $.cookie("ganglia-view-range-" + window.name);
	if (range == null)
          range = "hour";
	$("#view-range-"+range).click();
    } else
      view_name.value = "default";
    highlightSelectedView(view_name.value);
  });
  return false;
}

// This one avoids
function getViewsContentJustGraphs(viewName,range, cs, ce) {
    $("#view_graphs").html('');
    $.get('views.php', "view_name=" + viewName + "&just_graphs=1&r=" + range + "&cs=" + cs + "&ce=" + ce, function(data) {
	$("#view_graphs").html(data);
	document.getElementById('view_name').value = viewName;
     });
    return false;
}

function createView() {
  $("#create-new-view-confirmation-layer").html('');
  $.get('views.php', $("#create_view_form").serialize() , function(data) {
    $("#create-new-view-layer").toggle();
    $("#create-new-view-confirmation-layer").html(data);
  });
  return false;
}

function addItemToView() {
  $.get('views.php', $("#add_metric_to_view_form").serialize() + "&add_to_view=1" , function(data) {
      $("#metric-actions-dialog-content").html('');
      $("#metric-actions-dialog-content").html(data);
  });
  return false;
}
function metricActions(host_name,metric_name,type,graphargs) {
    $( "#metric-actions-dialog" ).dialog( "open" );
    $("#metric-actions-dialog-content").html('');
    $.get('actions.php', "action=show_views&host_name=" + host_name + "&metric_name=" + metric_name + "&type=" + type + graphargs, function(data) {
      $("#metric-actions-dialog-content").html(data);
     });
    return false;
}

function createAggregateGraph() {
  if ( $('#hreg').val() == "" ||  $('#metric_chooser').val() == "" ) {
      alert("Host regular expression and metric name can't be blank");
      return false;
  }
  $("#aggregate_graph_display").html('');
  $.get('graph_all_periods.php', $("#aggregate_graph_form").serialize() + "&aggregate=1&embed=1" , function(data) {
    $("#aggregate_graph_display").html(data);
  });
  return false;
}

function metricActionsAggregateGraph() {
    $( "#metric-actions-dialog" ).dialog( "open" );
    $("#metric-actions-dialog-content").html('');
    $.get('actions.php', "action=show_views&aggregate=1&" + $("#aggregate_graph_form").serialize(), function(data) {
      $("#metric-actions-dialog-content").html(data);
     });
    return false;
}

function autoRotationChooser() {
  $("#tabs-autorotation-chooser").html('');
  $.get('autorotation.php', "" , function(data) {
      $("#tabs-autorotation-chooser").html(data);
  });
}
function updateViewTimeRange() {
  alert("Not implemented yet");
}

function ganglia_submit(clearonly) {
  document.getElementById("datepicker-cs").value = "";
  document.getElementById("datepicker-ce").value = "";
  if (! clearonly)
    document.ganglia_form.submit();
}
<|endoftext|>


<commit_before>

module.exports = function () {

  var soFar = new Buffer(0)

  return {
    data: soFar,
    add: function (data) {
      if(!Buffer.isBuffer(data))
        throw new Error('data must be a buffer, was: ' + JSON.stringify(data))
      this.data = soFar = Buffer.concat([soFar, data])
      return this
    },
    has: function (n) {
      if(null == n) return soFar.length > 0
      return soFar.length - (n || 0) >= 0
    },
    get: function (n) {
      var next
      if(null == n) {
        next = soFar
        soFar = new Buffer(0)
        return next
      }
      next = soFar.slice(0, n)
      if(soFar.length < n) throw new Error('current length is:'+soFar.length + ', could not get:'+n + ' bytes')
      soFar = soFar.slice(n, soFar.length)
      return next
    }
  }

}
<commit_msg>rewrite using bl<commit_after>
var BufferList = require('bl')

module.exports = function () {

  var bl = new BufferList()

  function get (n) {
    var len = n == null ? bl.length : n
    var data = bl.slice(0, len)
    bl.consume(n)
    return data
  }

  return {
    data: bl,
    add: function (data) {
      bl.append(data)
      return this
    },
    has: function (n) {
      if(n == null) return bl.length > 0
      return bl.length >= n

    },
    get: function (n) {
      if(n == null) return get()
      if(!this.has(n))
        throw new Error(
          'current length is:'+bl.length
          + ', could not get:'+n + ' bytes'
        )
      return get(n)
    }
  }

  var soFar = new Buffer(0)

  return {
    data: soFar,
    add: function (data) {
      if(!Buffer.isBuffer(data))
        throw new Error('data must be a buffer, was: ' + JSON.stringify(data))
      this.data = soFar = Buffer.concat([soFar, data])
      return this
    },
    has: function (n) {
      if(null == n) return soFar.length > 0
      return soFar.length - (n || 0) >= 0
    },
    get: function (n) {
      var next
      if(null == n) {
        next = soFar
        soFar = new Buffer(0)
        return next
      }
      next = soFar.slice(0, n)
      if(soFar.length < n) throw new Error('current length is:'+soFar.length + ', could not get:'+n + ' bytes')
      soFar = soFar.slice(n, soFar.length)
      return next
    }
  }

}
<|endoftext|>


<commit_before>'use strict';

module.exports = {

    controller: function (args) {
        this.servico = args;
        this.converter = new window.showdown.Converter();
    },

    view: function (ctrl) {
        if (_.isEmpty(ctrl.servico.solicitantes())) {
            return m('');
        } else {
            return m('#servico-solicitantes', [
                m('h3.subtitulo-servico', 'Quem pode utilizar este serviço?'),
                ctrl.servico.solicitantes().map(function(s) {
                    return m('.solicitantes markdown margem-solicitantes', [
                        m('h4', m.trust(s.tipo())),
                        m.trust(ctrl.converter.makeHtml(s.requisitos()))
                    ]);
                })

            ]);
        }
    }
};
<commit_msg>Formatação<commit_after>'use strict';

module.exports = {

    controller: function (args) {
      this.servico = args;
      this.converter = new window.showdown.Converter();
    },

    view: function (ctrl) {
      if (_.isEmpty(ctrl.servico.solicitantes())) {
        return m('');
      } else {
        return m('#servico-solicitantes', [
                m('h3.subtitulo-servico', 'Quem pode utilizar este serviço?'),
                ctrl.servico.solicitantes().map(function (s) {
                return m('.solicitantes markdown margem-solicitantes', [
                        m('h4', m.trust(s.tipo()),
                      m.trust(ctrl.converter.makeHtml(s.requisitos()))
                      ]);
                })

              ]);
        }
      }
    };
<|endoftext|>