<commit_before>(function() {
    'use strict';

    // Check we have sweet alert js included
    if (angular.isUndefined(window.swal)) {
        throw "Please make sure Sweet Alert 2 is included! https://github.com/limonte/sweetalert2";
    }

angular.module('swangular', [])
    .factory('swangular', ['$compile', '$http', '$rootScope', '$q', '$controller', '$injector', '$templateCache',
        function($compile, $http, $rootScope, $q, $controller, $injector, $templateCache) {

        /*
         *
         * Sweet Alert functions
         * The four functions below are just convenience methods
         *
         * ex. Swangular.alert("This is a warning message");
         *
         */
        function swal_alert(message, customOptions) {

            var options = angular.extend({
                title: "Alert",
                text: message,
                type: "warning",
                showCancelButton: false
            }, customOptions);

            return swal(options);

        }

        function swal_info(message, customOptions) {

            var options = angular.extend({
                title: "Info",
                text: message,
                type: "info",
                showCancelButton: false
            }, customOptions);

            return swal(options);

        }

        function swal_success(message, customOptions) {

            var options = angular.extend({
                title: "Success",
                text: message,
                type: "success",
                showCancelButton: false
            }, customOptions);

            return swal(options);

        }

        function swal_confirm(message, customOptions) {

            var options = angular.extend({
                title: "Alert",
                text: message,
                type: "warning"
            }, customOptions);

            return swal(options);

        }

        /*
         *
         * HTML Sweet Alert function
         * Use this for for passing html that will be compiled to Angular
         * You can pass an HTML string directly via 'html' option, or you can pass a link to template via 'templateHtml' option.
         *
         *  ex. Swangular.html({title: "Please fill in!",scope: $scope,templateHtml: '/templates/template.html'})
         *         .then(function() { console.log("Done"); })
         *
         */
        function swal_open(options){

            var resolve = angular.extend({}, options.resolve);

            angular.forEach(resolve, function (value, key) {
                resolve[key] = angular.isString(value) ? $injector.get(value) : $injector.invoke(value, null, null, key);
            });

            return $q.all({
                html: _getHtml(options),
                locals: $q.all(resolve)
            }).then(function(setup){

                var scope = options.scope,
                    controller = options.controller,
                    controllerAsOption = options.controllerAs,
                    preConfirm = options.preConfirm;

                delete options.html;
                delete options.htmlTemplate;
                delete options.resolve;
                delete options.scope;
                delete options.controller;
                delete options.controllerAs;
                delete options.preConfirm;

                var locals = setup.locals;

                options.html = setup.html;

                if (controller){

                  var controllerAs;
                    scope = scope ? scope.$new() : $rootScope.$new();

                  if (controllerAsOption && angular.isString(controllerAsOption)) {
                      controllerAs = controllerAsOption;
                  }

                  var controllerInstance = $controller(controller, angular.extend(
                      locals,
                      {
                          $scope: scope
                      }), false, controllerAs);

                  if (typeof preConfirm === 'string'){
                      options.preConfirm = function() { return scope.$apply(controllerInstance[preConfirm]) };
                  }
                }

                if (typeof preConfirm === 'function'){
                    options.preConfirm = function() { return scope.$apply(preConfirm) };
                }

                var prom = swal(options);
                var html = document.getElementsByClassName('swal2-modal')[0];

                $compile(html)(scope);

                return prom;

            });

        }

        function _getHtml(options){

            if(options.htmlTemplate) {
                return _getTemplate(options.htmlTemplate)
            } else {
               return options.html;
            }

        }

        function _getTemplate(tmpl) {
            return $http.get(tmpl, {cache: $templateCache}).then(function(res) {
                return res.data || '';
            });
        }

        /*
         *
         * Base Sweet Alert function
         * Use this for for a direct mapping to sweetalert,
         * by either passing an options object or by passing up to 3 string arguments
         *
         * ex. 1: Swangular.swal("Good job!", "You clicked the button!", "success")
         *
         * ex. 2: Swangular.swal({title: "Auto close alert!", text: "I will close in 2 seconds.", timer: 2000});
         *
         */
        function swal_base(arg1, arg2, arg3) {

            // In case of options
            if(arg1 !== null && typeof arg1 === 'object') {
                return swal(arg1)
            }

            // In case of: title, text, type
            else {
                return swal(arg1, arg2, arg3);
            }
        }

        /*
         * SweetAlert2 Global Methods
         */

        function close() {
            $rootScope.$evalAsync(function(){
                swal.close();
            });
        }

        function disableButtons() {
            $rootScope.$evalAsync(function(){
                swal.disableButtons();
            });
        }

        function enableButtons() {
            $rootScope.$evalAsync(function(){
                swal.enableButtons();
            });
        }

        function disableConfirmButton() {
            $rootScope.$evalAsync(function(){
                swal.disableConfirmButton();
            });
        }

        function enableConfirmButton() {
            $rootScope.$evalAsync(function(){
                swal.enableConfirmButton();
            });
        }

        function clickConfirm() {
            $rootScope.$evalAsync(function(){
                swal.clickConfirm();
            });
        }

        function clickCancel() {
            $rootScope.$evalAsync(function(){
                swal.showLoading();
            });
        }

        function showLoading() {
            $rootScope.$evalAsync(function(){
                swal.clickCancel();
            });
        }

        function hideLoading() {
            $rootScope.$evalAsync(function(){
                swal.hideLoading();
            });
        }

        function setDefaults(options) {
            $rootScope.$evalAsync(function(){
                swal.setDefaults(options);
            });
        }

        return {
            alert: swal_alert,
            confirm: swal_confirm,
            info: swal_info,
            success: swal_success,
            open: swal_open,
            swal: swal_base,
            closeModal: close,
            close: close,
            disableButtons: disableButtons,
            enableButtons: enableButtons,
            disableConfirmButton: disableConfirmButton,
            enableConfirmButton: enableConfirmButton,
            clickConfirm: clickConfirm,
            clickCancel: clickCancel,
            showLoading: showLoading,
            enableLoading: showLoading,
            hideLoading: hideLoading,
            disableLoading: hideLoading,
            setDefaults: setDefaults
        }

    }]);

})();
<commit_msg>Show cancel button on confirm modal<commit_after>(function() {
    'use strict';

    // Check we have sweet alert js included
    if (angular.isUndefined(window.swal)) {
        throw "Please make sure Sweet Alert 2 is included! https://github.com/limonte/sweetalert2";
    }

angular.module('swangular', [])
    .factory('swangular', ['$compile', '$http', '$rootScope', '$q', '$controller', '$injector', '$templateCache',
        function($compile, $http, $rootScope, $q, $controller, $injector, $templateCache) {

        /*
         *
         * Sweet Alert functions
         * The four functions below are just convenience methods
         *
         * ex. Swangular.alert("This is a warning message");
         *
         */
        function swal_alert(message, customOptions) {

            var options = angular.extend({
                title: "Alert",
                text: message,
                type: "warning",
                showCancelButton: false
            }, customOptions);

            return swal(options);

        }

        function swal_info(message, customOptions) {

            var options = angular.extend({
                title: "Info",
                text: message,
                type: "info",
                showCancelButton: false
            }, customOptions);

            return swal(options);

        }

        function swal_success(message, customOptions) {

            var options = angular.extend({
                title: "Success",
                text: message,
                type: "success",
                showCancelButton: false
            }, customOptions);

            return swal(options);

        }

        function swal_confirm(message, customOptions) {

            var options = angular.extend({
                title: "Alert",
                text: message,
                type: "warning",
                showCancelButton: true
            }, customOptions);

            return swal(options);

        }

        /*
         *
         * HTML Sweet Alert function
         * Use this for for passing html that will be compiled to Angular
         * You can pass an HTML string directly via 'html' option, or you can pass a link to template via 'templateHtml' option.
         *
         *  ex. Swangular.html({title: "Please fill in!",scope: $scope,templateHtml: '/templates/template.html'})
         *         .then(function() { console.log("Done"); })
         *
         */
        function swal_open(options){

            var resolve = angular.extend({}, options.resolve);

            angular.forEach(resolve, function (value, key) {
                resolve[key] = angular.isString(value) ? $injector.get(value) : $injector.invoke(value, null, null, key);
            });

            return $q.all({
                html: _getHtml(options),
                locals: $q.all(resolve)
            }).then(function(setup){

                var scope = options.scope,
                    controller = options.controller,
                    controllerAsOption = options.controllerAs,
                    preConfirm = options.preConfirm;

                delete options.html;
                delete options.htmlTemplate;
                delete options.resolve;
                delete options.scope;
                delete options.controller;
                delete options.controllerAs;
                delete options.preConfirm;

                var locals = setup.locals;

                options.html = setup.html;

                if (controller){

                  var controllerAs;
                    scope = scope ? scope.$new() : $rootScope.$new();

                  if (controllerAsOption && angular.isString(controllerAsOption)) {
                      controllerAs = controllerAsOption;
                  }

                  var controllerInstance = $controller(controller, angular.extend(
                      locals,
                      {
                          $scope: scope
                      }), false, controllerAs);

                  if (typeof preConfirm === 'string'){
                      options.preConfirm = function() { return scope.$apply(controllerInstance[preConfirm]) };
                  }
                }

                if (typeof preConfirm === 'function'){
                    options.preConfirm = function() { return scope.$apply(preConfirm) };
                }

                var prom = swal(options);
                var html = document.getElementsByClassName('swal2-modal')[0];

                $compile(html)(scope);

                return prom;

            });

        }

        function _getHtml(options){

            if(options.htmlTemplate) {
                return _getTemplate(options.htmlTemplate)
            } else {
               return options.html;
            }

        }

        function _getTemplate(tmpl) {
            return $http.get(tmpl, {cache: $templateCache}).then(function(res) {
                return res.data || '';
            });
        }

        /*
         *
         * Base Sweet Alert function
         * Use this for for a direct mapping to sweetalert,
         * by either passing an options object or by passing up to 3 string arguments
         *
         * ex. 1: Swangular.swal("Good job!", "You clicked the button!", "success")
         *
         * ex. 2: Swangular.swal({title: "Auto close alert!", text: "I will close in 2 seconds.", timer: 2000});
         *
         */
        function swal_base(arg1, arg2, arg3) {

            // In case of options
            if(arg1 !== null && typeof arg1 === 'object') {
                return swal(arg1)
            }

            // In case of: title, text, type
            else {
                return swal(arg1, arg2, arg3);
            }
        }

        /*
         * SweetAlert2 Global Methods
         */

        function close() {
            $rootScope.$evalAsync(function(){
                swal.close();
            });
        }

        function disableButtons() {
            $rootScope.$evalAsync(function(){
                swal.disableButtons();
            });
        }

        function enableButtons() {
            $rootScope.$evalAsync(function(){
                swal.enableButtons();
            });
        }

        function disableConfirmButton() {
            $rootScope.$evalAsync(function(){
                swal.disableConfirmButton();
            });
        }

        function enableConfirmButton() {
            $rootScope.$evalAsync(function(){
                swal.enableConfirmButton();
            });
        }

        function clickConfirm() {
            $rootScope.$evalAsync(function(){
                swal.clickConfirm();
            });
        }

        function clickCancel() {
            $rootScope.$evalAsync(function(){
                swal.showLoading();
            });
        }

        function showLoading() {
            $rootScope.$evalAsync(function(){
                swal.clickCancel();
            });
        }

        function hideLoading() {
            $rootScope.$evalAsync(function(){
                swal.hideLoading();
            });
        }

        function setDefaults(options) {
            $rootScope.$evalAsync(function(){
                swal.setDefaults(options);
            });
        }

        return {
            alert: swal_alert,
            confirm: swal_confirm,
            info: swal_info,
            success: swal_success,
            open: swal_open,
            swal: swal_base,
            closeModal: close,
            close: close,
            disableButtons: disableButtons,
            enableButtons: enableButtons,
            disableConfirmButton: disableConfirmButton,
            enableConfirmButton: enableConfirmButton,
            clickConfirm: clickConfirm,
            clickCancel: clickCancel,
            showLoading: showLoading,
            enableLoading: showLoading,
            hideLoading: hideLoading,
            disableLoading: hideLoading,
            setDefaults: setDefaults
        }

    }]);

})();
<|endoftext|>


<commit_before>var ctx=document.getElementById("cvs").getContext("2d");
var timercount=200;
var timerctx;
var chrmtx=new Array();
var wait=false;
window.onload=(function(){
//vraminit();
document.onkeydown=getkeychr;
document.onkeyup=keyclr;
document.onmousedown=getmouse;
init();
timerctx=setInterval("routine();",timercount);
});

function settimer(t){
timercount=t;
}
function cleartimer(){
clearInterval(timerctx);
}

function peek(x,y){
//return chr;
}
function beep(mode){
switch(mode){
case 0:
alerm.play();
break;
case 1:
clck.play();
break;
default:
break;
}
}
function putc(chrcode,chrctx,cx,cy){
var i,j;
for(i=0;i<=chrctx[2]-1;i++){
for(j=0;j<=chrctx[1]-1;j++){
if(chrcode[i*chrctx[1]+j]==1){
ctx.fillRect((cx+j)*4,(cy+i)*4,3,3);
}

}
}

}
function color(cc){
/*
switch(cc){
case 0:
ctx.fillStyle="rgb(0,0,0)";
break;
case 1:
ctx.fillStyle="rgb(0,0,255)";
break;
case 2:
ctx.fillStyle="rgb(255,0,0)";
break;
case 3:
ctx.fillStyle="rgb(255,0,255)";
break;
case 4:
ctx.fillStyle="rgb(0,255,0)";
break;
case 5:
ctx.fillStyle="rgb(0,255,255)";
break;
case 6:
ctx.fillStyle="rgb(255,255,0)";
break;
case 7:
ctx.fillStyle="rgb(255,255,255)";
break;
default:
break;
}
*/
ctx.fillStyle="rgb(0,0,0)";

}
function cls(){
ctx.fillStyle="rgb(100,100,100)";
ctx.fillRect(0,0,640,420);
}
function getkeychr(ev){

evt=ev.which
keychr=String.fromCharCode(evt).toLowerCase();
if(evt==39){keychr="right";}
if(evt==37){keychr="left";}
if(evt==40){keychr="down";}
if(evt==38){keychr="up";}
if(evt==13){keychr="cr";wait=false;}

keyin(keychr);
}
function getmouse(ev){
var keychr;
if(ev.pageX>320){keychr="right";}else{keychr="left";}
keyin(keychr);
}
function keyclr(){
keychr="";
}
function printw(str){
println(str);
while(wait){
var muda=0;
muda++;
}
}
function setchrscreen(){
var i,j;
for(i=0;i<=19;i++){
for(j=0;j<=19;j++){
chrmtx[i*20+j]=0;
}
}
}
function setchrmode(){
}
function chrmove(){
}
function chrscreen(){
}
function scrollup(){
for (i=18 ; i>=0 ;i--){
for (j = 0 ;j<=19 ;j++){
chrmtx[(i+1)*20+j] = chrmtx[i*20+j];
}
}
for(i=0;i<=19;i++){
chrmtx[19*20+i]=0;
}
}
function scrolldown(){
for (i=0 ; i<=18 ;i++){
for (j = 0 ;j<=19 ;j++){
chrmtx[i*20+j] = chrmtx[(i+1)*20+j];
}
}
for(i=0;i<=19;i++){
chrmtx[i]=0;
}
}
function println(str){
ctx,fillStyle="rgb(255,255,255)";
ctx.font="16px 'MSSVbN'";
ctx.fillText(str,10,405);
}<commit_msg>Delete sysekisho.js<commit_after><|endoftext|>


<commit_before>/*!
 * tabulator
 * 2015 Codenautas
 * GNU Licensed
 */

/**
 * Module dependencies.
 */
"use strict";
/*jshint eqnull:true */
/*jshint globalstrict:true */
/*jshint node:true */
(function webpackUniversalModuleDefinition(root, factory) {
    /* global define */
    /* global globalModuleName */
    if(typeof root.globalModuleName !== 'string'){
        root.globalModuleName = factory.name;
    }
    /* istanbul ignore next */
    if(typeof exports === 'object' && typeof module === 'object')
        module.exports = factory();
    else if(typeof define === 'function' && define.amd)
        define(factory);
    else if(typeof exports === 'object')
        exports[root.globalModuleName] = factory();
    else
        root[root.globalModuleName] = factory();
    root.globalModuleName = null;
})(/*jshint -W040 */this, function Tabulator() {
/*jshint +W040 */

var _=require('lodash');
var html=require('js-to-html').html;

/*jshint -W004 */
var Tabulator = function(){
};
/*jshint +W004 */

 // import used by this file
// var dependency = dependency || require('dependency');

function array_combine(keys, values) {
  var new_array = {};
  for (var i = 0; i < keys.length; i++) {
    new_array[keys[i]] = values[i];
  }
  return new_array;
}

Tabulator.prototype.captionPart = function captionPart(matrix){
    return matrix.caption?html.caption(matrix.caption):null;
};

Tabulator.prototype.colGroups = function colGroups(matrix){
    //console.log("matrix.lineVariables",matrix.lineVariables);
    var lineVariablesPart=matrix.lineVariables?(
        html.colgroup(
            {'class':'headers'},
            matrix.lineVariables.map(function(lineVariable){
                return html.col({'class':lineVariable});
            })
        )
    ):null;
    var columnVariablesPart=(matrix.columns)?(
        html.colgroup(
            {'class':'data'},
            (matrix.oneColumnTitle)?(
                html.col({'class':'variable'})
            ):(
                matrix.columns.map(function(column){
                    return html.col({'class':JSON.stringify(array_combine(matrix.columnVariables,column.titles))});
                })
            )
        )
    ):null;
    return [].concat(lineVariablesPart,columnVariablesPart);
};

function labelVariableValues(matrix, varName, varValue){
    return (((((matrix.vars||{})[varName]||{}).values)||{})[varValue]||{}).label||varValue;
}

Tabulator.prototype.tHeadPart = function tHeadPart(matrix){
    if(!matrix.columnVariables) return null;
    function labelVariable(varName){
        return ((matrix.vars||{})[varName]||{}).label||varName;
    }
    var varObj=matrix.columns.length>0?{'class':'variable', colspan:matrix.columns.length}:{'class':'variable', rowspan:2};
    return html.thead(
        [
            html.tr(
                matrix.lineVariables.map(function(varName){
                    var columnVariablesLength = matrix.columnVariables.length>0?matrix.columnVariables.length:1;
                    return html.th({'class':'variable', 'rowspan':2*columnVariablesLength}, labelVariable(varName));
                }).concat(
                    html.th(varObj,labelVariable(matrix.columnVariables[0])||matrix.oneColumnTitle)
                )
            )
        ].concat(_.flatten(matrix.columnVariables.map(function(columnVariable,iColumnVariable){
            var lineTitles=[];
            var lineVariables=[];
            var previousValuesUptoThisRowJson="none";
            var colspan=1;
            function updateColspan(){
                if(colspan>1){
                    titleCellAttrs.colspan=colspan;
                    variableCellAttrs.colspan=colspan;
                }
            }
            for(var i=0; i<matrix.columns.length; i++){
                var actualValues=matrix.columns[i].titles;
                var actualValuesUptoThisRow=actualValues.slice(0,iColumnVariable+1);
                var actualValuesUptoThisRowJson=JSON.stringify(actualValuesUptoThisRow);
                if(actualValuesUptoThisRowJson!=previousValuesUptoThisRowJson){
                    updateColspan();
                    var titleCellAttrs={'class':'var_'+matrix.columnVariables[iColumnVariable]};
                    var varName = matrix.columnVariables[iColumnVariable];
                    var varValue = actualValues[iColumnVariable];
                    lineTitles.push(html.th(titleCellAttrs, labelVariableValues(matrix, varName,varValue)));
                    if(iColumnVariable+1<matrix.columnVariables.length){
                        var variableCellAttrs={'class':'variable'};
                        lineVariables.push(html.th(variableCellAttrs, labelVariable(matrix.columnVariables[iColumnVariable+1])));
                    }
                    previousValuesUptoThisRowJson=actualValuesUptoThisRowJson;
                    colspan=0;
                }
                colspan++;
            }
            updateColspan();
            if(iColumnVariable+1<matrix.columnVariables.length){
                //console.log("lineTitles: ", JSON.stringify(lineTitles));
                //console.log("lineVariables: ", JSON.stringify(lineVariables));
                return [html.tr(lineTitles), html.tr(lineVariables)];
            }else{
                //console.log("lineTitles: ", JSON.stringify(lineTitles));
                return [html.tr(lineTitles)];
            }
        }))
    ));
};

Tabulator.prototype.defaultShowAttribute='show';

Tabulator.prototype.toCellTable=function(cell){
    return html.td(cell,cell instanceof Object?cell[this.defaultShowAttribute]:null);
};

Tabulator.prototype.tBodyPart = function tBodyPart(matrix){
    var trList=[];
    var previousLineTitles=[];
    var titleLineAttrs=[];
    for(var i=0; i<matrix.lines.length;i++){
        var actualLine=matrix.lines[i];
        var actualLineTitles=actualLine.titles;
        var thListActualLine=[];
        var actualLineCells=matrix.lines[i].cells;
        var td=actualLineCells.map(function(cell){
            return (this.toCellTable(cell));
        },this);
        if(actualLineTitles){
            for(var j=0;j<actualLineTitles.length;j++){
                var varName=(matrix.lineVariables||{})[j]||null;
                var actualLineTitlesUpToNow=actualLineTitles.slice(0,j+1);
                var previousLineTitlesUpToNow=previousLineTitles.slice(0,j+1);
                if(JSON.stringify(actualLineTitlesUpToNow)!=JSON.stringify(previousLineTitlesUpToNow)){
                    titleLineAttrs[j]={};
                    if((matrix.lineVariables||{})[j]){
                        titleLineAttrs[j]['class']='var_'+(matrix.lineVariables||{})[j];
                    }
                    thListActualLine.push(html.th(titleLineAttrs[j],labelVariableValues(matrix, varName,actualLineTitles[j])));
                }else{
                    titleLineAttrs[j].rowspan=(titleLineAttrs[j].rowspan||1)+1;
                }
            }
            previousLineTitles=actualLineTitles;
        }
        trList.push(html.tr(thListActualLine.concat(td)));
    }
    return html.tbody(trList);
};

Tabulator.prototype.toHtmlTable = function toHtmlTable(matrix){
    this.controls(matrix);
    return html.table([].concat(
        this.captionPart(matrix),
        this.colGroups(matrix),
        this.tHeadPart(matrix),
        this.tBodyPart(matrix)
    ));
};

Tabulator.prototype.controls=function controls(matrix){
    var  matrixLineVariables=matrix.lineVariables;
    var  matrixLines=matrix.lines;
    var  matrixColumnVariables=matrix.columnVariables;
    var  matrixColumns=matrix.columns;
    if(matrixColumnVariables && matrixColumns /*&& matrixColumns.length*/){
        variableExistanceAndQuantity(matrixColumnVariables,matrixColumns,'columnVariables');
    }
    if(matrixLineVariables && matrixLines /*&& matrixLines.length*/){
        variableExistanceAndQuantity(matrixLineVariables,matrixLines,'lineVariables');
    }
    if(matrixColumns && matrixLines){
        cellExistanceAndQuantity(matrixColumns,matrixLines,'cells');
    }
    function variableExistanceAndQuantity(arrVar,objVar,nameArrVar){
        var varName=nameArrVar=='columnVariables'?'column ':'line ';
        var variablesQuantity=arrVar.length;
        for(var i=0;i<objVar.length;i++){
            if(objVar[i].titles){
                if(objVar[i].titles.length!=variablesQuantity){
                    throw new Error(varName+i+' has '+objVar[i].titles.length+' values but '+nameArrVar+' has '+variablesQuantity);
                }
            }else{
                throw new Error('there are no titles in '+ varName +i+' but '+nameArrVar+ ' exists');
            }
        }
    }

    function cellExistanceAndQuantity(matrixColumns,matrixLines,varName){
        var columnQuantity=matrixColumns.length||1;
        for(var i=0;i<matrixLines.length;i++){
            if(matrixLines[i].cells.length>0){
                if(matrixLines[i].cells.length!=columnQuantity){
                    throw new Error('line '+i+' has '+matrixLines[i].cells.length+' cells but columns has '+columnQuantity);
                }
            }else{
                throw new Error('there are no cells in line '+i+' but columns exists');
            }
        }
    }
};

Tabulator.prototype.controlsJoin=function controlsJoin(matrixList){
var firstMatrixListLinesLength = matrixList[0].lines.length;
if (!matrixList.every(function(element){return element.lines.length == firstMatrixListLinesLength})){
    throw new Error('line.length does not match in all matrix');
}
var firstMatrixListLine = matrixList[0].lines;
var JsonTitlesFirstMatrixListLine = firstMatrixListLine.map(function(obj){return JSON.stringify(obj.titles)});
if (!matrixList.every(
      function(element,index){
        return element.lines.every(
           function(elemento,indice){
             //return JSON.stringify(elemento.titles) == JSON.stringify(firstMatrixListLine[indice].titles)
             //console.log('Titulos ',JsonTitlesFirstMatrixListLine);
             //console.log('Titulos ',JSON.stringify(elemento.titles));
             return JsonTitlesFirstMatrixListLine.indexOf(JSON.stringify(elemento.titles)) > -1;
           })
      })
    ){
        throw new Error('line titles does not match in all matrix');
     }
}

Tabulator.prototype.toMatrix = function toMatrix(datum){
    var places={
        left:{place:'lineVariables'},
        top:{place:'columnVariables'},
        data:{place:'dataVariables'},
    };
    var matrix={lineVariables:[],columnVariables:[], dataVariables:[], columns:[], lines:[], vars:[]};
    for(var i=0; i<datum.vars.length;i++){
        var cadaVar=datum.vars[i];
        matrix[places[cadaVar.place].place].push(cadaVar.name);
        matrix.vars[cadaVar.name] = cadaVar;
    }
    matrix.oneColumnTitle=datum.oneColumnTitle;
    var vistosColumnVariables={};
    var vistosLineVariables={};
    for(var iList=0; iList<datum.list.length; iList++){
        var iCell;
        var iLine;
        var cadaList=datum.list[iList];
        iCell=matrix.columnVariables.length;
        for(var iColumn=0; iColumn<matrix.columnVariables.length;iColumn++){
            var cadaNameTop=matrix.columnVariables[iColumn];
            if (!vistosColumnVariables[cadaList[cadaNameTop]]){
                iCell=matrix.columns.push({titles:[cadaList[cadaNameTop]]})-1;
                vistosColumnVariables[cadaList[cadaNameTop]]={index: iCell};
            }else{
                iCell=vistosColumnVariables[cadaList[cadaNameTop]].index;
            }
        }
        var cadaDatoLeft=[];
        var cadaDatoData=[];
        for(var j=0; j<matrix.lineVariables.length;j++){
            cadaDatoLeft.push(cadaList[matrix.lineVariables[j]]);
            cadaDatoData.push(cadaList[matrix.dataVariables[j]]);
        }
        var jsonCadaDatoLeft=JSON.stringify(cadaDatoLeft);
        if (vistosLineVariables[jsonCadaDatoLeft]){
            iLine=vistosLineVariables[jsonCadaDatoLeft].index;
        }else{
            iLine=matrix.lines.push({titles:cadaDatoLeft, cells:[]})-1;
            vistosLineVariables[jsonCadaDatoLeft]={index: iLine};
        }
        var newCell={};
        if(datum.showFunction){
            newCell.display=datum.showFunction(cadaList);
        }
        for(var k=0; k<matrix.dataVariables.length; k++){
            var nombreVariable=matrix.dataVariables[k];
            newCell[nombreVariable]=cadaList[nombreVariable];
        }
        matrix.lines[iLine].cells[iCell]=newCell;
    }
    for(var l=0; l<matrix.lines.length; l++){
        for(var m=0; m<matrix.columns.length; m++){
            if (matrix.lines[l].cells[m]===undefined){
                matrix.lines[l].cells[m]=null;
            }
        }
    }
    return matrix;
};

Tabulator.prototype.matrixJoin = function matrixJoin(matrixList){
    this.controlsJoin(matrixList);

    var matrix={columnGroups:[], lineVariables:[], lines:[], vars:[]};
    var captions = matrixList.map(function(obj){return obj.caption});
    matrix.caption = captions.join(this.matrixJoin.captionSeparator);

    var reordererLines = [];
    matrixList.forEach(function(matrix){
        var lines = matrix.lines;
        var indexedLines = {};
        lines.forEach(function (line){
            var ind = JSON.stringify(line.titles);
            indexedLines[ind] = line.cells;
        });
        reordererLines.push(indexedLines);
    });
    console.log("reordererLines: ", reordererLines);

    matrix.columnGroups = matrixList.map(function(obj){
        var cGroup={};
        cGroup.columnVariables=obj.columnVariables;
        cGroup.columns=obj.columns;
        return cGroup;
    });
    matrix.lineVariables = matrixList[0].lineVariables;
    matrix.lines = matrixList[0].lines;
    // primer paso construir un arreglo indexado de líneas (indexado por título)
    // reordererLines[i_matrix][json_title] = line
    // segundo paso igual pero iterando sobre la matriz 0 (original) y buscando por índice (si un índice no está lanza excepción)
    matrixList.forEach(function(matrixToAdd, i_matrixToAdd){
        if (i_matrixToAdd>0){
            matrix.lines.forEach(function(line,ind){
                var lineToAdd = reordererLines[i_matrixToAdd][JSON.stringify(line.titles)];
                matrix.lines[ind].cells = matrix.lines[ind].cells.concat(lineToAdd);
            })
        }
    });
    return matrix;
}

Tabulator.prototype.matrixJoin.captionSeparator = ', ';

return Tabulator;

});<commit_msg>listo el caso de prueba 'should render line titles'<commit_after>/*!
 * tabulator
 * 2015 Codenautas
 * GNU Licensed
 */

/**
 * Module dependencies.
 */
"use strict";
/*jshint eqnull:true */
/*jshint globalstrict:true */
/*jshint node:true */
(function webpackUniversalModuleDefinition(root, factory) {
    /* global define */
    /* global globalModuleName */
    if(typeof root.globalModuleName !== 'string'){
        root.globalModuleName = factory.name;
    }
    /* istanbul ignore next */
    if(typeof exports === 'object' && typeof module === 'object')
        module.exports = factory();
    else if(typeof define === 'function' && define.amd)
        define(factory);
    else if(typeof exports === 'object')
        exports[root.globalModuleName] = factory();
    else
        root[root.globalModuleName] = factory();
    root.globalModuleName = null;
})(/*jshint -W040 */this, function Tabulator() {
/*jshint +W040 */

var _=require('lodash');
var html=require('js-to-html').html;

/*jshint -W004 */
var Tabulator = function(){
};
/*jshint +W004 */

 // import used by this file
// var dependency = dependency || require('dependency');

function array_combine(keys, values) {
  var new_array = {};
  for (var i = 0; i < keys.length; i++) {
    new_array[keys[i]] = values[i];
  }
  return new_array;
}

Tabulator.prototype.captionPart = function captionPart(matrix){
    return matrix.caption?html.caption(matrix.caption):null;
};

Tabulator.prototype.colGroups = function colGroups(matrix){
    //console.log("matrix.lineVariables",matrix.lineVariables);
    var lineVariablesPart=matrix.lineVariables?(
        html.colgroup(
            {'class':'headers'},
            matrix.lineVariables.map(function(lineVariable){
                return html.col({'class':lineVariable});
            })
        )
    ):null;
    var columnVariablesPart=(matrix.columns)?(
        html.colgroup(
            {'class':'data'},
            (matrix.oneColumnTitle)?(
                html.col({'class':'variable'})
            ):(
                matrix.columns.map(function(column){
                    return html.col({'class':JSON.stringify(array_combine(matrix.columnVariables,column.titles))});
                })
            )
        )
    ):null;
    return [].concat(lineVariablesPart,columnVariablesPart);
};

function labelVariableValues(matrix, varName, varValue){
    return (((((matrix.vars||{})[varName]||{}).values)||{})[varValue]||{}).label||varValue;
}

Tabulator.prototype.tHeadPart = function tHeadPart(matrix){
    if(!matrix.columnVariables) return null;
    function labelVariable(varName){
        return ((matrix.vars||{})[varName]||{}).label||varName;
    }
    var varObj=matrix.columns.length>0?{'class':'variable', colspan:matrix.columns.length}:{'class':'variable', rowspan:2};
    return html.thead(
        [
            html.tr(
                matrix.lineVariables.map(function(varName){
                    var columnVariablesLength = matrix.columnVariables.length>0?matrix.columnVariables.length:1;
                    return html.th({'class':'variable', 'rowspan':2*columnVariablesLength}, labelVariable(varName));
                }).concat(
                    html.th(varObj,labelVariable(matrix.columnVariables[0])||matrix.oneColumnTitle)
                )
            )
        ].concat(_.flatten(matrix.columnVariables.map(function(columnVariable,iColumnVariable){
            var lineTitles=[];
            var lineVariables=[];
            var previousValuesUptoThisRowJson="none";
            var colspan=1;
            function updateColspan(){
                if(colspan>1){
                    titleCellAttrs.colspan=colspan;
                    variableCellAttrs.colspan=colspan;
                }
            }
            for(var i=0; i<matrix.columns.length; i++){
                var actualValues=matrix.columns[i].titles;
                var actualValuesUptoThisRow=actualValues.slice(0,iColumnVariable+1);
                var actualValuesUptoThisRowJson=JSON.stringify(actualValuesUptoThisRow);
                if(actualValuesUptoThisRowJson!=previousValuesUptoThisRowJson){
                    updateColspan();
                    var titleCellAttrs={'class':'var_'+matrix.columnVariables[iColumnVariable]};
                    var varName = matrix.columnVariables[iColumnVariable];
                    var varValue = actualValues[iColumnVariable];
                    lineTitles.push(html.th(titleCellAttrs, labelVariableValues(matrix, varName,varValue)));
                    if(iColumnVariable+1<matrix.columnVariables.length){
                        var variableCellAttrs={'class':'variable'};
                        lineVariables.push(html.th(variableCellAttrs, labelVariable(matrix.columnVariables[iColumnVariable+1])));
                    }
                    previousValuesUptoThisRowJson=actualValuesUptoThisRowJson;
                    colspan=0;
                }
                colspan++;
            }
            updateColspan();
            if(iColumnVariable+1<matrix.columnVariables.length){
                //console.log("lineTitles: ", JSON.stringify(lineTitles));
                //console.log("lineVariables: ", JSON.stringify(lineVariables));
                return [html.tr(lineTitles), html.tr(lineVariables)];
            }else{
                //console.log("lineTitles: ", JSON.stringify(lineTitles));
                return [html.tr(lineTitles)];
            }
        }))
    ));
};

Tabulator.prototype.defaultShowAttribute='show';

Tabulator.prototype.toCellTable=function(cell){
    return html.td(cell,cell instanceof Object?cell[this.defaultShowAttribute]:null);
};

Tabulator.prototype.tBodyPart = function tBodyPart(matrix){
    var trList=[];
    var previousLineTitles=[];
    var titleLineAttrs=[];
    for(var i=0; i<matrix.lines.length;i++){
        var actualLine=matrix.lines[i];
        var actualLineTitles=actualLine.titles;
        var thListActualLine=[];
        var actualLineCells=matrix.lines[i].cells;
        var td=actualLineCells.map(function(cell){
            return (this.toCellTable(cell));
        },this);
        if(actualLineTitles){
            for(var j=0;j<actualLineTitles.length;j++){
                var varName=(matrix.lineVariables||{})[j]||null;
                var actualLineTitlesUpToNow=actualLineTitles.slice(0,j+1);
                var previousLineTitlesUpToNow=previousLineTitles.slice(0,j+1);
                if(JSON.stringify(actualLineTitlesUpToNow)!=JSON.stringify(previousLineTitlesUpToNow)){
                    titleLineAttrs[j]={};
                    if((matrix.lineVariables||{})[j]){
                        titleLineAttrs[j]['class']='var_'+(matrix.lineVariables||{})[j];
                    }
                    thListActualLine.push(html.th(titleLineAttrs[j],labelVariableValues(matrix, varName,actualLineTitles[j])));
                }else{
                    titleLineAttrs[j].rowspan=(titleLineAttrs[j].rowspan||1)+1;
                }
            }
            previousLineTitles=actualLineTitles;
        }
        trList.push(html.tr(thListActualLine.concat(td)));
    }
    return html.tbody(trList);
};

Tabulator.prototype.toHtmlTable = function toHtmlTable(matrix){
    this.controls(matrix);
    return html.table([].concat(
        this.captionPart(matrix),
        this.colGroups(matrix),
        this.tHeadPart(matrix),
        this.tBodyPart(matrix)
    ));
};

Tabulator.prototype.controls=function controls(matrix){
    var  matrixLineVariables=matrix.lineVariables;
    var  matrixLines=matrix.lines;
    var  matrixColumnVariables=matrix.columnVariables;
    var  matrixColumns=matrix.columns;
    if(matrixColumnVariables && matrixColumns /*&& matrixColumns.length*/){
        variableExistanceAndQuantity(matrixColumnVariables,matrixColumns,'columnVariables');
    }
    if(matrixLineVariables && matrixLines /*&& matrixLines.length*/){
        variableExistanceAndQuantity(matrixLineVariables,matrixLines,'lineVariables');
    }
    if(matrixColumns && matrixLines){
        cellExistanceAndQuantity(matrixColumns,matrixLines,'cells');
    }
    function variableExistanceAndQuantity(arrVar,objVar,nameArrVar){
        var varName=nameArrVar=='columnVariables'?'column ':'line ';
        var variablesQuantity=arrVar.length;
        for(var i=0;i<objVar.length;i++){
            if(objVar[i].titles){
                if(objVar[i].titles.length!=variablesQuantity){
                    throw new Error(varName+i+' has '+objVar[i].titles.length+' values but '+nameArrVar+' has '+variablesQuantity);
                }
            }else{
                throw new Error('there are no titles in '+ varName +i+' but '+nameArrVar+ ' exists');
            }
        }
    }

    function cellExistanceAndQuantity(matrixColumns,matrixLines,varName){
        var columnQuantity=matrixColumns.length||1;
        for(var i=0;i<matrixLines.length;i++){
            if(matrixLines[i].cells.length>0){
                if(matrixLines[i].cells.length!=columnQuantity){
                    throw new Error('line '+i+' has '+matrixLines[i].cells.length+' cells but columns has '+columnQuantity);
                }
            }else{
                throw new Error('there are no cells in line '+i+' but columns exists');
            }
        }
    }
};

Tabulator.prototype.controlsJoin=function controlsJoin(matrixList){
var firstMatrixListLinesLength = matrixList[0].lines.length;
if (!matrixList.every(function(element){return element.lines.length == firstMatrixListLinesLength})){
    throw new Error('line.length does not match in all matrix');
}
var firstMatrixListLine = matrixList[0].lines;
var JsonTitlesFirstMatrixListLine = firstMatrixListLine.map(function(obj){return JSON.stringify(obj.titles)});
if (!matrixList.every(
      function(element,index){
        return element.lines.every(
           function(elemento,indice){
             //return JSON.stringify(elemento.titles) == JSON.stringify(firstMatrixListLine[indice].titles)
             //console.log('Titulos ',JsonTitlesFirstMatrixListLine);
             //console.log('Titulos ',JSON.stringify(elemento.titles));
             return JsonTitlesFirstMatrixListLine.indexOf(JSON.stringify(elemento.titles)) > -1;
           })
      })
    ){
        throw new Error('line titles does not match in all matrix');
     }
}

Tabulator.prototype.toMatrix = function toMatrix(datum){
    var places={
        left:{place:'lineVariables'},
        top:{place:'columnVariables'},
        data:{place:'dataVariables'},
    };
    var matrix={lineVariables:[],columnVariables:[], dataVariables:[], columns:[], lines:[], vars:[]};
    for(var i=0; i<datum.vars.length;i++){
        var cadaVar=datum.vars[i];
        matrix[places[cadaVar.place].place].push(cadaVar.name);
        matrix.vars[cadaVar.name] = cadaVar;
    }
    matrix.oneColumnTitle=datum.oneColumnTitle;
    var vistosColumnVariables={};
    var vistosLineVariables={};
    for(var iList=0; iList<datum.list.length; iList++){
        var iCell;
        var iLine;
        var cadaList=datum.list[iList];
        iCell=matrix.columnVariables.length;
        for(var iColumn=0; iColumn<matrix.columnVariables.length;iColumn++){
            var cadaNameTop=matrix.columnVariables[iColumn];
            if (!vistosColumnVariables[cadaList[cadaNameTop]]){
                iCell=matrix.columns.push({titles:[cadaList[cadaNameTop]]})-1;
                vistosColumnVariables[cadaList[cadaNameTop]]={index: iCell};
            }else{
                iCell=vistosColumnVariables[cadaList[cadaNameTop]].index;
            }
        }
        var cadaDatoLeft=[];
        var cadaDatoData=[];
        for(var j=0; j<matrix.lineVariables.length;j++){
            cadaDatoLeft.push(cadaList[matrix.lineVariables[j]]);
            cadaDatoData.push(cadaList[matrix.dataVariables[j]]);
        }
        var jsonCadaDatoLeft=JSON.stringify(cadaDatoLeft);
        if (vistosLineVariables[jsonCadaDatoLeft]){
            iLine=vistosLineVariables[jsonCadaDatoLeft].index;
        }else{
            iLine=matrix.lines.push({titles:cadaDatoLeft, cells:[]})-1;
            vistosLineVariables[jsonCadaDatoLeft]={index: iLine};
        }
        var newCell={};
        if(datum.showFunction){
            newCell.display=datum.showFunction(cadaList);
        }
        for(var k=0; k<matrix.dataVariables.length; k++){
            var nombreVariable=matrix.dataVariables[k];
            newCell[nombreVariable]=cadaList[nombreVariable];
        }
        matrix.lines[iLine].cells[iCell]=newCell;
    }
    for(var l=0; l<matrix.lines.length; l++){
        for(var m=0; m<matrix.columns.length; m++){
            if (matrix.lines[l].cells[m]===undefined){
                matrix.lines[l].cells[m]=null;
            }
        }
    }
    return matrix;
};

Tabulator.prototype.matrixJoin = function matrixJoin(matrixList){
    this.controlsJoin(matrixList);

    var matrix={columnGroups:[], lineVariables:[], lines:[], vars:{}};
    var captions = matrixList.map(function(obj){return obj.caption});
    matrix.caption = captions.join(this.matrixJoin.captionSeparator);

    var reordererLines = [];
    matrixList.forEach(function(matrix){
        var lines = matrix.lines;
        var indexedLines = {};
        lines.forEach(function (line){
            var ind = JSON.stringify(line.titles);
            indexedLines[ind] = line.cells;
        });
        reordererLines.push(indexedLines);
    });
    //console.log("reordererLines: ", reordererLines);

    matrix.columnGroups = matrixList.map(function(obj){
        var cGroup={};
        cGroup.columnVariables=obj.columnVariables;
        cGroup.columns=obj.columns;
        return cGroup;
    });
    matrix.lineVariables = matrixList[0].lineVariables;
    matrix.lines = matrixList[0].lines;
    matrix.vars = matrixList[0].vars;
    // primer paso construir un arreglo indexado de líneas (indexado por título)
    // reordererLines[i_matrix][json_title] = line
    // segundo paso igual pero iterando sobre la matriz 0 (original) y buscando por índice (si un índice no está lanza excepción)
    matrixList.forEach(function(matrixToAdd, i_matrixToAdd){
        if (i_matrixToAdd>0){
            matrix.lines.forEach(function(line,ind){
                var lineToAdd = reordererLines[i_matrixToAdd][JSON.stringify(line.titles)];
                matrix.lines[ind].cells = matrix.lines[ind].cells.concat(lineToAdd);
            });
            for (var key in matrixToAdd.vars){
                matrix.vars[key] = matrixToAdd.vars[key];
            }
        }
    });
    return matrix;
}

Tabulator.prototype.matrixJoin.captionSeparator = ', ';

return Tabulator;

});<|endoftext|>


<commit_before>'use strict';
const childProcess = require('child_process');
const dargs = require('dargs');
const resolveCwd = require('resolve-cwd');

const BIN = require.resolve('ava/cli.js');

module.exports = grunt => {
	grunt.registerMultiTask('ava', 'Run AVA tests', function () {
		const cb = this.async();
		const opts = this.options();
		const args = [BIN].concat(this.filesSrc, '--color', dargs(opts, {excludes: ['nyc']}));

		if (opts.nyc) {
			const nycBin = resolveCwd('nyc/bin/nyc.js');

			if (nycBin) {
				args.unshift(nycBin);
			} else {
				grunt.warn('Couldn\'t find the `nyc` binary');
				cb();
				return;
			}
		}

		childProcess.execFile(process.execPath, args, (err, stdout, stderr) => {
			if (err) {
				grunt.warn(stderr || stdout || err);
				cb();
				return;
			}

			grunt.log.write(stderr + stdout);
			cb();
		});
	});
};
<commit_msg>Increase the max buffer so it never errors on that<commit_after>'use strict';
const childProcess = require('child_process');
const dargs = require('dargs');
const resolveCwd = require('resolve-cwd');

const BIN = require.resolve('ava/cli.js');
const HUNDRED_MEGABYTES = 1000 * 1000 * 100;

module.exports = grunt => {
	grunt.registerMultiTask('ava', 'Run AVA tests', function () {
		const cb = this.async();
		const opts = this.options();
		const args = [BIN].concat(this.filesSrc, '--color', dargs(opts, {excludes: ['nyc']}));

		if (opts.nyc) {
			const nycBin = resolveCwd('nyc/bin/nyc.js');

			if (nycBin) {
				args.unshift(nycBin);
			} else {
				grunt.warn('Couldn\'t find the `nyc` binary');
				cb();
				return;
			}
		}

		childProcess.execFile(process.execPath, args, {
			maxBuffer: HUNDRED_MEGABYTES
		}, (err, stdout, stderr) => {
			if (err) {
				grunt.warn(stderr || stdout || err);
				cb();
				return;
			}

			grunt.log.write(stderr + stdout);
			cb();
		});
	});
};
<|endoftext|>


<commit_before>'use strict';
var childProcess = require('child_process');
var BIN = require.resolve('ava/cli.js');

module.exports = function (grunt) {
	grunt.registerMultiTask('ava', 'Run AVA tests', function () {
		var cb = this.async();
		var args = this.filesSrc.concat('--color');

		args.unshift(BIN);

		childProcess.execFile('node', args, function (err, stdout, stderr) {
			if (err) {
				grunt.warn(stderr);
				cb();
				return;
			}

			grunt.log.write(stderr);
			cb();
		});
	});
};
<commit_msg>cleanup #1<commit_after>'use strict';
var childProcess = require('child_process');
var BIN = require.resolve('ava/cli.js');

module.exports = function (grunt) {
	grunt.registerMultiTask('ava', 'Run AVA tests', function () {
		var cb = this.async();
		var args = this.filesSrc.concat('--color');

		args.unshift(BIN);

		childProcess.execFile(process.execPath, args, function (err, stdout, stderr) {
			if (err) {
				grunt.warn(stderr);
				cb();
				return;
			}

			grunt.log.write(stderr);
			cb();
		});
	});
};
<|endoftext|>


<commit_before>/*
 * grunt-pack::tar
 * https://github.com/jussi-kalliokoski/grunt-pack
 *
 * Copyright (c) 2012 Jussi Kalliokoski
 * Licensed under the MIT license.
*/

module.exports = function(grunt) {
	var log = grunt.log

	grunt.registerMultiTask('tar', 'Packs files or folders into a .tar.gz', function () {
		var self = this
		var done = this.async()
		var files = grunt.file.expandFiles(this.file.src)

		var args = {
			cmd: 'tar',
			args: ['pczf', this.file.src]
				.concat(files)
		}

		if (this.file.cwd) {
			args.opts = {
				cwd: this.file.cwd
			}
		}

		grunt.utils.spawn(args, function (err, result) {
			if (err) {
				log.error(err)
				return done(false)
			}

			log.success('tar (' + self.file.dest + '): done.')
			done()
		})
	})
}
<commit_msg>Fix the arguments for tar<commit_after>/*
 * grunt-pack::tar
 * https://github.com/jussi-kalliokoski/grunt-pack
 *
 * Copyright (c) 2012 Jussi Kalliokoski
 * Licensed under the MIT license.
*/

module.exports = function(grunt) {
	var log = grunt.log

	grunt.registerMultiTask('tar', 'Packs files or folders into a .tar.gz', function () {
		var self = this
		var done = this.async()
		var files = grunt.file.expandFiles(this.file.src)

		var args = {
			cmd: 'tar',
			args: ['pczf', this.file.dest]
				.concat(files)
		}

		if (this.file.cwd) {
			args.opts = {
				cwd: this.file.cwd
			}
		}

		grunt.utils.spawn(args, function (err, result) {
			if (err) {
				log.error(err)
				return done(false)
			}

			log.success('tar (' + self.file.dest + '): done.')
			done()
		})
	})
}
<|endoftext|>


<commit_before>/*
 * grunt-flex-yui-group
 * http://gruntjs.com/
 *
 * Copyright (c) 2014 Bret K. Ikehara
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
    "use strict";

    var libpath = require('path'),
        libutil = require('util'),
        Handlebars = require('handlebars'),
        options = {
            buildDir: 'build',
            srcDir: 'src',
            version: 'dev',
            spaces: 2,
            configWrapper: __dirname + '/template/config-wrapper.hbs',
            moduleWrapper: __dirname + '/template/module-wrapper.hbs'
        },
        metaConfig = {
            metaConfig: {},
            read: function(cwd, files) {
                files.map(function(filepath) {
                    var filecontent = grunt.file.read(cwd + '/' + filepath),
                        meta = JSON.parse(filecontent);

                    Object.keys(meta).forEach(function(module) {
                        if (meta[module].submodules) {
                            Object.keys(meta[module].submodules).forEach(function(submodule) {
                                this.set(submodule, meta[module].submodules[submodule]);
                            }, this);
                        }
                        else {
                            this.set(module, meta[module]);
                        }
                    }, this);
                }, this);
                return this.get();
            },
            get: function(module) {

                if (module) {
                    return this.metaConfig[module];
                }
                return this.metaConfig;
            },
            set: function(module, config) {
                this.metaConfig[module] = config;
            },
            toString: function(spaces, module) {
                if (typeof spaces === 'string') {
                    module = spaces;
                }

                if (typeof spaces !== 'number') {
                    spaces = options.spaces;
                }

                return JSON.stringify(this.get(module), null, spaces);
            }
        },
        template = {
            init: function(name, filepath) {
                var content = grunt.file.read(filepath);

                // create template handler.
                if (!content) {
                    return null;
                }

                if (name === 'init') {
                    grunt.log.error("The init function cannot be overridden!");
                    return null;
                }
                else if (this[name]) {
                    grunt.log.warn("The %s will be overridden", name);
                }

                this[name] = Handlebars.compile(Handlebars.parse(content));

                return this[name];
            }
        },
        module = {
            read: function(cwd, files) {
                var content = [];

                // append all module the files together
                files.forEach(function(jsfile) {
                    var data = grunt.file.read(libpath.join(cwd, 'js', jsfile));
                    grunt.log.writeln('Reading module: %s', jsfile);
                    content.push(data);
                }, this);

                return content.join('\n');
            },
            wrap: function(moduleName, content) {
                // wrap module
                return template.wrapModule({
                    script: content,
                    name: moduleName,
                    meta: metaConfig.toString(moduleName),
                    version: options.version
                });
            },
            write: function(moduleName, content) {
                // Write joined contents to destination filepath.
                var destPath = libpath.join(options.buildDir, moduleName, moduleName + '.js');
                grunt.log.writeln('Writing file: %s', destPath);
                grunt.file.write(destPath, content);
            },
            findBuildFiles: function() {
                return grunt.file.expand({
                        cwd: options.srcDir
                    }, '**/build.json');
            }
        };

    var writeConfig = function(grunt, options) {
            var files,
                configContent;

            // read the config
            files = grunt.file.expand({
                cwd: options.srcDir
            }, '**/meta/*.json');

            metaConfig.read(options.srcDir, files);

            // wrap meta in the config.
            configContent = template.wrapConfig({
                meta: metaConfig.toString(options.spaces)
            });
            grunt.file.write(options.buildDir + '/config.js', configContent);
        },
        writeModules = function(grunt, options) {
            var files = module.findBuildFiles();

            // read the config
            files.forEach(function(buildFile) {
                var build,
                    buildPath;

                // build.json file and path.
                buildFile = libpath.join(options.srcDir, buildFile);
                buildPath = libpath.dirname(buildFile)

                grunt.log.writeln('Reading build: %s', buildFile);
                build = JSON.parse(grunt.file.read(buildFile));

                // loop through modules to build
                Object.keys(build.builds).forEach(function(moduleName) {
                    var content = module.read(buildPath, build.builds[moduleName].jsfiles);

                    content = module.wrap(moduleName, content);
                    module.write(moduleName, content);
                }, this);
            }, this);
        };

    grunt.registerTask('yui',
        'Defines the YUI task',
        function(phase) {
            // write to global options
            options = this.options(options);

            template.init('wrapConfig', options.configWrapper);
            template.init('wrapModule', options.moduleWrapper);

            // run task phases.
            if (phase === 'config') {
                writeConfig(grunt, options);
            }
            else {
                writeConfig(grunt, options);
                writeModules(grunt, options);
            }
        }
    );
};<commit_msg>Removed meta.toString function. Added a find meta.find to be similar to module.<commit_after>/*
 * grunt-flex-yui-group
 * http://gruntjs.com/
 *
 * Copyright (c) 2014 Bret K. Ikehara
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
    "use strict";

    var libpath = require('path'),
        libutil = require('util'),
        Handlebars = require('handlebars'),
        options = {
            buildDir: 'build',
            srcDir: 'src',
            version: 'dev',
            spaces: 2,
            configWrapper: __dirname + '/template/config-wrapper.hbs',
            moduleWrapper: __dirname + '/template/module-wrapper.hbs'
        },
        metaConfig = {
            metaConfig: {},
            find: function(options) {
                return grunt.file.expand({
                    cwd: options.srcDir
                }, '**/meta/*.json');
            },
            read: function(options, files) {
                files.map(function(filepath) {
                    var metaPath = libpath.join(options.srcDir, filepath),
                        meta = JSON.parse(grunt.file.read(metaPath));

                    Object.keys(meta).forEach(function(module) {
                        if (meta[module].submodules) {
                            Object.keys(meta[module].submodules).forEach(function(submodule) {
                                this.set(submodule, meta[module].submodules[submodule]);
                            }, this);
                        }
                        else {
                            this.set(module, meta[module]);
                        }
                    }, this);
                }, this);
                return this.get();
            },
            get: function(module) {

                if (module) {
                    return this.metaConfig[module];
                }
                return this.metaConfig;
            },
            set: function(module, config) {
                this.metaConfig[module] = config;
            }
        },
        template = {
            init: function(options, name, filepath) {
                var content = grunt.file.read(filepath);

                // create template handler.
                if (!content) {
                    return null;
                }

                if (name === 'init') {
                    grunt.log.error("The init function cannot be overridden!");
                    return null;
                }
                else if (this[name]) {
                    grunt.log.warn("The %s will be overridden", name);
                }

                this[name] = Handlebars.compile(Handlebars.parse(content));

                return this[name];
            }
        },
        module = {
            read: function(options, cwd, files) {
                var content = [];

                // append all module the files together
                files.forEach(function(jsfile) {
                    var data = grunt.file.read(libpath.join(cwd, 'js', jsfile));
                    grunt.log.writeln('Reading module: %s', jsfile);
                    content.push(data);
                }, this);

                return content.join('\n');
            },
            wrap: function(options, moduleName, content) {
                // wrap module
                return template.wrapModule({
                    script: content,
                    name: moduleName,
                    meta: JSON.stringify(metaConfig.get(moduleName), null, options.spaces),
                    version: options.version
                });
            },
            write: function(options, moduleName, content) {
                // Write joined contents to destination filepath.
                var destPath = libpath.join(options.buildDir, moduleName, moduleName + '.js');
                grunt.log.writeln('Writing file: %s', destPath);
                grunt.file.write(destPath, content);
            },
            find: function(options) {
                return grunt.file.expand({
                        cwd: options.srcDir
                    }, '**/build.json');
            }
        };

    var writeConfig = function(grunt, options) {
            var files,
                configContent;

            // read the config
            files = metaConfig.find(options);
            metaConfig.read(options, files);

            // wrap meta in the config.
            configContent = template.wrapConfig({
                meta: JSON.stringify(metaConfig.get(), null, options.spaces)
            });
            grunt.file.write(options.buildDir + '/config.js', configContent);
        },
        writeModules = function(grunt, options) {
            var files = module.find(options);

            // read the config
            files.forEach(function(buildFile) {
                var build,
                    buildPath;

                // build.json file and path.
                buildFile = libpath.join(options.srcDir, buildFile);
                buildPath = libpath.dirname(buildFile)

                grunt.log.writeln('Reading build: %s', buildFile);
                build = JSON.parse(grunt.file.read(buildFile));

                // loop through modules to build
                Object.keys(build.builds).forEach(function(moduleName) {
                    var content = module.read(options, buildPath, build.builds[moduleName].jsfiles);

                    content = module.wrap(options, moduleName, content);
                    module.write(options, moduleName, content);
                }, this);
            }, this);
        };

    grunt.registerTask('yui',
        'Defines the YUI task',
        function(phase) {
            // write to global options
            options = this.options(options);

            template.init('wrapConfig', options.configWrapper);
            template.init('wrapModule', options.moduleWrapper);

            // run task phases.
            if (phase === 'config') {
                writeConfig(grunt, options);
            }
            else {
                writeConfig(grunt, options);
                writeModules(grunt, options);
            }
        }
    );
};<|endoftext|>


<commit_before>var Net = require('net');

function TCPModbusServerRaw(options, callbackRequest) {
    var context = this;
    context.port = options.port?options.port:502;

    Net.createServer(function (socket) {

        socket.namePad = ('                          ' + socket.remoteAddress + ":" + socket.remotePort).slice(-26);

        console.log(new Date().toISOString() + socket.namePad + ' client connected');

        socket.on('data', function (request) {
            console.log(new Date().toISOString() + socket.namePad + '->' + request.toString('hex'));
            var tcpHeader = request.slice(0,6);
            callbackRequest(request.slice(6,request.length), function(reply) {
                var buf = Buffer.concat([tcpHeader, reply]);
                buf.writeUInt16BE(reply.length, 4);
                socket.write(buf);
                console.log(new Date().toISOString() + socket.namePad + '<-' + buf.toString('hex'));
            });
        });

        socket.on('end', function () {
            console.log(new Date().toISOString() + socket.namePad + ' client disconnected');
        });

        socket.on('close', function () {
            console.log(new Date().toISOString() + socket.namePad + ' connection closed');
        });

        socket.on('error', function () {
            console.log(new Date().toISOString() + socket.namePad + ' cocket error');
        });

        socket.on('timeout', function () {
            console.log(new Date().toISOString() + socket.namePad + ' connection timeout');
            socket.destroy();
        });

        socket.setTimeout(10000);

    }).listen(context.port);

    console.log(new Date().toISOString() + ' Modbus TCP server is waiting for connections at 502 port');
}

module.exports = TCPModbusServerRaw;
<commit_msg>Syntax error fix (cherry picked from commit 1df2595)<commit_after>var Net = require('net');

function TCPModbusServerRaw(options, callbackRequest) {
    var context = this;
    context.port = options.port?options.port:502;

    Net.createServer(function (socket) {

        socket.namePad = ('                          ' + socket.remoteAddress + ":" + socket.remotePort).slice(-26);

        console.log(new Date().toISOString() + socket.namePad + ' client connected');

        socket.on('data', function (request) {
            console.log(new Date().toISOString() + socket.namePad + '->' + request.toString('hex'));
            var tcpHeader = request.slice(0,6);
            callbackRequest(request.slice(6,request.length), function(reply) {
                var buf = Buffer.concat([tcpHeader, reply]);
                buf.writeUInt16BE(reply.length, 4);
                socket.write(buf);
                console.log(new Date().toISOString() + socket.namePad + '<-' + buf.toString('hex'));
            });
        });

        socket.on('end', function () {
            console.log(new Date().toISOString() + socket.namePad + ' client disconnected');
        });

        socket.on('close', function () {
            console.log(new Date().toISOString() + socket.namePad + ' connection closed');
        });

        socket.on('error', function () {
            console.log(new Date().toISOString() + socket.namePad + ' socket error');
        });

        socket.on('timeout', function () {
            console.log(new Date().toISOString() + socket.namePad + ' connection timeout');
            socket.destroy();
        });

        socket.setTimeout(10000);

    }).listen(context.port);

    console.log(new Date().toISOString() + ' Modbus TCP server is waiting for connections at 502 port');
}

module.exports = TCPModbusServerRaw;
<|endoftext|>


<commit_before>// saved buffer

var saveFlowTimeout = null;
var wordcount = 0;
var score = 0;
var sv_time = 0;
var flowing = false;

function saveFlow() {
    var text = $('#playingfield').val();
    var chars = text.length;
    var words = getWordCount(text);
    var flow_time = getElapsedSeconds();

    freezeFlowAndReset(text);

    wordcount += words;
    current_score = getScore(text, flow_time);
    score += current_score;

    scoreBoardUpdate(wordcount, score);

    updateFlowStatus();
    displayEncouragement(current_score);

    flowing = false;
}

function displayEncouragement(score) {
    var word;
    if (score > 50) { word = "okay"; }
    if (score > 100) { word = "cool"; }
    if (score > 200) { word = "nice"; }
    if (score > 300) { word = "sweet"; }
    if (score > 400) { word = "great"; }
    if (score > 600) { word = "awesome"; }
    if (score > 800) { word = "amazing"; }
    if (score > 1000) { word = "incredible"; }
    if (score > 1400) { word = "spectacular"; }
    if (score > 1800) { word = "unbelievable"; }
    if (score > 2200) { word = "extraordinary"; }
    $('.encouragement').html("
" + word + " flow!
");
    $('.encouragement').css("display", "block");
}

function hideEncouragement() {
    $('.encouragement').css("display", "none");
}

function freezeFlowAndReset(text) {
    $('.tekstflyt').before("

" + text + "

");
    $('#playingfield').val("");
}

function scoreBoardUpdate(wordcount, score) {
    $('#scoreboard').html("
Words: " + wordcount + " | Score: " + score + "
");
}

function scroll() {
    $("html, body").animate({ scrollTop: $('#playingfield').offset().top }, "slow");
}

// scores should be higher the longer the text is
// scores should be higher the longer the time is
// scores should be higher the higher the ratio of text to time is
function getScore(text, time) {
    var chars = text.length;
    var words = getWordCount(text);
    var wpm = (words / time) * 60;
    var score = Math.round(words*5*wpm/40);
    return score;
}

function getWordCount(text) {
    if (text == "") {
        return 0;
    }

    s = text.replace(/(^\s*)|(\s*$)/gi,"");
    s = s.replace(/[ ]{2,}/gi," ");
    s = s.replace(/\n /,"\n");
    return s.split(' ').length;
}

updateFlowStatus = function() {
    var text = $('#playingfield').val();
    var chars = text.length;
    var words = getWordCount(text);
    var seconds = getElapsedSeconds();
    var wpm = Math.round(words / seconds * 60);
    $('.stats').html('
Words: ' + words + ' (+' + words*5 + ' pts) | WPM: ' + wpm + ' (x' + (wpm / 40).toFixed(1) + ' bonus)

');
}

updateFlowState = function() {
    if (! flowing) {
        sv_time = getTime();
        hideEncouragement();
        flowing = true;
    }
    if (saveFlowTimeout) {
        window.clearTimeout(saveFlowTimeout);
    }

    updateFlowStatus();

    saveFlowTimeout = window.setTimeout(saveFlow, 1000);
}

function getTime() {
    return (new Date).getTime();
}

function getElapsedSeconds() {
    return (getTime() - sv_time) / 1000;
}

document.getElementById("playingfield").oninput = updateFlowState;

//function bind(sc, f) {
//    Mousetrap.bind(sc, function(e) {
//        if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; }
//        f();
//        status();
//    });
//}
//
//bind('ctrl+h', function() { left(); });
//bind('ctrl+l', function() { right(); });
//bind('ctrl+h', function() { left(); });
//bind('ctrl+l', function() { right(); });

//bind('alt+left', function() { left(); });
//bind('alt+right', function() { right(); });
//bind('alt+up', function() { commit(); });
//bind('alt+down', function() { scratch(); });

//bind('ctrl+s', function() { commit(); });
//bind('ctrl+space', function() { scratch(); });
<commit_msg>Make the default flow 'pathetic'<commit_after>// saved buffer

var saveFlowTimeout = null;
var wordcount = 0;
var score = 0;
var sv_time = 0;
var flowing = false;

function saveFlow() {
    var text = $('#playingfield').val();
    var chars = text.length;
    var words = getWordCount(text);
    var flow_time = getElapsedSeconds();

    freezeFlowAndReset(text);

    wordcount += words;
    current_score = getScore(text, flow_time);
    score += current_score;

    scoreBoardUpdate(wordcount, score);

    updateFlowStatus();
    displayEncouragement(current_score);

    flowing = false;
}

function displayEncouragement(score) {
    var word;
    word = "pathetic";
    if (score > 50) { word = "okay"; }
    if (score > 100) { word = "cool"; }
    if (score > 200) { word = "nice"; }
    if (score > 300) { word = "sweet"; }
    if (score > 400) { word = "great"; }
    if (score > 600) { word = "awesome"; }
    if (score > 800) { word = "amazing"; }
    if (score > 1000) { word = "incredible"; }
    if (score > 1400) { word = "spectacular"; }
    if (score > 1800) { word = "unbelievable"; }
    if (score > 2200) { word = "extraordinary"; }
    $('.encouragement').html("
" + word + " flow!
");
    $('.encouragement').css("display", "block");
}

function hideEncouragement() {
    $('.encouragement').css("display", "none");
}

function freezeFlowAndReset(text) {
    $('.tekstflyt').before("

" + text + "

");
    $('#playingfield').val("");
}

function scoreBoardUpdate(wordcount, score) {
    $('#scoreboard').html("
Words: " + wordcount + " | Score: " + score + "
");
}

function scroll() {
    $("html, body").animate({ scrollTop: $('#playingfield').offset().top }, "slow");
}

// scores should be higher the longer the text is
// scores should be higher the longer the time is
// scores should be higher the higher the ratio of text to time is
function getScore(text, time) {
    var chars = text.length;
    var words = getWordCount(text);
    var wpm = (words / time) * 60;
    var score = Math.round(words*5*wpm/40);
    return score;
}

function getWordCount(text) {
    if (text == "") {
        return 0;
    }

    s = text.replace(/(^\s*)|(\s*$)/gi,"");
    s = s.replace(/[ ]{2,}/gi," ");
    s = s.replace(/\n /,"\n");
    return s.split(' ').length;
}

updateFlowStatus = function() {
    var text = $('#playingfield').val();
    var chars = text.length;
    var words = getWordCount(text);
    var seconds = getElapsedSeconds();
    var wpm = Math.round(words / seconds * 60);
    $('.stats').html('
Words: ' + words + ' (+' + words*5 + ' pts) | WPM: ' + wpm + ' (x' + (wpm / 40).toFixed(1) + ' bonus)

');
}

updateFlowState = function() {
    if (! flowing) {
        sv_time = getTime();
        hideEncouragement();
        flowing = true;
    }
    if (saveFlowTimeout) {
        window.clearTimeout(saveFlowTimeout);
    }

    updateFlowStatus();

    saveFlowTimeout = window.setTimeout(saveFlow, 1000);
}

function getTime() {
    return (new Date).getTime();
}

function getElapsedSeconds() {
    return (getTime() - sv_time) / 1000;
}

document.getElementById("playingfield").oninput = updateFlowState;

//function bind(sc, f) {
//    Mousetrap.bind(sc, function(e) {
//        if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; }
//        f();
//        status();
//    });
//}
//
//bind('ctrl+h', function() { left(); });
//bind('ctrl+l', function() { right(); });
//bind('ctrl+h', function() { left(); });
//bind('ctrl+l', function() { right(); });

//bind('alt+left', function() { left(); });
//bind('alt+right', function() { right(); });
//bind('alt+up', function() { commit(); });
//bind('alt+down', function() { scratch(); });

//bind('ctrl+s', function() { commit(); });
//bind('ctrl+space', function() { scratch(); });
<|endoftext|>


<commit_before>(function () {
    var QueryResult = function($resource, $timeout) {
        var QueryResultResource = $resource('/api/query_results/:id', {id: '@id'}, {'post': {'method': 'POST'}});
        var Job = $resource('/api/jobs/:id', {id: '@id'});

        var updateFunction = function (props) {
            angular.extend(this, props);
            if ('query_result' in props) {
                this.status = "done";

                _.each(this.query_result.data.rows, function (row) {
                    _.each(row, function (v, k) {
                        if (_.isString(v) && v.match(/^\d{4}-\d{2}-\d{2}/)) {
                            row[k] = moment(v);
                        }
                    });
                });
            } else if (this.job.status == 3) {
                this.status = "processing";
            } else {
                this.status = undefined;
            }
        }

        function QueryResult(props) {
            this.job = {};
            this.query_result = {};
            this.status = "waiting";

            this.updatedAt = moment();

            if (props) {
                updateFunction.apply(this, [props]);
            }
        }

        var statuses = {
            1: "waiting",
            2: "processing",
            3: "done",
            4: "failed"
        }

        QueryResult.prototype.update = updateFunction;

        QueryResult.prototype.getId = function() {
            var id = null;
            if ('query_result' in this) {
                id = this.query_result.id;
            }
            return id;
        }

        QueryResult.prototype.getStatus = function() {
            return this.status || statuses[this.job.status];
        }

        QueryResult.prototype.getError = function() {
            // TODO: move this logic to the server...
            if (this.job.error == "None") {
                return undefined;
            }

            return this.job.error;
        }

        QueryResult.prototype.getUpdatedAt = function() {
            return this.query_result.retrieved_at || this.job.updated_at*1000.0 || this.updatedAt;
        }

        QueryResult.prototype.getRuntime = function() {
            return this.query_result.runtime;
        }

        QueryResult.prototype.getData = function() {
            if (!this.query_result.data) {
                return null;
            }

            var data = this.query_result.data.rows;
            return data;
        }

        QueryResult.prototype.getChartData = function () {
            var series = {};

            _.each(this.getData(), function (row) {
                var point = {};
                var seriesName = undefined;
                var xValue = 0;
                var yValues = {};

                _.each(row, function (value, definition) {
                    var type = definition.split("::")[1];
                    var name = definition.split("::")[0];

                    if (type == 'x') {
                        xValue = value;
                        point[type] = value;
                    }

                    if (type == 'y') {
                        yValues[name] = value;
                        point[type] = value;
                    }

                    if (type == 'series') {
                        seriesName = value.toString();
                    }
                });

                var addPointToSeries = function(seriesName, point) {
                    if (series[seriesName] == undefined) {
                        series[seriesName] = {
                            name: seriesName,
                            type: 'column',
                            data: []
                        }
                    }

                    series[seriesName]['data'].push(point);
                }

                if (seriesName === undefined) {
                    _.each(yValues, function(yValue, seriesName) {
                        addPointToSeries(seriesName, {'x': xValue, 'y': yValue});
                    });
                } else {
                    addPointToSeries(seriesName, point);
                }
            });

            _.each(series, function(series) {
                series.data = _.sortBy(series.data, 'x');
            });

            return _.values(series);
        };

        QueryResult.prototype.getColumns = function () {
            if (this.columns == undefined) {
                this.columns = _.map(this.query_result.data.columns, function(v) {
                    return v.name;
                })
            }

            return this.columns;
        }

        QueryResult.prototype.getColumnCleanName = function (column) {
            var parts = column.split('::');
            var name = parts[1];
            if (parts[0] != '') {
                name = parts[0].replace(/ /g, '_').replace(/\?/g,'');
            }
            return name;
        }

        QueryResult.prototype.getColumnFriendlyName = function (column) {
            return this.getColumnCleanName(column).replace(/_/g, ' ').replace(/(?:^|\s)\S/g, function (a) {
                return a.toUpperCase();
            });
        }

        QueryResult.prototype.getColumnCleanNames = function () {
            return _.map(this.getColumns(), function (col) {
                return this.getColumnCleanName(col);
            }, this);
        }

        QueryResult.prototype.getColumnFriendlyNames = function () {
            return _.map(this.getColumns(), function (col) {
                return this.getColumnFriendlyName(col);
            }, this);
        }

        QueryResult.prototype.getFilters = function () {
            var filterNames = [];
            _.each(this.getColumns(), function (col) {
                if (col.split('::')[1] == 'filter') {
                    filterNames.push(col);
                }
            });

            var filterValues = [];
            _.each(this.getData(), function (row) {
                _.each(filterNames, function (filter, i) {
                    if (filterValues[i] == undefined) {
                        filterValues[i] = [];
                    }
                    filterValues[i].push(row[filter]);
                })
            });

            var filters = _.map(filterNames, function (filter, i) {
                var f = {
                    name: filter,
                    friendlyName: this.getColumnFriendlyName(filter),
                    values: _.uniq(filterValues[i])
                };

                f.current = f.values[0];
                return f;
            }, this);

            return filters;
        };

        var refreshStatus = function(queryResult, query, ttl) {
            Job.get({'id': queryResult.job.id}, function(response) {
                queryResult.update(response);

                if (queryResult.getStatus() == "processing" && queryResult.job.query_result_id && queryResult.job.query_result_id != "None") {
                    QueryResultResource.get({'id': queryResult.job.query_result_id}, function(response) {
                        queryResult.update(response);
                    });
                } else if (queryResult.getStatus() != "failed") {
                    $timeout(function () {
                        refreshStatus(queryResult, query, ttl);
                    }, 3000);
                }
            })
        }

        QueryResult.getById = function (id) {
            var queryResult = new QueryResult();

            QueryResultResource.get({'id': id}, function (response) {
                queryResult.update(response);
            });

            return queryResult;
        }

        QueryResult.get = function (query, ttl) {
            var queryResult = new QueryResult();

            QueryResultResource.post({'query': query, 'ttl': ttl}, function (response) {
                queryResult.update(response);

                if ('job' in response) {
                    refreshStatus(queryResult, query, ttl);
                }
            });

            return queryResult;
        }

        return QueryResult;
    }

    var Query = function ($resource, QueryResult) {
        var Query = $resource('/api/queries/:id', {id: '@id'});

        Query.prototype.getQueryResult = function(ttl) {
            if (ttl == undefined) {
                ttl = this.ttl;
            }

            var queryResult = null;
            if (this.latest_query_data && ttl != 0) {
                queryResult = new QueryResult({'query_result': this.latest_query_data});
            } else if (this.latest_query_data_id && ttl != 0) {
                queryResult = QueryResult.getById(this.latest_query_data_id);
            } else {
                queryResult = QueryResult.get(this.query, ttl);
            }

            return queryResult;
        }

        return Query;
    }

    angular.module('redash.services', [])
        .factory('QueryResult', ['$resource', '$timeout', QueryResult])
        .factory('Query', ['$resource', 'QueryResult', Query])

})();
<commit_msg>Fix: use String ctor function instead of toString to handle nulls<commit_after>(function () {
    var QueryResult = function($resource, $timeout) {
        var QueryResultResource = $resource('/api/query_results/:id', {id: '@id'}, {'post': {'method': 'POST'}});
        var Job = $resource('/api/jobs/:id', {id: '@id'});

        var updateFunction = function (props) {
            angular.extend(this, props);
            if ('query_result' in props) {
                this.status = "done";

                _.each(this.query_result.data.rows, function (row) {
                    _.each(row, function (v, k) {
                        if (_.isString(v) && v.match(/^\d{4}-\d{2}-\d{2}/)) {
                            row[k] = moment(v);
                        }
                    });
                });
            } else if (this.job.status == 3) {
                this.status = "processing";
            } else {
                this.status = undefined;
            }
        }

        function QueryResult(props) {
            this.job = {};
            this.query_result = {};
            this.status = "waiting";

            this.updatedAt = moment();

            if (props) {
                updateFunction.apply(this, [props]);
            }
        }

        var statuses = {
            1: "waiting",
            2: "processing",
            3: "done",
            4: "failed"
        }

        QueryResult.prototype.update = updateFunction;

        QueryResult.prototype.getId = function() {
            var id = null;
            if ('query_result' in this) {
                id = this.query_result.id;
            }
            return id;
        }

        QueryResult.prototype.getStatus = function() {
            return this.status || statuses[this.job.status];
        }

        QueryResult.prototype.getError = function() {
            // TODO: move this logic to the server...
            if (this.job.error == "None") {
                return undefined;
            }

            return this.job.error;
        }

        QueryResult.prototype.getUpdatedAt = function() {
            return this.query_result.retrieved_at || this.job.updated_at*1000.0 || this.updatedAt;
        }

        QueryResult.prototype.getRuntime = function() {
            return this.query_result.runtime;
        }

        QueryResult.prototype.getData = function() {
            if (!this.query_result.data) {
                return null;
            }

            var data = this.query_result.data.rows;
            return data;
        }

        QueryResult.prototype.getChartData = function () {
            var series = {};

            _.each(this.getData(), function (row) {
                var point = {};
                var seriesName = undefined;
                var xValue = 0;
                var yValues = {};

                _.each(row, function (value, definition) {
                    var type = definition.split("::")[1];
                    var name = definition.split("::")[0];

                    if (type == 'x') {
                        xValue = value;
                        point[type] = value;
                    }

                    if (type == 'y') {
                        yValues[name] = value;
                        point[type] = value;
                    }

                    if (type == 'series') {
                        seriesName = value ? value.toString() : "null";
                    }
                });

                var addPointToSeries = function(seriesName, point) {
                    if (series[seriesName] == undefined) {
                        series[seriesName] = {
                            name: seriesName,
                            type: 'column',
                            data: []
                        }
                    }

                    series[seriesName]['data'].push(point);
                }

                if (seriesName === undefined) {
                    _.each(yValues, function(yValue, seriesName) {
                        addPointToSeries(seriesName, {'x': xValue, 'y': yValue});
                    });
                } else {
                    addPointToSeries(seriesName, point);
                }
            });

            _.each(series, function(series) {
                series.data = _.sortBy(series.data, 'x');
            });

            return _.values(series);
        };

        QueryResult.prototype.getColumns = function () {
            if (this.columns == undefined) {
                this.columns = _.map(this.query_result.data.columns, function(v) {
                    return v.name;
                })
            }

            return this.columns;
        }

        QueryResult.prototype.getColumnCleanName = function (column) {
            var parts = column.split('::');
            var name = parts[1];
            if (parts[0] != '') {
                name = parts[0].replace(/ /g, '_').replace(/\?/g,'');
            }
            return name;
        }

        QueryResult.prototype.getColumnFriendlyName = function (column) {
            return this.getColumnCleanName(column).replace(/_/g, ' ').replace(/(?:^|\s)\S/g, function (a) {
                return a.toUpperCase();
            });
        }

        QueryResult.prototype.getColumnCleanNames = function () {
            return _.map(this.getColumns(), function (col) {
                return this.getColumnCleanName(col);
            }, this);
        }

        QueryResult.prototype.getColumnFriendlyNames = function () {
            return _.map(this.getColumns(), function (col) {
                return this.getColumnFriendlyName(col);
            }, this);
        }

        QueryResult.prototype.getFilters = function () {
            var filterNames = [];
            _.each(this.getColumns(), function (col) {
                if (col.split('::')[1] == 'filter') {
                    filterNames.push(col);
                }
            });

            var filterValues = [];
            _.each(this.getData(), function (row) {
                _.each(filterNames, function (filter, i) {
                    if (filterValues[i] == undefined) {
                        filterValues[i] = [];
                    }
                    filterValues[i].push(row[filter]);
                })
            });

            var filters = _.map(filterNames, function (filter, i) {
                var f = {
                    name: filter,
                    friendlyName: this.getColumnFriendlyName(filter),
                    values: _.uniq(filterValues[i])
                };

                f.current = f.values[0];
                return f;
            }, this);

            return filters;
        };

        var refreshStatus = function(queryResult, query, ttl) {
            Job.get({'id': queryResult.job.id}, function(response) {
                queryResult.update(response);

                if (queryResult.getStatus() == "processing" && queryResult.job.query_result_id && queryResult.job.query_result_id != "None") {
                    QueryResultResource.get({'id': queryResult.job.query_result_id}, function(response) {
                        queryResult.update(response);
                    });
                } else if (queryResult.getStatus() != "failed") {
                    $timeout(function () {
                        refreshStatus(queryResult, query, ttl);
                    }, 3000);
                }
            })
        }

        QueryResult.getById = function (id) {
            var queryResult = new QueryResult();

            QueryResultResource.get({'id': id}, function (response) {
                queryResult.update(response);
            });

            return queryResult;
        }

        QueryResult.get = function (query, ttl) {
            var queryResult = new QueryResult();

            QueryResultResource.post({'query': query, 'ttl': ttl}, function (response) {
                queryResult.update(response);

                if ('job' in response) {
                    refreshStatus(queryResult, query, ttl);
                }
            });

            return queryResult;
        }

        return QueryResult;
    }

    var Query = function ($resource, QueryResult) {
        var Query = $resource('/api/queries/:id', {id: '@id'});

        Query.prototype.getQueryResult = function(ttl) {
            if (ttl == undefined) {
                ttl = this.ttl;
            }

            var queryResult = null;
            if (this.latest_query_data && ttl != 0) {
                queryResult = new QueryResult({'query_result': this.latest_query_data});
            } else if (this.latest_query_data_id && ttl != 0) {
                queryResult = QueryResult.getById(this.latest_query_data_id);
            } else {
                queryResult = QueryResult.get(this.query, ttl);
            }

            return queryResult;
        }

        return Query;
    }

    angular.module('redash.services', [])
        .factory('QueryResult', ['$resource', '$timeout', QueryResult])
        .factory('Query', ['$resource', 'QueryResult', Query])

})();
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */
var Canvas = require('term-canvas')
    , cp = require('child_process')
    , EventEmitter = require('events').EventEmitter
    , util = require('util')
    , path = require('path')
    , exec = cp.exec
    , spawn = cp.spawn;

//process.stdout.getWindowSize()
var canvas = new Canvas(100, 100)
  , ctx = canvas.getContext('2d')
  , max_limit = 10;

module.exports = TermChart;

process.on('SIGINT', function(){
  ctx.reset();
  process.nextTick(function(){
    process.exit();
  });
});

ctx.hideCursor();

function TermChart() {
    EventEmitter.apply(this);
}

util.inherits(TermChart, EventEmitter);
TermChart.prototype.max_limit = function(limit){
    this.max_limit = limit;
}

TermChart.prototype.draw = function(arr)
{
    ctx.clearRect(0,0,canvas.width, canvas.height);
    x = 3;
    arr.forEach(function(n){
        var y = 30
          , w = 5
          , h = 30*(n/max_limit);

        ctx.fillStyle = 'white';
        ctx.fillRect(x, y-h+3, w, h);
        ctx.fillStyle = 'black';
        ctx.fillText(n.toString(), x+2, y+1);
        x += 9;
    });
}

TermChart.prototype.trackLog = function(filename) {
    var fp = path.resolve(process.cwd(), filename);
    this.filename = fp;
    this.tail = spawn('tail', ['-F', this.filename]);
    this.tail.stdout.setEncoding('utf8');
    var lines = require('lines');
    lines(this.tail.stdout);
    termchart = this;

    this.tail.stdout.on('line', function(line){
        termchart.draw(line.split(" "));
    });

    this.tail.once('exit', function(code, signal){
        console.log("exit");
    });

   /* this.on('end', function(){
        console.log("end");
    });*/
}

var t = new TermChart();
t.trackLog("log.txt");
<commit_msg>refactor<commit_after>
/**
 * Module dependencies.
 */
var Canvas = require('term-canvas')
    , cp = require('child_process')
    , EventEmitter = require('events').EventEmitter
    , util = require('util')
    , path = require('path')
    , spawn = cp.spawn;

//process.stdout.getWindowSize()
var canvas = new Canvas(100, 100)
  , ctx = canvas.getContext('2d');

module.exports = TermChart;

//Clear canvas when recieved terminate signal like [^C]
process.on('SIGINT', function(){
  ctx.reset();
  process.nextTick(function(){
    process.exit();
  });
});

// hide curser from context
ctx.hideCursor();

/*
 * Our termchart object inherits from eventemitter
 */
function TermChart() {
    EventEmitter.apply(this);
}
util.inherits(TermChart, EventEmitter);

/*
 *  max limit of chart
 *  @param limit
 */
TermChart.prototype.max_limit = function(limit){
    this.max_limit = limit;
}

/*
 *  Draw the given data array into the canvas
 *  @param arr contains the last line of the file
 */
TermChart.prototype.draw = function(arr)
{
    ctx.clearRect(0,0,canvas.width, canvas.height);
    x = 3;
    termchart = this;
    arr.forEach(function(n){
        var y = 30
          , w = 5
          , h = 30*(n/termchart.max_limit);

        ctx.fillStyle = 'white';
        ctx.fillRect(x, y-h+3, w, h);
        ctx.fillStyle = 'black';
        ctx.fillText(n.toString(), x+2, y+1);
        x += 9;
    });
}

/**
 *  Execute tail as child process.
 *  Generate for every single line appended
 *  @param absolute path of the file
 */
TermChart.prototype.execTail = function(filename){
    this.filename = filename;

    this.tail = spawn('tail', ['-F', this.filename]);
    this.tail.stdout.setEncoding('utf8');
    var lines = require('lines');
    lines(this.tail.stdout);
    termchart = this;
    this.tail.stdout.on('line', function(line){
        termchart.draw(line.split(" "));
    });

    this.tail.once('exit', function(code, signal){
        termchart.emit('error', new Error("tail subprocess ended badly"));
        termchart.emit('endtermchart');
    });
}

/**
 *  Track file. if data is appended the generate
 *  event to update the chart.
 *  @param filename
 */
TermChart.prototype.trackLog = function(filename) {
    var fp = path.resolve(process.cwd(), filename);
    this.execTail(fp);
    this.on('endtermchart', function(){
        this.tail.kill();
    })
}

TermChart.prototype.close = function(){
    this.emit('endtermchart');
}

var t = new TermChart();
t.max_limit(10);
t.trackLog("log.txt");
<|endoftext|>