<commit_before>$(document).ready(mainFunction);
var examUrl = null;
var clockStatus = null;
var countdownTime = 0;
var timeout;
var MILLIS2SEC = 1000;
var check1 = 0;
var check2 = 0;
var check3 = 0;
var check4 = 0;
var radio = 0;
var w = 1;
var idQuestion = 1;

function mainFunction() {
    callForClockAulaStatus();
    loadQuestion();

    $("#btnFinish").click(function() {
        var confirmDelivery = confirm("ATTENZIONE!!!\n Sei sicuro di voler consegnare il tuo esame???\n Cliccando su OK consegnerai il tuo elaborato definitivamente,\ne questa sarà la versione che verrà corretta");
        if (confirmDelivery){
            deliveryExam();
        }
    });

    $("#btnNotFinish").click(function() {
        var confirmDelivery = confirm("ATTENZIONE!!!\n Sei sicuro di voler non consegnare il tuo esame???\n Cliccando su OK confermerai la tua scelta");
        if (confirmDelivery){
            notDeliveryExam();
        }
    });

    $(document).on('click','a[id^="link"]', function(){
        var id = $(this).attr("id");
        loadValueToJsbin(id.slice(-1));
    });

    /* Gestione click checkbox, di seguito viene riportata la logica implementativa solo del primo caso, in quanto tutti gli altri sono analoghi */
    /* CON QUESTA CONFIGURAZIONE SELEZIONANDO UN CHECKBOX LA SPUNTA NON SI LEVA PIU' SE CI SI CLICCA SOPRA -____- PERO' FUNZIA CAMBIANDO CHECKBOX */
    $(document).on('click','input[id^="choise"]', function(){
        var i, ID;
        var id = $(this).attr("id");
        check1 = 0;
        check2 = 0;
        check3 = 0;
        check4 = 0;
        var value = document.getElementById(id).value;
        storeIdJsbinChecked(id, value);
        var lastCharId = id.slice(-1);
        var checked = "check"+lastCharId;
        /* primo checkbox */
        if(checked === "check1"){
            /* quando si clicca su un checkbox tutti gli altri vengono disabilitati, in quanto allo studente viene concesso di
             * scegliere solo una delle quattro opzioni */
            for (i = 1; i <= 4; i++) {
                if(i !== 1) {
                    ID = id.slice(0,7)+i;
                    console.log("IIIIIIIIIIIIIIIII "+ID);
                    document.getElementById(ID).setAttribute("checked", "false");
                    document.getElementById(ID).checked = false;
                }
                else{
                    document.getElementById(id).setAttribute("checked", "true");
                }
            }
        }
        /* secondo checkbox */
        if(checked === "check2"){
            for (i = 1; i <= 4; i++){
                if(i !== 2) {
                    ID = id.slice(0,7)+i;
                    document.getElementById(ID).setAttribute("checked", "false");
                    document.getElementById(ID).checked = false;
                }
                else{
                    document.getElementById(id).setAttribute("checked", "true");
                }
            }
        }
        /* terzo checkbox */
        if(checked === "check3"){
            for (i = 1; i <= 4; i++){
                if(i !== 3) {
                    ID = id.slice(0,7)+i;
                    document.getElementById(ID).setAttribute("checked", "false");
                    document.getElementById(ID).checked = false;
                }
                else{
                    document.getElementById(id).setAttribute("checked", "true");
                }
            }
        }
        /* quarto checkbox */
        if(checked === "check4"){
            for (i = 1; i <= 4; i++){
                if(i !== 4) {
                    ID = id.slice(0,7)+i;
                    document.getElementById(ID).setAttribute("checked", "false");
                    document.getElementById(ID).checked = false;
                }
                else{
                    document.getElementById(id).setAttribute("checked", "true");
                }
            }
        }
    });
}

function createCountdownElement(millisec){
    var second = millisec / MILLIS2SEC;
    $("#divCountdown").empty();
    myCountdown = new Countdown({
        time: second,
        width:200,
        height:25,
        inline:true,
        hideLabels	: true,
        target: "Countdown",
        onComplete: function(){
            //alert("time is up");
            $("div[id^='Container_jbeeb']").css("background-color", "red");
        },
        hideLine: true,
        numbers		: 	{
            font 	: "Arial",
            color	: "#FFFFFF",
            bkgd	: "#1E90FF",
            rounded	: 0.15,
            shadow	: {
                x : 0,
                y : 3,
                s : 4,
                c : "#000000",
                a : 0.4
            }
        },
        labels : {
            font   : "Arial",
            color  : "#a8a8a8",
            weight : "normal" // < - no comma on last item!
        },
        rangeHi:"hour"	// <- no comma on last item!
    });
}

function callForClockAulaStatus() {

    $.ajax({
        url: "getClockAula",
        dataType: "json",
        success: function (data) {
            console.log("dati arrivati");
            if (data.status !== clockStatus){
                clockStatus = data.status;
                console.log("STATUS SERVER "+clockStatus);
                switch (clockStatus){
                    case "overtime":
                        countdownTime = data.durationOverTime;
                        createCountdownObject(countdownTime);
                        break;
                    case "start":
                        timeout = data.timeout;
                        createCountdownElement(timeout);
                        examUrl = data.url;
                        break;
                    case "over":
                        deliveryExam();
                        break;
                }
            }
            setTimeout(callForClockAulaStatus, 5000);
        },

        error: function () {
            alert("Si è verificato un problema (call)");
        }
    });
}

function loadQuestion(){
    $.ajax({
        url: "loadQuestion",
        dataType: "json",
        type: "POST",
        success: function (data) {
            var res = JSON.parse(data.content);
            add(res.question);
        },

        error: function () {
            alert("Si è verificato un problema (load)");
        }
    });
}

function loadValueToJsbin(id){
    $.ajax({
        url: "loadValueToJsbin",
        dataType: "json",
        data: {id:id},
        type: "POST",
        success: function (data){
            //alert(data);
        },

        error: function () {
            alert("Si è verificato un problema load to Jsbin");
        }
    });
}

function add(question){
    var i, j, link,textarea, input,label, v;
    for(i=0; i<question.length; i++) {
        var z = (i+1) + ". ";
        var x = i+1;
        var div = document.createElement("div");
        var para = document.createElement("P");                          // Create a
 node
        var number =  document.createTextNode(z);
        para.appendChild(number);
        for (j = 0; j < question[i].text.length; j++) {
            var t = document.createTextNode(question[i].text[j] + "\n");        // Create a text node
            para.appendChild(t);                                        // Append the text to

            var newLine = document.createElement('br');
            para.appendChild(newLine);
        }
        /* domanda a risposta aperta */
        if(question[i].type === "text"){
            textarea = document.createElement("textarea");
            textarea.setAttribute("id", "textarea"+x);
            textarea.setAttribute("onchange","change(this.id)");
            para.appendChild(textarea);
        }
        /* domanda a risposta multipla */
        else if(question[i].type === "radio") {
            radio++;
            var arr = [];
            /* salvo le quattro opzioni in un array */
            for (var y = 0; y < 4; y++){
                arr.push(question[i].options[y]);
            }
            /* inserisco randomicamente le 4 opzioni eliminando ogni volta quella inserita per evitare che si ripeta */
            for (var k = 0; k < 4; k++) {
                var rand = Math.round((arr.length-1)*Math.random());
                var textChoise = document.createTextNode(arr[rand] + "\n");
                input = document.createElement("input");
                label = document.createElement("label");
                input.setAttribute("type", "radio");
                input.setAttribute("id", "choise"+ x + (k+1));
                input.setAttribute("value", arr[rand]);
                label.appendChild(textChoise);
                para.appendChild(input);
                para.appendChild(label);
                para.appendChild(document.createElement("br"));
                arr.splice(rand, 1);
            }
        }
        /* jsbin */
        else{
            var id = "link" + x;
            link = document.createElement("a");
            link.setAttribute("href", examUrl);
            link.setAttribute("target", "_black");
            link.setAttribute("id", id);
            v = document.createTextNode("JSBIN");
            link.appendChild(v);
            para.appendChild(link);
        }
        para.setAttribute("class", "question");                         // Add class to node p
        para.setAttribute("id", idQuestion);                                // Add id to node p
        div.appendChild(para);
        document.getElementById("divQuestion").appendChild(div);        // Append node p to div*/
        idQuestion++;
    }
}

function storeIdJsbinChecked(id, value){
    var data = {
        id: id,
        value: value
    };
    $.ajax({
        url: "saveRadioChecked",
        data: data,
        dataType: "json",
        type: "POST",
        success: function (response) {
            console.log("RESPONSE " +response);
        },

        error: function () {
            alert("Si è verificato un problema (json file)");
        }
    });
}

function deliveryExam(){
    var urlExam = location.pathname.split('/')[1];
        urlExam += "_delivery";
    //console.log("URLDELIVERYEXAM "+urlExam);
    var examRevision = 1;

    var data = {
        urlExam: urlExam,
        examRevision: examRevision
    };
    $.ajax({
        url: "/deliveryExam", //this is the right route
        dataType: "json",
        type: "POST",
        data: data,
        success: function (response) { //TODO here I need a switch block to manage different clock status
            console.log(response);
            window.location.href = response.finishPageUrl;
        },

        error: function () {
            alert("Si è verificato un problema (delivery exam)");
        }
    });
}

function notDeliveryExam(){
    var urlExam = location.pathname.split('/')[1];
        urlExam += "_notdelivery";
    var examRevision = 1;

    var data = {
        urlExam: urlExam,
        examRevision: examRevision
    };
    $.ajax({
        url: "/deliveryExam", //this is the right route
        dataType: "json",
        type: "POST",
        data: data,
        success: function (response) { //TODO here I need a switch block to manage different clock status
            console.log(response);
            window.location.href = response.finishPageUrl;
        },

        error: function () {
            alert("Si è verificato un problema (not delivery exam)");
        }
    });
}

function change(id){
    var value = document.getElementById(id).value;
    var data = {
        answer: value,
        id: id
    };
    console.log("value "+value);
    $.ajax({
        url: "saveValueTextarea",
        data: data,
        dataType: "json",
        type: "POST",
        success: function (response) {
            console.log("RESPONSE " +response);
        },

        error: function () {
            alert("Si è verificato un problema (textarea)");
        }
    });
}<commit_msg>sistemato bug radio lato studente<commit_after>$(document).ready(mainFunction);
var examUrl = null;
var clockStatus = null;
var countdownTime = 0;
var timeout;
var MILLIS2SEC = 1000;
var radio = 0;
var w = 1;
var idQuestion = 1;

function mainFunction() {
    callForClockAulaStatus();
    loadQuestion();

    $("#btnFinish").click(function() {
        var confirmDelivery = confirm("ATTENZIONE!!!\n Sei sicuro di voler consegnare il tuo esame???\n Cliccando su OK consegnerai il tuo elaborato definitivamente,\ne questa sarà la versione che verrà corretta");
        if (confirmDelivery){
            deliveryExam();
        }
    });

    $("#btnNotFinish").click(function() {
        var confirmDelivery = confirm("ATTENZIONE!!!\n Sei sicuro di voler non consegnare il tuo esame???\n Cliccando su OK confermerai la tua scelta");
        if (confirmDelivery){
            notDeliveryExam();
        }
    });

    $(document).on('click','a[id^="link"]', function(){
        var id = $(this).attr("id");
        loadValueToJsbin(id.slice(-1));
    });

    /* Ad ogni click viene salvato il valore del campo radio spuntato */
    $(document).on('click','input[id^="choise"]', function(){
        var id = $(this).attr("id");
        var value = document.getElementById(id).value;
        storeIdJsbinChecked(id, value);
    });
}

function createCountdownElement(millisec){
    var second = millisec / MILLIS2SEC;
    $("#divCountdown").empty();
    myCountdown = new Countdown({
        time: second,
        width:200,
        height:25,
        inline:true,
        hideLabels	: true,
        target: "Countdown",
        onComplete: function(){
            //alert("time is up");
            $("div[id^='Container_jbeeb']").css("background-color", "red");
        },
        hideLine: true,
        numbers		: 	{
            font 	: "Arial",
            color	: "#FFFFFF",
            bkgd	: "#1E90FF",
            rounded	: 0.15,
            shadow	: {
                x : 0,
                y : 3,
                s : 4,
                c : "#000000",
                a : 0.4
            }
        },
        labels : {
            font   : "Arial",
            color  : "#a8a8a8",
            weight : "normal" // < - no comma on last item!
        },
        rangeHi:"hour"	// <- no comma on last item!
    });
}

function callForClockAulaStatus() {

    $.ajax({
        url: "getClockAula",
        dataType: "json",
        success: function (data) {
            console.log("dati arrivati");
            if (data.status !== clockStatus){
                clockStatus = data.status;
                console.log("STATUS SERVER "+clockStatus);
                switch (clockStatus){
                    case "overtime":
                        countdownTime = data.durationOverTime;
                        createCountdownObject(countdownTime);
                        break;
                    case "start":
                        timeout = data.timeout;
                        createCountdownElement(timeout);
                        examUrl = data.url;
                        break;
                    case "over":
                        deliveryExam();
                        break;
                }
            }
            setTimeout(callForClockAulaStatus, 5000);
        },

        error: function () {
            alert("Si è verificato un problema (call)");
        }
    });
}

function loadQuestion(){
    $.ajax({
        url: "loadQuestion",
        dataType: "json",
        type: "POST",
        success: function (data) {
            var res = JSON.parse(data.content);
            add(res.question);
        },

        error: function () {
            alert("Si è verificato un problema (load)");
        }
    });
}

function loadValueToJsbin(id){
    $.ajax({
        url: "loadValueToJsbin",
        dataType: "json",
        data: {id:id},
        type: "POST",
        success: function (data){
            //alert(data);
        },

        error: function () {
            alert("Si è verificato un problema load to Jsbin");
        }
    });
}

function add(question){
    var i, j, link,textarea, input,label, v;
    for(i=0; i<question.length; i++) {
        var z = (i+1) + ". ";
        var x = i+1;
        var div = document.createElement("div");
        var para = document.createElement("P");                          // Create a
 node
        var number =  document.createTextNode(z);
        para.appendChild(number);
        for (j = 0; j < question[i].text.length; j++) {
            var t = document.createTextNode(question[i].text[j] + "\n");        // Create a text node
            para.appendChild(t);                                        // Append the text to

            var newLine = document.createElement('br');
            para.appendChild(newLine);
        }
        /* domanda a risposta aperta */
        if(question[i].type === "text"){
            textarea = document.createElement("textarea");
            textarea.setAttribute("id", "textarea"+x);
            textarea.setAttribute("onchange","change(this.id)");
            para.appendChild(textarea);
        }
        /* domanda a risposta multipla */
        else if(question[i].type === "radio") {
            radio++;
            var arr = [];
            /* salvo le quattro opzioni in un array */
            for (var y = 0; y < 4; y++){
                arr.push(question[i].options[y]);
            }
            /* inserisco randomicamente le 4 opzioni eliminando ogni volta quella inserita per evitare che si ripeta */
            for (var k = 0; k < 4; k++) {
                var rand = Math.round((arr.length-1)*Math.random());
                var textChoise = document.createTextNode(arr[rand] + "\n");
                input = document.createElement("input");
                label = document.createElement("label");
                input.setAttribute("type", "radio");
                input.setAttribute("id", "choise"+ x + (k+1));
                input.setAttribute("name", "opt" + x);
                input.setAttribute("value", arr[rand]);
                label.appendChild(textChoise);
                para.appendChild(input);
                para.appendChild(label);
                para.appendChild(document.createElement("br"));
                arr.splice(rand, 1);
            }
        }
        /* jsbin */
        else{
            var id = "link" + x;
            link = document.createElement("a");
            link.setAttribute("href", examUrl);
            link.setAttribute("target", "_black");
            link.setAttribute("id", id);
            v = document.createTextNode("JSBIN");
            link.appendChild(v);
            para.appendChild(link);
        }
        para.setAttribute("class", "question");                         // Add class to node p
        para.setAttribute("id", idQuestion);                                // Add id to node p
        div.appendChild(para);
        document.getElementById("divQuestion").appendChild(div);        // Append node p to div*/
        idQuestion++;
    }
}

function storeIdJsbinChecked(id, value){
    var data = {
        id: id,
        value: value
    };
    $.ajax({
        url: "saveRadioChecked",
        data: data,
        dataType: "json",
        type: "POST",
        success: function (response) {
            console.log("RESPONSE " +response);
        },

        error: function () {
            alert("Si è verificato un problema (json file)");
        }
    });
}

function deliveryExam(){
    var urlExam = location.pathname.split('/')[1];
        urlExam += "_delivery";
    //console.log("URLDELIVERYEXAM "+urlExam);
    var examRevision = 1;

    var data = {
        urlExam: urlExam,
        examRevision: examRevision
    };
    $.ajax({
        url: "/deliveryExam", //this is the right route
        dataType: "json",
        type: "POST",
        data: data,
        success: function (response) { //TODO here I need a switch block to manage different clock status
            console.log(response);
            window.location.href = response.finishPageUrl;
        },

        error: function () {
            alert("Si è verificato un problema (delivery exam)");
        }
    });
}

function notDeliveryExam(){
    var urlExam = location.pathname.split('/')[1];
        urlExam += "_notdelivery";
    var examRevision = 1;

    var data = {
        urlExam: urlExam,
        examRevision: examRevision
    };
    $.ajax({
        url: "/deliveryExam", //this is the right route
        dataType: "json",
        type: "POST",
        data: data,
        success: function (response) { //TODO here I need a switch block to manage different clock status
            console.log(response);
            window.location.href = response.finishPageUrl;
        },

        error: function () {
            alert("Si è verificato un problema (not delivery exam)");
        }
    });
}

function change(id){
    var value = document.getElementById(id).value;
    var data = {
        answer: value,
        id: id
    };
    console.log("value "+value);
    $.ajax({
        url: "saveValueTextarea",
        data: data,
        dataType: "json",
        type: "POST",
        success: function (response) {
            console.log("RESPONSE " +response);
        },

        error: function () {
            alert("Si è verificato un problema (textarea)");
        }
    });
}<|endoftext|>


<commit_before>define([
  'underscore',
  'backbone',
  'collections/users',
  'collections/comments',
  'text!templates/show_user_page.html'
], function module(_, Backbone, userCollection, commentCollection, template){

  var View = Backbone.View.extend({
    template: _.template( template ),
    initialize: function(){
      this.render();
    },
    remove: function(){
      this.undelegateEvents();
      Backbone.View.prototype.remove.call(this);
    },
    render: function(){
      var id = this.options.params[0],
          user = userCollection.get(id),
          html = this.template({
            user: user,
            comments: commentCollection.first(3)
          });
      this.$el.html( html );
    }
  });
  return View;

});
<commit_msg>only show users comments on profile page<commit_after>define([
  'underscore',
  'backbone',
  'collections/users',
  'collections/comments',
  'text!templates/show_user_page.html'
], function module(_, Backbone, userCollection, commentCollection, template){

  var View = Backbone.View.extend({
    template: _.template( template ),
    initialize: function(){
      this.render();
    },
    remove: function(){
      this.undelegateEvents();
      Backbone.View.prototype.remove.call(this);
    },
    render: function(){
      var id = this.options.params[0],
          user = userCollection.get(id),
          html = this.template({
            user: user,
            comments: commentCollection.where({owner_id:user.get('id')})
          });
      this.$el.html( html );
    }
  });
  return View;

});
<|endoftext|>


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

	var register = new registerPage();
	register.init();

	jQuery('#register-btn')
	.mouseenter(function(){
		jQuery(this).addClass('btn-info');
	})
	.mouseleave(function(){
		jQuery(this).removeClass('btn-info');
	})
	.click(register.registerText);

});

registerPage = function () {
    'use strict';
};

registerPage.prototype = {

		init: function(){
			console.log(local_data);
		},

		registerText:function(event){

			var textMod = ccmf.Text.create();
			var dataMod = ccmf.Data.create();

			var registerText = jQuery('#register-area > textarea').val();
			var registeringTextShingles = textMod.removedStopWordShingles(registerText,9);
			var registerShinglesFing = textMod.shinglesFingerprintConv(registeringTextShingles);

			/* Extract the Signature */
			var signature = [];
			signature[0] = registerShinglesFing;
			var minHashSignature = textMod.minHashSignaturesGen(signature);

			/* Register the Signature into the Registry*/

			dataMod.storeLsh(minHashSignature,null,{
														author:
														{
															first:local_data.first,
															last:local_data.last,
															email:local_data.email
														}
												   }
			);

			jQuery('#result > span').text('Text Registered');
		}
};<commit_msg>Pass in callback if error occurs during registering of articles<commit_after>jQuery(document).ready(function(){

	var register = new registerPage();
	register.init();

	jQuery('#register-btn')
	.mouseenter(function(){
		jQuery(this).addClass('btn-info');
	})
	.mouseleave(function(){
		jQuery(this).removeClass('btn-info');
	})
	.click(register.registerText);

});

registerPage = function () {
    'use strict';
};

registerPage.prototype = {

		init: function(){
		},

		registerText:function(event){

			var textMod = ccmf.Text.create();
			var dataMod = ccmf.Data.create();

			var registerText = jQuery('#register-area > textarea').val();
			var registeringTextShingles = textMod.removedStopWordShingles(registerText,9);
			var registerShinglesFing = textMod.shinglesFingerprintConv(registeringTextShingles);

			/* Extract the Signature */
			var signature = [];
			signature[0] = registerShinglesFing;
			var minHashSignature = textMod.minHashSignaturesGen(signature);

			/* Register the Signature into the Registry*/

			dataMod.storeLsh(minHashSignature,
							 function(error){
								if(error===null){
									jQuery('#result > span').text('Text Registered');
								}
								else{
									jQuery('#result > span').text('Register Failed');
								}
							}
							,
							{
							 author:
								{
									first:local_data.first,
									last:local_data.last,
									email:local_data.email
								}
						    }
			);
		}
};<|endoftext|>


<commit_before>define(function(require) {

    'use strict';

    var Backbone = require('backbone')
      , _        = require('underscore')
      , log      = require('bows.min')('Models:Post')
      , socket   = require('app/utils/socket')

    return Backbone.Model.extend({

      xmppEvents: {
        'get': 'xmpp.buddycloud.retrieve',
        'post': 'xmpp.buddycloud.publish'
      },

      defaults: {
        content: null,
        author: {},
        published: null,
        commentCount: 0
      },

      embedReceipts: [
        {
          name: 'WiFi TV',
          regex: /.*connectuptv.pockittv.mobi\/v\/(\w*)/g,
          substitution: '
<video width="320" height="240" poster="https://connectuptv.pockittv.mobi/video/image/$1" controls><source src="$&"></video>
'
        }
        // {
        //   name: 'Images',
        //   regex: /[a-z\-_0-9\/\:\.]*\.(jpg|jpeg|png|gif|svg)/g,
        //   substitution: '

'
        // },
        // {
        //   name: 'Youtube',
        //   regex: /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/g,
        //   substitution: '

'
        // }
      ],

      initialize: function(post) {
        if (!post.entry) {
          /* We probably want the model to
           * load this for us
           */
          return this.set(post, { silent: true })
        }
        var data = this._mapPost(post)
        this.set(data, { silent: true })
        this.requestCommentCount()
      },

      requestCommentCount: function() {
        var self = this
        var options = {
          node: this.get('node'),
          id: this.get('localId'),
          rsm: { max: 1 }
        }

        socket.send('xmpp.buddycloud.items.replies', options, function(error, data, rsm) {
          if (error) {
            return self.trigger('error', error)
          }
          self.set({ commentCount: rsm.count || 0 })
        })
      },

      sync: function(method, collection, options) {
        if (!method) {
          method = 'get'
        }

        switch (method) {
          case 'get':
            return this.getPost()
          case 'post':
          case 'create':
            return this.publish()
          default:
            throw new Error('Unhandled method: ' + method)
        }

      },

      getPost: function() {
        var event = this.xmppEvents['get']
        var self = this
        var options = {
          node: this.get('node'),
          id: this.get('localId')
        }
        socket.send(event, options, function(error, post) {
          if (error) {
            return self.trigger('error', error)
          }
          self.set(self._mapPost(post[0]), { silent: true })
          self.trigger('loaded:post')
        })
      },

      publish: function() {
        var payload = {
            node: this.get('node'),
            content: {
              atom: {
                content: this.get('content')
            },
            'in-reply-to': { ref: this.get('inReplyTo') }
          }
        }
        var self = this
        var event = this.xmppEvents['post']
        socket.send(event, payload, function(error, success) {
          if (error) {
            return self.trigger('publish:error', error)
          }
          self.trigger('publish:success')
        })
      },

      _mapPost: function(post) {
        var username = post.entry.atom.author.uri.substr(5)
        var usernameParts = username.split('@')
        if (usernameParts[1] === localStorage.getItem('jid').split('@')[1]) {
          username = usernameParts[0]
        }
        return {
          displayName: null,
          username: username,
          published: Date.parse(post.entry.atom.published),
          content: this.parseContent(post.entry.atom.content.content),
          node: post.node,
          channelJid: post.node.split('/')[2],
          globalId: post.entry.atom.id,
          localId: post.entry.atom.id.split(',')[2] || post.entry.atom.id,
          canComment: true,
          isReply: ('comment' === post.entry.activity),
          inReplyTo: (post.entry['in-reply-to'] || {}).ref,
          likes: 1,
          commentCount: null
        }
      },

      parseContent: function(content) {
        content = _.escape(content)
          .replace(/\{/g, '{')
          .replace(///g, '/')
          .replace(/\}/g, '}')
          .replace(/\n/g, '
')

        this.embedReceipts.forEach(function(receipt) {
          content = content
            .replace(receipt.regex, receipt.substitution)
        }, this)
        return content
      },

      addComment: function() {
        this.set('commentCount', this.attributes.commentCount + 1)
      },

      removeComment: function() {
        this.set(
          'commentCount',
          (this.attributes.commentCount > 0) ? this.attributes.commentCount - 1 : 0
        )
      }

    })

})
<commit_msg>add insert images to topics<commit_after>define(function(require) {

    'use strict';

    var Backbone = require('backbone')
      , _        = require('underscore')
      , log      = require('bows.min')('Models:Post')
      , socket   = require('app/utils/socket')

    return Backbone.Model.extend({

      xmppEvents: {
        'get': 'xmpp.buddycloud.retrieve',
        'post': 'xmpp.buddycloud.publish'
      },

      defaults: {
        content: null,
        author: {},
        published: null,
        commentCount: 0
      },

      embedReceipts: [
        {
          name: 'WiFi TV',
          regex: /.*connectuptv.pockittv.mobi\/v\/(\w*)/g,
          substitution: '
<video width="320" height="240" poster="https://connectuptv.pockittv.mobi/video/image/$1" controls><source src="$&"></video>
'
        },
        {
          name: 'Images',
          regex: /[a-z\-_0-9\/\:\.]*\.(jpg|jpeg|png|gif|svg)/g,
          substitution: '

'
        },
        // {
        //   name: 'Youtube',
        //   regex: /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/g,
        //   substitution: '

'
        // }
      ],

      initialize: function(post) {
        if (!post.entry) {
          /* We probably want the model to
           * load this for us
           */
          return this.set(post, { silent: true })
        }
        var data = this._mapPost(post)
        this.set(data, { silent: true })
        this.requestCommentCount()
      },

      requestCommentCount: function() {
        var self = this
        var options = {
          node: this.get('node'),
          id: this.get('localId'),
          rsm: { max: 1 }
        }

        socket.send('xmpp.buddycloud.items.replies', options, function(error, data, rsm) {
          if (error) {
            return self.trigger('error', error)
          }
          self.set({ commentCount: rsm.count || 0 })
        })
      },

      sync: function(method, collection, options) {
        if (!method) {
          method = 'get'
        }

        switch (method) {
          case 'get':
            return this.getPost()
          case 'post':
          case 'create':
            return this.publish()
          default:
            throw new Error('Unhandled method: ' + method)
        }

      },

      getPost: function() {
        var event = this.xmppEvents['get']
        var self = this
        var options = {
          node: this.get('node'),
          id: this.get('localId')
        }
        socket.send(event, options, function(error, post) {
          if (error) {
            return self.trigger('error', error)
          }
          self.set(self._mapPost(post[0]), { silent: true })
          self.trigger('loaded:post')
        })
      },

      publish: function() {
        var payload = {
            node: this.get('node'),
            content: {
              atom: {
                content: this.get('content')
            },
            'in-reply-to': { ref: this.get('inReplyTo') }
          }
        }
        var self = this
        var event = this.xmppEvents['post']
        socket.send(event, payload, function(error, success) {
          if (error) {
            return self.trigger('publish:error', error)
          }
          self.trigger('publish:success')
        })
      },

      _mapPost: function(post) {
        var username = post.entry.atom.author.uri.substr(5)
        var usernameParts = username.split('@')
        if (usernameParts[1] === localStorage.getItem('jid').split('@')[1]) {
          username = usernameParts[0]
        }
        return {
          displayName: null,
          username: username,
          published: Date.parse(post.entry.atom.published),
          content: this.parseContent(post.entry.atom.content.content),
          node: post.node,
          channelJid: post.node.split('/')[2],
          globalId: post.entry.atom.id,
          localId: post.entry.atom.id.split(',')[2] || post.entry.atom.id,
          canComment: true,
          isReply: ('comment' === post.entry.activity),
          inReplyTo: (post.entry['in-reply-to'] || {}).ref,
          likes: 1,
          commentCount: null
        }
      },

      parseContent: function(content) {
        content = _.escape(content)
          .replace(/\{/g, '{')
          .replace(///g, '/')
          .replace(/\}/g, '}')
          .replace(/\n/g, '
')

        this.embedReceipts.forEach(function(receipt) {
          content = content
            .replace(receipt.regex, receipt.substitution)
        }, this)
        return content
      },

      addComment: function() {
        this.set('commentCount', this.attributes.commentCount + 1)
      },

      removeComment: function() {
        this.set(
          'commentCount',
          (this.attributes.commentCount > 0) ? this.attributes.commentCount - 1 : 0
        )
      }

    })

})
<|endoftext|>


<commit_before>var Hapi = require('hapi')
var test = require('tap').test
var PouchDB = require('pouchdb-core')
  .plugin(require('pouchdb-mapreduce'))
  .plugin(require('pouchdb-adapter-memory'))

var hoodie = require('../../').register
var hapiPluginOptions = {
  register: hoodie,
  options: {
    inMemory: true,
    loglevel: 'error',
    paths: {},
    PouchDB: PouchDB
  }
}

require('npmlog').level = 'error'

test('respond to all /hoodie/* - requests with an index.html', function (group) {
  var server

  group.beforeEach(function (done) {
    server = new Hapi.Server()
    server.connection({port: 8090})
    server.register(hapiPluginOptions, function () {
      done()
    })
  })

  group.afterEach(function (done) {
    server.stop(done)
  })

  group.test('respond to /admin/', function (t) {
    checkRequestForPath(t, '/hoodie/admin/')
  })

  group.test('repond to /account/', function (t) {
    checkRequestForPath(t, '/hoodie/account/')
  })

  group.test('respond to /store/', function (t) {
    checkRequestForPath(t, '/hoodie/store/')
  })

  group.test('respond to simple /hoodie/', function (t) {
    server.inject({
      url: 'http://localhost:8090/hoodie/unkown.css',
      headers: {
        accept: 'text/css'
      }
    }, function (response) {
      t.is(response.statusCode, 404, 'statusCode is 404')

      t.end()
    })
  })

  group.test('respond to simple /hoodie/', function (t) {
    server.inject({
      url: 'http://localhost:8090/hoodie/unkown',
      headers: {
        accept: 'text/html'
      }
    }, function (response) {
      t.is(response.statusCode, 200, 'statusCode is 200')

      server.stop(t.end)
    })
  })

  function checkRequestForPath (t, path) {
    server.inject({
      url: 'http://localhost:8090' + path + 'unknownSubPath',
      headers: {
        accept: 'text/html'
      }
    }, function (response) {
      t.is(response.statusCode, 200, 'statusCode is 200')
      t.match(response.payload, /<html/, 'response is HTML')

      t.end()
    })
  }

  group.end()
})
<commit_msg>test: /hoodie/unknown responds with 404<commit_after>var Hapi = require('hapi')
var test = require('tap').test
var PouchDB = require('pouchdb-core')
  .plugin(require('pouchdb-mapreduce'))
  .plugin(require('pouchdb-adapter-memory'))

var hoodie = require('../../').register
var hapiPluginOptions = {
  register: hoodie,
  options: {
    inMemory: true,
    loglevel: 'error',
    paths: {},
    PouchDB: PouchDB
  }
}

require('npmlog').level = 'error'

test('respond to all /hoodie/* - requests with an index.html', function (group) {
  var server

  group.beforeEach(function (done) {
    server = new Hapi.Server()
    server.connection({port: 8090})
    server.register(hapiPluginOptions, function () {
      done()
    })
  })

  group.afterEach(function (done) {
    server.stop(done)
  })

  group.test('respond to /admin/', function (t) {
    checkRequestForPath(t, '/hoodie/admin/')
  })

  group.test('repond to /account/', function (t) {
    checkRequestForPath(t, '/hoodie/account/')
  })

  group.test('respond to /store/', function (t) {
    checkRequestForPath(t, '/hoodie/store/')
  })

  group.test('respond to /hoodie/unkown', function (t) {
    server.inject({
      url: 'http://localhost:8090/hoodie/unkown',
      headers: {
        accept: 'text/html'
      }
    }, function (response) {
      t.is(response.statusCode, 404, 'statusCode is 404')

      server.stop(t.end)
    })
  })

  function checkRequestForPath (t, path) {
    server.inject({
      url: 'http://localhost:8090' + path,
      headers: {
        accept: 'text/html'
      }
    }, function (response) {
      t.is(response.statusCode, 200, 'statusCode is 200')
      t.match(response.payload, /<html/, 'response is HTML')

      t.end()
    })
  }

  group.end()
})
<|endoftext|>


<commit_before>var expect = require('chai').expect,
    sinon = require('sinon');

describe.only('different case url', function() {
    var testrun;
    describe('lowercase', function() {
        before(function(done) {
            this.run({
                collection: {
                    item: [{
                        request: {
                            url: 'http://postman-echo.com/post',
                            method: 'POST'
                        }
                    }]
                }
            }, function(err, result) {
                testrun = result;
                done(err);
            });
        });

        it('should process request when url is in lowercase', function() {
            sinon.assert.calledOnce(testrun.start);
            sinon.assert.calledOnce(testrun.done);
            sinon.assert.calledWith(testrun.done.getCall(0), null);
            sinon.assert.calledOnce(testrun.request);
            sinon.assert.calledWith(testrun.request.getCall(0), null);
            sinon.assert.calledOnce(testrun.response);
            sinon.assert.calledWith(testrun.response.getCall(0), null);

            expect(testrun.response.getCall(0).args[2]).to.have.property('code', 200);
            expect(testrun.response.getCall(0).args[2].stream.toString()).to.include('https://postman-echo.com/post');
        });
    });

    describe('uppercase', function() {
        before(function(done) {
            this.run({
                collection: {
                    item: [{
                        request: {
                            url: 'HTTP://POSTMAN-ECHO.COM/POST',
                            method: 'POST'
                        }
                    }]
                }
            }, function(err, result) {
                testrun = result;
                done(err);
            });
        });

        it('should process request when url is in uppercase', function() {
            sinon.assert.calledOnce(testrun.start);
            sinon.assert.calledOnce(testrun.done);
            sinon.assert.calledWith(testrun.done.getCall(0), null);
            sinon.assert.calledOnce(testrun.request);
            sinon.assert.calledWith(testrun.request.getCall(0), null);
            sinon.assert.calledOnce(testrun.response);
            sinon.assert.calledWith(testrun.response.getCall(0), null);

            expect(testrun.response.getCall(0).args[2]).to.have.property('code', 200);
            expect(testrun.response.getCall(0).args[2].stream.toString()).to.include('https://postman-echo.com/POST');
        });
    });

    describe('mixed Case', function() {
        before(function(done) {
            this.run({
                collection: {
                    item: [{
                        request: {
                            url: 'HtTp://POSTMAN-ECHO.COM/POST',
                            method: 'POST'
                        }
                    }]
                }
            }, function(err, result) {
                testrun = result;
                done(err);
            });
        });

        it('should process request when url is in mixed case', function() {
            sinon.assert.calledOnce(testrun.start);
            sinon.assert.calledOnce(testrun.done);
            sinon.assert.calledWith(testrun.done.getCall(0), null);
            sinon.assert.calledWith(testrun.done.getCall(0), null);
            sinon.assert.calledOnce(testrun.request);
            sinon.assert.calledWith(testrun.request.getCall(0), null);
            sinon.assert.calledOnce(testrun.response);
            sinon.assert.calledWith(testrun.response.getCall(0), null);

            expect(testrun.response.getCall(0).args[2]).to.have.property('code', 200);
            expect(testrun.response.getCall(0).args[2].stream.toString()).to.include('https://postman-echo.com/POST');

        });
    });

    describe('mixed Case with https', function() {
        before(function(done) {
            this.run({
                collection: {
                    item: [{
                        request: {
                            url: 'HtTpS://POsTMaN-ecHo.cOm/PosT',
                            method: 'POST'
                        }
                    }]
                }
            }, function(err, result) {
                testrun = result;
                done(err);
            });
        });

        it('should process https request when url is in mixed case : HtTpS://...', function() {
            sinon.assert.calledOnce(testrun.start);
            sinon.assert.calledOnce(testrun.done);
            sinon.assert.calledWith(testrun.done.getCall(0), null);
            sinon.assert.calledWith(testrun.done.getCall(0), null);
            sinon.assert.calledOnce(testrun.request);
            sinon.assert.calledWith(testrun.request.getCall(0), null);
            sinon.assert.calledOnce(testrun.response);
            sinon.assert.calledWith(testrun.response.getCall(0), null);

            expect(testrun.response.getCall(0).args[2]).to.have.property('code', 200);
            expect(testrun.response.getCall(0).args[2].stream.toString()).to.include('https://postman-echo.com/PosT');

        });
    });

});
<commit_msg>Remove only from describe block<commit_after>var expect = require('chai').expect,
    sinon = require('sinon');

describe('different case url', function() {
    var testrun;
    describe('lowercase', function() {
        before(function(done) {
            this.run({
                collection: {
                    item: [{
                        request: {
                            url: 'http://postman-echo.com/post',
                            method: 'POST'
                        }
                    }]
                }
            }, function(err, result) {
                testrun = result;
                done(err);
            });
        });

        it('should process request when url is in lowercase', function() {
            sinon.assert.calledOnce(testrun.start);
            sinon.assert.calledOnce(testrun.done);
            sinon.assert.calledWith(testrun.done.getCall(0), null);
            sinon.assert.calledOnce(testrun.request);
            sinon.assert.calledWith(testrun.request.getCall(0), null);
            sinon.assert.calledOnce(testrun.response);
            sinon.assert.calledWith(testrun.response.getCall(0), null);

            expect(testrun.response.getCall(0).args[2]).to.have.property('code', 200);
            expect(testrun.response.getCall(0).args[2].stream.toString()).to.include('https://postman-echo.com/post');
        });
    });

    describe('uppercase', function() {
        before(function(done) {
            this.run({
                collection: {
                    item: [{
                        request: {
                            url: 'HTTP://POSTMAN-ECHO.COM/POST',
                            method: 'POST'
                        }
                    }]
                }
            }, function(err, result) {
                testrun = result;
                done(err);
            });
        });

        it('should process request when url is in uppercase', function() {
            sinon.assert.calledOnce(testrun.start);
            sinon.assert.calledOnce(testrun.done);
            sinon.assert.calledWith(testrun.done.getCall(0), null);
            sinon.assert.calledOnce(testrun.request);
            sinon.assert.calledWith(testrun.request.getCall(0), null);
            sinon.assert.calledOnce(testrun.response);
            sinon.assert.calledWith(testrun.response.getCall(0), null);

            expect(testrun.response.getCall(0).args[2]).to.have.property('code', 200);
            expect(testrun.response.getCall(0).args[2].stream.toString()).to.include('https://postman-echo.com/POST');
        });
    });

    describe('mixed Case', function() {
        before(function(done) {
            this.run({
                collection: {
                    item: [{
                        request: {
                            url: 'HtTp://POSTMAN-ECHO.COM/POST',
                            method: 'POST'
                        }
                    }]
                }
            }, function(err, result) {
                testrun = result;
                done(err);
            });
        });

        it('should process request when url is in mixed case', function() {
            sinon.assert.calledOnce(testrun.start);
            sinon.assert.calledOnce(testrun.done);
            sinon.assert.calledWith(testrun.done.getCall(0), null);
            sinon.assert.calledWith(testrun.done.getCall(0), null);
            sinon.assert.calledOnce(testrun.request);
            sinon.assert.calledWith(testrun.request.getCall(0), null);
            sinon.assert.calledOnce(testrun.response);
            sinon.assert.calledWith(testrun.response.getCall(0), null);

            expect(testrun.response.getCall(0).args[2]).to.have.property('code', 200);
            expect(testrun.response.getCall(0).args[2].stream.toString()).to.include('https://postman-echo.com/POST');

        });
    });

    describe('mixed Case with https', function() {
        before(function(done) {
            this.run({
                collection: {
                    item: [{
                        request: {
                            url: 'HtTpS://POsTMaN-ecHo.cOm/PosT',
                            method: 'POST'
                        }
                    }]
                }
            }, function(err, result) {
                testrun = result;
                done(err);
            });
        });

        it('should process https request when url is in mixed case : HtTpS://...', function() {
            sinon.assert.calledOnce(testrun.start);
            sinon.assert.calledOnce(testrun.done);
            sinon.assert.calledWith(testrun.done.getCall(0), null);
            sinon.assert.calledWith(testrun.done.getCall(0), null);
            sinon.assert.calledOnce(testrun.request);
            sinon.assert.calledWith(testrun.request.getCall(0), null);
            sinon.assert.calledOnce(testrun.response);
            sinon.assert.calledWith(testrun.response.getCall(0), null);

            expect(testrun.response.getCall(0).args[2]).to.have.property('code', 200);
            expect(testrun.response.getCall(0).args[2].stream.toString()).to.include('https://postman-echo.com/PosT');

        });
    });

});
<|endoftext|>


<commit_before>const E2eHelpers = require('../e2e/e2e-helpers');
const Timeouts = require('../e2e/timeouts.js');
const GibsHelpers = require('../e2e/post-911-gib-status-helpers.js');
const LoginHelpers = require('../e2e/login-helpers');

module.exports = E2eHelpers.createE2eTest(
  (client) => {
    const token = LoginHelpers.getUserToken();

    GibsHelpers.initApplicationMock(token);

    // Ensure main status page renders.
    LoginHelpers.logIn(token, client, '/education/gi-bill/post-9-11/ch-33-benefit', 3)
      .waitForElementVisible('body', Timeouts.normal)
      .axeCheck('.main')
      .assert.title('Check Benefit: Vets.gov')
      .waitForElementVisible('.schemaform-title', Timeouts.slow);  // First render of React may be slow.

    // Checking field in UserInfoSection has rendered
    client.expect.element('#fullName').text.to.contain('First Last');

    // Checking field in EnrollmentHistory has rendered
    client.expect.element('#enrollment-0 h4').text.to.contain('11/01/2012 to 12/01/2012 at Purdue University');

    // Click on print page
    client
      .click('#print-button')
      .window_handles((result) => {
        const newWindow = result.value[1];
        client.switchWindow(newWindow);
      });

    // Ensure print page renders.
    // We need to log in again here because Electron loses the session
    // when opening a new window.
    LoginHelpers.logIn(token, client, '/education/gi-bill/post-9-11/ch-33-benefit/print', 3)
      .waitForElementVisible('body', Timeouts.normal)
      .axeCheck('.main')
      .assert.title('Check Benefit: Vets.gov')
      .waitForElementVisible('.print-status', Timeouts.slow);  // First render of React may be slow.

    client.expect.element('.section-header').text.to.contain('Post-9/11 GI Bill Benefit Information');

    client.axeCheck('.main');

    client.end();
  }
);
<commit_msg>Try moving entire block into window_handles<commit_after>const E2eHelpers = require('../e2e/e2e-helpers');
const Timeouts = require('../e2e/timeouts.js');
const GibsHelpers = require('../e2e/post-911-gib-status-helpers.js');
const LoginHelpers = require('../e2e/login-helpers');

module.exports = E2eHelpers.createE2eTest(
  (client) => {
    const token = LoginHelpers.getUserToken();

    GibsHelpers.initApplicationMock(token);

    // Ensure main status page renders.
    LoginHelpers.logIn(token, client, '/education/gi-bill/post-9-11/ch-33-benefit', 3)
      .waitForElementVisible('body', Timeouts.normal)
      .axeCheck('.main')
      .assert.title('Check Benefit: Vets.gov')
      .waitForElementVisible('.schemaform-title', Timeouts.slow);  // First render of React may be slow.

    // Checking field in UserInfoSection has rendered
    client.expect.element('#fullName').text.to.contain('First Last');

    // Checking field in EnrollmentHistory has rendered
    client.expect.element('#enrollment-0 h4').text.to.contain('11/01/2012 to 12/01/2012 at Purdue University');

    // Click on print page
    client
      .click('#print-button')
      .window_handles((result) => {
        const newWindow = result.value[1];
        client.switchWindow(newWindow);

        // Ensure print page renders.
        // We need to log in again here because Electron loses the session
        // when opening a new window.
        LoginHelpers.logIn(token, client, '/education/gi-bill/post-9-11/ch-33-benefit/print', 3)
          .waitForElementVisible('body', Timeouts.normal)
          .axeCheck('.main')
          .assert.title('Check Benefit: Vets.gov')
          .waitForElementVisible('.print-status', Timeouts.slow);  // First render of React may be slow.

        client.expect.element('.section-header').text.to.contain('Post-9/11 GI Bill Benefit Information');
      });

    client.axeCheck('.main');

    client.end();
  }
);
<|endoftext|>


<commit_before>var $ = require('jquery');
var createVis = require('../../../../src/api/create-vis');
var scenarios = require('./scenarios');

describe('create-vis-new', function () {
  beforeEach(function () {
    this.container = $('
').css('height', '200px');
    this.containerId = this.container[0].id;
    $('body').append(this.container);
  });

  afterEach(function () {
    this.container.remove();
  });

  describe('CreateVis', function () {
    it('should set the right map center', function () {
      var visJson = scenarios.load(0);
      var vis = createVis(this.containerId, visJson);
      expect(vis.map.get('center')).toEqual(visJson.center);
    });
  });
});
<commit_msg>Add visModel basic tests (skip failing ones)<commit_after>var $ = require('jquery');
var createVis = require('../../../../src/api/create-vis');
var scenarios = require('./scenarios');

describe('create-vis-new:', function () {
  beforeEach(function () {
    this.container = $('
').css('height', '200px');
    this.containerId = this.container[0].id;
    $('body').append(this.container);
  });

  afterEach(function () {
    this.container.remove();
  });

  describe('CreateVis', function () {
    it('should set the right map center', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.map.get('center')).toEqual(visJson.center);
    });
    it('should initialize the right title', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('title')).toEqual(visJson.title);
    });
    it('should initialize the right description', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('description')).toEqual(visJson.description);
    });
    it('should initialize the right protocol', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('https')).toEqual(false);
    });
    it('should not have interactive features by default', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('interactiveFeatures')).toEqual(false);
    });
    it('should not have interactive features by default', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('interactiveFeatures')).toEqual(false);
    });
    xit('should not have "tiles_loader" by default', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('tiles_loader')).toEqual(false);
    });
    xit('should not have "loaderControl" by default', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('loaderControl')).toEqual(false);
    });
    xit('should have "infowindow" by default', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('infowindow')).toEqual(true);
    });
    xit('should have "tooltip" by default', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('tooltip')).toEqual(true);
    });
    xit('should have "logo" by default', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('logo')).toEqual(true);
    });
    xit('should have "show_empty_infowindow_fields" by default', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('show_empty_infowindow_fields')).toEqual(true);
    });
    xit('should have legends', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('showLegends')).toEqual(true);
    });
    xit('should show layer selector', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('showLayerSelector')).toEqual(true);
    });
    xit('should allow scrollwheel', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('scrollwheel')).toEqual(true);
    });
    xit('should have dashboard_menu', function () {
      var visJson = scenarios.load(0);
      var visModel = createVis(this.containerId, visJson);
      expect(visModel.get('dashboard_menu')).toEqual(true);
    });
  });
});
<|endoftext|>


<commit_before>exports['Should Correctly group using replicaset'] = function(configuration, test) {
  var mongo = configuration.getMongoPackage()
    ReadPreference = mongo.ReadPreference;

  var db = configuration.db();
  var collection = db.collection('testgroup_replicaset', {
        readPreference: ReadPreference.SECONDARY
      , w:2, wtimeout: 10000
    });

  collection.insert([{key:1,x:10}, {key:2,x:30}, {key:1,x:20}, {key:3,x:20}], {safe:{w:3, wtimeout:10000}}, function(err, result) {
    // Kill the primary
    configuration.killPrimary(function(node) {
      // Do a collection find
      collection.group(['key'], {}, {sum:0}, function reduce(record, memo){
        memo.sum += record.x;
      }, true, function(err, items){
        test.equal(null, err);
        test.equal(3, items.length);
        test.done();
      })
    });
  });
}

exports['Should fail to do map reduce to out collection'] = function(configuration, test) {
  var mongo = configuration.getMongoPackage()
    ReadPreference = mongo.ReadPreference;

  var db = configuration.db();
  var collection = db.collection('test_map_reduce_functions_notInline_map_reduce', {
        readPreference: ReadPreference.SECONDARY
      , w:2, wtimeout: 10000
    });

  // Parse version of server if available
  db.admin().serverInfo(function(err, result){

    // Only run if the MongoDB version is higher than 1.7.6
    if(parseInt((result.version.replace(/\./g, ''))) >= 176) {
      // Map function
      var map = function() { emit(this.user_id, 1); };
      // Reduce function
      var reduce = function(k,vals) { return 1; };

      try {
        // Execute map reduce and return results inline
        collection.mapReduce(map, reduce
          , {out : {replace:'replacethiscollection'}, readPreference:ReadPreference.SECONDARY}, function(err, results) {
        });

        test.ok(false);
      } catch (err) {
        test.done();
      }
    } else {
      test.done();
    }
  });
}

exports['Should correctly query secondaries'] = function(configuration, test) {
  var mongo = configuration.getMongoPackage()
    , ReplSetServers = mongo.ReplSetServers
    , Server = mongo.Server
    , Db = mongo.Db;

  // Replset start port
  var replicasetManager = configuration.getReplicasetManager();

  // Replica configuration
  var replSet = new ReplSetServers( [
      new Server(replicasetManager.host, replicasetManager.ports[0]),
    ],
    {rs_name:replicasetManager.name, read_secondary:true}
  );

  // Insert some data
  var db = new Db('integration_test_', replSet, {w:0});
  db.open(function(err, p_db) {

    var collection = db.collection('testsets', {w:3, wtimeout:10000});
    collection.insert([{a:20}, {a:30}, {a:40}], {safe:{w:3, wtimeout:10000}}, function(err, result) {
      // Kill the primary
      configuration.killPrimary(2, function(node) {

        collection.find().setReadPreference(ReadPreference.SECONDARY).toArray(function(err, items) {
          test.equal(null, err);
          test.equal(3, items.length);
          p_db.close();
          test.done();
        });
      });
    });
  });
}

exports['Should allow to force read with primary'] = function(configuration, test) {
  var mongo = configuration.getMongoPackage()
    ReadPreference = mongo.ReadPreference;

  var db = configuration.db();
  var collection = db.collection('shouldAllowToForceReadWithPrimary');

  // Insert a document
  collection.insert({a:1}, {w:2, wtimeout:10000}, function(err, result) {
    test.equal(null, err);

    // Force read using primary
    var cursor = collection.find({}, {readPreference: ReadPreference.PRIMARY});
    // Get documents
    cursor.toArray(function(err, items) {
      test.equal(1, items.length);
      test.equal(1, items[0].a);
      test.done();
    });
  });
}

/**
 * @ignore
 */
exports['Should correctly read from secondary even if primary is down'] = function(configuration, test) {
  var mongo = configuration.getMongoPackage()
    , ReadPreference = mongo.ReadPreference
    , ReplSetServers = mongo.ReplSetServers
    , Server = mongo.Server
    , Db = mongo.Db;

  // Replset start port
  var replicasetManager = configuration.getReplicasetManager();

  // Replica configuration
  var replSet = new ReplSetServers( [
      new Server(replicasetManager.host, replicasetManager.ports[0]),
      new Server(replicasetManager.host, replicasetManager.ports[1]),
      new Server(replicasetManager.host, replicasetManager.ports[2])
    ],
    {rs_name:replicasetManager.name, readPreference:ReadPreference.PRIMARY_PREFERRED}
  );

  new Db('integration_test_', replSet, {w:0}).open(function(err, p_db) {
    test.ok(err == null);
    test.equal(true, p_db.serverConfig.isConnected());

    var collection = p_db.collection('notempty');

    // Insert a document
    collection.insert({a:1}, {w:2, wtimeout:10000}, function(err, result) {

      // Run a simple query
      collection.findOne(function (err, doc) {
        test.ok(err == null);
        test.ok(1, doc.a);

        // Shut down primary server
        configuration.killPrimary(function (err, result) {
          test.ok(Object.keys(replSet._state.secondaries).length > 0);

          // Run a simple query
          collection.findOne(function (err, doc) {
            test.ok(Object.keys(replSet._state.secondaries).length > 0);
            test.equal(null, err);
            test.ok(doc != null);

            p_db.close();
            test.done();
          });
        });
      });
    });
  });
}

<commit_msg>Fixed broken test<commit_after>exports['Should Correctly group using replicaset'] = function(configuration, test) {
  var mongo = configuration.getMongoPackage()
    ReadPreference = mongo.ReadPreference;

  var db = configuration.db();
  var collection = db.collection('testgroup_replicaset', {
        readPreference: ReadPreference.SECONDARY
      , w:2, wtimeout: 10000
    });

  collection.insert([{key:1,x:10}, {key:2,x:30}, {key:1,x:20}, {key:3,x:20}], {safe:{w:3, wtimeout:10000}}, function(err, result) {
    // Kill the primary
    configuration.killPrimary(function(node) {
      // Do a collection find
      collection.group(['key'], {}, {sum:0}, function reduce(record, memo){
        memo.sum += record.x;
      }, true, function(err, items){
        test.equal(null, err);
        test.equal(3, items.length);
        test.done();
      })
    });
  });
}

exports['Should fail to do map reduce to out collection'] = function(configuration, test) {
  var mongo = configuration.getMongoPackage()
    ReadPreference = mongo.ReadPreference;

  var db = configuration.db();
  var collection = db.collection('test_map_reduce_functions_notInline_map_reduce', {
        readPreference: ReadPreference.SECONDARY
      , w:2, wtimeout: 10000
    });

  // Parse version of server if available
  db.admin().serverInfo(function(err, result){

    // Only run if the MongoDB version is higher than 1.7.6
    if(parseInt((result.version.replace(/\./g, ''))) >= 176) {
      // Map function
      var map = function() { emit(this.user_id, 1); };
      // Reduce function
      var reduce = function(k,vals) { return 1; };

      try {
        // Execute map reduce and return results inline
        collection.mapReduce(map, reduce
          , {out : {replace:'replacethiscollection'}, readPreference:ReadPreference.SECONDARY}, function(err, results) {
        });

        test.ok(false);
      } catch (err) {
        test.done();
      }
    } else {
      test.done();
    }
  });
}

exports['Should correctly query secondaries'] = function(configuration, test) {
  var mongo = configuration.getMongoPackage()
    , ReplSetServers = mongo.ReplSetServers
    , Server = mongo.Server
    , Db = mongo.Db;

  // Replset start port
  var replicasetManager = configuration.getReplicasetManager();

  // Replica configuration
  var replSet = new ReplSetServers( [
      new Server(replicasetManager.host, replicasetManager.ports[0]),
    ],
    {rs_name:replicasetManager.name, read_secondary:true}
  );

  // Insert some data
  var db = new Db('integration_test_', replSet, {w:0});
  db.open(function(err, p_db) {

    var collection = db.collection('testsets', {w:3, wtimeout:10000});
    collection.insert([{a:20}, {a:30}, {a:40}], {safe:{w:3, wtimeout:10000}}, function(err, result) {
      // Kill the primary
      configuration.killPrimary(2, function(node) {

        collection.find().setReadPreference(ReadPreference.SECONDARY).toArray(function(err, items) {
          test.equal(null, err);
          test.equal(3, items.length);
          p_db.close();
          test.done();
        });
      });
    });
  });
}

exports['Should allow to force read with primary'] = function(configuration, test) {
  var mongo = configuration.getMongoPackage()
    ReadPreference = mongo.ReadPreference;

  var db = configuration.db();
  var collection = db.collection('shouldAllowToForceReadWithPrimary');

  // Insert a document
  collection.insert({a:1}, {w:2, wtimeout:10000}, function(err, result) {
    test.equal(null, err);

    // Force read using primary
    var cursor = collection.find({}, {readPreference: ReadPreference.PRIMARY});
    // Get documents
    cursor.toArray(function(err, items) {
      test.equal(1, items.length);
      test.equal(1, items[0].a);
      test.done();
    });
  });
}

/**
 * @ignore
 */
exports['Should correctly read from secondary even if primary is down'] = function(configuration, test) {
  var mongo = configuration.getMongoPackage()
    , ReadPreference = mongo.ReadPreference
    , ReplSetServers = mongo.ReplSetServers
    , Server = mongo.Server
    , Db = mongo.Db;

  // Replset start port
  var replicasetManager = configuration.getReplicasetManager();

  // Replica configuration
  var replSet = new ReplSetServers( [
      new Server(replicasetManager.host, replicasetManager.ports[0]),
      new Server(replicasetManager.host, replicasetManager.ports[1]),
      new Server(replicasetManager.host, replicasetManager.ports[2])
    ],
    {rs_name:replicasetManager.name, readPreference:ReadPreference.PRIMARY_PREFERRED}
  );

  new Db('integration_test_', replSet, {w:0}).open(function(err, p_db) {
    test.ok(err == null);
    test.equal(true, p_db.serverConfig.isConnected());

    var collection = p_db.collection('notempty');

    // Insert a document
    collection.insert({a:1}, {w:2, wtimeout:10000}, function(err, result) {

      // Run a simple query
      collection.findOne(function (err, doc) {
        // console.log("======================================== 0")
        // console.dir(err)
        // console.dir(doc)
        test.ok(err == null);
        test.ok(1, doc.a);

        // Shut down primary server
        configuration.killPrimary(function (err, result) {
          test.ok(Object.keys(replSet._state.secondaries).length > 0);

          // Run a simple query
          collection.findOne(function (err, doc) {
            // console.log("======================================== 1")
            // console.dir(err)
            // console.dir(doc)

            test.ok(Object.keys(replSet._state.secondaries).length > 0);
            test.equal(null, err);
            test.ok(doc != null);

            p_db.close();
            test.done();
          });
        });
      });
    });
  });
}

<|endoftext|>


<commit_before>import Vue from 'vue'
import { patch } from 'web/runtime/patch'
import VNode from 'core/vdom/vnode'

describe('hydration', () => {
  let vnode0
  beforeEach(() => {
    vnode0 = new VNode('p', { attrs: { id: '1' }}, [createTextVNode('hello world')])
    patch(null, vnode0)
  })

  it('should hydrate elements when server-rendered DOM tree is same as virtual DOM tree', () => {
    const result = []
    function init (vnode) { result.push(vnode) }
    function createServerRenderedDOM () {
      const root = document.createElement('div')
      root.setAttribute('server-rendered', 'true')
      const span = document.createElement('span')
      root.appendChild(span)
      const div = document.createElement('div')
      const child1 = document.createElement('span')
      const child2 = document.createElement('span')
      child1.textContent = 'hi'
      child2.textContent = 'ho'
      div.appendChild(child1)
      div.appendChild(child2)
      root.appendChild(div)
      return root
    }
    const node0 = createServerRenderedDOM()
    const vnode1 = new VNode('div', {}, [
      new VNode('span', {}),
      new VNode('div', { hook: { init }}, [
        new VNode('span', {}, [new VNode(undefined, undefined, undefined, 'hi')]),
        new VNode('span', {}, [new VNode(undefined, undefined, undefined, 'ho')])
      ])
    ])
    patch(node0, vnode1)
    expect(result.length).toBe(1)

    function traverseAndAssert (vnode, element) {
      expect(vnode.elm).toBe(element)
      if (vnode.children) {
        vnode.children.forEach((node, i) => {
          traverseAndAssert(node, element.childNodes[i])
        })
      }
    }
    // ensure vnodes are correctly associated with actual DOM
    traverseAndAssert(vnode1, node0)

    // check update
    const vnode2 = new VNode('div', { props: { id: 'foo' }}, [
      new VNode('span', { props: { id: 'bar' }}),
      new VNode('div', { hook: { init }}, [
        new VNode('span', {}),
        new VNode('span', {})
      ])
    ])
    patch(vnode1, vnode2)
    expect(node0.id).toBe('foo')
    expect(node0.children[0].id).toBe('bar')
  })

  it('should warn message that virtual DOM tree is not matching when hydrate element', () => {
    function createServerRenderedDOM () {
      const root = document.createElement('div')
      root.setAttribute('server-rendered', 'true')
      const span = document.createElement('span')
      root.appendChild(span)
      const div = document.createElement('div')
      const child1 = document.createElement('span')
      div.appendChild(child1)
      root.appendChild(div)
      return root
    }
    const node0 = createServerRenderedDOM()
    const vnode1 = new VNode('div', {}, [
      new VNode('span', {}),
      new VNode('div', {}, [
        new VNode('span', {}),
        new VNode('span', {})
      ])
    ])
    patch(node0, vnode1)
    expect('The client-side rendered virtual DOM tree is not matching').toHaveBeenWarned()
  })

  // component hydration is better off with a more e2e approach
  it('should hydrate components when server-rendered DOM tree is same as virtual DOM tree', done => {
    const dom = document.createElement('div')
    dom.setAttribute('server-rendered', 'true')
    dom.innerHTML = 'foo
foo qux
'
    const originalNode1 = dom.children[0]
    const originalNode2 = dom.children[1]

    const vm = new Vue({
      template: '
{{msg}}<test class="a" :msg="msg"></test>
',
      data: {
        msg: 'foo'
      },
      components: {
        test: {
          props: ['msg'],
          data () {
            return { a: 'qux' }
          },
          template: '
{{msg}} {{a}}
'
        }
      }
    })

    expect(() => { vm.$mount(dom) }).not.toThrow()
    expect('not matching server-rendered content').not.toHaveBeenWarned()
    expect(vm.$el).toBe(dom)
    expect(vm.$children[0].$el).toBe(originalNode2)
    expect(vm.$el.children[0]).toBe(originalNode1)
    expect(vm.$el.children[1]).toBe(originalNode2)
    vm.msg = 'bar'
    waitForUpdate(() => {
      expect(vm.$el.innerHTML).toBe('bar
bar qux
')
      vm.$children[0].a = 'ququx'
    }).then(() => {
      expect(vm.$el.innerHTML).toBe('bar
bar ququx
')
    }).then(done)
  })

  it('should warn failed hydration for non-matching DOM in child component', () => {
    const dom = document.createElement('div')
    dom.setAttribute('server-rendered', 'true')
    dom.innerHTML = '
foo
'

    const vm = new Vue({
      template: '
<test :msg="msg"></test>
',
      components: {
        test: {
          data () {
            return { a: 'qux' }
          },
          template: '
{{a}}
'
        }
      }
    })

    vm.$mount(dom)
    expect('not matching server-rendered content').toHaveBeenWarned()
  })
})
<commit_msg>fix hydration warning test in phantomjs<commit_after>import Vue from 'vue'
import { patch } from 'web/runtime/patch'
import VNode from 'core/vdom/vnode'

describe('hydration', () => {
  let vnode0
  beforeEach(() => {
    vnode0 = new VNode('p', { attrs: { id: '1' }}, [createTextVNode('hello world')])
    patch(null, vnode0)
  })

  it('should hydrate elements when server-rendered DOM tree is same as virtual DOM tree', () => {
    const result = []
    function init (vnode) { result.push(vnode) }
    function createServerRenderedDOM () {
      const root = document.createElement('div')
      root.setAttribute('server-rendered', 'true')
      const span = document.createElement('span')
      root.appendChild(span)
      const div = document.createElement('div')
      const child1 = document.createElement('span')
      const child2 = document.createElement('span')
      child1.textContent = 'hi'
      child2.textContent = 'ho'
      div.appendChild(child1)
      div.appendChild(child2)
      root.appendChild(div)
      return root
    }
    const node0 = createServerRenderedDOM()
    const vnode1 = new VNode('div', {}, [
      new VNode('span', {}),
      new VNode('div', { hook: { init }}, [
        new VNode('span', {}, [new VNode(undefined, undefined, undefined, 'hi')]),
        new VNode('span', {}, [new VNode(undefined, undefined, undefined, 'ho')])
      ])
    ])
    patch(node0, vnode1)
    expect(result.length).toBe(1)

    function traverseAndAssert (vnode, element) {
      expect(vnode.elm).toBe(element)
      if (vnode.children) {
        vnode.children.forEach((node, i) => {
          traverseAndAssert(node, element.childNodes[i])
        })
      }
    }
    // ensure vnodes are correctly associated with actual DOM
    traverseAndAssert(vnode1, node0)

    // check update
    const vnode2 = new VNode('div', { props: { id: 'foo' }}, [
      new VNode('span', { props: { id: 'bar' }}),
      new VNode('div', { hook: { init }}, [
        new VNode('span', {}),
        new VNode('span', {})
      ])
    ])
    patch(vnode1, vnode2)
    expect(node0.id).toBe('foo')
    expect(node0.children[0].id).toBe('bar')
  })

  it('should warn message that virtual DOM tree is not matching when hydrate element', () => {
    function createServerRenderedDOM () {
      const root = document.createElement('div')
      root.setAttribute('server-rendered', 'true')
      const span = document.createElement('span')
      root.appendChild(span)
      const div = document.createElement('div')
      const child1 = document.createElement('span')
      div.appendChild(child1)
      root.appendChild(div)
      return root
    }
    const node0 = createServerRenderedDOM()
    const vnode1 = new VNode('div', {}, [
      new VNode('span', {}),
      new VNode('div', {}, [
        new VNode('span', {}),
        new VNode('span', {})
      ])
    ])
    patch(node0, vnode1)
    expect('The client-side rendered virtual DOM tree is not matching').toHaveBeenWarned()
  })

  // component hydration is better off with a more e2e approach
  it('should hydrate components when server-rendered DOM tree is same as virtual DOM tree', done => {
    const dom = document.createElement('div')
    dom.setAttribute('server-rendered', 'true')
    dom.innerHTML = 'foo
foo qux
'
    const originalNode1 = dom.children[0]
    const originalNode2 = dom.children[1]

    const vm = new Vue({
      template: '
{{msg}}<test class="a" :msg="msg"></test>
',
      data: {
        msg: 'foo'
      },
      components: {
        test: {
          props: ['msg'],
          data () {
            return { a: 'qux' }
          },
          template: '
{{msg}} {{a}}
'
        }
      }
    })

    expect(() => { vm.$mount(dom) }).not.toThrow()
    expect('not matching server-rendered content').not.toHaveBeenWarned()
    expect(vm.$el).toBe(dom)
    expect(vm.$children[0].$el).toBe(originalNode2)
    expect(vm.$el.children[0]).toBe(originalNode1)
    expect(vm.$el.children[1]).toBe(originalNode2)
    vm.msg = 'bar'
    waitForUpdate(() => {
      expect(vm.$el.innerHTML).toBe('bar
bar qux
')
      vm.$children[0].a = 'ququx'
    }).then(() => {
      expect(vm.$el.innerHTML).toBe('bar
bar ququx
')
    }).then(done)
  })

  it('should warn failed hydration for non-matching DOM in child component', () => {
    const dom = document.createElement('div')
    dom.setAttribute('server-rendered', 'true')
    dom.innerHTML = '
foo
'

    const vm = new Vue({
      template: '
<test></test>
',
      components: {
        test: {
          data () {
            return { a: 'qux' }
          },
          template: '
{{a}}
'
        }
      }
    })

    vm.$mount(dom)
    expect('not matching server-rendered content').toHaveBeenWarned()
  })
})
<|endoftext|>


<commit_before>describe('Gist', function() {
    before(function(done) {
        setTimeout(function() {
            done();
        }, 1000);
    });

    beforeEach(function() {
        gists = document.getElementsByClassName('gist-file');
    });

    it('are loaded', function() {
        expect(gists.length).to.equal(3);
    });

    context('when language is supported', function() {
        beforeEach(function() {
            gist = gists[0];
        });

        ['run', 'flush'].forEach(function(name) {
            expectToHaveButton(name);
        });

        it('has a link to grounds.io', function() {
            var link = getGroundsLink();

            expect(link.href).to.equal('http://beta.42grounds.io/');
        });

        expectToHaveEmptyConsole();

        context('after clicking run button', function() {
            beforeEach(function(done){
                getElement('run').click();
                setTimeout(function() {
                    done();
                }, 1000);
            });

            it('has output on console', function() {
                var output = [
                    'hello javascript!',
                    '[Program exited with status: 0]',
                ].join('\n');

                expect(consoleHasOutput(output)).to.be.true;
            });

            context('after clicking flush button', function() {
                beforeEach(function(done){
                    getElement('flush').click();
                    setTimeout(function() {
                        done();
                    }, 1000);
                });

                expectToHaveEmptyConsole();
            });
        });

        function expectToHaveButton(name) {
            it('has a '+name+' button', function() {
                expect(getElement(name)).not.to.be.undefined;
            });
        }

        function expectToHaveEmptyConsole() {
            it('has an empty console', function() {
                expect(consoleHasOutput('')).to.be.true;
            });
        }
    });

    context('when language is not supported', function() {
        beforeEach(function() {
            gist = gists[2];
        });

        ['run', 'flush'].forEach(function(name) {
            expectNotToHaveButton(name);
        });

        it('has no link to grounds.io', function() {
            expect(getGroundsLink).to.throw(TypeError);
        });

        function expectNotToHaveButton(name) {
            it('has no '+name+' button', function() {
                expect(getElement(name)).to.be.undefined;
            });
        }
    });

    function consoleHasOutput(output) {
        return getElement('console').textContent === output;
    }

    function getElement(name) {
        return gist.getElementsByClassName(name)[0];
    }

    function getGroundsLink() {
        return gist.getElementsByClassName('gist-meta')[1]
                   .getElementsByTagName('a')[0];
    }
});
<commit_msg>add better message for tests<commit_after>describe('Each gist file', function() {
    before(function(done) {
        setTimeout(function() {
            done();
        }, 1000);
    });

    beforeEach(function() {
        gists = document.getElementsByClassName('gist-file');
    });

    it('is loaded', function() {
        expect(gists.length).to.equal(3);
    });

    context('when language is supported', function() {
        beforeEach(function() {
            gist = gists[0];
        });

        ['run', 'flush'].forEach(function(name) {
            expectToHaveButton(name);
        });

        it('has a link to grounds.io', function() {
            var link = getGroundsLink();

            expect(link.href).to.equal('http://beta.42grounds.io/');
        });

        expectToHaveEmptyConsole();

        context('after clicking run button', function() {
            beforeEach(function(done){
                getElement('run').click();
                setTimeout(function() {
                    done();
                }, 1000);
            });

            it('has proper output on console', function() {
                var output = [
                    'hello javascript!',
                    '[Program exited with status: 0]',
                ].join('\n');

                expect(consoleHasOutput(output)).to.be.true;
            });

            context('after clicking flush button', function() {
                beforeEach(function(done){
                    getElement('flush').click();
                    setTimeout(function() {
                        done();
                    }, 1000);
                });

                expectToHaveEmptyConsole();
            });
        });

        function expectToHaveButton(name) {
            it('has a '+name+' button', function() {
                expect(getElement(name)).not.to.be.undefined;
            });
        }

        function expectToHaveEmptyConsole() {
            it('has an empty console', function() {
                expect(consoleHasOutput('')).to.be.true;
            });
        }
    });

    context('when language is not supported', function() {
        beforeEach(function() {
            gist = gists[2];
        });

        ['run', 'flush'].forEach(function(name) {
            expectNotToHaveButton(name);
        });

        it('has no link to grounds.io', function() {
            expect(getGroundsLink).to.throw(TypeError);
        });

        function expectNotToHaveButton(name) {
            it('has no '+name+' button', function() {
                expect(getElement(name)).to.be.undefined;
            });
        }
    });

    function consoleHasOutput(output) {
        return getElement('console').textContent === output;
    }

    function getElement(name) {
        return gist.getElementsByClassName(name)[0];
    }

    function getGroundsLink() {
        return gist.getElementsByClassName('gist-meta')[1]
                   .getElementsByTagName('a')[0];
    }
});
<|endoftext|>


<commit_before>/**
 *  This program 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 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 Library General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * The class that handles the logging.
 * Copyright (C) 2010 Simon Newton
 */

goog.require('goog.debug.DivConsole');
goog.require('goog.debug.LogManager');
goog.require('goog.debug.Logger');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.math');
goog.require('goog.positioning.Corner');
goog.require('goog.ui.Control');
goog.require('goog.ui.Popup');

goog.provide('ola.LoggerWindow');

var ola = ola || {}
ola.logger = goog.debug.Logger.getLogger('ola');

/**
 * Setup the logger window
 * @constructor
 */
ola.LoggerWindow = function() {
  goog.debug.LogManager.getRoot().setLevel(goog.debug.Logger.Level.ALL);
  var logconsole = new goog.debug.DivConsole(goog.dom.$('log'));
  logconsole.setCapturing(true);

  this.log_control = goog.dom.$('log_control');

  var control = new goog.ui.Control("log_control");
  control.decorate(this.log_control);
  goog.events.listen(this.log_control, goog.events.EventType.CLICK,
                     this.Show, false, this);

  var popupElt = document.getElementById('log_popup');
  this.popup = new goog.ui.Popup(popupElt);
  this.popup.setHideOnEscape(true);
  this.popup.setAutoHide(true);
}

/**
 * Display the logger window
 */
ola.LoggerWindow.prototype.Show = function() {
  this.popup.setVisible(false);
  this.popup.setPinnedCorner(goog.positioning.Corner.TOP_RIGHT);
  var margin = new goog.math.Box(2, 2, 2, 2);
  this.popup.setMargin(margin);
  this.popup.setPosition(new goog.positioning.AnchoredViewportPosition(
    this.log_control,
    goog.positioning.Corner.BOTTOM_RIGHT));
  this.popup.setVisible(true);
}
<commit_msg> * clean up the logger a bit<commit_after>/**
 *  This program 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 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 Library General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * The class that handles the logging.
 * Copyright (C) 2010 Simon Newton
 */

goog.require('goog.debug.DivConsole');
goog.require('goog.debug.LogManager');
goog.require('goog.debug.Logger');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.math');
goog.require('goog.positioning.Corner');
goog.require('goog.ui.Control');
goog.require('goog.ui.Popup');

goog.provide('ola.LoggerWindow');

var ola = ola || {}
ola.logger = goog.debug.Logger.getLogger('ola');

/**
 * Setup the logger window
 * @constructor
 */
ola.LoggerWindow = function() {
  goog.debug.LogManager.getRoot().setLevel(goog.debug.Logger.Level.ALL);

  // setup the log console
  var log_console = new goog.debug.DivConsole(goog.dom.$('log'));
  log_console.setCapturing(true);

  // setup the control which shows the console
  this.log_control = goog.dom.$('log_control');
  var control = new goog.ui.Control();
  control.decorate(this.log_control);
  goog.events.listen(this.log_control, goog.events.EventType.CLICK,
                     this.Show, false, this);

  // setup the popup that the console is contained in
  var popupElt = document.getElementById('log_popup');
  this.popup = new goog.ui.Popup(popupElt);
  this.popup.setHideOnEscape(true);
  this.popup.setAutoHide(true);
}

/**
 * Display the logger window
 */
ola.LoggerWindow.prototype.Show = function() {
  this.popup.setVisible(false);
  this.popup.setPinnedCorner(goog.positioning.Corner.TOP_RIGHT);
  var margin = new goog.math.Box(2, 2, 2, 2);
  this.popup.setMargin(margin);
  this.popup.setPosition(new goog.positioning.AnchoredViewportPosition(
    this.log_control,
    goog.positioning.Corner.BOTTOM_RIGHT));
  this.popup.setVisible(true);
}
<|endoftext|>


<commit_before>"use strict";
/**
It usage process.env.NODE_ENV to show vesbose log.
*/
var winston = require('winston'),
	util = require('util'),
	fs = require("fs");
var customLevels = {
	levels: {
		debug: 0,
		info: 1,
		warn: 2,
		error: 3
	},
	colors: {
		debug: 'blue',
		info: 'green',
		warn: 'yellow',
		error: 'red'
	}
};
var logger = new(winston.Logger)({
	transports: [
		new(winston.transports.Console)({
			level: 'debug',
			levels: customLevels.levels,
			colorize: true
		})
	]
});

function line(args) {
	var parts = [
			(new Error()).stack.
		replace(/.*(Error|node_modules|logger|native).*\n/g, ''). // remove lines with these words
		replace(/\n[\s\S]*$/, ''). // take the first line
		replace(/^[\s\S]*?\/home\/scrollback\/autostage\//, ''). // relative path
		replace(/^.*\s+at\s*/, '').
		replace(/[\)\(]/g, '')
	],
		logLine;
	logLine = util.format.apply(util, args).replace(/\s+/g, ' ');
	parts.push(logLine);

	return parts.join(' ');
}

var log = function() {
	logger.info(line(arguments));
};

log.i = function() {
	logger.info(line(arguments));
};

log.e = function() {
	var l = line(arguments);
	logger.error(l);
};

log.w = function() {
	logger.warn(line(arguments));
};

log.d = function() {
	//	if(process.env.TRAVIS){
	//		return;
	//	}

};

module.exports = log;
<commit_msg>change the user name<commit_after>"use strict";
/**
It usage process.env.NODE_ENV to show vesbose log.
*/
var winston = require('winston'),
	util = require('util'),
	fs = require("fs");
var customLevels = {
	levels: {
		debug: 0,
		info: 1,
		warn: 2,
		error: 3
	},
	colors: {
		debug: 'blue',
		info: 'green',
		warn: 'yellow',
		error: 'red'
	}
};
var logger = new(winston.Logger)({
	transports: [
		new(winston.transports.Console)({
			level: 'debug',
			levels: customLevels.levels,
			colorize: true
		})
	]
});

function line(args) {
	var parts = [
			(new Error()).stack.
		replace(/.*(Error|node_modules|logger|native).*\n/g, ''). // remove lines with these words
		replace(/\n[\s\S]*$/, ''). // take the first line
		replace(/^[\s\S]*?\/home\/ubuntu\/autostage\//, ''). // relative path
		replace(/^.*\s+at\s*/, '').
		replace(/[\)\(]/g, '')
	],
		logLine;
	logLine = util.format.apply(util, args).replace(/\s+/g, ' ');
	parts.push(logLine);

	return parts.join(' ');
}

var log = function() {
	logger.info(line(arguments));
};

log.i = function() {
	logger.info(line(arguments));
};

log.e = function() {
	var l = line(arguments);
	logger.error(l);
};

log.w = function() {
	logger.warn(line(arguments));
};

log.d = function() {
	//	if(process.env.TRAVIS){
	//		return;
	//	}

};

module.exports = log;
<|endoftext|>


<commit_before><commit_msg>fixed tests relying on local phantomjs binary<commit_after><|endoftext|>


<commit_before>'use strict';
var plugin = [];
plugin.command = []; // extra commands
plugin.commandName = []; // extra commands
plugin.addToHelp = [];
plugin.gamemodeId = [];
plugin.gamemode = [];

plugin.name = "example plugin"; // Name of plugin where it would be listed in
plugin.author = "andrews54757"; // author
plugin.commandName[0] = "tptoplayer";
plugin.description = "An example plugin";
plugin.addToHelp[0] = "tptoplayer : tps to a player";
plugin.command[0] = require("./tptoplayer.js");
plugin.commandName[1] = "plugin";
plugin.addToHelp[1] = "plugin     : manage plugins";
plugin.command[1] = require("./plugin.js");
plugin.version = '1.0.0';
plugin.compatVersion = ''; // compatable with (todo)
plugin.gamemodeId[0] = 80;
plugin.gamemode[0] = require("./sffa.js");

plugin.init = function (gameServer) {
  // init, Used to do stuff such as overriding things

};
module.exports = plugin;

<commit_msg>Update index.js<commit_after>'use strict';
var plugin = [];
plugin.command = []; // extra commands
plugin.commandName = []; // extra commands
plugin.addToHelp = [];
plugin.gamemodeId = [];
plugin.gamemode = [];

plugin.name = "example plugin"; // Name of plugin where it would be listed in
plugin.author = "andrews54757"; // author
plugin.commandName[0] = "tptoplayer";
plugin.description = "An example plugin";
plugin.addToHelp[0] = "tptoplayer : tps to a player";
plugin.command[0] = require("./tptoplayer.js");
plugin.version = '1.0.0';
plugin.compatVersion = ''; // compatable with (todo)
plugin.gamemodeId[0] = 80;
plugin.gamemode[0] = require("./sffa.js");

plugin.init = function (gameServer) {
  // init, Used to do stuff such as overriding things

};
module.exports = plugin;

<|endoftext|>