<commit_before>var s = require('shared');

var findNearby = function(src, typ, filter){
    var area = src.room.lookForAtArea(typ, src.pos.y - 1, src.pos.x - 1, src.pos.y + 1, src.pos.x + 1, true);
    //console.log(area.length);
    //console.log(area[0].structure.structureType);
    var results = _.filter(area, filter);
    if (results[0]) {
        return results[0].structure;
    } else {
        return false;
    }
};

var freeSpace = function(src) {
    //todo: make this source-agnostic
    var area = src.room.lookForAtArea(LOOK_STRUCTURES, src.pos.y - 1, src.pos.x - 1, src.pos.y + 1, src.pos.x + 1, true);
    var free = _.filter(area, (str) => {
        let st = str.structure;
        console.log('looking for fat asses at ' + st.id);
        let fatHarvesters = st.room.find(FIND_MY_CREEPS, {filter: (creep) => {
            return creep.memory.role == 'fatHarvester' && creep.memory.container !== undefined && creep.memory.container == st.id;
        } });
        console.log('found ' + fatHarvesters.length);
        let result = st.structureType == STRUCTURE_CONTAINER && fatHarvesters.length === 0;
        return result;
    });
    var free_containers = [];
    for (var name in free) {
        free_containers.push(free[name].structure);
    }
    console.log('found ' + free_containers.length + ' free containers at ' + src.id);
    // return free[0].structure;
    return free_containers;
};

function onTop(creep, container) {
    return creep.pos == container.pos;
}

var immobileHarvester = {
    run: function(creep, stageC) {
        var err = OK;
        var m = creep.memory;
        var source;
        var container;
        //m.container = undefined;
        //m.source = undefined;
        if ( m.source === undefined || m.container === undefined) {
            let index = -1;
            let sources = creep.room.find(FIND_SOURCES, {});
            while ( container === undefined && index < sources.length) {
                index++;
                console.log('trying source ' + (index) + ' for ' + creep.name );
                source = sources[index];
                let containers = freeSpace(source);
                console.log('found ' + containers.length + ' containers free for ' + creep.name);
                container = containers[0];
                //index++;
            }

            // let sources = creep.room.find(FIND_SOURCES, {})
            // let index = ~~(Math.random() * sources.length );
            // console.log(sources);
            // console.log('setting source ' + index + ' for ' + creep.name);
            // source = sources[~~(Math.random * sources.length)];
            if (source !== undefined && container !== undefined) {
                console.log('selected source ' + index + ' for ' + creep.name);
                m.source = source.id;
                m.container = container.id;
            }
        } else {
            source = Game.getObjectById(m.source);
            container = Game.getObjectById(m.container);
            //console.log('remembered ' + m.source + ' for ' + creep.name);
        }
 /*
        if (m.container !== undefined) {
            container = Game.getObjectById(m.container);

        } else {
             container = freeSpace(source);

        }
*/
/*
        if (false && container !== undefined && container !== null) {
            m.container = container.id;
        } else {
            //console.log(' no free containers for ' + creep.name);
            return;
        }*/
        //console.log('looking for link near ' + creep.id);
        let link = findNearby(creep, LOOK_STRUCTURES, (str) => str.structure.structureType == STRUCTURE_LINK);
        //console.log(link);

        if (creep.pos.x == container.pos.x && creep.pos.y == container.pos.y) {
            err = creep.harvest(source);
            if (link) {
                //console.log('tying to use link ' + link.id);
                creep.withdraw(container, RESOURCE_ENERGY);
                creep.transfer(link, RESOURCE_ENERGY);
            } else {
                //console.log('found no links');
            }
        } else {
            err = creep.moveTo(container, {visualizePathStyle: {stroke: '#ffaa00'}});
        }

        switch (err) {
            case ERR_FULL:
                //creep.say('err?!')
                //break;
            case ERR_NOT_ENOUGH_ENERGY:
        //    case ERR_NOT_ENOUGH_RESOURCES:
            case ERR_TIRED:
            case OK:
                break;
            default:
                s.creepErr(creep, err);
            break;
        }
        return OK;
    }
};

module.exports = immobileHarvester;<commit_msg>fix incorrect string in harvester class<commit_after>var s = require('shared');

var findNearby = function(src, typ, filter){
    var area = src.room.lookForAtArea(typ, src.pos.y - 1, src.pos.x - 1, src.pos.y + 1, src.pos.x + 1, true);
    //console.log(area.length);
    //console.log(area[0].structure.structureType);
    var results = _.filter(area, filter);
    if (results[0]) {
        return results[0].structure;
    } else {
        return false;
    }
};

var freeSpace = function(src) {
    //todo: make this source-agnostic
    var area = src.room.lookForAtArea(LOOK_STRUCTURES, src.pos.y - 1, src.pos.x - 1, src.pos.y + 1, src.pos.x + 1, true);
    var free = _.filter(area, (str) => {
        let st = str.structure;
        console.log('looking for fat asses at ' + st.id + ' ' + st.structureType);
        let fatHarvesters = st.room.find(FIND_MY_CREEPS, {filter: (creep) => {
            return creep.memory.role == 'containerHarvester' && creep.memory.container !== undefined && creep.memory.container == st.id;
        } });
        console.log('found ' + fatHarvesters.length);
        let result = st.structureType == STRUCTURE_CONTAINER && fatHarvesters.length === 0;
        return result;
    });
    var free_containers = [];
    for (var name in free) {
        free_containers.push(free[name].structure);
    }
    console.log('found ' + free_containers.length + ' free containers at ' + src.id);
    // return free[0].structure;
    return free_containers;
};

function onTop(creep, container) {
    return creep.pos == container.pos;
}

var immobileHarvester = {
    run: function(creep, stageC) {
        var err = OK;
        var m = creep.memory;
        var source;
        var container;
        //m.container = undefined;
        //m.source = undefined;
        if ( m.source === undefined || m.container === undefined) {
            let index = -1;
            let sources = creep.room.find(FIND_SOURCES, {});
            while ( container === undefined && index < sources.length) {
                index++;
                console.log('trying source ' + (index) + ' for ' + creep.name );
                source = sources[index];
                let containers = freeSpace(source);
                console.log('found ' + containers.length + ' containers free for ' + creep.name);
                container = containers[0];
                //index++;
            }

            // let sources = creep.room.find(FIND_SOURCES, {})
            // let index = ~~(Math.random() * sources.length );
            // console.log(sources);
            // console.log('setting source ' + index + ' for ' + creep.name);
            // source = sources[~~(Math.random * sources.length)];
            if (source !== undefined && container !== undefined) {
                console.log('selected source ' + index + ' for ' + creep.name);
                m.source = source.id;
                m.container = container.id;
            }
        } else {
            source = Game.getObjectById(m.source);
            container = Game.getObjectById(m.container);
            //console.log('remembered ' + m.source + ' for ' + creep.name);
        }
 /*
        if (m.container !== undefined) {
            container = Game.getObjectById(m.container);

        } else {
             container = freeSpace(source);

        }
*/
/*
        if (false && container !== undefined && container !== null) {
            m.container = container.id;
        } else {
            //console.log(' no free containers for ' + creep.name);
            return;
        }*/
        //console.log('looking for link near ' + creep.id);
        let link = findNearby(creep, LOOK_STRUCTURES, (str) => str.structure.structureType == STRUCTURE_LINK);
        //console.log(link);

        if (creep.pos.x == container.pos.x && creep.pos.y == container.pos.y) {
            err = creep.harvest(source);
            if (link) {
                //console.log('tying to use link ' + link.id);
                creep.withdraw(container, RESOURCE_ENERGY);
                creep.transfer(link, RESOURCE_ENERGY);
            } else {
                //console.log('found no links');
            }
        } else {
            err = creep.moveTo(container, {visualizePathStyle: {stroke: '#ffaa00'}});
        }

        switch (err) {
            case ERR_FULL:
                //creep.say('err?!')
                //break;
            case ERR_NOT_ENOUGH_ENERGY:
        //    case ERR_NOT_ENOUGH_RESOURCES:
            case ERR_TIRED:
            case OK:
                break;
            default:
                s.creepErr(creep, err);
            break;
        }
        return OK;
    }
};

module.exports = immobileHarvester;<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>Add playToFive function<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    if (playerMove == computerMove) {
        winner = "Tie";
    }
    else if ((playerMove === "rock" && computerMove === "scissors") || (playerMove === "scissors" && comuterMove === "paper") || (playerMove === "paper" && computerMove === "rock")) {
        winner = "Player";
    }
    else {
        winner = "Computer";
    }
    return winner;
    }

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    while (playerWins < 5 && computerWins < 5) {
        var playerMove = getPlayerMove();
        var computerMove = getComputerMove();
        var returnWinner = getWinner(playerMove, computerMove);

        if (returnWinner == "Player") {
            playerWins += 1;
        }

        if (returnWinner == "Computer") {
        computerWins +=1;
        }

    console.log("Player picked: " + playerMove + ", Computer picked: " + computerMove + ".");
    console.log("Winner: " + returnWinner + "! Score is Player: " + playerWins + ", Computer: " + computerWins + "." );

    }

    return [playerWins, computerWins];
}

<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return /* Your Expression */;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return /* Your Expression */;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>Add basic expressions from 3.6 homework<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    var move = x || getInput(); // Use OR function to equal getInput() unless x =/= null
    return move;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    var move = x || randomPlay();
    return move;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
	var playerMove = move || getInput();
	return playerMove;
}

function getComputerMove(move) {
	var computerMove = move || randomPlay();
	return computerMove;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>Wrote rock paper scissors code<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
	var playerMove = move || getInput();
	return playerMove;
}

function getComputerMove(move) {
	var computerMove = move || randomPlay();
	return computerMove;
}

function getWinner(playerMove,computerMove) {
	var winner;
	if (playerMove == ‘rock’) {
		if (computerMove == ‘rock’) {
			winner = “Tie!”;
		}
		else if (computerMove == ‘paper’) {
			winner = ‘Computer!”;
		}
		else {
			winner = “Player!”;
		}
	}
	else if (playerMove == ‘paper’) {
		if (computerMove == ‘paper’) {
			winner = ‘Tie!’;
		}
		else if (computerMove == ‘scissors’);{
			winner = ‘Computer!’;
		}
		else {
			winner = ‘Player!’;
		}
	{
	else if (playerMove == ‘scissors’) {
		if (computerMove == ‘scissors’) {
			winner = ‘Tie!’;
		}
		else if (computerMove == ‘rock’){
			winner = ‘Computer!’;
		}
		else {
			winner = ‘Player’;
		}
	}
}
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<|endoftext|>


<commit_before>var WhiteTheme = function(name, id) {
  this.name = name;
  this.id = id || 'ace/theme/' + name.toLowerCase().replace(/\s/g, '_');
  this.cls = 'ace-theme-white';
};

var BlackTheme = function(name, id) {
  WhiteTheme.call(this, name, id);
  this.cls = 'ace-theme-black';
};

TD.service('settings', function($rootScope, storage, log, VimHandler, EmacsHandler) {
  var settings = this;

  this.THEMES = [
    new WhiteTheme('Chrome'),
    new WhiteTheme('Clouds'),
    new BlackTheme('Clouds Midnight'),
    new BlackTheme('Cobalt'),
    new WhiteTheme('Crimson Editor'),
    new WhiteTheme('Dawn'),
    new WhiteTheme('Dreamweaver'),
    new WhiteTheme('Eclipse'),
    new BlackTheme('idleFingers', 'ace/theme/idle_fingers'),
    new BlackTheme('krTheme', 'ace/theme/kr_theme'),
    new BlackTheme('Merbivore'),
    new BlackTheme('Merbivore Soft'),
    new BlackTheme('Mono Industrial'),
    new BlackTheme('Monokai'),
    new BlackTheme('Pastel on dark'),
    new BlackTheme('Solarized Dark'),
    new WhiteTheme('Solarized Light'),
    new WhiteTheme('TextMate'),
    new BlackTheme('Twilight'),
    new WhiteTheme('Tomorrow'),
    new BlackTheme('Tomorrow Night'),
    new BlackTheme('Tomorrow Night Blue'),
    new BlackTheme('Tomorrow Night Bright'),
    new BlackTheme('Tomorrow Night 80s', 'ace/theme/tomorrow_night_eighties'),
    new BlackTheme('Vibrant Ink')
  ];

  this.KEY_MODES = [
    {name: 'ACE', id: 'ace', handler: null},
    {name: 'Vim', id: 'vim', handler: VimHandler},
    {name: 'Emacs', id: 'emacs', handler: EmacsHandler}
  ];

  this.SOFT_WRAP = [
    {name: 'OFF', value: -1},
    {name: 'FREE', value: 0},
    {name: '80', value: 80},
    {name: '100', value: 100}
  ];

  var findById = function(collection, id) {
    for (var i = 0; i < collection.length; i++) {
      if (collection[i].id === id) {
        return collection[i];
      }
    }
  };

  // defaults
  var data = {
    theme: findById(this.THEMES, 'ace/theme/monokai'),
    keyMode: findById(this.KEY_MODES, 'ace'),
    useSoftTabs: true,
    tabSize: 4,
    softWrap: 0 // wrap free
  };

  var listeners = {};

  var defineProperty = function(name) {
    settings.__defineGetter__(name, function() {
      return data[name];
    });

    settings.__defineSetter__(name, function(value) {
      data[name] = value;

      if (!listeners[name]) {
        return;
      }

      listeners[name].forEach(function(fn) {
        fn(value);
      });
    });
  };

  defineProperty('theme');
  defineProperty('keyMode');
  defineProperty('useSoftTabs');
  defineProperty('tabSize');
  defineProperty('softWrap');

  this.on = function(name, fn) {
    if (!listeners[name]) {
      listeners[name] = [];
    }

    listeners[name].push(fn);
  };

  this.store = function() {
    storage.set({
      settings: {
        theme: data.theme.id,
        keyMode: data.keyMode.id,
        useSoftTabs: data.useSoftTabs,
        tabSize: data.tabSize,
        softWrap: data.softWrap
      }
    }, function() {
      log('settings saved');
    });
  };

  this.load = function() {
    storage.get(['settings'], function(data) {
      data = data.settings || {};

      if (data.theme) {
        settings.theme = findById(settings.THEMES, data.theme);
        log('loaded theme', settings.theme.id);
      }

      if (data.keyMode) {
        settings.keyMode = findById(settings.KEY_MODES, data.keyMode);
        log('loaded keyMode', settings.keyMode.id);
      }

      if (angular.isDefined(data.useSoftTabs)) {
        settings.useSoftTabs = data.useSoftTabs;
        log('loaded useSoftTabs', settings.useSoftTabs);
      }

      if (angular.isDefined(data.tabSize)) {
        settings.tabSize = data.tabSize;
        log('loaded tabSize', settings.tabSize);
      }

      if (angular.isDefined(data.softWrap)) {
        settings.softWrap = data.softWrap;
        log('loaded softWrap', settings.softWrap);
      }
    });
  };
});<commit_msg>Fix default settings<commit_after>var WhiteTheme = function(name, id) {
  this.name = name;
  this.id = id || 'ace/theme/' + name.toLowerCase().replace(/\s/g, '_');
  this.cls = 'ace-theme-white';
};

var BlackTheme = function(name, id) {
  WhiteTheme.call(this, name, id);
  this.cls = 'ace-theme-black';
};

TD.service('settings', function($rootScope, storage, log, VimHandler, EmacsHandler) {
  var settings = this;

  this.THEMES = [
    new WhiteTheme('Chrome'),
    new WhiteTheme('Clouds'),
    new BlackTheme('Clouds Midnight'),
    new BlackTheme('Cobalt'),
    new WhiteTheme('Crimson Editor'),
    new WhiteTheme('Dawn'),
    new WhiteTheme('Dreamweaver'),
    new WhiteTheme('Eclipse'),
    new BlackTheme('idleFingers', 'ace/theme/idle_fingers'),
    new BlackTheme('krTheme', 'ace/theme/kr_theme'),
    new BlackTheme('Merbivore'),
    new BlackTheme('Merbivore Soft'),
    new BlackTheme('Mono Industrial'),
    new BlackTheme('Monokai'),
    new BlackTheme('Pastel on dark'),
    new BlackTheme('Solarized Dark'),
    new WhiteTheme('Solarized Light'),
    new WhiteTheme('TextMate'),
    new BlackTheme('Twilight'),
    new WhiteTheme('Tomorrow'),
    new BlackTheme('Tomorrow Night'),
    new BlackTheme('Tomorrow Night Blue'),
    new BlackTheme('Tomorrow Night Bright'),
    new BlackTheme('Tomorrow Night 80s', 'ace/theme/tomorrow_night_eighties'),
    new BlackTheme('Vibrant Ink')
  ];

  this.KEY_MODES = [
    {name: 'ACE', id: 'ace', handler: null},
    {name: 'Vim', id: 'vim', handler: VimHandler},
    {name: 'Emacs', id: 'emacs', handler: EmacsHandler}
  ];

  this.SOFT_WRAP = [
    {name: 'OFF', value: -1},
    {name: 'FREE', value: 0},
    {name: '80', value: 80},
    {name: '100', value: 100}
  ];

  var findById = function(collection, id) {
    for (var i = 0; i < collection.length; i++) {
      if (collection[i].id === id) {
        return collection[i];
      }
    }
  };

  var data = {};
  var listeners = {};

  var defineProperty = function(name) {
    settings.__defineGetter__(name, function() {
      return data[name];
    });

    settings.__defineSetter__(name, function(value) {
      data[name] = value;

      if (!listeners[name]) {
        return;
      }

      listeners[name].forEach(function(fn) {
        fn(value);
      });
    });
  };

  defineProperty('theme');
  defineProperty('keyMode');
  defineProperty('useSoftTabs');
  defineProperty('tabSize');
  defineProperty('softWrap');

  this.on = function(name, fn) {
    if (!listeners[name]) {
      listeners[name] = [];
    }

    listeners[name].push(fn);
  };

  this.store = function() {
    storage.set({
      settings: {
        theme: data.theme.id,
        keyMode: data.keyMode.id,
        useSoftTabs: data.useSoftTabs,
        tabSize: data.tabSize,
        softWrap: data.softWrap
      }
    }, function() {
      log('settings saved');
    });
  };

  this.load = function() {
    storage.get(['settings'], function(data) {
      data = data.settings || {};

      if (data.theme) {
        settings.theme = findById(settings.THEMES, data.theme);
        log('loaded theme', settings.theme.id);
      } else {
        settings.theme = findById(settings.THEMES, 'ace/theme/monokai');
        log('default theme', settings.theme.id);
      }

      if (data.keyMode) {
        settings.keyMode = findById(settings.KEY_MODES, data.keyMode);
        log('loaded keyMode', settings.keyMode.id);
      } else {
        settings.keyMode = findById(settings.KEY_MODES, 'ace');
        log('default keyMode', settings.keyMode.id);
      }

      if (angular.isDefined(data.useSoftTabs)) {
        settings.useSoftTabs = data.useSoftTabs;
        log('loaded useSoftTabs', settings.useSoftTabs);
      } else {
        settings.useSoftTabs = true;
        log('default useSoftTabs', settings.useSoftTabs);
      }

      if (angular.isDefined(data.tabSize)) {
        settings.tabSize = data.tabSize;
        log('loaded tabSize', settings.tabSize);
      } else {
        settings.tabSize = 4;
        log('default tabSize', settings.tabSize);
      }

      if (angular.isDefined(data.softWrap)) {
        settings.softWrap = data.softWrap;
        log('loaded softWrap', settings.softWrap);
      } else {
        settings.softWrap = 0;
        log('default softWrap', settings.softWrap);
      }
    });
  };
});<|endoftext|>


<commit_before>"use strict";

angular.module("piadinamia").factory("sharedCartService",
    ["$firebase", "Firebase", "FBURL",
    function ($firebase, Firebase, FBURL) {
        var mySubscribers = [],
            cartByUser = {},
            cartByItem = {};

        function calcCartByUser(user, cart) {
            var myCart = [],
                total = 0;

            angular.forEach(cart, function (item) {
                myCart.push(item);
                total += item.qty * item.price;
            });

            cartByUser[user.id] = {
                name: user.name,
                total: total,
                cart: myCart
            };
        }

        function calcCartByItem() {
            cartByItem = {};

            angular.forEach(cartByUser, function (user) {
                user.cart.forEach(function (item) {
                    var counter = 0;

                    if (cartByItem[item.item]) {
                        counter = cartByItem[item.item].total + item.qty;
                    } else {
                        counter = item.qty;
                    }

                    cartByItem[item.item] = {
                        total: counter
                    };
                });
            });
        }

        function subscribeCarts(catalogName) {
            mySubscribers.forEach(function (user) {
                var ref = new Firebase(FBURL + "/users/" + user.id +
                            "/catalogs/" + catalogName + "/cart"),
                    cartSync = $firebase(ref).$asArray();

                cartSync.$watch(function () {
                    cartSync.$loaded().then(function () {
                        calcCartByUser(user, cartSync);
                        calcCartByItem();
                    });
                });
            });
        }

        return {
            init: function (userId, catalogName) {
                var ref = new Firebase(FBURL + "/users/" + userId +
                            "/catalogs/" + catalogName + "/subscribers"),
                    subscribersSync = $firebase(ref).$asArray();

                mySubscribers = subscribersSync;

                subscribersSync.$loaded().then(function () {
                    mySubscribers = subscribersSync;
                    subscribeCarts(catalogName);
                });
            },

            getCartByItem: function () {
                return cartByItem;
            },

            getCartByUser: function () {
                return cartByUser;
            }

        };

    }]);
<commit_msg>Refactor sharedCartService.js with Papa's style guide.<commit_after>(function () {
    "use strict";

    angular
        .module("piadinamia")
        .factory("sharedCartService", sharedCartService);

    sharedCartService.$inject = ["$firebase", "Firebase", "FBURL"];

    function sharedCartService($firebase, Firebase, FBURL) {
        var mySubscribers = [],
            cartByUser = {},
            cartByItem = {},
            service = {
                init: init,
                getCartByItem: getCartByItem,
                getCartByUser: getCartByUser
            };

        return service;

        function calcCartByUser(user, cart) {
            var myCart = [],
                total = 0;

            angular.forEach(cart, function (item) {
                myCart.push(item);
                total += item.qty * item.price;
            });

            cartByUser[user.id] = {
                name: user.name,
                total: total,
                cart: myCart
            };
        }

        function calcCartByItem() {
            cartByItem = {};

            angular.forEach(cartByUser, function (user) {
                user.cart.forEach(function (item) {
                    var counter = 0;

                    if (cartByItem[item.item]) {
                        counter = cartByItem[item.item].total + item.qty;
                    } else {
                        counter = item.qty;
                    }

                    cartByItem[item.item] = {
                        total: counter
                    };
                });
            });
        }

        function subscribeCarts(catalogName) {
            mySubscribers.forEach(function (user) {
                var ref = new Firebase(FBURL + "/users/" + user.id +
                            "/catalogs/" + catalogName + "/cart"),
                    cartSync = $firebase(ref).$asArray();

                cartSync.$watch(function () {
                    cartSync.$loaded().then(function () {
                        calcCartByUser(user, cartSync);
                        calcCartByItem();
                    });
                });
            });
        }

        function init(userId, catalogName) {
            var ref = new Firebase(FBURL + "/users/" + userId +
                        "/catalogs/" + catalogName + "/subscribers"),
                subscribersSync = $firebase(ref).$asArray();

            mySubscribers = subscribersSync;

            subscribersSync.$loaded().then(function () {
                mySubscribers = subscribersSync;
                subscribeCarts(catalogName);
            });
        }

        function getCartByItem() {
            return cartByItem;
        }

        function getCartByUser() {
            return cartByUser;
        }

    }

}());
<|endoftext|>


<commit_before>/*******************************************************************************
 * The MIT License (MIT)
 * Copyright © 2015 Inshua,inshua@gmail.com, All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
 * associated documentation files (the “Software”), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
 * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *******************************************************************************/
// ================= 扩充函数 ========================
/**
 * 根据判据函数查找满足条件的序号。如果没有找到返回 -1。
 * 用法:
 * ```js
 * [1, 2, 3, 4].find(function(item, index){
 * 		return item % 2 == 0;
 * });
 * ```
 * 得到 1。
 * @param fn {function} ***function(item, index) { return boolean}***
 * @returns {Object}
 */
Array.prototype.findIndex = function(fn, scope){
	for(var i=0; i< this.length; i++){
		if(fn.call(scope, this[i], i)) return i;
	}
	return -1;
};

/**
 * 根据判据函数查找满足条件的元素。如果没有找到返回 undefined。
 * 用法:
 * ```js
 * [1, 2, 3, 4].find(function(item, index){
 * 		return item % 2 == 0;
 * });
 * ```
 * 得到 2。
 * @param fn {function} ***function(item, index) { return boolean}***
 * @returns {Number}
 */
Array.prototype.find = function(fn, scope){
	for(var i=0; i< this.length; i++){
		if(fn.call(scope, this[i], i)) return this[i];
	}
};

/**
 * 找出两个数组（集合）的变化。
 * 例如
 * ```js
 *     [1,2,3].diff([3,4])
 * ```
 * 得到
 * ```js
 * 	   {appended : [4], removed : [1,2]}
 * ```
 * @param newArray {array} 新版本的数组
 * @returns {Object} {appended : [], removed : []}
 */
Array.prototype.diff = function(newArray){
	var n = [], r = [];
	for(var i=0; i<this.length; i++){
		if(newArray.indexOf(this[i]) == -1){
			r.push(this[i]);
		}
	}
	for(var i=0; i<newArray.length; i++){
		if(this.indexOf(newArray[i]) == -1){
			n.push(newArray[i]);
		}
	}
	return {appended : n, removed : r};
}

/**
 * 去除数组中所有相同的元素,得到新数组
 */
Array.prototype.distinct = function(){
	var arr = [];
	for(var i=0; i<this.length; i++){
		if(arr.indexOf(this[i]) == -1){
			arr.push(this[i]);
		}
	}
	return arr;
}

/**
 * 得到按属性的索引，如:
 * 		[{name: 'mike', phone: '12233'}, {name: 'tom', phone: '53332'},].indexOf('phone')
 * 得到：
 * 		{'12233' : {name: 'mike', phone: '12233'}, '53332': {name: 'tom', phone: '53332'}}
 * 这里值部分为对象引用。
 */
Array.prototype.indexBy = function(key){
	var result = {};
	for(var i=0; i<this.length; i++){
		var el = this[i];
		var v = el[key];
		if(v != null && v !== ''){		// '' == 0 but '' !== 0
			result[v] = el;
		}
	}
	return result;
}

/**
 * 将当前对象与另一对象合并，另一对象的属性复制到本对象。
 * narshorn 的bug，当使用 JSON.parse(obj, parseDate) 后，随着 merge 的引入，就会出现堆栈溢出
 * 所以采用 defineProperty 的方式声明该成员不可枚举，无法被 JSON.stringify
 * @param b 另一对象
 * @param override 仅复制本对象没有的属性。
 * @returns {Object} 当前对象本身
 */
Object.defineProperty(Object.prototype, 'merge', {value: function(b, override){
	for(var k in b){
		if(override != false || k in this == false){
			this[k] = b[k];
		}
	}
	return this;
}, enumerable: false});

if (typeof Object.assign != 'function') {
  Object.assign = function(target, varArgs) { // .length of function is 2
    if (target == null) { // TypeError if undefined or null
      throw new TypeError('Cannot convert undefined or null to object');
    }

    var to = Object(target);

    for (var index = 1; index < arguments.length; index++) {
      var nextSource = arguments[index];

      if (nextSource != null) { // Skip over if undefined or null
        for (var nextKey in nextSource) {
          // Avoid bugs when hasOwnProperty is shadowed
          if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
    }
    return to;
  };
}

var JsTypeUtil = Java.type('org.siphon.common.js.JsTypeUtil');
/**
 * 将本对象转为Java对象，为 JsTypeUtil.jsObjectToJava 的包装。
 * 很多库，比如activiti，都需要传递 Map<String, Object>等，采取本方式可以写作:
 *   submit({username: xxx, password: ''}.toJava())
 *
 * (未实现)如对象已有 _java_type 说明，则自动取该说明指定的对象类型。如 {_java_type: 'com.my.entity.Person', name:'Mike'}.toJava() 可得到类型为 com.my.entity.Person 的对象。
 * @param [selfType] {Java.type|string} Java.type('') 返回值, or java class name。对数组默认为 ArrayList，对对象默认为 HashMap<String,Object>。
 * @param [elementType] {Java.type|string} Java.type('') 返回值, or java class name. 对数组默认为 ArrayList，对对象默认为 HashMap<String,Object>。
 * @returns {Object} java object
 */
Object.defineProperty(Object.prototype, 'toJava', {value: function(selfType, elementType){
	return JsTypeUtil.jsObjectToJava(this);
}, enumerable: false});

var jsTypeUtil = new JsTypeUtil(engine);
(function(){
	/**
	 * 从Java对象（Map<String,Object>, List,数组等）转换得到Js对象
	 * @param b 另一对象
	 * @returns {Object} 当前对象本身
	 */
	Object.fromJava = function(javaObj){
		return jsTypeUtil.javaObjectToJs(javaObj);
	}
})();

if(!String.prototype.trim){
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g, '');
	};
}

String.prototype.contains = function(t) {
	return this.indexOf(t) >= 0;
};

/**
 * 格式化字符串。
 * Usage:
 * ```js
 *   alert('Program: {key1} {key2}'.format({ 'key1' : 'Hello', 'key2' : 'World' }));
 * ```
 * @param values
 * @returns {String}
 */
String.prototype.format = function (values) {

    var regex = /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g;

    var getValue = function (key) {
            if (values == null || typeof values === 'undefined') return null;

            var value = values[key];
            var type = typeof value;

            return type === 'string' || type === 'number' ? value : null;
        };

    return this.replace(regex, function (match) {
        //match will look like {sample-match}
        //key will be 'sample-match';
        var key = match.substr(1, match.length - 2);

        var value = getValue(key);

        return value != null ? value : match;
    });
};

/**
 * 通过排序得到的新数组
 * @param fn {function} 排序函数，与 Array.prototype.sort 同
 * @param [scope] {object} 传入的 this 对象
 * @returns {Array}
 */
Array.prototype.orderBy = function(fn, scope) {
	var result = this.slice();
	result.sort(function(){fn.apply(scope, arguments);});
	return result;
};

/**
 * 使Error对象能Json化，see http://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify
 */
Object.defineProperty(Error.prototype, 'toJSON', {
    value: function () {
        var alt = {};

        Object.getOwnPropertyNames(this).forEach(function (key) {
            alt[key] = this[key];
        }, this);

        return alt;
    },
    configurable: true
});

/**
 * 表示失败的错误
 */
function FailedError(message){
	Error.prototype.constructor.call(this);
	this.name = 'FailedError';
	this.message = message;
}

/**
 * 表示致命错误的错误
 */
function FatalError(message){
	Error.prototype.constructor.call(this);
	this.name = 'FatalError';
	this.message = message;
}

/**
 * 多个错误
 */
function MultiError(errors){
	Error.prototype.constructor.call(this);
	this.name = 'MultiError';
	this.errors = errors || [];
	this.toString = function(){
		return '(MutiError '  + this.errors + ')';
	}
}

/**
 * 校验错误
 */
function ValidationError(field, validator, message){
	this.name = 'ValidationError';
	this.field = field;
	this.validator = validator;
	this.message = message;
}

var Throwable = Java.type('java.lang.Throwable'),
	ScriptException = Java.type('javax.script.ScriptException'),
	ECMAException = Java.type('jdk.nashorn.internal.runtime.ECMAException'),
	StackTraceElement = Java.type('java.lang.StackTraceElement');

/**
 * 将 js 错误包装为可用的 java 错误, 以便在 logger.error(msg, warpJsError(error)) 中使用
 * @param e {Error} js error
 * @returns {ECMAException}
 */
function wrapJsError(e){
	if(Throwable.class.isInstance(e)) return e;

	if(e instanceof Error){
		var ecmaException = ECMAException.create(e, e.fileName, e.lineNumber, e.columnNumber);
		var stack = e.stack.split(/\r\n|\n|\r/);
		var javaStack = [];
		for(var i=0;i<stack.length; i++){
			var line = stack[i];
			var match = /at\s(.+)\s\((.*):(\d+)\)/.exec(line);
			if(match){
				var stackElement = new StackTraceElement('<nashorn>', match[1], match[2], match[3]);
				javaStack.push(stackElement);
			}
		}
		ecmaException.setStackTrace(Java.to(javaStack, 'java.lang.StackTraceElement[]'));
		return ecmaException;
	} else {
		return new ECMAException(e, null);
	}
}

/**
 * wrapJsError 的别名
 * @param e {Error} js error
 * @returns {ECMAException}
 */
Error.toJava = wrapJsError;
Object.defineProperty(Error, 'toJava', {value: wrapJsError, enumerable: false});

/**
 * 对对象的属性名做映射, 得到一个新对象.
 * 如
 * ```js
 * 	translateObject({name : 'Mike', gender : 'M'}, ['name', 'gender'], ['姓名', '性别'])
 * ```
 * 得到 `{姓名 : 'Mike', 性别 :'M'}`
 * @param obj {object} 原对象
 * @param originAttrs {string[]} 原属性名列表, 数组
 * @param map {string[]} 映射后的属性名列表, 数组
 */
function translateObject(obj, originAttrs, map){
	var result = {};
	for(var i=0; i< originAttrs.length; i++){
		result[map[i]] = obj[originAttrs[i]];
	}
	return result;
}

<commit_msg>增加 String.prototype.repeat, String.prototype.toHtml<commit_after>/*******************************************************************************
 * The MIT License (MIT)
 * Copyright © 2015 Inshua,inshua@gmail.com, All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
 * associated documentation files (the “Software”), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
 * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *******************************************************************************/
// ================= 扩充函数 ========================
/**
 * 根据判据函数查找满足条件的序号。如果没有找到返回 -1。
 * 用法:
 * ```js
 * [1, 2, 3, 4].find(function(item, index){
 * 		return item % 2 == 0;
 * });
 * ```
 * 得到 1。
 * @param fn {function} ***function(item, index) { return boolean}***
 * @returns {Object}
 */
Array.prototype.findIndex = function(fn, scope){
	for(var i=0; i< this.length; i++){
		if(fn.call(scope, this[i], i)) return i;
	}
	return -1;
};

/**
 * 根据判据函数查找满足条件的元素。如果没有找到返回 undefined。
 * 用法:
 * ```js
 * [1, 2, 3, 4].find(function(item, index){
 * 		return item % 2 == 0;
 * });
 * ```
 * 得到 2。
 * @param fn {function} ***function(item, index) { return boolean}***
 * @returns {Number}
 */
Array.prototype.find = function(fn, scope){
	for(var i=0; i< this.length; i++){
		if(fn.call(scope, this[i], i)) return this[i];
	}
};

/**
 * 找出两个数组（集合）的变化。
 * 例如
 * ```js
 *     [1,2,3].diff([3,4])
 * ```
 * 得到
 * ```js
 * 	   {appended : [4], removed : [1,2]}
 * ```
 * @param newArray {array} 新版本的数组
 * @returns {Object} {appended : [], removed : []}
 */
Array.prototype.diff = function(newArray){
	var n = [], r = [];
	for(var i=0; i<this.length; i++){
		if(newArray.indexOf(this[i]) == -1){
			r.push(this[i]);
		}
	}
	for(var i=0; i<newArray.length; i++){
		if(this.indexOf(newArray[i]) == -1){
			n.push(newArray[i]);
		}
	}
	return {appended : n, removed : r};
}

/**
 * 去除数组中所有相同的元素,得到新数组
 */
Array.prototype.distinct = function(){
	var arr = [];
	for(var i=0; i<this.length; i++){
		if(arr.indexOf(this[i]) == -1){
			arr.push(this[i]);
		}
	}
	return arr;
}

/**
 * 得到按属性的索引，如:
 * 		[{name: 'mike', phone: '12233'}, {name: 'tom', phone: '53332'},].indexOf('phone')
 * 得到：
 * 		{'12233' : {name: 'mike', phone: '12233'}, '53332': {name: 'tom', phone: '53332'}}
 * 这里值部分为对象引用。
 */
Array.prototype.indexBy = function(key){
	var result = {};
	for(var i=0; i<this.length; i++){
		var el = this[i];
		var v = el[key];
		if(v != null && v != ''){
			result[v] = el;
		}
	}
	return result;
}

/**
 * 将当前对象与另一对象合并，另一对象的属性复制到本对象。
 * narshorn 的bug，当使用 JSON.parse(obj, parseDate) 后，随着 merge 的引入，就会出现堆栈溢出
 * 所以采用 defineProperty 的方式声明该成员不可枚举，无法被 JSON.stringify
 * @param b 另一对象
 * @param override 仅复制本对象没有的属性。
 * @returns {Object} 当前对象本身
 */
Object.defineProperty(Object.prototype, 'merge', {value: function(b, override){
	for(var k in b){
		if(override != false || k in this == false){
			this[k] = b[k];
		}
	}
	return this;
}, enumerable: false});

if (typeof Object.assign != 'function') {
  Object.assign = function(target, varArgs) { // .length of function is 2
    if (target == null) { // TypeError if undefined or null
      throw new TypeError('Cannot convert undefined or null to object');
    }

    var to = Object(target);

    for (var index = 1; index < arguments.length; index++) {
      var nextSource = arguments[index];

      if (nextSource != null) { // Skip over if undefined or null
        for (var nextKey in nextSource) {
          // Avoid bugs when hasOwnProperty is shadowed
          if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
    }
    return to;
  };
}

var JsTypeUtil = Java.type('org.siphon.common.js.JsTypeUtil');
/**
 * 将本对象转为Java对象，为 JsTypeUtil.jsObjectToJava 的包装。
 * 很多库，比如activiti，都需要传递 Map<String, Object>等，采取本方式可以写作:
 *   submit({username: xxx, password: ''}.toJava())
 *
 * (未实现)如对象已有 _java_type 说明，则自动取该说明指定的对象类型。如 {_java_type: 'com.my.entity.Person', name:'Mike'}.toJava() 可得到类型为 com.my.entity.Person 的对象。
 * @param [selfType] {Java.type|string} Java.type('') 返回值, or java class name。对数组默认为 ArrayList，对对象默认为 HashMap<String,Object>。
 * @param [elementType] {Java.type|string} Java.type('') 返回值, or java class name. 对数组默认为 ArrayList，对对象默认为 HashMap<String,Object>。
 * @returns {Object} java object
 */
Object.defineProperty(Object.prototype, 'toJava', {value: function(selfType, elementType){
	return JsTypeUtil.jsObjectToJava(this);
}, enumerable: false});

var jsTypeUtil = new JsTypeUtil(engine);
(function(){
	/**
	 * 从Java对象（Map<String,Object>, List,数组等）转换得到Js对象
	 * @param b 另一对象
	 * @returns {Object} 当前对象本身
	 */
	Object.fromJava = function(javaObj){
		return jsTypeUtil.javaObjectToJs(javaObj);
	}
})();

if(!String.prototype.trim){
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g, '');
	};
}

String.prototype.contains = function(t) {
	return this.indexOf(t) >= 0;
};

String.prototype.toHtml = function(){
	return this.replace(/&/g, '&')
            .replace(/"/g, '"')
            .replace(/'/g, ''')
            .replace(/</g, '<')
            .replace(/>/g, '>')
            .replace(/\r\n|\r|\n/g, '<br>');
}

String.prototype.repeat = function(count){
	var arr = []
	for(var i=0; i< count; i++) arr.push(this);
	return arr.join('');
}

/**
 * 格式化字符串。
 * Usage:
 * ```js
 *   alert('Program: {key1} {key2}'.format({ 'key1' : 'Hello', 'key2' : 'World' }));
 * ```
 * @param values
 * @returns {String}
 */
String.prototype.format = function (values) {

    var regex = /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g;

    var getValue = function (key) {
            if (values == null || typeof values === 'undefined') return null;

            var value = values[key];
            var type = typeof value;

            return type === 'string' || type === 'number' ? value : null;
        };

    return this.replace(regex, function (match) {
        //match will look like {sample-match}
        //key will be 'sample-match';
        var key = match.substr(1, match.length - 2);

        var value = getValue(key);

        return value != null ? value : match;
    });
};

/**
 * 通过排序得到的新数组
 * @param fn {function} 排序函数，与 Array.prototype.sort 同
 * @param [scope] {object} 传入的 this 对象
 * @returns {Array}
 */
Array.prototype.orderBy = function(fn, scope) {
	var result = this.slice();
	result.sort(function(){fn.apply(scope, arguments);});
	return result;
};

/**
 * 使Error对象能Json化，see http://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify
 */
Object.defineProperty(Error.prototype, 'toJSON', {
    value: function () {
        var alt = {};

        Object.getOwnPropertyNames(this).forEach(function (key) {
            alt[key] = this[key];
        }, this);

        return alt;
    },
    configurable: true
});

/**
 * 表示失败的错误
 */
function FailedError(message){
	Error.prototype.constructor.call(this);
	this.name = 'FailedError';
	this.message = message;
}

/**
 * 表示致命错误的错误
 */
function FatalError(message){
	Error.prototype.constructor.call(this);
	this.name = 'FatalError';
	this.message = message;
}

/**
 * 多个错误
 */
function MultiError(errors){
	Error.prototype.constructor.call(this);
	this.name = 'MultiError';
	this.errors = errors || [];
	this.toString = function(){
		return '(MutiError '  + this.errors + ')';
	}
}

/**
 * 校验错误
 */
function ValidationError(field, validator, message){
	this.name = 'ValidationError';
	this.field = field;
	this.validator = validator;
	this.message = message;
}

var Throwable = Java.type('java.lang.Throwable'),
	ScriptException = Java.type('javax.script.ScriptException'),
	ECMAException = Java.type('jdk.nashorn.internal.runtime.ECMAException'),
	StackTraceElement = Java.type('java.lang.StackTraceElement');

/**
 * 将 js 错误包装为可用的 java 错误, 以便在 logger.error(msg, warpJsError(error)) 中使用
 * @param e {Error} js error
 * @returns {ECMAException}
 */
function wrapJsError(e){
	if(Throwable.class.isInstance(e)) return e;

	if(e instanceof Error){
		var ecmaException = ECMAException.create(e, e.fileName, e.lineNumber, e.columnNumber);
		var stack = e.stack.split(/\r\n|\n|\r/);
		var javaStack = [];
		for(var i=0;i<stack.length; i++){
			var line = stack[i];
			var match = /at\s(.+)\s\((.*):(\d+)\)/.exec(line);
			if(match){
				var stackElement = new StackTraceElement('<nashorn>', match[1], match[2], match[3]);
				javaStack.push(stackElement);
			}
		}
		ecmaException.setStackTrace(Java.to(javaStack, 'java.lang.StackTraceElement[]'));
		return ecmaException;
	} else {
		return new ECMAException(e, null);
	}
}

/**
 * wrapJsError 的别名
 * @param e {Error} js error
 * @returns {ECMAException}
 */
Error.toJava = wrapJsError;
Object.defineProperty(Error, 'toJava', {value: wrapJsError, enumerable: false});

/**
 * 对对象的属性名做映射, 得到一个新对象.
 * 如
 * ```js
 * 	translateObject({name : 'Mike', gender : 'M'}, ['name', 'gender'], ['姓名', '性别'])
 * ```
 * 得到 `{姓名 : 'Mike', 性别 :'M'}`
 * @param obj {object} 原对象
 * @param originAttrs {string[]} 原属性名列表, 数组
 * @param map {string[]} 映射后的属性名列表, 数组
 */
function translateObject(obj, originAttrs, map){
	var result = {};
	for(var i=0; i< originAttrs.length; i++){
		result[map[i]] = obj[originAttrs[i]];
	}
	return result;
}

<|endoftext|>


<commit_before>
var App = function() {

	// create nodes
	var	win = $(window),
		body = $(document.body),
		container = $('

').appendTo(body),
		header = $('

').appendTo(container),
		main = $('

').appendTo(container),
		footer = $('

').appendTo(container),
		ext = {};

	function init() {

		var mainMenu = new MainMenu(header);

		// create objects
		var windowManager = new WindowManager(main);

		ext.windowManager = windowManager;

		// combine nodes and objects
		win.on('resize', resize);
		win.on('orientationchange', resize);
		resize();

		var settings = getWindowSettings(),
			windowWidth = win.width();
		//console.log('settings',settings, settings.length);

		if (windowWidth < 768 && settings.windows.length >= 3) {
			settings.windows = settings.windows.slice(0,2);
		}
		if (windowWidth < 480 && settings.windows.length >= 2) {
			settings.windows = settings.windows.slice(0,1);
		}

		// create windows
		for (var i=0, il=settings.windows.length; i<il; i++) {
			var setting = settings.windows[i],
				windowType = setting.windowType;

			if (!setting.windowType) {

				switch (setting.type) {
					case 'bible':
						windowType = 'BibleWindow';
						break;
					case 'commentary':
						windowType = 'CommentaryWindow';
						break;
					case 'map':
						windowType = 'MapsWindow';
						break;
					case 'search':
						windowType = 'SearchWindow';
						break;
					case 'media':
						windowType = 'MediaWindow';
						break;
					default:
						windowType = setting.type;

				}
			}

			// create window
			//console.log('create',i, windowType, setting.data);
			windowManager.add(windowType, setting.data);
		}

		var settingsTimer = new Timer(storeSettings, 1000);

		windowManager.on('settingschange', function(e) {

			// title to show active window's position
			if (e.data && e.data.label && e.data.hasFocus) {
				document.title = e.data.labelLong;
			}

			settingsTimer.start();

		});

		var plugins = []
		ext.plugins = plugins;
		// run plugins
		for (var x in sofia.plugins) {
			plugin = new window[ sofia.plugins[x] ](this);
			plugins.push(plugin);

			if (plugin.on) {

				plugin.on('globalmessage', handleGlobalMessage);
			}
		}
	}

	function resize() {
		console.log('app resize');

		PlaceKeeper.storePlace();

		// get window size
		var width = win.width(),
			height = win.height(),

			// calculate size
			areaHeight = height - header.outerHeight() + footer.outerHeight(),
			areaWidth = width - parseInt(main.css('margin-left'), 10) - parseInt(main.css('margin-right'), 10);

		if (width < 410) {
			header.hide();
			areaHeight = height;
		} else {
			header.show();
		}

		// set height
		main.height(areaHeight);
		main.width(areaWidth);

		// pass new size down to area
		ext.windowManager.size(areaWidth, areaHeight);

		PlaceKeeper.restorePlace();
	}

	var settingsKey = 'app-windows';

	function getWindowSettings() {

		// (1) get default settings
		var settings = {
			windows: sofia.config.windows
		};

		// (2) replace defaults with user settings
		settings = AppSettings.getValue(settingsKey, settings);

		// (3) overwrite with QueryString when present
		var queryData = stringUtility.parseQuerystring();
		if (queryData["win1"]) {

			var tempSettings = [];

			for (var i=1; i<=4; i++) {
				var winType = queryData["win" + i.toString()],
					setting = {
						type: winType,
						data: {}
					};

				if (typeof winType != 'undefined') {
					// go though all querystring values, and anything that ends with '1' goes with this data
					for (var q in queryData) {
						var key = q.substring(0, q.length-1),
							number = q.substring(q.length-1),
							value = queryData[q];

						if (key != 'win' && number == i.toString()) {
							setting.data[key] = value;
						}
					}

					tempSettings.push(setting);
				}
			}

			// overwrite settings
			if (tempSettings.length > 0) {
				settings.windows = tempSettings;
			}

		}
		return settings;
	}

	function storeSettings() {

			// get settings from al windows
		var windowSettings = ext.windowManager.getSettings(),
			// later we'll need these
			headerSettings = {},
			settings = {
				windows: windowSettings
			};

		//console.log('storeSettings', settings);

		// store
		AppSettings.setValue(settingsKey, settings );
	}

	function handleGlobalMessage(e) {
		// give to other windows
		var windows = ext.windowManager.getWindows();

		for (var i=0, il=windows.length; i<il; i++) {
			var w = windows[i];

			if (w.id != e.id) {
		 		// pass message down
		 		w.trigger('message', e);
			}
		}

		// plugins
		for (var i=0, il=ext.plugins.length; i<il; i++) {
			var p = sofia.app.plugins[i];

			if (p.trigger) {
				// pass message down
				p.trigger('message', e);
			}
		}

	}

	ext.init = init;
	ext.handleGlobalMessage = handleGlobalMessage;

	i18n.init({fallbackLng: 'en', resStore: sofia.resources});
	setTimeout(function() {
		$('#config-language').val( i18n.lng() );
	},50);

	return ext;
};<commit_msg>find sub languages<commit_after>
var App = function() {

	// create nodes
	var	win = $(window),
		body = $(document.body),
		container = $('

').appendTo(body),
		header = $('

').appendTo(container),
		main = $('

').appendTo(container),
		footer = $('

').appendTo(container),
		ext = {};

	function init() {

		var mainMenu = new MainMenu(header);

		// create objects
		var windowManager = new WindowManager(main);

		ext.windowManager = windowManager;

		// combine nodes and objects
		win.on('resize', resize);
		win.on('orientationchange', resize);
		resize();

		var settings = getWindowSettings(),
			windowWidth = win.width();
		//console.log('settings',settings, settings.length);

		if (windowWidth < 768 && settings.windows.length >= 3) {
			settings.windows = settings.windows.slice(0,2);
		}
		if (windowWidth < 480 && settings.windows.length >= 2) {
			settings.windows = settings.windows.slice(0,1);
		}

		// create windows
		for (var i=0, il=settings.windows.length; i<il; i++) {
			var setting = settings.windows[i],
				windowType = setting.windowType;

			if (!setting.windowType) {

				switch (setting.type) {
					case 'bible':
						windowType = 'BibleWindow';
						break;
					case 'commentary':
						windowType = 'CommentaryWindow';
						break;
					case 'map':
						windowType = 'MapsWindow';
						break;
					case 'search':
						windowType = 'SearchWindow';
						break;
					case 'media':
						windowType = 'MediaWindow';
						break;
					default:
						windowType = setting.type;

				}
			}

			// create window
			//console.log('create',i, windowType, setting.data);
			windowManager.add(windowType, setting.data);
		}

		var settingsTimer = new Timer(storeSettings, 1000);

		windowManager.on('settingschange', function(e) {

			// title to show active window's position
			if (e.data && e.data.label && e.data.hasFocus) {
				document.title = e.data.labelLong;
			}

			settingsTimer.start();

		});

		var plugins = []
		ext.plugins = plugins;
		// run plugins
		for (var x in sofia.plugins) {
			plugin = new window[ sofia.plugins[x] ](this);
			plugins.push(plugin);

			if (plugin.on) {

				plugin.on('globalmessage', handleGlobalMessage);
			}
		}
	}

	function resize() {
		console.log('app resize');

		PlaceKeeper.storePlace();

		// get window size
		var width = win.width(),
			height = win.height(),

			// calculate size
			areaHeight = height - header.outerHeight() + footer.outerHeight(),
			areaWidth = width - parseInt(main.css('margin-left'), 10) - parseInt(main.css('margin-right'), 10);

		if (width < 410) {
			header.hide();
			areaHeight = height;
		} else {
			header.show();
		}

		// set height
		main.height(areaHeight);
		main.width(areaWidth);

		// pass new size down to area
		ext.windowManager.size(areaWidth, areaHeight);

		PlaceKeeper.restorePlace();
	}

	var settingsKey = 'app-windows';

	function getWindowSettings() {

		// (1) get default settings
		var settings = {
			windows: sofia.config.windows
		};

		// (2) replace defaults with user settings
		settings = AppSettings.getValue(settingsKey, settings);

		// (3) overwrite with QueryString when present
		var queryData = stringUtility.parseQuerystring();
		if (queryData["win1"]) {

			var tempSettings = [];

			for (var i=1; i<=4; i++) {
				var winType = queryData["win" + i.toString()],
					setting = {
						type: winType,
						data: {}
					};

				if (typeof winType != 'undefined') {
					// go though all querystring values, and anything that ends with '1' goes with this data
					for (var q in queryData) {
						var key = q.substring(0, q.length-1),
							number = q.substring(q.length-1),
							value = queryData[q];

						if (key != 'win' && number == i.toString()) {
							setting.data[key] = value;
						}
					}

					tempSettings.push(setting);
				}
			}

			// overwrite settings
			if (tempSettings.length > 0) {
				settings.windows = tempSettings;
			}

		}
		return settings;
	}

	function storeSettings() {

			// get settings from al windows
		var windowSettings = ext.windowManager.getSettings(),
			// later we'll need these
			headerSettings = {},
			settings = {
				windows: windowSettings
			};

		//console.log('storeSettings', settings);

		// store
		AppSettings.setValue(settingsKey, settings );
	}

	function handleGlobalMessage(e) {
		// give to other windows
		var windows = ext.windowManager.getWindows();

		for (var i=0, il=windows.length; i<il; i++) {
			var w = windows[i];

			if (w.id != e.id) {
		 		// pass message down
		 		w.trigger('message', e);
			}
		}

		// plugins
		for (var i=0, il=ext.plugins.length; i<il; i++) {
			var p = sofia.app.plugins[i];

			if (p.trigger) {
				// pass message down
				p.trigger('message', e);
			}
		}

	}

	ext.init = init;
	ext.handleGlobalMessage = handleGlobalMessage;

	i18n.init({fallbackLng: 'en', resStore: sofia.resources});
	setTimeout(function() {

		// look for match
		var option = $('#config-language option[val="' + i18n.lng() + '"]');

		if (option.length == 0) {
			option = $('#config-language option[val="' + i18n.lng().split('-')[0] + '"]');
		}

		if (option.length > 0) {
			option.prop('selected',true);
		}

		//$('#config-language').val( i18n.lng() );

	},50);

	return ext;
};<|endoftext|>


<commit_before><commit_msg>08/04/2016<commit_after><|endoftext|>


<commit_before>
engine.ImportExtension("qt.core");
engine.ImportExtension("qt.gui");

engine.IncludeFile("jsmodules/lib/class.js");

var WebCamClient = Class.extend
({
    init: function()
    {
        this.widget = new QWidget();
        this.widget.windowFlags = Qt.Tool;
        this.widget.windowTitle = "Web Camera Client";
        this.widget.setLayout(new QVBoxLayout());

        var infoLabel = new QLabel("This widget will show the current feed from a webview if one is available. \nThe web cam feed is provided by CameraInputModule and all the functionality to invoke it and show the feed is in JavaScript. \nThe c++ module caps FPS to 15 at the moment to leave time for Qts/our mainloop to run smoothly aswell.\nYou can find the example code from <install_dir>/data/jsmodules/startup/WebCamClient.js.");
        infoLabel.wordWrap = true;
        infoLabel.alignment = Qt.AlignCenter;
        infoLabel.setStyleSheet("font: Calibri; font-size: 12px;");

        this.pictureFrame = new QLabel();
        this.toggleCaptureButton = new QPushButton("Start Capturing");

        this.widget.layout().addWidget(infoLabel, 0, 0);
        this.widget.layout().addWidget(this.pictureFrame, 0, 0);
        this.widget.layout().addWidget(this.toggleCaptureButton, 0, 0);

        this.toggleCaptureButton.clicked.connect(this.toggleCapturing);

        this.visibToggleAction = ui.MainWindow().AddMenuAction("&View", "Web Camera", new QIcon("./data/ui/images/communications_iconVideo.png"));
        this.visibToggleAction.triggered.connect(this.toggleWidgetVisibility);

        camerainput.frameUpdate.connect(this.frameUpdated);
        camerainput.Capturing.connect(this.captureStateChanged);
    },

    toggleWidgetVisibility: function()
    {
        p_.widget.visible = !p_.widget.visible;
    },

    toggleCapturing: function()
    {
        if (camerainput.IsCapturing())
            camerainput.StopCapturing();
        else
            camerainput.StartCapturing();
    },

    captureStateChanged: function(capturing)
    {
        if (capturing)
            p_.toggleCaptureButton.text = "Stop Capturing";
        else
            p_.toggleCaptureButton.text = "Start Capturing";
    },

    frameUpdated: function(frame)
    {
        if (p_.widget.visible)
        {
            var pixmap = QPixmap.fromImage(frame);
            if (pixmap.isNull())
                return;
            var pixmapSize = pixmap.size();
            if (pixmapSize.width() <= 0 || pixmapSize.height() <= 0)
                return;
            if (p_.pictureFrame.size != pixmap.size)
            {
                p_.pictureFrame.setFixedSize(pixmap.size());
                p_.widget.resize(1,1);
            }
            p_.pictureFrame.setPixmap(pixmap);
        }
    }
});

if (!server.IsAboutToStart() && !framework.IsHeadless())
{
    var p_ = new WebCamClient();
}<commit_msg>CamClient: Add check that he cam input module exists before running.<commit_after>
engine.ImportExtension("qt.core");
engine.ImportExtension("qt.gui");

engine.IncludeFile("jsmodules/lib/class.js");

var WebCamClient = Class.extend
({
    init: function()
    {
        this.widget = new QWidget();
        this.widget.windowFlags = Qt.Tool;
        this.widget.windowTitle = "Web Camera Client";
        this.widget.setLayout(new QVBoxLayout());

        var infoLabel = new QLabel("This widget will show the current feed from a webview if one is available. \nThe web cam feed is provided by CameraInputModule and all the functionality to invoke it and show the feed is in JavaScript. \nThe c++ module caps FPS to 15 at the moment to leave time for Qts/our mainloop to run smoothly aswell.\nYou can find the example code from <install_dir>/data/jsmodules/startup/WebCamClient.js.");
        infoLabel.wordWrap = true;
        infoLabel.alignment = Qt.AlignCenter;
        infoLabel.setStyleSheet("font: Calibri; font-size: 12px;");

        this.pictureFrame = new QLabel();
        this.toggleCaptureButton = new QPushButton("Start Capturing");

        this.widget.layout().addWidget(infoLabel, 0, 0);
        this.widget.layout().addWidget(this.pictureFrame, 0, 0);
        this.widget.layout().addWidget(this.toggleCaptureButton, 0, 0);

        this.toggleCaptureButton.clicked.connect(this.toggleCapturing);

        this.visibToggleAction = ui.MainWindow().AddMenuAction("&View", "Web Camera", new QIcon("./data/ui/images/communications_iconVideo.png"));
        this.visibToggleAction.triggered.connect(this.toggleWidgetVisibility);

        camerainput.frameUpdate.connect(this.frameUpdated);
        camerainput.Capturing.connect(this.captureStateChanged);
    },

    toggleWidgetVisibility: function()
    {
        p_.widget.visible = !p_.widget.visible;
    },

    toggleCapturing: function()
    {
        if (camerainput.IsCapturing())
            camerainput.StopCapturing();
        else
            camerainput.StartCapturing();
    },

    captureStateChanged: function(capturing)
    {
        if (capturing)
            p_.toggleCaptureButton.text = "Stop Capturing";
        else
            p_.toggleCaptureButton.text = "Start Capturing";
    },

    frameUpdated: function(frame)
    {
        if (p_.widget.visible)
        {
            var pixmap = QPixmap.fromImage(frame);
            if (pixmap.isNull())
                return;
            var pixmapSize = pixmap.size();
            if (pixmapSize.width() <= 0 || pixmapSize.height() <= 0)
                return;
            if (p_.pictureFrame.size != pixmap.size)
            {
                p_.pictureFrame.setFixedSize(pixmap.size());
                p_.widget.resize(1,1);
            }
            p_.pictureFrame.setPixmap(pixmap);
        }
    }
});

if (!server.IsAboutToStart() && !framework.IsHeadless() && framework.GetModuleQObj("CameraInputModule") != null)
{
    var p_ = new WebCamClient();
}<|endoftext|>


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

angular.module(PKG.name + '.feature.adapters')
  .controller('AdaptersDetailLogController', function($scope, AdapterDetail, $timeout) {

    $scope.loadingNext = true;
    var logsParams = {};
    var runsParams = {};
    angular.copy(AdapterDetail.params, runsParams);
    angular.copy(AdapterDetail.logsParams, logsParams);
    logsParams.scope = $scope;

    AdapterDetail.logsApi.pollLatestRun(logsParams)
      .$promise
      .then(function (runs) {
        if (runs.length === 0) { return; }

        logsParams.runId = runs[0].runid;

        AdapterDetail.logsApi.prevLogs(angular.extend({max: 50}, logsParams))
          .$promise
          .then(function (logs) {
            $scope.logs = logs;
            $scope.loadingNext = false;
          });
      });

    $scope.loadNextLogs = function () {
      if ($scope.loadingNext) {
        return;
      }

      $scope.loadingNext = true;
      logsParams.fromOffset = ($scope.logs[$scope.logs.length-1] && $scope.logs[$scope.logs.length-1].offset);

      AdapterDetail.logsApi.nextLogs(angular.extend({max: 50}, logsParams))
        .$promise
        .then(function (res) {
          $scope.logs = _.uniq($scope.logs.concat(res));
          $scope.loadingNext = false;
        });
    };

    $scope.loadPrevLogs = function () {
      if ($scope.loadingPrev) {
        return;
      }

      $scope.loadingPrev = true;
      logsParams.fromOffset = ($scope.logs[0] && $scope.logs[0].offset);

      AdapterDetail.logsApi.prevLogs(logsParams)
        .$promise
        .then(function (res) {
          $scope.logs = _.uniq(res.concat($scope.logs));
          $scope.loadingPrev = false;

          $timeout(function() {
            var container = angular.element(document.querySelector('[infinite-scroll]'))[0];
            var logItem = angular.element(document.getElementById(logsParams.fromOffset))[0];
            container.scrollTop = logItem.offsetTop;
          });
        });
    };

  });
<commit_msg>Fixes polling repeatedly for logs (avoids refreshing logs view every 10 seconds)<commit_after>/*
 * Copyright © 2015 Cask Data, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

angular.module(PKG.name + '.feature.adapters')
  .controller('AdaptersDetailLogController', function($scope, AdapterDetail, $timeout) {

    $scope.loadingNext = true;
    var logsParams = {};
    var runsParams = {};
    angular.copy(AdapterDetail.params, runsParams);
    angular.copy(AdapterDetail.logsParams, logsParams);
    logsParams.scope = $scope;
    AdapterDetail.logsApi.pollLatestRun(logsParams)
      .$promise
      .then(function (runs) {
        if (runs.length === 0 || (runs.length && logsParams.runId === runs[0].runid)) { return; }

        logsParams.runId = runs[0].runid;

        AdapterDetail.logsApi.prevLogs(angular.extend({max: 50}, logsParams))
          .$promise
          .then(function (logs) {
            $scope.logs = logs;
            $scope.loadingNext = false;
          });
      });

    $scope.loadNextLogs = function () {
      if ($scope.loadingNext) {
        return;
      }

      $scope.loadingNext = true;
      logsParams.fromOffset = ($scope.logs[$scope.logs.length-1] && $scope.logs[$scope.logs.length-1].offset);

      AdapterDetail.logsApi.nextLogs(angular.extend({max: 50}, logsParams))
        .$promise
        .then(function (res) {
          $scope.logs = _.uniq($scope.logs.concat(res));
          $scope.loadingNext = false;

        });
    };

    $scope.loadPrevLogs = function () {
      if ($scope.loadingPrev) {
        return;
      }

      $scope.loadingPrev = true;
      logsParams.fromOffset = ($scope.logs[0] && $scope.logs[0].offset);

      AdapterDetail.logsApi.prevLogs(logsParams)
        .$promise
        .then(function (res) {
          $scope.logs = _.uniq(res.concat($scope.logs));
          $scope.loadingPrev = false;

          $timeout(function() {
            var container = angular.element(document.querySelector('[infinite-scroll]'))[0];
            var logItem = angular.element(document.getElementById(logsParams.fromOffset))[0];
            container.scrollTop = logItem.offsetTop;
          });
        });
    };

  });
<|endoftext|>


<commit_before>var color = require("color");

var colors   = require("lib/colors");
var measures = require("lib/measures");

exports.base = {
    display: "flex",
    justifyContent: "space-between",
    padding: "15px",
    width: "100%",
    height: "100%"
};

exports.buttonSelectValore = {
    marginTop: "6px",
    fontSize: "13px",
    border: "1px " + colors.greyBorder
};

exports.colVerticalPadding = {
    paddingTop: "10px",
    paddingBottom: "15px",
    paddingLeft: "0px",
    paddingRight: "0px"
};

exports.flexBase = {
    display: "flex"
};

exports.flexCentered = {
    justifyContent: "center",
    alignItems: "center"
};

exports.mainDivStyle = {
    width: "96%",
    marginLeft: "2%",
    marginTop: "1%",
    borderRadius: "3px",
    overflow: "hidden",
    padding: "10px",
    boxShadow: "2px 2px 5px " + colors.greySubTitle,
    height: measures.mainComponentHeight
};

exports.tabbedArea = {
    width: "96%",
    marginLeft: "2%",
    marginTop: "1%",
    height: "calc(100vh - 150px)",
    borderRadius: "3px",
    overflow: "hidden"
};

// TODO capire perchè serve un marginTop di -20px
exports.titlePage = {
    width: "100%",
    color: colors.titleColor,
    backgroundColor: colors.greyBackground,
    paddingLeft: "10px",
    paddingRight: "10px",
    marginTop: "-20px",
    height: "56px"
};

exports.inputLine = {
    borderTop: "0px",
    borderLeft: "0px",
    borderRight: "0px",
    borderRadius: "0px",
    WebkitBoxShadow: "none",
    boxShadow: "none"
};

exports.inputRange = {
    width: "80%",
    marginLeft: "10%",
    backgroundColor: colors.greyBackground,
    padding: "0px",
    border: "0px",
    WebkitBoxShadow: "none",
    boxShadow: "none",
    outline: "0px"
};

exports.divAlarmOpenModal = {
    height: "34px",
    width: "100%",
    borderBottom: "1px solid" + colors.greyBorder,
    cursor: "pointer"
};

exports.titleTab = {
    color: colors.titleColor,
    fontSize: "16pt"
};

exports.tabForm = {
    ".nav-tabs.nav > .active > a": {
        color: colors.titleColor,
        backgroundColor: colors.white,
        width: "200px",
        textAlign: "center"
    },
    ".nav-tabs.nav > li > a": {
        backgroundColor: colors.primary,
        color: colors.white,
        width: "200px",
        textAlign: "center"
    },
    ".tabbed-area > div": {
        height: "100%"
    },
    ".tab-content": {
        height: "90%",
        borderBottom: "solid 1px " + color(colors.darkBlack).alpha(0.1).rgbString(),
        borderRight: "solid 1px " + color(colors.darkBlack).alpha(0.1).rgbString(),
        borderLeft: "solid 1px " + color(colors.darkBlack).alpha(0.1).rgbString(),
        borderTop: "0px",
        boxShadow: "2px 2px 5px " + colors.greySubTitle
    }
};
<commit_msg>Styles file now uses the restyling colors<commit_after>var color = require("color");

var colors   = require("lib/colors_restyling");
var measures = require("lib/measures");

exports.base = {
    display: "flex",
    justifyContent: "space-between",
    padding: "15px",
    width: "100%",
    height: "100%"
};

exports.buttonSelectValore = {
    marginTop: "6px",
    fontSize: "13px",
    border: "1px " + colors.greyBorder
};

exports.colVerticalPadding = {
    paddingTop: "10px",
    paddingBottom: "15px",
    paddingLeft: "0px",
    paddingRight: "0px"
};

exports.flexBase = {
    display: "flex"
};

exports.flexCentered = {
    justifyContent: "center",
    alignItems: "center"
};

exports.mainDivStyle = {
    width: "96%",
    marginLeft: "2%",
    marginTop: "1%",
    borderRadius: "3px",
    overflow: "hidden",
    padding: "10px",
    boxShadow: "2px 2px 5px " + colors.greySubTitle,
    height: measures.mainComponentHeight
};

exports.tabbedArea = {
    width: "96%",
    marginLeft: "2%",
    marginTop: "1%",
    height: "calc(100vh - 150px)",
    borderRadius: "3px",
    overflow: "hidden"
};

// TODO capire perchè serve un marginTop di -20px
exports.titlePage = {
    width: "100%",
    color: colors.titleColor,
    backgroundColor: colors.greyBackground,
    paddingLeft: "10px",
    paddingRight: "10px",
    marginTop: "-20px",
    height: "56px"
};

exports.inputLine = {
    borderTop: "0px",
    borderLeft: "0px",
    borderRight: "0px",
    borderRadius: "0px",
    WebkitBoxShadow: "none",
    boxShadow: "none"
};

exports.inputRange = {
    width: "80%",
    marginLeft: "10%",
    backgroundColor: colors.greyBackground,
    padding: "0px",
    border: "0px",
    WebkitBoxShadow: "none",
    boxShadow: "none",
    outline: "0px"
};

exports.divAlarmOpenModal = {
    height: "34px",
    width: "100%",
    borderBottom: "1px solid" + colors.greyBorder,
    cursor: "pointer"
};

exports.titleTab = {
    color: colors.titleColor,
    fontSize: "16pt"
};

exports.tabForm = {
    ".nav-tabs.nav > .active > a": {
        color: colors.titleColor,
        backgroundColor: colors.white,
        width: "200px",
        textAlign: "center"
    },
    ".nav-tabs.nav > li > a": {
        backgroundColor: colors.primary,
        color: colors.white,
        width: "200px",
        textAlign: "center"
    },
    ".tabbed-area > div": {
        height: "100%"
    },
    ".tab-content": {
        height: "90%",
        borderBottom: "solid 1px " + color(colors.darkBlack).alpha(0.1).rgbString(),
        borderRight: "solid 1px " + color(colors.darkBlack).alpha(0.1).rgbString(),
        borderLeft: "solid 1px " + color(colors.darkBlack).alpha(0.1).rgbString(),
        borderTop: "0px",
        boxShadow: "2px 2px 5px " + colors.greySubTitle
    }
};
<|endoftext|>


<commit_before>function GetFile(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);

    xhr.onload = () => {
        if (xhr.readyState === xhr.DONE) {
            if (xhr.status === 200) {
                callback(xhr.responseText);
            }
        }
    };

    xhr.send(null);
}

var onLoadCount = 0;
var totalOnLoad = 0;
function LoadScript(scriptUrl, callback) {
    totalOnLoad++;
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.onload = () => {
        onLoadCount++;
        if(onLoadCount >= totalOnLoad)
            callback();
    };
    script.src = scriptUrl;
    document.body.appendChild(script);
}

function LoadCSS(cssUrl) {
    var css = document.createElement("link");
    css.rel = "stylesheet";
    css.href = cssUrl;
    document.body.appendChild(css);
}

function AddDependencies(scriptFolder, callback) {
    LoadScript("https://rawgit.com/Microsoft/TypeScript/master/lib/typescriptServices.js", callback);
    LoadScript("https://unpkg.com/j-templates/jTemplates.js", callback);
    LoadScript(scriptFolder + "codemirror.js", callback);
    LoadScript(scriptFolder + "javascript.js", callback);
    LoadCSS(scriptFolder + "/styles/codemirror.css");
}

function ExecuteTs(container, code) {
    var iframe = container.querySelector("iframe");
    if(iframe)
        container.removeChild(iframe);

    iframe = document.createElement("iframe");
    iframe.className = "output";
    iframe.srcDoc = '<!DOCTYPE html>';
    container.appendChild(iframe);
    var jTempScript = iframe.contentDocument.createElement("script");
    jTempScript.type = "text/javascript";
    jTempScript.src = "https://unpkg.com/j-templates/jTemplates.js";
    jTempScript.onload = () => {
        var js = ts.transpile(code, { target: "es6" });
        js = js.replace(/^import.*$/gm, "");
        var script = iframe.contentDocument.createElement("script");
        script.type = "text/javascript";
        script.innerHTML = js;
        iframe.contentDocument.head.appendChild(script);
    };
    iframe.contentDocument.head.appendChild(jTempScript);
}

var changeTimeout = null;
function CreateCodeMirror(container, initValue) {
    var cm = CodeMirror(container, {
        value: initValue,
        lineNumbers: true
    });
    cm.on("change", () => {
        clearTimeout(changeTimeout);
        changeTimeout = setTimeout(() => {
            ExecuteTs(container, cm.getDoc().getValue());
        }, 4000);
    });
}

function CreateSample(sample) {
    var container = document.getElementById(sample);
    container.innerHTML = "Loading...";
    var curScriptUrl = document.querySelector("[src$='docHelpers.js'").src;
    var curScriptFolder = curScriptUrl.replace(/docHelpers\.js$/, "");
    AddDependencies(curScriptFolder, () => {
        var samplesFolder = curScriptFolder + "../samples/";
        var sampleUrl = samplesFolder + sample + ".ts";

        GetFile(sampleUrl, (text) => {
            container.innerHTML = "";

            var h2 = document.createElement("h2");
            h2.innerText = "Code";
            container.appendChild(h2);

            CreateCodeMirror(container, text);

            h2 = document.createElement("h2");
            h2.innerText = "Output";
            container.appendChild(h2);

            ExecuteTs(container, text);
        });
    });
}
<commit_msg>added styles.css<commit_after>function GetFile(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);

    xhr.onload = () => {
        if (xhr.readyState === xhr.DONE) {
            if (xhr.status === 200) {
                callback(xhr.responseText);
            }
        }
    };

    xhr.send(null);
}

var onLoadCount = 0;
var totalOnLoad = 0;
function LoadScript(scriptUrl, callback) {
    totalOnLoad++;
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.onload = () => {
        onLoadCount++;
        if(onLoadCount >= totalOnLoad)
            callback();
    };
    script.src = scriptUrl;
    document.body.appendChild(script);
}

function LoadCSS(cssUrl) {
    var css = document.createElement("link");
    css.rel = "stylesheet";
    css.href = cssUrl;
    document.body.appendChild(css);
}

function AddDependencies(scriptFolder, callback) {
    LoadScript("https://rawgit.com/Microsoft/TypeScript/master/lib/typescriptServices.js", callback);
    LoadScript("https://unpkg.com/j-templates/jTemplates.js", callback);
    LoadScript(scriptFolder + "codemirror.js", callback);
    LoadScript(scriptFolder + "javascript.js", callback);
    LoadCSS(scriptFolder + "/styles/codemirror.css");
    LoadCSS(scriptFolder + "/styles/styles.css");
}

function ExecuteTs(container, code) {
    var iframe = container.querySelector("iframe");
    if(iframe)
        container.removeChild(iframe);

    iframe = document.createElement("iframe");
    iframe.className = "output";
    iframe.srcDoc = '<!DOCTYPE html>';
    container.appendChild(iframe);
    var jTempScript = iframe.contentDocument.createElement("script");
    jTempScript.type = "text/javascript";
    jTempScript.src = "https://unpkg.com/j-templates/jTemplates.js";
    jTempScript.onload = () => {
        var js = ts.transpile(code, { target: "es6" });
        js = js.replace(/^import.*$/gm, "");
        var script = iframe.contentDocument.createElement("script");
        script.type = "text/javascript";
        script.innerHTML = js;
        iframe.contentDocument.head.appendChild(script);
    };
    iframe.contentDocument.head.appendChild(jTempScript);
}

var changeTimeout = null;
function CreateCodeMirror(container, initValue) {
    var cm = CodeMirror(container, {
        value: initValue,
        lineNumbers: true
    });
    cm.on("change", () => {
        clearTimeout(changeTimeout);
        changeTimeout = setTimeout(() => {
            ExecuteTs(container, cm.getDoc().getValue());
        }, 4000);
    });
}

function CreateSample(sample) {
    var container = document.getElementById(sample);
    container.innerHTML = "Loading...";
    var curScriptUrl = document.querySelector("[src$='docHelpers.js'").src;
    var curScriptFolder = curScriptUrl.replace(/docHelpers\.js$/, "");
    AddDependencies(curScriptFolder, () => {
        var samplesFolder = curScriptFolder + "../samples/";
        var sampleUrl = samplesFolder + sample + ".ts";

        GetFile(sampleUrl, (text) => {
            container.innerHTML = "";

            var h2 = document.createElement("h2");
            h2.innerText = "Code";
            container.appendChild(h2);

            CreateCodeMirror(container, text);

            h2 = document.createElement("h2");
            h2.innerText = "Output";
            container.appendChild(h2);

            ExecuteTs(container, text);
        });
    });
}
<|endoftext|>


<commit_before>export default [
  {
    name: 'Razvan Stoenescu',
    role: 'Creator, Lead Dev & Architect',
    avatar: 'razvan_stoenescu.jpeg',
    email: 'razvan@quasar.dev',
    twitter: 'quasarframework',
    github: 'rstoenescu',
    desc: 'Architecture and development of Quasar on all fronts.'
  },

  {
    name: 'Dan Popescu',
    role: 'Senior Core Developer',
    avatar: 'dan_popescu.jpg',
    email: 'dan@quasar.dev',
    github: 'pdanpdan',
    desc: 'Focuses on Quasar UI components, directives and plugins.'
  },

  {
    name: 'Denjell Thompson-Yvetot',
    role: 'Senior Dev & Security Engineer',
    avatar: 'daniel_thompson-yvetot.jpg',
    email: 'denjell@quasar.dev',
    twitter: 'nothingismagick',
    github: 'nothingismagick',
    desc: 'Tooling and rigging app extensions, product development, Quasar Radio Show, community manager. Also writes articles.'
  },

  {
    name: 'Jeff Galbraith',
    role: 'Senior Developer',
    avatar: 'jeff_galbraith.jpg',
    email: 'jeff@quasar.dev',
    twitter: 'jgalbraith64',
    github: 'hawkeye64',
    desc: 'UI app extensions, the Quasar Radio Show and community outreach.'
  },

  {
    name: 'Lucas Nogueira',
    role: 'Senior Developer',
    avatar: 'lucas_nogueira.jpg',
    github: 'lucasfernog',
    desc: 'Quasar CLI development, Webview Quasar mode.'
  },

  {
    name: 'Allan Gaunt',
    role: 'Senior Developer',
    avatar: 'allan_gaunt.png',
    github: 'webnoob',
    desc: 'Web products and security research.'
  },

  {
    name: 'Scott Molinari',
    role: 'DevOps / Senior Developer',
    avatar: 'scott_molinari.jpg',
    github: 'smolinari',
    desc: 'Helps with docs, bug reports, external systems, writes articles and offers community support.'
  },

  {
    name: 'Tobias Mesquita',
    role: 'Senior Developer',
    avatar: 'tobias_mesquita.jpg',
    github: 'TobyMosque',
    desc: 'Help desk'
  },

  {
    name: 'Kerry Huguet',
    role: 'Senior Developer',
    avatar: 'kerry_huguet.jpeg',
    github: 'outofmemoryagain',
    desc: 'Typescript support'
  },

  {
    name: 'Noah Klayman',
    role: 'DevOps / Community Staff',
    avatar: 'noah_klayman.jpeg',
    github: 'nklayman',
    desc: 'GraphQL, App Extensions'
  },

  {
    name: 'Aldrin Marquez',
    role: 'Community Staff',
    avatar: 'aldrin_marquez.jpg',
    github: 'metalsadman',
    desc: 'Help desk'
  },

  {
    name: 'Matyáš Racek',
    role: 'Community Staff',
    avatar: 'matyas_panstromek.jpeg',
    github: 'panstromek',
    desc: 'Help desk'
  },

  {
    name: 'James Harrington',
    role: 'Community Staff',
    avatar: 'james_harrington.jpeg',
    github: 'codenamezjames',
    desc: 'Help desk'
  },

  {
    name: 'Ross Ball',
    role: 'Designer / Community Staff',
    avatar: 'ross_ball.jpeg',
    github: 'rossity',
    desc: 'Quasar Themes'
  },

  {
    name: 'James Gilchrist',
    role: 'Community Staff',
    avatar: 'james_gilchrist.png',
    github: 'jpgilchrist',
    desc: 'Help desk'
  },

  {
    name: 'Ben Coughenour',
    role: 'Community Staff',
    avatar: 'ben_coughenour.jpg',
    github: 'sskwrl',
    desc: 'Help desk'
  },

  {
    name: 'Heitor Ribeiro',
    role: 'Community Staff',
    avatar: 'heitor_ribeiro.jpg',
    github: 'bloodf',
    desc: 'Writes articles and offers community support.'
  }
]
<commit_msg>feat(staff) Add newest members to the team page<commit_after>export default [
  {
    name: 'Razvan Stoenescu',
    role: 'Creator, Lead Dev & Architect',
    avatar: 'razvan_stoenescu.jpeg',
    email: 'razvan@quasar.dev',
    twitter: 'quasarframework',
    github: 'rstoenescu',
    desc: 'Architecture and development of Quasar on all fronts.'
  },

  {
    name: 'Dan Popescu',
    role: 'Senior Core Developer',
    avatar: 'dan_popescu.jpg',
    email: 'dan@quasar.dev',
    github: 'pdanpdan',
    desc: 'Focuses on Quasar UI components, directives and plugins.'
  },

  {
    name: 'Denjell Thompson-Yvetot',
    role: 'Senior Dev & Security Engineer',
    avatar: 'daniel_thompson-yvetot.jpg',
    email: 'denjell@quasar.dev',
    twitter: 'nothingismagick',
    github: 'nothingismagick',
    desc: 'Tooling and rigging app extensions, product development, Quasar Radio Show, community manager. Also writes articles.'
  },

  {
    name: 'Jeff Galbraith',
    role: 'Senior Developer',
    avatar: 'jeff_galbraith.jpg',
    email: 'jeff@quasar.dev',
    twitter: 'jgalbraith64',
    github: 'hawkeye64',
    desc: 'UI app extensions, the Quasar Radio Show and community outreach.'
  },

  {
    name: 'Lucas Nogueira',
    role: 'Senior Developer',
    avatar: 'lucas_nogueira.jpg',
    github: 'lucasfernog',
    desc: 'Quasar CLI development, Webview Quasar mode.'
  },

  {
    name: 'Allan Gaunt',
    role: 'Senior Developer',
    avatar: 'allan_gaunt.png',
    github: 'webnoob',
    desc: 'Web products and security research.'
  },

  {
    name: 'Scott Molinari',
    role: 'DevOps / Senior Developer',
    avatar: 'scott_molinari.jpg',
    github: 'smolinari',
    desc: 'Helps with docs, bug reports, external systems, writes articles and offers community support.'
  },

  {
    name: 'Tobias Mesquita',
    role: 'Senior Developer',
    avatar: 'tobias_mesquita.jpg',
    github: 'TobyMosque',
    desc: 'Help desk'
  },

  {
    name: 'Kerry Huguet',
    role: 'Senior Developer',
    avatar: 'kerry_huguet.jpeg',
    github: 'outofmemoryagain',
    desc: 'Typescript support'
  },

  {
    name: 'Noah Klayman',
    role: 'DevOps / Community Staff',
    avatar: 'noah_klayman.jpeg',
    github: 'nklayman',
    desc: 'GraphQL, App Extensions'
  },

  {
    name: 'Aldrin Marquez',
    role: 'Community Staff',
    avatar: 'aldrin_marquez.jpg',
    github: 'metalsadman',
    desc: 'Help desk'
  },

  {
    name: 'Matyáš Racek',
    role: 'Community Staff',
    avatar: 'matyas_panstromek.jpeg',
    github: 'panstromek',
    desc: 'Help desk'
  },

  {
    name: 'James Harrington',
    role: 'Community Staff',
    avatar: 'james_harrington.jpeg',
    github: 'codenamezjames',
    desc: 'Help desk'
  },

  {
    name: 'Ross Ball',
    role: 'Designer / Community Staff',
    avatar: 'ross_ball.jpeg',
    github: 'rossity',
    desc: 'Quasar Themes'
  },

  {
    name: 'James Gilchrist',
    role: 'Community Staff',
    avatar: 'james_gilchrist.png',
    github: 'jpgilchrist',
    desc: 'Help desk'
  },

  {
    name: 'Ben Coughenour',
    role: 'Community Staff',
    avatar: 'ben_coughenour.jpg',
    github: 'sskwrl',
    desc: 'Help desk'
  },

  {
    name: 'Heitor Ribeiro',
    role: 'Community Staff',
    avatar: 'heitor_ribeiro.jpg',
    github: 'bloodf',
    desc: 'Writes articles and offers community support.'
  },

    {
    name: 'David Watson',
    role: 'Community Staff',
    avatar: 'david_watson.jpg',
    github: 'realtimeappsolutions',
    desc: 'Marketing and PR.'
  },

  {
    name: 'Stanislav Valasek',
    role: 'Community Staff',
    avatar: 'stanislav_valasek.jpg',
    github: 'valasek',
    desc: 'Marketing, Open Source Compliance, Community experience.'
  }
]
<|endoftext|>