<commit_before>
    $j(document).ready(function()     {
        var idx = $j("#editIndex").attr("value");
        var editType = $j("#editType").attr("value");
        if (idx != undefined && idx != -1) {
            if (editType == 'active') {
                $j("#A"+idx).click();
                if ($j("#financialEntityHelper\\.activeFinancialEntities\\["+idx+"\\]\\.finEntityContactInfos\\[0\\]\\.countryCode").length > 0) {
                    var countryCode = $j("#financialEntityHelper\\.activeFinancialEntities\\["+idx+"\\]\\.finEntityContactInfos\\[0\\]\\.countryCode").val();
                    if (countryCode != '' && countryCode != 'USA') {
                       updateStateCode('financialEntityHelper.activeFinancialEntities['+idx+'].finEntityContactInfos[0].countryCode', '');
                    }
                }

                $j("#financialEntityHelper\\.activeFinancialEntities\\["+idx+"\\]\\.sponsorCode").focus(function() {
                    displayAlertMessage('messageBox'+idx, 'The entity address fields will be overriden when a valid sponsor code is entered');
                });
            } else {
                $j("#A"+idx+"i").click();
                if ($j("#financialEntityHelper\\.inactiveFinancialEntities\\["+idx+"\\]\\.finEntityContactInfos\\[0\\]\\.countryCode").length > 0) {
                    var countryCode = $j("#financialEntityHelper\\.inactiveFinancialEntities\\["+idx+"\\]\\.finEntityContactInfos\\[0\\]\\.countryCode").val();
                    if (countryCode != '' && countryCode != 'USA') {
                       updateStateCode('financialEntityHelper.inactiveFinancialEntities['+idx+'].finEntityContactInfos[0].countryCode', '');
                    }
                }

                $j("#financialEntityHelper\\.inactiveFinancialEntities\\["+idx+"\\]\\.sponsorCode").focus(function() {
                    displayAlertMessage('messageBox'+idx, 'The entity address fields will be overriden when a valid sponsor code is entered');
                });
            }
        }

        $j("#financialEntityHelper\\.newPersonFinancialEntity\\.sponsorCode").focus(function() {
            displayAlertMessage('messageBox', 'The entity address fields will be overriden when a valid sponsor code is entered');
          //return false;
        });

        if ($j("#financialEntityHelper\\.newPersonFinancialEntity\\.finEntityContactInfos\\[0\\]\\.countryCode").length > 0) {
             // ".length >0" check to make sure this element does exist
              var countryCode = $j("#financialEntityHelper\\.newPersonFinancialEntity\\.finEntityContactInfos\\[0\\]\\.countryCode").val();
              if (countryCode != '' && countryCode != 'USA') {
                  updateStateCode('financialEntityHelper.newPersonFinancialEntity.finEntityContactInfos[0].countryCode', '');
              }
        }

        $j('input[name^="methodToCall.performLookup.(!!org.kuali.kra.bo.Sponsor!!)"]').click(function() {
            if(!confirm('The entity address fields will be overriden when a valid sponsor is selected.  Do you want to continue ?')) {
                return false;
            }
        });

      // there are 2 different rows, one is the entity name/sponsor .. row, and the other row is
      // this history header row of the entity listed above.  However, the sorter can't distinguish them.
      // this widget is to reloacate the 'history row' back immediately following its belonging entity.
        $j.tablesorter.addWidget({
             // give the widget a id
            id: "relocaterow",
            // format is called when the on init and when a sorting has finished
            format: function(table) {

            // loop all tr elements and insert a copy of the "headers"
                for(var i=0; i
 1) {
                        var idx = $j(table.tBodies[0].rows[i]).attr("id").substring(6); // "hdrrowxx"
                        var tableRow = $j("#G"+idx);
                        $j(tableRow).insertAfter(table.tBodies[0].rows[i]);
                    }
                }
            }
        });

 // there is no proper parser for date/time field.  'shortDate is only for date'
 // add this parser for 'last update' column
        $j.tablesorter.addParser({
            id: "datetime",
            is: function(s) {
                return s.match(new RegExp(/^([0]\d|[1][0-2])\/([0-2]\d|[3][0-1])\/([2][01]|[1][6-9])\d{2}(\s([0]\d|[1][0-2])(\:[0-5]\d){1,2})*\s*([aApP][mM]{0,2})?$/));
            },
            format: function(s) {
                return $j.tablesorter.formatFloat(new Date(s).getTime());
            },
            type: "numeric"
        });

// call the tablesorter plugin and assign widgets with id "zebra" (Default widget in the core) and the newly created "relocaterow"

      try {
      $j("#activeEntities-table").tablesorter(

        // pass the headers argument and assing a object
         {  widgets: ['zebra','relocaterow'],
           // initial sort on 2nd column (entity name) on ascending order
            sortList: [[1,0]],
            // "header" is conflict with kuali-stylesheet.css; so
            cssHeader: "sorterheader",
            headers: {             // assign the first column (we start counting zero)
               0: {                 // disable it by setting the property sorter to false
                  sorter: false             },
               3: {sorter:'datetime' },
               4: {                 // disable it by setting the property sorter to false
                   sorter: false             }
                     }
          }
          );
     } catch (err) {
       // if active list is empty, then .ready skipped the rest of codes.  not sure why.
       // so use this try catch to keep it going.
     }

      try {
      $j("#inActiveEntities-table").tablesorter(

           {  widgets: ['zebra','relocaterow'],
              sortList: [[1,0]],
            // "header" is conflict with kuali-stylesheet.css; so
            cssHeader: "sorterheader",
              headers: {             // assign the first column (we start counting zero)
                 0: {                 // disable it by setting the property sorter to false
                    sorter: false             },
                 3: {sorter:'datetime' },
                 4: {                 // disable it by setting the property sorter to false
                     sorter: false             }
                     }
            }
          );
     } catch (err) {
       // if inactive list is empty, then .ready skipped the rest of codes.  not sure why.
       // so use this try catch to keep it going.
       // alert("inactive table sorter has error "+err);
     }
           if ($j(".financialEntitySubpanel").length > 0) {
               $j(".financialEntitySubpanel").toggle(
                        function()
                        {
                            var controlId = $j(this).attr("id");
                            var contentId = controlId.replace("Control","Content");
                            $j("#"+contentId).slideDown(500);
                            $j(this).html("");
                        },function(){
                            var controlId = $j(this).attr("id");
                            var contentId = controlId.replace("Control","Content");
                            $j("#"+contentId).slideUp(500);
                            $j(this).html("");
                        }
               );
               $j(".financialEntitySubpanel").click();
           }

           $j(".relationDetailSubpanel").toggle(
                        function()
                        {
                            var controlId = $j(this).attr("id");
                            var contentId = controlId.replace("Control","Content");
                            $j("#"+contentId).slideDown(500);
                            $j(this).html("");
                        },function(){
                            var controlId = $j(this).attr("id");
                            var contentId = controlId.replace("Control","Content");
                            $j("#"+contentId).slideUp(500);
                            $j(this).html("");
                        }
               );
                $j(".relationDetailSubpanelContent").hide();

  // the show/hide for entity and relation detail panels are not from kuali framework
  // so to override the onclick here to also expand entity and relation detail panels
  // first remove the 'onclick' attribute, then add 'click' function
  $j('input[name=methodToCall\\.showAllTabs]').attr('onclick', '').click(function() {
		expandAllTab();
		if ($j("#financialEntityControl").html().indexOf("show.gif") > -1) {
            $j("#financialEntityControl").click();
        }
		if ($j("#relationDetailControl").html().indexOf("show.gif") > -1) {
            $j("#relationDetailControl").click();
        }
        return false;
	});

    } );  // end document.ready

    function displayAlertMessage(messagedivid, message) {
        var timeOut = 5
        $j('#'+messagedivid).text(message).fadeIn().css({"display":"block","color":"red"});
        setTimeout(function() {
            $j('#'+messagedivid).fadeOut().css("display", "none");
         }, timeOut * 1000);
    }

    function updateStateOnClick(countryCodeFieldName) {
    	var stateField = findElPrefix( countryCodeFieldName )+".state";
	    var countryCode = DWRUtil.getValue( countryCodeFieldName );
        updateStateCode(countryCodeFieldName, $(stateField).value);
    }

    function updateStateCode(countryCodeFieldName, state) {
    var stateField = findElPrefix( countryCodeFieldName )+".state";
    var countryCode = DWRUtil.getValue( countryCodeFieldName);

    var dwrReply = {
        callback:function(data) {
            	if ( data != null && data.length > 0 ) {
            		$(stateField).disabled = false;
                	DWRUtil.removeAllOptions( stateField );
                	$(stateField).options[0] = new Option('', '');
                	DWRUtil.addOptions( stateField, data, 'postalStateCode', 'postalStateName' );
                	if (state != '') {
                        DWRUtil.setValue(stateField, state);
                	}
	            } else {
	                DWRUtil.setValue(stateField, '');
       	    		$(stateField).disabled = true;
            }
        },
        errorHandler:function( errorMessage ) {
            window.status = errorMessage;
        }
    };

    StateService.findAllStatesByAltCountryCode(countryCode, dwrReply);
    }

    function loadEntityContactInfoFromRolodex(rolodexId, prefix) {
//        var rolodexId = DWRUtil.getValue( rolodexFieldName );

        if (rolodexId != '') {
            var dwrReply = {
                callback:function(data) {
                    if ( data != null ) {
                        DWRUtil.setValue(prefix+".addressLine1", data.addressLine1);
                        DWRUtil.setValue(prefix+".addressLine2", data.addressLine2);
                        DWRUtil.setValue(prefix+".addressLine3", data.addressLine3);
                        DWRUtil.setValue(prefix+".city", data.city);
                        DWRUtil.setValue(prefix+".countryCode", data.countryCode);
                        updateStateCode(prefix+".countryCode", data.state)
                        DWRUtil.setValue(prefix+".state", data.state);
                        DWRUtil.setValue(prefix+".postalCode", data.postalCode);
                    }
                },
                errorHandler:function( errorMessage ) {
                    window.status = errorMessage;
                }
            };
            RolodexService.getRolodex(rolodexId, dwrReply);
        }

}
    <commit_msg>KCCOI-90: Add ability to associate attachments to Financial Entities<commit_after>
    $j(document).ready(function()     {
        var idx = $j("#editIndex").attr("value");
        var editType = $j("#editType").attr("value");
        if (idx != undefined && idx != -1) {
            if (editType == 'active') {
                $j("#A"+idx).click();
                if ($j("#financialEntityHelper\\.activeFinancialEntities\\["+idx+"\\]\\.finEntityContactInfos\\[0\\]\\.countryCode").length > 0) {
                    var countryCode = $j("#financialEntityHelper\\.activeFinancialEntities\\["+idx+"\\]\\.finEntityContactInfos\\[0\\]\\.countryCode").val();
                    if (countryCode != '' && countryCode != 'USA') {
                       updateStateCode('financialEntityHelper.activeFinancialEntities['+idx+'].finEntityContactInfos[0].countryCode', '');
                    }
                }

                $j("#financialEntityHelper\\.activeFinancialEntities\\["+idx+"\\]\\.sponsorCode").focus(function() {
                    displayAlertMessage('messageBox'+idx, 'The entity address fields will be overriden when a valid sponsor code is entered');
                });
            } else {
                $j("#A"+idx+"i").click();
                if ($j("#financialEntityHelper\\.inactiveFinancialEntities\\["+idx+"\\]\\.finEntityContactInfos\\[0\\]\\.countryCode").length > 0) {
                    var countryCode = $j("#financialEntityHelper\\.inactiveFinancialEntities\\["+idx+"\\]\\.finEntityContactInfos\\[0\\]\\.countryCode").val();
                    if (countryCode != '' && countryCode != 'USA') {
                       updateStateCode('financialEntityHelper.inactiveFinancialEntities['+idx+'].finEntityContactInfos[0].countryCode', '');
                    }
                }

                $j("#financialEntityHelper\\.inactiveFinancialEntities\\["+idx+"\\]\\.sponsorCode").focus(function() {
                    displayAlertMessage('messageBox'+idx, 'The entity address fields will be overriden when a valid sponsor code is entered');
                });
            }
        }

        $j("#financialEntityHelper\\.newPersonFinancialEntity\\.sponsorCode").focus(function() {
            displayAlertMessage('messageBox', 'The entity address fields will be overriden when a valid sponsor code is entered');
          //return false;
        });

        if ($j("#financialEntityHelper\\.newPersonFinancialEntity\\.finEntityContactInfos\\[0\\]\\.countryCode").length > 0) {
             // ".length >0" check to make sure this element does exist
              var countryCode = $j("#financialEntityHelper\\.newPersonFinancialEntity\\.finEntityContactInfos\\[0\\]\\.countryCode").val();
              if (countryCode != '' && countryCode != 'USA') {
                  updateStateCode('financialEntityHelper.newPersonFinancialEntity.finEntityContactInfos[0].countryCode', '');
              }
        }

        $j('input[name^="methodToCall.performLookup.(!!org.kuali.kra.bo.Sponsor!!)"]').click(function() {
            if(!confirm('The entity address fields will be overriden when a valid sponsor is selected.  Do you want to continue ?')) {
                return false;
            }
        });

      // there are 2 different rows, one is the entity name/sponsor .. row, and the other row is
      // this history header row of the entity listed above.  However, the sorter can't distinguish them.
      // this widget is to reloacate the 'history row' back immediately following its belonging entity.
        $j.tablesorter.addWidget({
             // give the widget a id
            id: "relocaterow",
            // format is called when the on init and when a sorting has finished
            format: function(table) {

            // loop all tr elements and insert a copy of the "headers"
                for(var i=0; i
 1) {
                        var idx = $j(table.tBodies[0].rows[i]).attr("id").substring(6); // "hdrrowxx"
                        var tableRow = $j("#G"+idx);
                        $j(tableRow).insertAfter(table.tBodies[0].rows[i]);
                    }
                }
            }
        });

 // there is no proper parser for date/time field.  'shortDate is only for date'
 // add this parser for 'last update' column
        $j.tablesorter.addParser({
            id: "datetime",
            is: function(s) {
                return s.match(new RegExp(/^([0]\d|[1][0-2])\/([0-2]\d|[3][0-1])\/([2][01]|[1][6-9])\d{2}(\s([0]\d|[1][0-2])(\:[0-5]\d){1,2})*\s*([aApP][mM]{0,2})?$/));
            },
            format: function(s) {
                return $j.tablesorter.formatFloat(new Date(s).getTime());
            },
            type: "numeric"
        });

// call the tablesorter plugin and assign widgets with id "zebra" (Default widget in the core) and the newly created "relocaterow"

      try {
      $j("#activeEntities-table").tablesorter(

        // pass the headers argument and assing a object
         {  widgets: ['zebra','relocaterow'],
           // initial sort on 2nd column (entity name) on ascending order
            sortList: [[1,0]],
            // "header" is conflict with kuali-stylesheet.css; so
            cssHeader: "sorterheader",
            headers: {             // assign the first column (we start counting zero)
               0: {                 // disable it by setting the property sorter to false
                  sorter: false             },
               3: {sorter:'datetime' },
               4: {                 // disable it by setting the property sorter to false
                   sorter: false             }
                     }
          }
          );
     } catch (err) {
       // if active list is empty, then .ready skipped the rest of codes.  not sure why.
       // so use this try catch to keep it going.
     }

      try {
      $j("#inActiveEntities-table").tablesorter(

           {  widgets: ['zebra','relocaterow'],
              sortList: [[1,0]],
            // "header" is conflict with kuali-stylesheet.css; so
            cssHeader: "sorterheader",
              headers: {             // assign the first column (we start counting zero)
                 0: {                 // disable it by setting the property sorter to false
                    sorter: false             },
                 3: {sorter:'datetime' },
                 4: {                 // disable it by setting the property sorter to false
                     sorter: false             }
                     }
            }
          );
     } catch (err) {
       // if inactive list is empty, then .ready skipped the rest of codes.  not sure why.
       // so use this try catch to keep it going.
       // alert("inactive table sorter has error "+err);
     }
           if ($j(".financialEntitySubpanel").length > 0) {
               $j(".financialEntitySubpanel").toggle(
                        function()
                        {
                            var controlId = $j(this).attr("id");
                            var contentId = controlId.replace("Control","Content");
                            $j("#"+contentId).slideDown(500);
                            $j(this).html("");
                        },function(){
                            var controlId = $j(this).attr("id");
                            var contentId = controlId.replace("Control","Content");
                            $j("#"+contentId).slideUp(500);
                            $j(this).html("");
                        }
               );
               $j(".financialEntitySubpanel").click();
           }

           $j(".relationDetailSubpanel").toggle(
                        function()
                        {
                            var controlId = $j(this).attr("id");
                            var contentId = controlId.replace("Control","Content");
                            $j("#"+contentId).slideDown(500);
                            $j(this).html("");
                        },function(){
                            var controlId = $j(this).attr("id");
                            var contentId = controlId.replace("Control","Content");
                            $j("#"+contentId).slideUp(500);
                            $j(this).html("");
                        }
               );
           $j(".relationDetailSubpanelContent").hide();

           $j(".finEntityAttachmentsSubpanel").toggle(
                        function()
                        {
                            var controlId = $j(this).attr("id");
                            var contentId = controlId.replace("Control","Content");
                            $j("#"+contentId).slideDown(500);
                            $j(this).html("");
                        },function(){
                            var controlId = $j(this).attr("id");
                            var contentId = controlId.replace("Control","Content");
                            $j("#"+contentId).slideUp(500);
                            $j(this).html("");
                        }
               );
           $j(".finEntityAttachmentsSubpanelContent").hide();

  // the show/hide for entity and relation detail panels are not from kuali framework
  // so to override the onclick here to also expand entity and relation detail panels
  // first remove the 'onclick' attribute, then add 'click' function
  $j('input[name=methodToCall\\.showAllTabs]').attr('onclick', '').click(function() {
		expandAllTab();
		if ($j("#financialEntityControl").html().indexOf("show.gif") > -1) {
            $j("#financialEntityControl").click();
        }
		if ($j("#relationDetailControl").html().indexOf("show.gif") > -1) {
            $j("#relationDetailControl").click();
        }
        return false;
	});

    } );  // end document.ready

    function displayAlertMessage(messagedivid, message) {
        var timeOut = 5
        $j('#'+messagedivid).text(message).fadeIn().css({"display":"block","color":"red"});
        setTimeout(function() {
            $j('#'+messagedivid).fadeOut().css("display", "none");
         }, timeOut * 1000);
    }

    function updateStateOnClick(countryCodeFieldName) {
    	var stateField = findElPrefix( countryCodeFieldName )+".state";
	    var countryCode = DWRUtil.getValue( countryCodeFieldName );
        updateStateCode(countryCodeFieldName, $(stateField).value);
    }

    function updateStateCode(countryCodeFieldName, state) {
    var stateField = findElPrefix( countryCodeFieldName )+".state";
    var countryCode = DWRUtil.getValue( countryCodeFieldName);

    var dwrReply = {
        callback:function(data) {
            	if ( data != null && data.length > 0 ) {
            		$(stateField).disabled = false;
                	DWRUtil.removeAllOptions( stateField );
                	$(stateField).options[0] = new Option('', '');
                	DWRUtil.addOptions( stateField, data, 'postalStateCode', 'postalStateName' );
                	if (state != '') {
                        DWRUtil.setValue(stateField, state);
                	}
	            } else {
	                DWRUtil.setValue(stateField, '');
       	    		$(stateField).disabled = true;
            }
        },
        errorHandler:function( errorMessage ) {
            window.status = errorMessage;
        }
    };

    StateService.findAllStatesByAltCountryCode(countryCode, dwrReply);
    }

    function loadEntityContactInfoFromRolodex(rolodexId, prefix) {
//        var rolodexId = DWRUtil.getValue( rolodexFieldName );

        if (rolodexId != '') {
            var dwrReply = {
                callback:function(data) {
                    if ( data != null ) {
                        DWRUtil.setValue(prefix+".addressLine1", data.addressLine1);
                        DWRUtil.setValue(prefix+".addressLine2", data.addressLine2);
                        DWRUtil.setValue(prefix+".addressLine3", data.addressLine3);
                        DWRUtil.setValue(prefix+".city", data.city);
                        DWRUtil.setValue(prefix+".countryCode", data.countryCode);
                        updateStateCode(prefix+".countryCode", data.state)
                        DWRUtil.setValue(prefix+".state", data.state);
                        DWRUtil.setValue(prefix+".postalCode", data.postalCode);
                    }
                },
                errorHandler:function( errorMessage ) {
                    window.status = errorMessage;
                }
            };
            RolodexService.getRolodex(rolodexId, dwrReply);
        }

}
    <|endoftext|>


<commit_before>#!/usr/bin/env node

var exec = require('child_process').exec;
var spawn = require('child_process').spawn;

// MDM NOTE that node v0.12 or higher is required for this.
var execSync = require('child_process').execSync;
var spawnSync = require('child_process').spawnSync;

var spawnargs = require('spawn-args');

//=========== run_command_sync_to_console: run one command and let output immediately flow to console ============
var run_command_sync_to_console = function (cmd) {
    execSync(cmd, {stdio:[0,1,2]}, function(error, stdout, stderr) {
        if (error) {
            console.log('======= RUN ERROR =======');
            throw error;
        }
    });
}

//=========== run_command_async_to_console: async run one command and dump output to console when complete ============
var run_command_async_to_console = function (cmd) {
    exec(cmd, function(error, stdout, stderr) {
        if (stdout.length > 0 ) console.log(stdout);
        if (stderr.length > 0 ) console.log(stderr);
    });
}

//=========== run_command_quietly: runs without output unless error ============
var run_command_quietly = function (cmd) {
    execSync(cmd, function(error, stdout, stderr) {
        if (error) {
            console.log('======= RUN ERROR =======');
            throw error;
        }
    });
}

// =========== run_command: run one command and get output ============
// Run a command asynchronously and get the output when it finishes in a callback.
// Usage:
// run_command( "ls -l", function(text) { console.log (text) });
var run_command = function (cmd, callBack ) {

    var fullargs = spawnargs(cmd);
    cmd = fullargs[0];
    var args = fullargs.slice(1);

    // DEBUG this works!
    // var args = ["status"];
    // cmd = "git";

    // DEBUG this works!
    // cmd = "git";
    // var args = ["commit","-a","-m",'"synctrouble"'];

    // DEBUG:
    // console.log('cmd args: ' + cmd + ' ----- ' + args);

    var spawn = require('child_process').spawn;

    var child = spawn(cmd, args);
    // var child = spawn(cmd, args, {stdio: "inherit"});

    var resp = "";
    child.stdout.on('data', function (buffer) { resp += buffer.toString() });
    child.stderr.on('data', function (buffer) { resp += 'ERROR: ' + buffer.toString() });

    child.stdout.on('end', function() { callBack (resp) });
}

// =========== run_command_sync: run one command and get output ============
// Run a command synchronously and get the output when it finishes.
// Usage:
// var lsout = run_command_sync( "ls", ["-l"]);
var run_command_sync = function (cmd) {

    var fullargs = spawnargs(cmd);
    cmd = fullargs[0];
    var args = fullargs.slice(1);

    var spawnSync = require('child_process').spawnSync;
    var outp = spawnSync(cmd, args, { encoding : 'utf8' });
    return outp.stdout;

    // From here:
    //  http://stackoverflow.com/questions/32393250/nodejs-child-process-spawnsync-or-child-process-spawn-wrapped-in-yieldable-gener
    // More example cde:
    // var ls = cp.spawnSync('ls', ['-l', '/usr'], { encoding : 'utf8' });
    // uncomment the following if you want to see everything returned by the spawnSync command
    // console.log('ls: ' , ls);
    // console.log('stdout here: \n' + ls.stdout);
}

// =========== runsteps: run a specific set of commands in specific directories ============
// Given: steps, an array of {name,folder,cmd} objects, eg:
//
//      var my_steps =
//      [
//          { name: 'update Project'        , folder: '.'       , cmd: 'git pull'       },
//          { name: 'build Project'         , folder: '.'       , cmd: 'make'           },
//      ];
//
// This function runs the requested steps.
// Verbosity can be:
//		"quiet"		no output
//		undefined	normal output - the step name and command output are logged to console
//		"verbose"	more output - step name, folder, command output
// Define async to get asynchronous execution.
var runsteps = function (steps,verbosity,async) {

    var path = require('path');

    for (var i = 0;i < steps.length;i++) {

        try {

        	if (verbosity != "quiet") {
                console.log('step: ' + steps[i].name);
        	}
            if (verbosity == "verbose") {
                console.log('cd: ' + process.cwd());
            }

            process.chdir(path.normalize(steps[i].folder));

            if (async) {

                run_command(steps[i].cmd, function(text) {
                    console.log ('------------------------------');
                    // console.log(steps[i].cmd);
                    console.log ('------------------------------');
                    console.log (text)
                });

                // Workaround during testing
                // run_command_async_to_console(steps[i].cmd);

            } else if (verbosity != "quiet") {
        		run_command_sync_to_console(steps[i].cmd);
        	} else {
        		run_command_quietly(steps[i].cmd);
        	}
        }
        catch (err) {
            if (verbosity == "verbose") {
            	console.log(err);
            }
        }
    }
}

var combine_params = function(params) {
    var result = "";
    if (params.length > 0)
    {
        params.forEach(function(val,index,array){
            if (index != 0) { result += " "; }
            result += val;
        });
    }
    return result;
}

module.exports.run_command_sync = run_command_sync;
module.exports.run_command_sync_to_console = run_command_sync_to_console;
module.exports.run_command_async_to_console = run_command_async_to_console;
module.exports.run_command_quietly = run_command_quietly;
module.exports.run_command = run_command;
module.exports.runsteps = runsteps;
module.exports.combine_params = combine_params;
<commit_msg>"testing on pi"<commit_after>#!/usr/bin/env node

var exec = require('child_process').exec;
var spawn = require('child_process').spawn;

// MDM NOTE that node v0.12 or higher is required for this.
var execSync = require('child_process').execSync;
var spawnSync = require('child_process').spawnSync;

var spawnargs = require('spawn-args');

//=========== run_command_sync_to_console: run one command and let output immediately flow to console ============
var run_command_sync_to_console = function (cmd) {
    execSync(cmd, {stdio:[0,1,2]}, function(error, stdout, stderr) {
        if (error) {
            console.log('======= RUN ERROR =======');
            throw error;
        }
    });
}

//=========== run_command_async_to_console: async run one command and dump output to console when complete ============
var run_command_async_to_console = function (cmd) {
    exec(cmd, function(error, stdout, stderr) {
        if (stdout.length > 0 ) console.log(stdout);
        if (stderr.length > 0 ) console.log(stderr);
    });
}

//=========== run_command_quietly: runs without output unless error ============
var run_command_quietly = function (cmd) {
    execSync(cmd, function(error, stdout, stderr) {
        if (error) {
            console.log('======= RUN ERROR =======');
            throw error;
        }
    });
}

// =========== run_command: run one command and get output ============
// Run a command asynchronously and get the output when it finishes in a callback.
// Usage:
// run_command( "ls -l", function(text) { console.log (text) });
var run_command = function (cmd, callBack ) {

    var fullargs = spawnargs(cmd);
    cmd = fullargs[0];
    var args = fullargs.slice(1);

    // DEBUG this works!
    // var args = ["status"];
    // cmd = "git";

    // DEBUG this works!
    // cmd = "git";
    // var args = ["commit","-a","-m",'"synctrouble"'];

    // DEBUG:
    // console.log('cmd args: ' + cmd + ' ----- ' + args);

    var spawn = require('child_process').spawn;

    var child = spawn(cmd, args);
    // var child = spawn(cmd, args, {stdio: "inherit"});

    var resp = "";
    child.stdout.on('data', function (buffer) { resp += buffer.toString() });
    child.stderr.on('data', function (buffer) { resp += 'ERROR: ' + buffer.toString() });

    child.stdout.on('end', function() { callBack (resp) });
}

// =========== run_command_sync: run one command and get output ============
// Run a command synchronously and get the output when it finishes.
// Usage:
// var lsout = run_command_sync( "ls", ["-l"]);
var run_command_sync = function (cmd) {

    var fullargs = spawnargs(cmd);
    cmd = fullargs[0];
    var args = fullargs.slice(1);

    var spawnSync = require('child_process').spawnSync;
    var outp = spawnSync(cmd, args, { encoding : 'utf8' });
    return outp.stdout;

    // From here:
    //  http://stackoverflow.com/questions/32393250/nodejs-child-process-spawnsync-or-child-process-spawn-wrapped-in-yieldable-gener
    // More example cde:
    // var ls = cp.spawnSync('ls', ['-l', '/usr'], { encoding : 'utf8' });
    // uncomment the following if you want to see everything returned by the spawnSync command
    // console.log('ls: ' , ls);
    // console.log('stdout here: \n' + ls.stdout);
}

// =========== runsteps: run a specific set of commands in specific directories ============
// Given: steps, an array of {name,folder,cmd} objects, eg:
//
//      var my_steps =
//      [
//          { name: 'update Project'        , folder: '.'       , cmd: 'git pull'       },
//          { name: 'build Project'         , folder: '.'       , cmd: 'make'           },
//      ];
//
// This function runs the requested steps.
// Verbosity can be:
//		"quiet"		no output
//		undefined	normal output - the step name and command output are logged to console
//		"verbose"	more output - step name, folder, command output
// Define async to get asynchronous execution.
var runsteps = function (steps,verbosity,async) {

    var path = require('path');

    steps.forEach(function(step,i) {
    // for (var i = 0;i < steps.length;i++) {

        try {

        	if (verbosity != "quiet") {
                console.log('step: ' + step.name);
        	}
            if (verbosity == "verbose") {
                console.log('cd: ' + process.cwd());
            }

            process.chdir(path.normalize(step.folder));

            if (async) {

                run_command(step.cmd, function(text) {
                    console.log ('------------------------------');
                    console.log(step.cmd);
                    console.log ('------------------------------');
                    console.log (text)
                });

                // Workaround during testing
                // run_command_async_to_console(steps[i].cmd);

            } else if (verbosity != "quiet") {
        		run_command_sync_to_console(step.cmd);
        	} else {
        		run_command_quietly(step.cmd);
        	}
        }
        catch (err) {
            if (verbosity == "verbose") {
            	console.log(err);
            }
        }
    });
}

var combine_params = function(params) {
    var result = "";
    if (params.length > 0)
    {
        params.forEach(function(val,index,array){
            if (index != 0) { result += " "; }
            result += val;
        });
    }
    return result;
}

module.exports.run_command_sync = run_command_sync;
module.exports.run_command_sync_to_console = run_command_sync_to_console;
module.exports.run_command_async_to_console = run_command_async_to_console;
module.exports.run_command_quietly = run_command_quietly;
module.exports.run_command = run_command;
module.exports.runsteps = runsteps;
module.exports.combine_params = combine_params;
<|endoftext|>


<commit_before>'use strict';

var connect = require('sensorjs'),
    sensorDriver = connect.sensor,
    logger = require('log4js').getLogger('Sensor'),
    _ = require('lodash');

var app,
    sensors = {};

var RECOMMENDED_INTERVAL = 60 * 1000,
    MAX_VALUES_LENGTH = 100;

function init(appServer, options, cb) {
  app = connect().
      use(function (data, next) {
        if (data && data.id && _.isObject(sensors[data.id])) {
          sensors[data.id].latest = data.value;
          sensors[data.id].status = data.status;
          sensors[data.id].time = data.time;
          sensors[data.id].type = data.type;
          sensors[data.id].message = data.message;

          if (_.isArray(sensors[data.id].values)) {
            if (sensors[data.id].values.length < MAX_VALUES_LENGTH) {
              sensors[data.id].values.push([data.time, data.value]);
            } else {
              sensors[data.id].values.shift();
              sensors[data.id].values.push([data.time, data.value]);
            }
          }
        }

        logger.info('sensors', sensors);

        next();
      }).
      use(connect.filter({$between: [-50, 1000]})). // filter: passing between -50 and 50
//      use(connect.average(25 /*duration*/)).     // reduce: values to an average every 20 sec.
//      use(function (data, next) {                // custom middleware
//        if (Math.max.apply(null, data.queue) < data.value) {
//          console.log('new record', data.value);
//        }
//        next();
//      }).
//      use(connect.queue(2)).                   // buffering max # of 100.
      use('/w1/*/ds18b20', function (data, next) {
        logger.info('[wot/use] ds18b20 temperature', data.value);
        next();
      }).
      use('/i2c/*/BH1750', function (data, next) {
        logger.info('[wot/use] BH1750 light', data.value);
        next();
      }).
      // transport(mqtt, localStorage, websocket and etc)
      //use(connect.websocket('http://yourhost.com', 'temperature/{id}'/*topic*/));
      use(connect.websocketServer(appServer, options && options.websocketTopic));

  return cb && cb();
}

function createSensor(sensorUrl, cb) {
  var sensor,
      sensorId,
      parsedSensorUrl,
      sensorProperties;

  try {
    sensor = sensorDriver.createSensor(sensorUrl);
    parsedSensorUrl = sensorDriver.parseSensorUrl(sensorUrl);
    sensorId = parsedSensorUrl.id;
    sensorProperties = sensorDriver.getSensorProperties(parsedSensorUrl.model);

    sensors[sensorId] = {
      sensor: sensor, // instance
      url: sensorUrl,
      values: [],
      latest: null,
      status: null,
      time: null,
      type: null,
      message: null,
      interval: sensorProperties && sensorProperties.recommendedInterval || RECOMMENDED_INTERVAL
    };

    app.listen(sensor);

    logger.info('[wot/createSensor] sensor is created', sensorId, sensors);

    return cb && cb(null, sensor)
  } catch (e) {
    logger.error('[wot/createSensor] sensor is not created', sensorUrl, e);
    return cb && cb(e);
  }
}

function discoverSensors(driverName, cb) {
  sensorDriver.discover(driverName, function (err, devices) {
    logger.info('[wot/discoverSensors] discovered devices', err, devices);
    return cb && cb(err, devices);
  });
}

exports.sensors = sensors;

exports.init = init;
exports.createSensor = createSensor;
exports.discoverSensors = discoverSensors;<commit_msg>* Logger 변경.<commit_after>'use strict';

var connect = require('sensorjs'),
    sensorDriver = connect.sensor,
    logger = require('log4js').getLogger('WoT'),
    _ = require('lodash');

var app,
    sensors = {};

var RECOMMENDED_INTERVAL = 60 * 1000,
    MAX_VALUES_LENGTH = 100;

function init(appServer, options, cb) {
  app = connect().
      use(function (data, next) {
        if (data && data.id && _.isObject(sensors[data.id])) {
          sensors[data.id].latest = data.value;
          sensors[data.id].status = data.status;
          sensors[data.id].time = data.time;
          sensors[data.id].type = data.type;
          sensors[data.id].message = data.message;

          if (_.isArray(sensors[data.id].values)) {
            if (sensors[data.id].values.length < MAX_VALUES_LENGTH) {
              sensors[data.id].values.push([data.time, data.value]);
            } else {
              sensors[data.id].values.shift();
              sensors[data.id].values.push([data.time, data.value]);
            }
          }
        }

        logger.info('sensors', sensors);

        next();
      }).
      use(connect.filter({$between: [-50, 1000]})). // filter: passing between -50 and 50
//      use(connect.average(25 /*duration*/)).     // reduce: values to an average every 20 sec.
//      use(function (data, next) {                // custom middleware
//        if (Math.max.apply(null, data.queue) < data.value) {
//          console.log('new record', data.value);
//        }
//        next();
//      }).
//      use(connect.queue(2)).                   // buffering max # of 100.
      use('/w1/*/ds18b20', function (data, next) {
        logger.info('[wot/use] ds18b20 temperature', data.value);
        next();
      }).
      use('/i2c/*/BH1750', function (data, next) {
        logger.info('[wot/use] BH1750 light', data.value);
        next();
      }).
      // transport(mqtt, localStorage, websocket and etc)
      //use(connect.websocket('http://yourhost.com', 'temperature/{id}'/*topic*/));
      use(connect.websocketServer(appServer, options && options.websocketTopic));

  return cb && cb();
}

function createSensor(sensorUrl, cb) {
  var sensor,
      sensorId,
      parsedSensorUrl,
      sensorProperties;

  try {
    sensor = sensorDriver.createSensor(sensorUrl);
    parsedSensorUrl = sensorDriver.parseSensorUrl(sensorUrl);
    sensorId = parsedSensorUrl.id;
    sensorProperties = sensorDriver.getSensorProperties(parsedSensorUrl.model);

    sensors[sensorId] = {
      sensor: sensor, // instance
      url: sensorUrl,
      values: [],
      latest: null,
      status: null,
      time: null,
      type: null,
      message: null,
      interval: sensorProperties && sensorProperties.recommendedInterval || RECOMMENDED_INTERVAL
    };

    app.listen(sensor);

    logger.info('[wot/createSensor] sensor is created', sensorId, sensors);

    return cb && cb(null, sensor)
  } catch (e) {
    logger.error('[wot/createSensor] sensor is not created', sensorUrl, e);
    return cb && cb(e);
  }
}

function discoverSensors(driverName, cb) {
  sensorDriver.discover(driverName, function (err, devices) {
    logger.info('[wot/discoverSensors] discovered devices', err, devices);
    return cb && cb(err, devices);
  });
}

exports.sensors = sensors;

exports.init = init;
exports.createSensor = createSensor;
exports.discoverSensors = discoverSensors;<|endoftext|>


<commit_before>"use strict";
(function () {
    module.exports = function (grunt) {
        require("time-grunt")(grunt);
        require("load-grunt-tasks")(grunt);
        grunt.initConfig({
            nodeunit: { files: ["test/**/*_test.js"] },
            eslint: {
                gruntfile: ["Gruntfile.js"],
                lib: [
                    "lib/**/*.js",
                    "!lib/parser.js"
                ],
                test: ["test/**/*.js"]
            },
            mochacli: {
                options: {
                    reporter: "spec",
                    bail: true,
                    timeout: 15000
                },
                all: ["test/*.js"]
            },
            watch: {
                gruntfile: {
                    files: "<%= jshint.gruntfile.src %>",
                    tasks: ["jshint:gruntfile"]
                },
                lib: {
                    files: "<%= jshint.lib.src %>",
                    tasks: [
                        "jshint:lib",
                        "mochacli"
                    ]
                },
                test: {
                    files: "<%= jshint.test.src %>",
                    tasks: [
                        "jshint:test",
                        "mochacli"
                    ]
                }
            },
            peg: {
                spider: {
                    src: "src/spider.pegjs",
                    dest: "lib/parser.js"
                }
            },
            mocha_istanbul: {
                coverage: {
                    src: "test",
                    options: {
                        mask: "*.js",
                        excludes: ["lib/parser.js"]
                    }
                }
            },
            clean: { build: ["lib/"] },
            spider_script: {
                options: {},
                build: {
                    files: [{
                            expand: true,
                            cwd: "src",
                            src: ["**/*.spider"],
                            dest: "lib/",
                            ext: ".js"
                        }]
                }
            },
            copy: {
                build: {
                    files: [{
                            expand: true,
                            cwd: "src",
                            src: ["**/*.js"],
                            dest: "lib/"
                        }]
                }
            }
        });
        grunt.registerTask("default", [
            "build",
            "eslint",
            "mochacli"
        ]);
        grunt.registerTask("build", [
            "clean:build",
            "peg",
            "spider_script:build",
            "copy:build"
        ]);
        grunt.registerTask("coverage", ["mocha_istanbul:coverage"]);
    };
}());

//# sourceMappingURL=Gruntfile.js.map<commit_msg>oops, remove test file<commit_after><|endoftext|>


<commit_before>const { Listener } = require('discord-akairo');
const Logger = require('../../../util/Logger');

function exec(close) {
    Logger.info(`Client disconnected with code ${close.code}.`);
    if (this.client.config.exitOnDisconnect) process.exit();
}

module.exports = new Listener('disconnect', exec, {
    emitter: 'client',
    eventName: 'disconnect',
    category: 'client'
});
<commit_msg>Delete disconnect.js<commit_after><|endoftext|>


<commit_before>var robot = require('robotjs')
var tinycolor = require('tinycolor2')
var AbstractReader = require('../reader/AbstractReader')
var gameWindow = require('../gameWindow')
var Rect = require('../geometry/Rect')

var MyCollectionCardReader = function(row, column) {
    AbstractReader.call(this)

    // 0 based.
    this.row = row
    this.column = column
}
MyCollectionCardReader.prototype = Object.create(AbstractReader.prototype)
MyCollectionCardReader.prototype.constructor = MyCollectionCardReader

MyCollectionCardReader.prototype.getPolygon = function() {
    if (gameWindow.hasResolution(1024, 768)) {
        // Card locations are kind of crazy.
        if (this.row === 0) {
            if (this.column === 0) {
                return new Rect(40, 137, 155, 229)
            } else if (this.column === 1) {
                return new Rect(213, 137, 154, 229)
            } else if (this.column === 2) {
                return new Rect(385, 137, 153, 229)
            } else if (this.column === 3) {
                return new Rect(558, 137, 153, 229)
            }
        } else if (this.row === 1) {
            if (this.column === 0) {
                return new Rect(40, 409, 155, 228)
            } else if (this.column === 1) {
                return new Rect(213, 409, 154, 228)
            } else if (this.column === 2) {
                return new Rect(385, 409, 153, 228)
            } else if (this.column === 3) {
                return new Rect(558, 409, 153, 228)
            }
        }
        throw new Error('`row` must be between 0 and 1 inclusive. `column` must be between 0 and 3 inclusive')
    } else {
        throw new Error('`gameWindow` resolution is not supported.')
    }
}

MyCollectionCardReader.prototype.getCost = function() {
    var polygon = this.getPolygon()
    var costPolygon = new Rect(polygon.x, polygon.y, 27, 23)
    var points = costPolygon.getPoints()

    var numBright = points
    .map((point) => point.add(gameWindow.getOffset()))
    .map((screenPoint) => robot.getPixelColor(screenPoint.x, screenPoint.y))
    .map((color) => tinycolor('#' + color).getLuminance())
    .reduce((prev, curr) => prev + (curr >= 1 ? 1 : 0), 0)

    console.log(numBright)
    // .forEach((point) => robot.moveMouse(point.x, point.y))

    // console.log(points.length)
    // console.log(colors[0])
}

MyCollectionCardReader.prototype.getCard = function() {
    // var polygon = this.getPolygon()
    var cost = this.getCost()

    // 77, 212
    // top 286
    // bottom 292
    //

    // console.log(11111)
    // console.log(polygon)
}

module.exports = MyCollectionCardReader
<commit_msg>pure white color classification will not work<commit_after>var robot = require('robotjs')
var tinycolor = require('tinycolor2')
var AbstractReader = require('../reader/AbstractReader')
var gameWindow = require('../gameWindow')
var Rect = require('../geometry/Rect')

var MyCollectionCardReader = function(row, column) {
    AbstractReader.call(this)

    // 0 based.
    this.row = row
    this.column = column
}
MyCollectionCardReader.prototype = Object.create(AbstractReader.prototype)
MyCollectionCardReader.prototype.constructor = MyCollectionCardReader

MyCollectionCardReader.prototype.getPolygon = function() {
    if (gameWindow.hasResolution(1024, 768)) {
        // Card locations are kind of crazy.
        if (this.row === 0) {
            if (this.column === 0) {
                return new Rect(40, 137, 155, 229)
            } else if (this.column === 1) {
                return new Rect(213, 137, 154, 229)
            } else if (this.column === 2) {
                return new Rect(385, 137, 153, 229)
            } else if (this.column === 3) {
                return new Rect(558, 137, 153, 229)
            }
        } else if (this.row === 1) {
            if (this.column === 0) {
                return new Rect(40, 409, 155, 228)
            } else if (this.column === 1) {
                return new Rect(213, 409, 154, 228)
            } else if (this.column === 2) {
                return new Rect(385, 409, 153, 228)
            } else if (this.column === 3) {
                return new Rect(557, 409, 153, 228)
            }
        }
        throw new Error('`row` must be between 0 and 1 inclusive. `column` must be between 0 and 3 inclusive')
    } else {
        throw new Error('`gameWindow` resolution is not supported.')
    }
}

MyCollectionCardReader.prototype.getCost = function() {
    var polygon = this.getPolygon()
    var costPolygon = new Rect(polygon.x + 5, polygon.y - 3, 23, 25)
    var points = costPolygon.getPoints()

    var numBright = points
    .map((point) => point.add(gameWindow.getOffset()))
    // .forEach((point) => robot.moveMouse(point.x, point.y))
    .map((screenPoint) => robot.getPixelColor(screenPoint.x, screenPoint.y))
    .map((color) => tinycolor('#' + color).getLuminance())
    .reduce((prev, curr) => prev + (curr >= 0.97 ? 1 : 0), 0)

    console.log(numBright)

    // console.log(points.length)
    // console.log(colors[0])
}

MyCollectionCardReader.prototype.getCard = function() {
    // var polygon = this.getPolygon()
    var cost = this.getCost()

    // 77, 212
    // top 286
    // bottom 292
    //

    // console.log(11111)
    // console.log(polygon)
}

module.exports = MyCollectionCardReader
<|endoftext|>


<commit_before>/* jshint node:true */
/**
 * PUSH Notification server
 * (c) Telefonica Digital, 2012 - All rights reserved
 * License: GNU Affero V3 (see LICENSE file)
 * Fernando Rodríguez Sela <frsela@tid.es>
 * Guillermo Lopez Leal <gll@tid.es>
 */

'use strict';

function ConnectorWebSocket(data, connection) {
    this.data = data;
    this.connection = connection;
}

ConnectorWebSocket.prototype = {
    getType: function() {
        return 'WS';
    },

    getServer: function() {
        return process.serverId;
    },

    getConnection: function() {
        return this.connection;
    },

    getInterface: function() {
        return null;
    },

    getMobileNetwork: function() {
        return null;
    },

    getProtocol: function() {
        return 'ws';
    },

    canBeWakeup: function() {
        return false;
    },

    resetAutoclose: function() {
        // nothing to do on this connector
    },

    notify: function(msgList) {
        this.connection.sendUTF(JSON.stringify(msgList));
    }
};

module.exports = ConnectorWebSocket;<commit_msg>Save mcc-mnc data to WS connector, so monitor is able to print logs for Deployment KPIs<commit_after>/* jshint node:true */
/**
 * PUSH Notification server
 * (c) Telefonica Digital, 2012 - All rights reserved
 * License: GNU Affero V3 (see LICENSE file)
 * Fernando Rodríguez Sela <frsela@tid.es>
 * Guillermo Lopez Leal <gll@tid.es>
 */

'use strict';

function ConnectorWebSocket(data, connection) {
    this.data = data;
    this.connection = connection;
}

ConnectorWebSocket.prototype = {
    getType: function() {
        return 'WS';
    },

    getServer: function() {
        return process.serverId;
    },

    getConnection: function() {
        return this.connection;
    },

    getInterface: function() {
        return null;
    },

    getMobileNetwork: function() {
        return this.data.mobilenetwork || null;
    },

    getProtocol: function() {
        return 'ws';
    },

    canBeWakeup: function() {
        return false;
    },

    resetAutoclose: function() {
        // nothing to do on this connector
    },

    notify: function(msgList) {
        this.connection.sendUTF(JSON.stringify(msgList));
    }
};

module.exports = ConnectorWebSocket;<|endoftext|>


<commit_before>function DataUpdater(allViewModels) {
    var self = this;

    self.allViewModels = allViewModels;

    self._socket = undefined;
    self._autoReconnecting = false;
    self._autoReconnectTrial = 0;
    self._autoReconnectTimeouts = [1, 1, 2, 3, 5, 8, 13, 20, 40, 100];

    self.connect = function() {
        var options = {};
        if (SOCKJS_DEBUG) {
            options["debug"] = true;
        }

        self._socket = new SockJS(SOCKJS_URI, undefined, options);
        self._socket.onopen = self._onconnect;
        self._socket.onclose = self._onclose;
        self._socket.onmessage = self._onmessage;
    };

    self.reconnect = function() {
        delete self._socket;
        self.connect();
    };

    self._onconnect = function() {
        self._autoReconnecting = false;
        self._autoReconnectTrial = 0;
    };

    self._onclose = function() {
        var handled = false;
        _.each(self.allViewModels, function(viewModel) {
            if (handled == true) {
                return;
            }

            if (viewModel.hasattr("onServerDisconnect")) {
                if (!viewModel.onServerDisconnect()) {
                    handled = true;
                }
            }
        });

        if (handled) {
            return;
        }

        showOfflineOverlay(
            gettext("Server is offline"),
            gettext("The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below."),
            self.reconnect
        );

        if (self._autoReconnectTrial < self._autoReconnectTimeouts.length) {
            var timeout = self._autoReconnectTimeouts[self._autoReconnectTrial];
            console.log("Reconnect trial #" + self._autoReconnectTrial + ", waiting " + timeout + "s");
            setTimeout(self.reconnect, timeout * 1000);
            self._autoReconnectTrial++;
        } else {
            self._onreconnectfailed();
        }
    };

    self._onreconnectfailed = function() {
        var handled = false;
        _.each(self.allViewModels, function(viewModel) {
            if (handled == true) {
                return;
            }

            if (viewModel.hasattr("onServerDisconnect")) {
                if (!viewModel.onServerDisconnect()) {
                    handled = true;
                }
            }
        });

        if (handled) {
            return;
        }

        $("#offline_overlay_title").text(gettext("Server is offline"));
        $("#offline_overlay_message").html(gettext("The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below."));
    };

    self._onmessage = function(e) {
        for (var prop in e.data) {
            if (!e.data.hasOwnProperty(prop)) {
                continue;
            }

            var data = e.data[prop];

            switch (prop) {
                case "connected": {
                    // update the current UI API key and send it with any request
                    UI_API_KEY = data["apikey"];
                    $.ajaxSetup({
                        headers: {"X-Api-Key": UI_API_KEY}
                    });

                    VERSION = data["version"];
                    DISPLAY_VERSION = data["display_version"];
                    $("span.version").text(DISPLAY_VERSION);

                    if ($("#offline_overlay").is(":visible")) {
                        hideOfflineOverlay();
                        _.each(self.allViewModels, function(viewModel) {
                            if (viewModel.hasOwnProperty("onDataUpdaterReconnect")) {
                                viewModel.onDataUpdaterReconnect();
                            }
                        });

                        if ($('#tabs li[class="active"] a').attr("href") == "#control") {
                            $("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
                        }
                    }

                    break;
                }
                case "history": {
                    _.each(self.allViewModels, function(viewModel) {
                        if (viewModel.hasOwnProperty("fromHistoryData")) {
                            viewModel.fromHistoryData(data);
                        }
                    });
                    break;
                }
                case "current": {
                    _.each(self.allViewModels, function(viewModel) {
                        if (viewModel.hasOwnProperty("fromCurrentData")) {
                            viewModel.fromCurrentData(data);
                        }
                    });
                    break;
                }
                case "event": {
                    var type = data["type"];
                    var payload = data["payload"];
                    var html = "";

                    var gcodeUploadProgress = $("#gcode_upload_progress");
                    var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);

                    if (type == "UpdatedFiles") {
                        _.each(self.allViewModels, function(viewModel) {
                            if (viewModel.hasOwnProperty("onUpdatedFiles")) {
                                viewModel.onUpdatedFiles(payload);
                            }
                        });
                    } else if (type == "MetadataAnalysisFinished") {
                        _.each(self.allViewModels, function(viewModel) {
                            if (viewModel.hasOwnProperty("onMetadataAnalysisFinished")) {
                                viewModel.onMetadataAnalysisFinished(payload);
                            }
                        });
                    } else if (type == "MovieRendering") {
                        new PNotify({title: gettext("Rendering timelapse"), text: _.sprintf(gettext("Now rendering timelapse %(movie_basename)s"), payload)});
                    } else if (type == "MovieDone") {
                        new PNotify({title: gettext("Timelapse ready"), text: _.sprintf(gettext("New timelapse %(movie_basename)s is done rendering."), payload)});
                        timelapseViewModel.requestData();
                    } else if (type == "MovieFailed") {
                        html = "
" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failedwith return code %(returncode)s"), payload) + "
";
                        html += pnotifyAdditionalInfo('
' + payload.error + '
');
                        new PNotify({title: gettext("Rendering failed"), text: html, type: "error", hide: false});
                    } else if (type == "SlicingStarted") {
                        gcodeUploadProgress.addClass("progress-striped").addClass("active");
                        gcodeUploadProgressBar.css("width", "100%");
                        gcodeUploadProgressBar.text(gettext("Slicing ..."));
                    } else if (type == "SlicingDone") {
                        gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
                        gcodeUploadProgressBar.css("width", "0%");
                        gcodeUploadProgressBar.text("");
                        new PNotify({title: gettext("Slicing done"), text: _.sprintf(gettext("Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"), payload)});
                        gcodeFilesViewModel.requestData(payload.gcode);
                    } else if (type == "SlicingFailed") {
                        gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
                        gcodeUploadProgressBar.css("width", "0%");
                        gcodeUploadProgressBar.text("");

                        html = _.sprintf(gettext("Could not slice %(stl)s to %(gcode)s: %(reason)s"), payload);
                        new PNotify({title: gettext("Slicing failed"), text: html, type: "error", hide: false});
                    } else if (type == "TransferStarted") {
                        gcodeUploadProgress.addClass("progress-striped").addClass("active");
                        gcodeUploadProgressBar.css("width", "100%");
                        gcodeUploadProgressBar.text(gettext("Streaming ..."));
                    } else if (type == "TransferDone") {
                        gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
                        gcodeUploadProgressBar.css("width", "0%");
                        gcodeUploadProgressBar.text("");
                        new PNotify({title: gettext("Streaming done"), text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload)});
                        gcodeFilesViewModel.requestData(payload.remote, "sdcard");
                    }
                    break;
                }
                case "feedbackCommandOutput": {
                    _.each(self.allViewModels, function(viewModel) {
                        if (viewModel.hasOwnProperty("fromFeedbackCommandData")) {
                            viewModel.fromFeedbackCommandData(data);
                        }
                    });
                    break;
                }
                case "timelapse": {
                    _.each(self.allViewModels, function(viewModel) {
                        if (viewModel.hasOwnProperty("fromTimelapseData")) {
                            viewModel.fromTimelapseData(data);
                        }
                    });
                    break;
                }
            }
        }
    };

    self.connect();
}
<commit_msg>Fixed issue that broke the offline dialog<commit_after>function DataUpdater(allViewModels) {
    var self = this;

    self.allViewModels = allViewModels;

    self._socket = undefined;
    self._autoReconnecting = false;
    self._autoReconnectTrial = 0;
    self._autoReconnectTimeouts = [1, 1, 2, 3, 5, 8, 13, 20, 40, 100];

    self.connect = function() {
        var options = {};
        if (SOCKJS_DEBUG) {
            options["debug"] = true;
        }

        self._socket = new SockJS(SOCKJS_URI, undefined, options);
        self._socket.onopen = self._onconnect;
        self._socket.onclose = self._onclose;
        self._socket.onmessage = self._onmessage;
    };

    self.reconnect = function() {
        delete self._socket;
        self.connect();
    };

    self._onconnect = function() {
        self._autoReconnecting = false;
        self._autoReconnectTrial = 0;
    };

    self._onclose = function() {
        var handled = false;
        _.each(self.allViewModels, function(viewModel) {
            if (handled == true) {
                return;
            }

            if (viewModel.hasOwnProperty("onServerDisconnect")) {
                if (!viewModel.onServerDisconnect()) {
                    handled = true;
                }
            }
        });

        if (handled) {
            return;
        }

        showOfflineOverlay(
            gettext("Server is offline"),
            gettext("The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below."),
            self.reconnect
        );

        if (self._autoReconnectTrial < self._autoReconnectTimeouts.length) {
            var timeout = self._autoReconnectTimeouts[self._autoReconnectTrial];
            console.log("Reconnect trial #" + self._autoReconnectTrial + ", waiting " + timeout + "s");
            setTimeout(self.reconnect, timeout * 1000);
            self._autoReconnectTrial++;
        } else {
            self._onreconnectfailed();
        }
    };

    self._onreconnectfailed = function() {
        var handled = false;
        _.each(self.allViewModels, function(viewModel) {
            if (handled == true) {
                return;
            }

            if (viewModel.hasOwnProperty("onServerDisconnect")) {
                if (!viewModel.onServerDisconnect()) {
                    handled = true;
                }
            }
        });

        if (handled) {
            return;
        }

        $("#offline_overlay_title").text(gettext("Server is offline"));
        $("#offline_overlay_message").html(gettext("The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below."));
    };

    self._onmessage = function(e) {
        for (var prop in e.data) {
            if (!e.data.hasOwnProperty(prop)) {
                continue;
            }

            var data = e.data[prop];

            switch (prop) {
                case "connected": {
                    // update the current UI API key and send it with any request
                    UI_API_KEY = data["apikey"];
                    $.ajaxSetup({
                        headers: {"X-Api-Key": UI_API_KEY}
                    });

                    VERSION = data["version"];
                    DISPLAY_VERSION = data["display_version"];
                    $("span.version").text(DISPLAY_VERSION);

                    if ($("#offline_overlay").is(":visible")) {
                        hideOfflineOverlay();
                        _.each(self.allViewModels, function(viewModel) {
                            if (viewModel.hasOwnProperty("onDataUpdaterReconnect")) {
                                viewModel.onDataUpdaterReconnect();
                            }
                        });

                        if ($('#tabs li[class="active"] a').attr("href") == "#control") {
                            $("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
                        }
                    }

                    break;
                }
                case "history": {
                    _.each(self.allViewModels, function(viewModel) {
                        if (viewModel.hasOwnProperty("fromHistoryData")) {
                            viewModel.fromHistoryData(data);
                        }
                    });
                    break;
                }
                case "current": {
                    _.each(self.allViewModels, function(viewModel) {
                        if (viewModel.hasOwnProperty("fromCurrentData")) {
                            viewModel.fromCurrentData(data);
                        }
                    });
                    break;
                }
                case "event": {
                    var type = data["type"];
                    var payload = data["payload"];
                    var html = "";

                    var gcodeUploadProgress = $("#gcode_upload_progress");
                    var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);

                    if (type == "UpdatedFiles") {
                        _.each(self.allViewModels, function(viewModel) {
                            if (viewModel.hasOwnProperty("onUpdatedFiles")) {
                                viewModel.onUpdatedFiles(payload);
                            }
                        });
                    } else if (type == "MetadataAnalysisFinished") {
                        _.each(self.allViewModels, function(viewModel) {
                            if (viewModel.hasOwnProperty("onMetadataAnalysisFinished")) {
                                viewModel.onMetadataAnalysisFinished(payload);
                            }
                        });
                    } else if (type == "MovieRendering") {
                        new PNotify({title: gettext("Rendering timelapse"), text: _.sprintf(gettext("Now rendering timelapse %(movie_basename)s"), payload)});
                    } else if (type == "MovieDone") {
                        new PNotify({title: gettext("Timelapse ready"), text: _.sprintf(gettext("New timelapse %(movie_basename)s is done rendering."), payload)});
                        timelapseViewModel.requestData();
                    } else if (type == "MovieFailed") {
                        html = "
" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failedwith return code %(returncode)s"), payload) + "
";
                        html += pnotifyAdditionalInfo('
' + payload.error + '
');
                        new PNotify({title: gettext("Rendering failed"), text: html, type: "error", hide: false});
                    } else if (type == "SlicingStarted") {
                        gcodeUploadProgress.addClass("progress-striped").addClass("active");
                        gcodeUploadProgressBar.css("width", "100%");
                        gcodeUploadProgressBar.text(gettext("Slicing ..."));
                    } else if (type == "SlicingDone") {
                        gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
                        gcodeUploadProgressBar.css("width", "0%");
                        gcodeUploadProgressBar.text("");
                        new PNotify({title: gettext("Slicing done"), text: _.sprintf(gettext("Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"), payload)});
                        gcodeFilesViewModel.requestData(payload.gcode);
                    } else if (type == "SlicingFailed") {
                        gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
                        gcodeUploadProgressBar.css("width", "0%");
                        gcodeUploadProgressBar.text("");

                        html = _.sprintf(gettext("Could not slice %(stl)s to %(gcode)s: %(reason)s"), payload);
                        new PNotify({title: gettext("Slicing failed"), text: html, type: "error", hide: false});
                    } else if (type == "TransferStarted") {
                        gcodeUploadProgress.addClass("progress-striped").addClass("active");
                        gcodeUploadProgressBar.css("width", "100%");
                        gcodeUploadProgressBar.text(gettext("Streaming ..."));
                    } else if (type == "TransferDone") {
                        gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
                        gcodeUploadProgressBar.css("width", "0%");
                        gcodeUploadProgressBar.text("");
                        new PNotify({title: gettext("Streaming done"), text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload)});
                        gcodeFilesViewModel.requestData(payload.remote, "sdcard");
                    }
                    break;
                }
                case "feedbackCommandOutput": {
                    _.each(self.allViewModels, function(viewModel) {
                        if (viewModel.hasOwnProperty("fromFeedbackCommandData")) {
                            viewModel.fromFeedbackCommandData(data);
                        }
                    });
                    break;
                }
                case "timelapse": {
                    _.each(self.allViewModels, function(viewModel) {
                        if (viewModel.hasOwnProperty("fromTimelapseData")) {
                            viewModel.fromTimelapseData(data);
                        }
                    });
                    break;
                }
            }
        }
    };

    self.connect();
}
<|endoftext|>


<commit_before>goog.provide('ol.interaction.PinchZoom');

goog.require('goog.asserts');
goog.require('goog.style');
goog.require('ol.Coordinate');
goog.require('ol.ViewHint');
goog.require('ol.interaction.Interaction');
goog.require('ol.interaction.Pointer');

/**
 * @classdesc
 * Allows the user to zoom the map by pinching with two fingers
 * on a touch screen.
 *
 * @constructor
 * @extends {ol.interaction.Pointer}
 * @param {olx.interaction.PinchZoomOptions=} opt_options Options.
 * @api stable
 */
ol.interaction.PinchZoom = function(opt_options) {

  goog.base(this, {
    handleDownEvent: ol.interaction.PinchZoom.handleDownEvent_,
    handleDragEvent: ol.interaction.PinchZoom.handleDragEvent_,
    handleUpEvent: ol.interaction.PinchZoom.handleUpEvent_
  });

  var options = goog.isDef(opt_options) ? opt_options : {};

  /**
   * @private
   * @type {ol.Coordinate}
   */
  this.anchor_ = null;

  /**
   * @private
   * @type {number}
   */
  this.duration_ = goog.isDef(options.duration) ? options.duration : 400;

  /**
   * @private
   * @type {number|undefined}
   */
  this.lastDistance_ = undefined;

  /**
   * @private
   * @type {number}
   */
  this.lastScaleDelta_ = 1;

};
goog.inherits(ol.interaction.PinchZoom, ol.interaction.Pointer);

/**
 * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
 * @this {ol.interaction.PinchZoom}
 * @private
 */
ol.interaction.PinchZoom.handleDragEvent_ = function(mapBrowserEvent) {
  goog.asserts.assert(this.targetPointers.length >= 2);
  var scaleDelta = 1.0;

  var touch0 = this.targetPointers[0];
  var touch1 = this.targetPointers[1];
  var dx = touch0.clientX - touch1.clientX;
  var dy = touch0.clientY - touch1.clientY;

  // distance between touches
  var distance = Math.sqrt(dx * dx + dy * dy);

  if (goog.isDef(this.lastDistance_)) {
    scaleDelta = this.lastDistance_ / distance;
  }
  this.lastDistance_ = distance;
  if (scaleDelta != 1.0) {
    this.lastScaleDelta_ = scaleDelta;
  }

  var map = mapBrowserEvent.map;
  var view = map.getView();
  var viewState = view.getState();

  // scale anchor point.
  var viewportPosition = goog.style.getClientPosition(map.getViewport());
  var centroid =
      ol.interaction.Pointer.centroid(this.targetPointers);
  centroid[0] -= viewportPosition.x;
  centroid[1] -= viewportPosition.y;
  this.anchor_ = map.getCoordinateFromPixel(centroid);

  // scale, bypass the resolution constraint
  map.render();
  ol.interaction.Interaction.zoomWithoutConstraints(
      map, view, viewState.resolution * scaleDelta, this.anchor_);

};

/**
 * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
 * @return {boolean} Stop drag sequence?
 * @this {ol.interaction.PinchZoom}
 * @private
 */
ol.interaction.PinchZoom.handleUpEvent_ = function(mapBrowserEvent) {
  if (this.targetPointers.length < 2) {
    var map = mapBrowserEvent.map;
    var view = map.getView();
    view.setHint(ol.ViewHint.INTERACTING, -1);
    var viewState = view.getState();
    // Zoom to final resolution, with an animation, and provide a
    // direction not to zoom out/in if user was pinching in/out.
    // Direction is > 0 if pinching out, and < 0 if pinching in.
    var direction = this.lastScaleDelta_ - 1;
    ol.interaction.Interaction.zoom(map, view, viewState.resolution,
        this.anchor_, this.duration_, direction);
    return false;
  } else {
    return true;
  }
};

/**
 * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
 * @return {boolean} Start drag sequence?
 * @this {ol.interaction.PinchZoom}
 * @private
 */
ol.interaction.PinchZoom.handleDownEvent_ = function(mapBrowserEvent) {
  if (this.targetPointers.length >= 2) {
    var map = mapBrowserEvent.map;
    this.anchor_ = null;
    this.lastDistance_ = undefined;
    this.lastScaleDelta_ = 1;
    if (!this.handlingDownUpSequence) {
      map.getView().setHint(ol.ViewHint.INTERACTING, 1);
    }
    map.render();
    return true;
  } else {
    return false;
  }
};

/**
 * @inheritDoc
 */
ol.interaction.PinchZoom.prototype.shouldStopEvent = goog.functions.FALSE;
<commit_msg>Use view.getResolution instead of view.getState<commit_after>goog.provide('ol.interaction.PinchZoom');

goog.require('goog.asserts');
goog.require('goog.style');
goog.require('ol.Coordinate');
goog.require('ol.ViewHint');
goog.require('ol.interaction.Interaction');
goog.require('ol.interaction.Pointer');

/**
 * @classdesc
 * Allows the user to zoom the map by pinching with two fingers
 * on a touch screen.
 *
 * @constructor
 * @extends {ol.interaction.Pointer}
 * @param {olx.interaction.PinchZoomOptions=} opt_options Options.
 * @api stable
 */
ol.interaction.PinchZoom = function(opt_options) {

  goog.base(this, {
    handleDownEvent: ol.interaction.PinchZoom.handleDownEvent_,
    handleDragEvent: ol.interaction.PinchZoom.handleDragEvent_,
    handleUpEvent: ol.interaction.PinchZoom.handleUpEvent_
  });

  var options = goog.isDef(opt_options) ? opt_options : {};

  /**
   * @private
   * @type {ol.Coordinate}
   */
  this.anchor_ = null;

  /**
   * @private
   * @type {number}
   */
  this.duration_ = goog.isDef(options.duration) ? options.duration : 400;

  /**
   * @private
   * @type {number|undefined}
   */
  this.lastDistance_ = undefined;

  /**
   * @private
   * @type {number}
   */
  this.lastScaleDelta_ = 1;

};
goog.inherits(ol.interaction.PinchZoom, ol.interaction.Pointer);

/**
 * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
 * @this {ol.interaction.PinchZoom}
 * @private
 */
ol.interaction.PinchZoom.handleDragEvent_ = function(mapBrowserEvent) {
  goog.asserts.assert(this.targetPointers.length >= 2);
  var scaleDelta = 1.0;

  var touch0 = this.targetPointers[0];
  var touch1 = this.targetPointers[1];
  var dx = touch0.clientX - touch1.clientX;
  var dy = touch0.clientY - touch1.clientY;

  // distance between touches
  var distance = Math.sqrt(dx * dx + dy * dy);

  if (goog.isDef(this.lastDistance_)) {
    scaleDelta = this.lastDistance_ / distance;
  }
  this.lastDistance_ = distance;
  if (scaleDelta != 1.0) {
    this.lastScaleDelta_ = scaleDelta;
  }

  var map = mapBrowserEvent.map;
  var view = map.getView();
  var resolution = view.getResolution();

  // scale anchor point.
  var viewportPosition = goog.style.getClientPosition(map.getViewport());
  var centroid =
      ol.interaction.Pointer.centroid(this.targetPointers);
  centroid[0] -= viewportPosition.x;
  centroid[1] -= viewportPosition.y;
  this.anchor_ = map.getCoordinateFromPixel(centroid);

  // scale, bypass the resolution constraint
  map.render();
  ol.interaction.Interaction.zoomWithoutConstraints(
      map, view, resolution * scaleDelta, this.anchor_);

};

/**
 * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
 * @return {boolean} Stop drag sequence?
 * @this {ol.interaction.PinchZoom}
 * @private
 */
ol.interaction.PinchZoom.handleUpEvent_ = function(mapBrowserEvent) {
  if (this.targetPointers.length < 2) {
    var map = mapBrowserEvent.map;
    var view = map.getView();
    view.setHint(ol.ViewHint.INTERACTING, -1);
    var resolution = view.getResolution();
    // Zoom to final resolution, with an animation, and provide a
    // direction not to zoom out/in if user was pinching in/out.
    // Direction is > 0 if pinching out, and < 0 if pinching in.
    var direction = this.lastScaleDelta_ - 1;
    ol.interaction.Interaction.zoom(map, view, resolution,
        this.anchor_, this.duration_, direction);
    return false;
  } else {
    return true;
  }
};

/**
 * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
 * @return {boolean} Start drag sequence?
 * @this {ol.interaction.PinchZoom}
 * @private
 */
ol.interaction.PinchZoom.handleDownEvent_ = function(mapBrowserEvent) {
  if (this.targetPointers.length >= 2) {
    var map = mapBrowserEvent.map;
    this.anchor_ = null;
    this.lastDistance_ = undefined;
    this.lastScaleDelta_ = 1;
    if (!this.handlingDownUpSequence) {
      map.getView().setHint(ol.ViewHint.INTERACTING, 1);
    }
    map.render();
    return true;
  } else {
    return false;
  }
};

/**
 * @inheritDoc
 */
ol.interaction.PinchZoom.prototype.shouldStopEvent = goog.functions.FALSE;
<|endoftext|>


<commit_before>var http = require('http');
var q = require('q');
var request = require('request');

describe('HTTP', function() {

  var encode = function(command) {
    var host = 'http://localhost:13000/testSelector';
    return host + '?popupInput=' + encodeURIComponent(command);
  };

  var callElementor = function(command) {
    var deferred = q.defer();

    var url = encode(command);
    request(url, function(error, response, body) {
      if (error) {
        console.log("Got error: " + error);
        return deferred.reject(error);
      }
      deferred.resolve(JSON.parse(body));
    });

    return deferred.promise;
  };

  it('should navigate to protractor website', function(done) {
    var url = 'browser.get(\'http://angular.github.io/protractor/#/api\')';

    // Given that you navigate to the protractor website.
    callElementor(url).then(function() {
      // When you get the current URL.
      return callElementor('browser.getCurrentUrl()');
    }).then(function(response) {
      // Then ensure the URL has changed.
      expect(response).toEqual({
        results: {
          'browser.getCurrentUrl()': 'http://angular.github.io/protractor/#/api'
        }
      });
      done();
    });
  });
}) ;
<commit_msg>Add test for by.css<commit_after>var http = require('http');
var q = require('q');
var request = require('request');

describe('HTTP', function() {

  var encode = function(command) {
    var host = 'http://localhost:13000/testSelector';
    return host + '?popupInput=' + encodeURIComponent(command);
  };

  var callElementor = function(command) {
    var deferred = q.defer();

    var url = encode(command);
    request(url, function(error, response, body) {
      if (error) {
        console.log("Got error: " + error);
        return deferred.reject(error);
      }
      deferred.resolve(JSON.parse(body));
    });

    return deferred.promise;
  };

  it('should navigate to protractor website', function(done) {
    var url = 'browser.get(\'http://angular.github.io/protractor/#/api\')';

    // Given that you navigate to the protractor website.
    callElementor(url).then(function() {
      // When you get the current URL.
      return callElementor('browser.getCurrentUrl()');
    }).then(function(response) {
      // Then ensure the URL has changed.
      expect(response).toEqual({
        results: {
          'browser.getCurrentUrl()': 'http://angular.github.io/protractor/#/api'
        }
      });
      done();
    });
  });

  it('should transform by input into count expression', function(done) {
    // When you select by css.
    callElementor('by.css(\'#title\')').then(function(response) {
      // Then ensure the input is turned into count expression.
      expect(response).toEqual({
        results: {
          'element.all(by.css(\'#title\')).count()': 1
        }
      });
      done();
    });
  });
});
<|endoftext|>


<commit_before>/* jshint camelcase: false */
/* jshint expr: true */
var chai      = require('chai')
  , expect    = chai.expect
  , Support   = require(__dirname + '/../support')
  , Sequelize = require(__dirname + '/../../index')
  , DataTypes = require(__dirname + "/../../lib/data-types")
  , datetime  = require('chai-datetime')
  , async     = require('async');

chai.use(datetime)
chai.config.includeStack = true

describe(Support.getTestDialectTeaser("Include"), function () {
  describe('find', function () {
    it('should include a non required model, with conditions and two includes N:M 1:M', function ( done ) {
      var A = this.sequelize.define('A', { name: DataTypes.STRING(40) }, { paranoid: true })
        , B = this.sequelize.define('B', { name: DataTypes.STRING(40) }, { paranoid: true })
        , C = this.sequelize.define('C', { name: DataTypes.STRING(40) }, { paranoid: true })
        , D = this.sequelize.define('D', { name: DataTypes.STRING(40) }, { paranoid: true });

      // Associations
      A.hasMany(B);

      B.belongsTo(B);
      B.belongsTo(D);
      B.hasMany(C, {
        through: 'BC',
      });

      C.hasMany(B, {
        through: 'BC',
      });

      D.hasMany(B);

      this.sequelize.sync({ force: true }).done(function ( err ) {
        expect( err ).not.to.be.ok;

        A.find({
          include: [
            { model: B, required: false, include: [
              { model: C, required: false },
              { model: D }
            ]}
          ]
        }).done( function ( err ) {
          expect( err ).not.to.be.ok;
          done();
        });
      });

    });

    it("should still pull the main record when an included model is not required and has where restrictions without matches", function () {
      var A = this.sequelize.define('a', {
          name: DataTypes.STRING(40)
        })
        , B = this.sequelize.define('b', {
          name: DataTypes.STRING(40)
        });

      A.hasMany(B);
      B.hasMany(A);

      return this.sequelize
        .sync({force: true})
        .then(function () {
          return A.create({
            name: 'Foobar'
          });
        })
        .then(function () {
          return A.find({
            where: {name: 'Foobar'},
            include: [
              {model: B, where: {name: 'idontexist'}, required: false}
            ]
          });
        })
        .then(function (a) {
          expect(a).to.not.equal(null);
          expect(a.get('bs')).to.deep.equal([]);
        });
    });

    it('should support many levels of belongsTo (with a lower level having a where)', function (done) {
      var A = this.sequelize.define('a', {})
        , B = this.sequelize.define('b', {})
        , C = this.sequelize.define('c', {})
        , D = this.sequelize.define('d', {})
        , E = this.sequelize.define('e', {})
        , F = this.sequelize.define('f', {})
        , G = this.sequelize.define('g', {
          name: DataTypes.STRING
        })
        , H = this.sequelize.define('h', {
          name: DataTypes.STRING
        });

      A.belongsTo(B);
      B.belongsTo(C);
      C.belongsTo(D);
      D.belongsTo(E);
      E.belongsTo(F);
      F.belongsTo(G);
      G.belongsTo(H);

      var b, singles = [
        B,
        C,
        D,
        E,
        F,
        G,
        H
      ];

      this.sequelize.sync().done(function () {
        async.auto({
          a: function (callback) {
            A.create({}).done(callback);
          },
          singleChain: function (callback) {
            var previousInstance;

            async.eachSeries(singles, function (model, callback) {
              var values = {};

              if (model.name === 'g') {
                values.name = 'yolo';
              }
              model.create(values).done(function (err, instance) {
                if (previousInstance) {
                  previousInstance["set"+Sequelize.Utils.uppercaseFirst(model.name)](instance).done(function () {
                    previousInstance = instance;
                    callback();
                  });
                } else {
                  previousInstance = b = instance;
                  callback();
                }
              });
            }, callback);
          },
          ab: ['a', 'singleChain', function (callback, results) {
            results.a.setB(b).done(callback);
          }]
        }, function () {

          A.find({
            include: [
              {model: B, include: [
                {model: C, include: [
                  {model: D, include: [
                    {model: E, include: [
                      {model: F, include: [
                        {model: G, where: {
                          name: 'yolo'
                        }, include: [
                          {model: H}
                        ]}
                      ]}
                    ]}
                  ]}
                ]}
              ]}
            ]
          }).done(function (err, a) {
            expect(err).not.to.be.ok;
            expect(a.b.c.d.e.f.g.h).to.be.ok;
            done();
          });
        });
      });
    });
  });
});
<commit_msg>unit test possible covering #2029<commit_after>/* jshint camelcase: false */
/* jshint expr: true */
var chai      = require('chai')
  , expect    = chai.expect
  , Support   = require(__dirname + '/../support')
  , Sequelize = require(__dirname + '/../../index')
  , DataTypes = require(__dirname + "/../../lib/data-types")
  , datetime  = require('chai-datetime')
  , async     = require('async');

chai.use(datetime)
chai.config.includeStack = true

describe(Support.getTestDialectTeaser("Include"), function () {
  describe('find', function () {
    it('should include a non required model, with conditions and two includes N:M 1:M', function ( done ) {
      var A = this.sequelize.define('A', { name: DataTypes.STRING(40) }, { paranoid: true })
        , B = this.sequelize.define('B', { name: DataTypes.STRING(40) }, { paranoid: true })
        , C = this.sequelize.define('C', { name: DataTypes.STRING(40) }, { paranoid: true })
        , D = this.sequelize.define('D', { name: DataTypes.STRING(40) }, { paranoid: true });

      // Associations
      A.hasMany(B);

      B.belongsTo(B);
      B.belongsTo(D);
      B.hasMany(C, {
        through: 'BC',
      });

      C.hasMany(B, {
        through: 'BC',
      });

      D.hasMany(B);

      this.sequelize.sync({ force: true }).done(function ( err ) {
        expect( err ).not.to.be.ok;

        A.find({
          include: [
            { model: B, required: false, include: [
              { model: C, required: false },
              { model: D }
            ]}
          ]
        }).done( function ( err ) {
          expect( err ).not.to.be.ok;
          done();
        });
      });
    });

    it('should include a model with a where condition but no required', function () {
      var User = this.sequelize.define('User', {}, { paranoid: false })
        , Task = this.sequelize.define('Task', {
          deletedAt: {
            type: DataTypes.DATE
          }
        }, { paranoid: false });

      User.hasMany(Task, {foreignKey: 'userId'});
      Task.belongsTo(User, {foreignKey: 'userId'});

      return this.sequelize.sync({
        force: true
      }).then(function () {
        return User.create();
      }).then(function (user) {
        return Task.bulkCreate([
          {userId: user.get('id'), deletedAt: new Date()},
          {userId: user.get('id'), deletedAt: new Date()},
          {userId: user.get('id'), deletedAt: new Date()}
        ]);
      }).then(function () {
        return User.find({
          include: [
            {model: Task, where: {deletedAt: null}, required: false}
          ]
        });
      }).then(function (user) {
        expect(user).to.be.ok;
        expect(user.Tasks.length).to.equal(0);
      });
    });

    it("should still pull the main record when an included model is not required and has where restrictions without matches", function () {
      var A = this.sequelize.define('a', {
          name: DataTypes.STRING(40)
        })
        , B = this.sequelize.define('b', {
          name: DataTypes.STRING(40)
        });

      A.hasMany(B);
      B.hasMany(A);

      return this.sequelize
        .sync({force: true})
        .then(function () {
          return A.create({
            name: 'Foobar'
          });
        })
        .then(function () {
          return A.find({
            where: {name: 'Foobar'},
            include: [
              {model: B, where: {name: 'idontexist'}, required: false}
            ]
          });
        })
        .then(function (a) {
          expect(a).to.not.equal(null);
          expect(a.get('bs')).to.deep.equal([]);
        });
    });

    it('should support many levels of belongsTo (with a lower level having a where)', function (done) {
      var A = this.sequelize.define('a', {})
        , B = this.sequelize.define('b', {})
        , C = this.sequelize.define('c', {})
        , D = this.sequelize.define('d', {})
        , E = this.sequelize.define('e', {})
        , F = this.sequelize.define('f', {})
        , G = this.sequelize.define('g', {
          name: DataTypes.STRING
        })
        , H = this.sequelize.define('h', {
          name: DataTypes.STRING
        });

      A.belongsTo(B);
      B.belongsTo(C);
      C.belongsTo(D);
      D.belongsTo(E);
      E.belongsTo(F);
      F.belongsTo(G);
      G.belongsTo(H);

      var b, singles = [
        B,
        C,
        D,
        E,
        F,
        G,
        H
      ];

      this.sequelize.sync().done(function () {
        async.auto({
          a: function (callback) {
            A.create({}).done(callback);
          },
          singleChain: function (callback) {
            var previousInstance;

            async.eachSeries(singles, function (model, callback) {
              var values = {};

              if (model.name === 'g') {
                values.name = 'yolo';
              }
              model.create(values).done(function (err, instance) {
                if (previousInstance) {
                  previousInstance["set"+Sequelize.Utils.uppercaseFirst(model.name)](instance).done(function () {
                    previousInstance = instance;
                    callback();
                  });
                } else {
                  previousInstance = b = instance;
                  callback();
                }
              });
            }, callback);
          },
          ab: ['a', 'singleChain', function (callback, results) {
            results.a.setB(b).done(callback);
          }]
        }, function () {

          A.find({
            include: [
              {model: B, include: [
                {model: C, include: [
                  {model: D, include: [
                    {model: E, include: [
                      {model: F, include: [
                        {model: G, where: {
                          name: 'yolo'
                        }, include: [
                          {model: H}
                        ]}
                      ]}
                    ]}
                  ]}
                ]}
              ]}
            ]
          }).done(function (err, a) {
            expect(err).not.to.be.ok;
            expect(a.b.c.d.e.f.g.h).to.be.ok;
            done();
          });
        });
      });
    });
  });
});
<|endoftext|>