<commit_before>Game.Crates = {};

Game.Crates = {
  init: function() {
    this.colors = Game.Crates.colors.randomize();
    this.crates = Game.Crates.types.randomize();
  },
  random: function(limit) {
    limit = limit || this.crates.length - 1;
    return Math.floor(ROT.RNG.getUniform() * limit);
  },
  getTile: function(index) {
    if (this.crates[index].known) {
      return this.crates[index].tile;
    } else {
      return "crate_unknown";
    }
  },
  getColor: function(index) {
    return this.colors[index];
  },
  identify: function(index) {
    this.crates[index].known = true;
  },
  doAction: function(index, x, y, map) {
    this.crates[index].action.call(null, x, y, map, index);
  }
};

Game.Crates.Group = {
  init: function() {
    this.crateList = [];
    return this;
  },
  add: function(crate) {
    this.crateList.push(crate)
  },
  remove: function(crateToRemove) {
    this.crateList = this.crateList.filter(function(crate) {
      return crate !== crateToRemove
    });
  },
  act: function() {
    this._sortCrates();
    return this.crateList.reduce(function(prevPromise, crate) {
      return prevPromise.then(function() {
        return crate.act();
      });
    }, Promise.resolve());
  },
  _sortCrates() {
    this.crateList = this.crateList.sort(function(crateA, crateB) {
      return (crateB.y * 100 + crateB.x) - (crateA.y * 100 + crateA.x);
    });
  }
}

Game.Crates.colors = [
0xC2C3C7,
0xFFA300,
0x29ADFF,
0xFF004D,
0x00E756,
];

Game.Crates.actions = {};

Game.Crates.actions.createDecoy = function(x, y, map, crateId) {
  Game.Sound.play('decoy_hello');
  var decoy = Object.create(Game.Entity).init(Game.Entity.templates.decoy, x, y);
  map.addEntity(decoy);
  map.targets.push(decoy);
};

Game.Crates.actions.createDigCrate = function(x, y, map, crateId) {
  var digCrate = Object.create(Game.Entity).init(Game.Entity.templates.digCrate, x, y);
  digCrate.color = Game.Crates.getColor(crateId);
  map.addEntity(digCrate);
  digCrate.falling = 2;
  digCrate.act();
};

Game.Crates.actions.createEnemy = function(x, y, map, crateId) {
  Game.Sound.play('skull_hello');
  var enemy = Object.create(Game.Entity).init(Game.Entity.templates.skullbot, x, y);
  map.addEntity(enemy);
};

Game.Crates.actions.explode = function(x, y, map, crateId) {
  var blastZone = [{x: x - 1, y: y - 1}, {x: x, y: y - 1}, {x: x + 1, y: y - 1},
                   {x: x - 1, y: y},     {x: x, y: y},     {x: x + 1, y: y},
                   {x: x - 1, y: y + 1}, {x: x, y: y + 1}, {x: x + 1, y: y + 1}];
  function blastCell(pos) {
    Game.Screen.addEffect("boom", pos, 0xffffff, 300);
    var cell = map.grid.getCell(pos.x, pos.y);
    if (cell) {
      var target = map.entityAt(cell.x, cell.y);
      if (target) {
        target.kill({tile:'explosion', niceToBots: false});
      }
      cell.blasted = true;
      cell.neighbors().forEach(function(neighbor){ //link to blasted neigbors
        if (neighbor.blasted && !cell.linked(neighbor)) {
          cell.link(neighbor);
        }
      });
    }
  }
  function cleanUp(pos) {
    var cell = map.grid.getCell(pos.x, pos.y);
    if (cell) {
      cell.blasted = undefined;
    }
  }

  Game.Sound.play('explode_1');
  blastZone.forEach(blastCell);
  Game.display.render(Game.stage);
  blastZone.forEach(cleanUp);
};

Game.Crates.actions.laserBlast = function(x, y, map, crateId) {
  var blastZone = [                   {x: x, y: y - 2},
                                      {x: x, y: y - 1},
  {x: x - 2, y: y}, {x: x - 1, y: y}, {x: x, y: y}, {x: x + 1, y: y}, {x: x + 2, y: y},
                                      {x: x, y: y + 1},
                                      {x: x, y: y + 2}];
  var zapcolor = 0xffffff;
  var zapduration = 300;
  Game.Screen.addEffect("laser_top", blastZone[0], zapcolor, zapduration);
  Game.Screen.addEffect("laser_vertical", blastZone[1], zapcolor, zapduration);
  Game.Screen.addEffect("laser_left", blastZone[2], zapcolor, zapduration);
  Game.Screen.addEffect("laser_horizontal", blastZone[3], zapcolor, zapduration);
  Game.Screen.addEffect("laser_center", blastZone[4], zapcolor, zapduration);
  Game.Screen.addEffect("laser_horizontal", blastZone[5], zapcolor, zapduration);
  Game.Screen.addEffect("laser_right", blastZone[6], zapcolor, zapduration);
  Game.Screen.addEffect("laser_vertical", blastZone[7], zapcolor, zapduration);
  Game.Screen.addEffect("laser_bottom", blastZone[8], zapcolor, zapduration);
  function blastCell(pos) {
    var cell = map.grid.getCell(pos.x, pos.y);
    if (cell) {
      var target = map.entityAt(cell.x, cell.y);
      if (target) {
        target.kill({tile:'explosion', niceToBots: false});
      }
      cell.blasted = true;
      cell.neighbors().forEach(function(neighbor){ //link to blasted neigbors
        if (neighbor.blasted && !cell.linked(neighbor)) {
          cell.link(neighbor);
        }
      });
    }
  }
  function cleanUp(pos) {
    var cell = map.grid.getCell(pos.x, pos.y);
    if (cell) {
      cell.blasted = undefined;
    }
  }

  Game.Sound.play('explode_2');
  blastZone.forEach(blastCell);
  Game.display.render(Game.stage);
  blastZone.forEach(cleanUp);
};

Game.Crates.types = [
  {
    name: "decoy",
    known: false,
    tile: "crate_decoy",
    action: Game.Crates.actions.createDecoy
  },{
    name: "exploding",
    known: false,
    tile: "crate_blast",
    action: Game.Crates.actions.explode
  },{
    name: "enemy",
    known: false,
    tile: "crate_enemy",
    action: Game.Crates.actions.createEnemy
  },{
    name: "laser",
    known: false,
    tile: "crate_cross",
    action: Game.Crates.actions.laserBlast
  },{
    name: "dig",
    known: false,
    tile: "crate_fall",
    action: Game.Crates.actions.createDigCrate
  }
];
<commit_msg>Don't get stuck in an infinite loop when all moving things are dead<commit_after>Game.Crates = {};

Game.Crates = {
  init: function() {
    this.colors = Game.Crates.colors.randomize();
    this.crates = Game.Crates.types.randomize();
  },
  random: function(limit) {
    limit = limit || this.crates.length - 1;
    return Math.floor(ROT.RNG.getUniform() * limit);
  },
  getTile: function(index) {
    if (this.crates[index].known) {
      return this.crates[index].tile;
    } else {
      return "crate_unknown";
    }
  },
  getColor: function(index) {
    return this.colors[index];
  },
  identify: function(index) {
    this.crates[index].known = true;
  },
  doAction: function(index, x, y, map) {
    this.crates[index].action.call(null, x, y, map, index);
  }
};

Game.Crates.Group = {
  init: function() {
    this.crateList = [];
    return this;
  },
  add: function(crate) {
    this.crateList.push(crate)
  },
  remove: function(crateToRemove) {
    this.crateList = this.crateList.filter(function(crate) {
      return crate !== crateToRemove
    });
  },
  act: function() {
    this.sanityCheck();
    this._sortCrates();
    return this.crateList.reduce(function(prevPromise, crate) {
      return prevPromise.then(function() {
        return crate.act();
      });
    }, Promise.resolve());
  },
  _sortCrates: function() {
    this.crateList = this.crateList.sort(function(crateA, crateB) {
      return (crateB.y * 100 + crateB.x) - (crateA.y * 100 + crateA.x);
    });
  },
  sanityCheck: function() {
    var entitiesInMotion = Object.keys(Game.currentScreen.map.entities)
      .map(function(key) {
        return Game.currentScreen.map.entities[key]
      })
      .filter(function(entity) {
        return ((entity.crateType !== undefined && entity.falling > 0) ||
          entity.isPlayer ||
          entity.canKill
        );
      });
    if (entitiesInMotion.length === 0) {
      Game.currentScreen.map.engine.lock();
    }
  }
}

Game.Crates.colors = [
0xC2C3C7,
0xFFA300,
0x29ADFF,
0xFF004D,
0x00E756,
];

Game.Crates.actions = {};

Game.Crates.actions.createDecoy = function(x, y, map, crateId) {
  Game.Sound.play('decoy_hello');
  var decoy = Object.create(Game.Entity).init(Game.Entity.templates.decoy, x, y);
  map.addEntity(decoy);
  map.targets.push(decoy);
};

Game.Crates.actions.createDigCrate = function(x, y, map, crateId) {
  var digCrate = Object.create(Game.Entity).init(Game.Entity.templates.digCrate, x, y);
  digCrate.color = Game.Crates.getColor(crateId);
  map.addEntity(digCrate);
  digCrate.falling = 2;
  digCrate.act();
};

Game.Crates.actions.createEnemy = function(x, y, map, crateId) {
  Game.Sound.play('skull_hello');
  var enemy = Object.create(Game.Entity).init(Game.Entity.templates.skullbot, x, y);
  map.addEntity(enemy);
};

Game.Crates.actions.explode = function(x, y, map, crateId) {
  var blastZone = [{x: x - 1, y: y - 1}, {x: x, y: y - 1}, {x: x + 1, y: y - 1},
                   {x: x - 1, y: y},     {x: x, y: y},     {x: x + 1, y: y},
                   {x: x - 1, y: y + 1}, {x: x, y: y + 1}, {x: x + 1, y: y + 1}];
  function blastCell(pos) {
    Game.Screen.addEffect("boom", pos, 0xffffff, 300);
    var cell = map.grid.getCell(pos.x, pos.y);
    if (cell) {
      var target = map.entityAt(cell.x, cell.y);
      if (target) {
        target.kill({tile:'explosion', niceToBots: false});
      }
      cell.blasted = true;
      cell.neighbors().forEach(function(neighbor){ //link to blasted neigbors
        if (neighbor.blasted && !cell.linked(neighbor)) {
          cell.link(neighbor);
        }
      });
    }
  }
  function cleanUp(pos) {
    var cell = map.grid.getCell(pos.x, pos.y);
    if (cell) {
      cell.blasted = undefined;
    }
  }

  Game.Sound.play('explode_1');
  blastZone.forEach(blastCell);
  Game.display.render(Game.stage);
  blastZone.forEach(cleanUp);
};

Game.Crates.actions.laserBlast = function(x, y, map, crateId) {
  var blastZone = [                   {x: x, y: y - 2},
                                      {x: x, y: y - 1},
  {x: x - 2, y: y}, {x: x - 1, y: y}, {x: x, y: y}, {x: x + 1, y: y}, {x: x + 2, y: y},
                                      {x: x, y: y + 1},
                                      {x: x, y: y + 2}];
  var zapcolor = 0xffffff;
  var zapduration = 300;
  Game.Screen.addEffect("laser_top", blastZone[0], zapcolor, zapduration);
  Game.Screen.addEffect("laser_vertical", blastZone[1], zapcolor, zapduration);
  Game.Screen.addEffect("laser_left", blastZone[2], zapcolor, zapduration);
  Game.Screen.addEffect("laser_horizontal", blastZone[3], zapcolor, zapduration);
  Game.Screen.addEffect("laser_center", blastZone[4], zapcolor, zapduration);
  Game.Screen.addEffect("laser_horizontal", blastZone[5], zapcolor, zapduration);
  Game.Screen.addEffect("laser_right", blastZone[6], zapcolor, zapduration);
  Game.Screen.addEffect("laser_vertical", blastZone[7], zapcolor, zapduration);
  Game.Screen.addEffect("laser_bottom", blastZone[8], zapcolor, zapduration);
  function blastCell(pos) {
    var cell = map.grid.getCell(pos.x, pos.y);
    if (cell) {
      var target = map.entityAt(cell.x, cell.y);
      if (target) {
        target.kill({tile:'explosion', niceToBots: false});
      }
      cell.blasted = true;
      cell.neighbors().forEach(function(neighbor){ //link to blasted neigbors
        if (neighbor.blasted && !cell.linked(neighbor)) {
          cell.link(neighbor);
        }
      });
    }
  }
  function cleanUp(pos) {
    var cell = map.grid.getCell(pos.x, pos.y);
    if (cell) {
      cell.blasted = undefined;
    }
  }

  Game.Sound.play('explode_2');
  blastZone.forEach(blastCell);
  Game.display.render(Game.stage);
  blastZone.forEach(cleanUp);
};

Game.Crates.types = [
  {
    name: "decoy",
    known: false,
    tile: "crate_decoy",
    action: Game.Crates.actions.createDecoy
  },{
    name: "exploding",
    known: false,
    tile: "crate_blast",
    action: Game.Crates.actions.explode
  },{
    name: "enemy",
    known: false,
    tile: "crate_enemy",
    action: Game.Crates.actions.createEnemy
  },{
    name: "laser",
    known: false,
    tile: "crate_cross",
    action: Game.Crates.actions.laserBlast
  },{
    name: "dig",
    known: false,
    tile: "crate_fall",
    action: Game.Crates.actions.createDigCrate
  }
];
<|endoftext|>


<commit_before>load('steal/rhino/steal.js')

steal.File("../jmvcdownload").removeDir()
steal.File("jmvcdownload.zip").remove()
steal.File("../jmvcdownload").mkdir()

var ignore = [".git", ".gitignore", "dist"]

steal.File("../jmvcdownload/documentjs").mkdir()
steal.File("documentjs").copyTo("../jmvcdownload/documentjs/", ignore)

steal.File("../jmvcdownload/funcunit").mkdir()
steal.File("funcunit").copyTo("../jmvcdownload/funcunit/", ignore)

steal.File("../jmvcdownload/jquery").mkdir()
steal.File("jquery").copyTo("../jmvcdownload/jquery/", ignore)

steal.File("../jmvcdownload/steal").mkdir()
steal.File("steal").copyTo("../jmvcdownload/steal/", ignore)

steal.File("js").copyTo("../jmvcdownload/js", [])
steal.File("js.bat").copyTo("../jmvcdownload/js.bat", [])

steal.File("../jmvcdownload").zipDir("javascriptmvc-3.0.0.zip", "..\\jmvcdownload\\")<commit_msg>build keeps file permissions<commit_after>load('steal/rhino/steal.js')

steal.File("../jmvcdownload").removeDir()
steal.File("jmvcdownload.zip").remove()
steal.File("../jmvcdownload").mkdir()

var ignore = [".git", ".gitignore", "dist"]

steal.File("../jmvcdownload/documentjs").mkdir()
steal.File("documentjs").copyTo("../jmvcdownload/documentjs/", ignore)

steal.File("../jmvcdownload/funcunit").mkdir()
steal.File("funcunit").copyTo("../jmvcdownload/funcunit/", ignore)

steal.File("../jmvcdownload/jquery").mkdir()
steal.File("jquery").copyTo("../jmvcdownload/jquery/", ignore)

steal.File("../jmvcdownload/steal").mkdir()
steal.File("steal").copyTo("../jmvcdownload/steal/", ignore)

steal.File("js").copyTo("../jmvcdownload/js", [])
steal.File("js.bat").copyTo("../jmvcdownload/js.bat", [])

//steal.File("../jmvcdownload").zipDir("javascriptmvc-3.0.0.zip", "../jmvcdownload/")
runCommand("sh", "-c", 'zip -r javascriptmvc-3.0.0.zip documentjs jquery funcunit steal js js.bat -x "*/.git/*"');
<|endoftext|>


<commit_before>// Copyright 2014 CloudFounders NV
//
// 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.
/*global define, window, document, location */
define(['jquery', 'jqp/pnotify'], function($) {
    "use strict";
    function getTimestamp() {
        return new Date().getTime();
    }
    function buildString(value, times) {
        var i, returnvalue = '';
        for (i = 0; i < times; i += 1) {
            returnvalue += value.toString();
        }
        return returnvalue;
    }
    function deg2rad(deg) {
		return deg * Math.PI / 180;
	}
    function setDecimals(value, decimals) {
        decimals = decimals || 2;
        var parts = [];
        if (isNaN(value)) {
            parts = ["0"];
        } else {
            parts = value.toString().split('.');
        }

        if (decimals <= 0) {
            return parts[0];
        }

        if (parts.length === 1) {
            parts.push(buildString('0', decimals));
        }
        while (parts[1].length < decimals) {
            parts[1] = parts[1] + '0';
        }
        return parts[0] + '.' + parts[1];
    }
    function round(value, decimals) {
        decimals = decimals || 0;
        if (decimals === 0) {
            return Math.round(value);
        }
        var factor = Math.pow(10, decimals);
        return Math.round(value * factor) / factor;
    }
    function ceil(value, decimals) {
        decimals = decimals || 0;
        if (decimals === 0) {
            return Math.ceil(value);
        }
        var factor = Math.pow(10, decimals);
        return Math.ceil(value * factor) / factor;
    }
    function formatBytes(value) {
        var units, counter;
        units = ['b', 'kib', 'mib', 'gib', 'tib'];
        counter = 0;
        while (value >= 1000) {
            value = value / 1024;
            counter += 1;
        }
        return setDecimals(round(value, 2), 2) + ' ' + $.t('ovs:generic.' + units[counter]);
    }
    function formatSpeed(value) {
        var units, counter;
        units = ['b', 'kib', 'mib', 'gib', 'tib'];
        counter = 0;
        while (value >= 1000) {
            value = value / 1024;
            counter += 1;
        }
        return setDecimals(round(value, 2), 2) + ' ' + $.t('ovs:generic.' + units[counter] + 's');
    }
    function formatRatio(value) {
        return setDecimals(round(value, 2), 2) + ' %';
    }
    function formatShort(value) {
        var units, counter, returnValue;
        units = ['k', 'm', 'g', 't'];
        counter = 0;
        while (value >= 1000) {
            value = value / 1000;
            counter += 1;
        }
        returnValue = setDecimals(round(value, 2), 2);
        if (counter > 0) {
            returnValue += ' ' + $.t('ovs:generic.' + units[counter - 1]);
        }
        return returnValue;
    }
    function formatNumber(value) {
        if (value !== undefined) {
            value = round(value).toString();
            var regex = /(\d+)(\d{3})/;
            while (regex.test(value)) {
                value = value.replace(regex, '$1' + $.t('ovs:generic.thousandseparator') + '$2');
            }
            return value;
        }
        return undefined;
    }
    function formatPercentage(value) {
        value = Math.round(value * 10000) / 100;
        return formatNumber(value) + ' %';
    }
    function padRight(value, character, length) {
        while (value.length < length) {
            value += character;
        }
        return value;
    }
    function padLeft(value, character, length) {
        while (value.length < length) {
            value = character + value;
        }
        return value;
    }
    function tryGet(object, key, fallback) {
        if (object !== undefined && object.hasOwnProperty(key)) {
            return object[key];
        }
        return fallback;
    }
    function trySet(observable, object, key, formatFunction) {
        if (object !== undefined && object.hasOwnProperty(key)) {
            if (formatFunction !== undefined && formatFunction.call) {
                observable(formatFunction(object[key]));
            } else {
                observable(object[key]);
            }
        }
    }
    function lower(value) {
        return value.toLowerCase();
    }
    function alert(title, message, type) {
        var data = {
            title: title,
            text: message,
            nonblock: true,
            delay: 3000
        };
        if (type !== undefined) {
            data.type = type;
        }
        return $.pnotify(data);
    }
    function alertInfo(title, message) {
        return alert(title, message, 'info');
    }
    function alertSuccess(title, message) {
        return alert(title, message, 'success');
    }
    function alertError(title, message) {
        return alert(title, message, 'error');
    }
    function keys(object) {
        var allKeys = [], key;
        for (key in object) {
            if (object.hasOwnProperty(key)) {
                allKeys.push(key);
            }
        }
        return allKeys;
    }
    function xhrAbort(token) {
        if (token !== undefined && token.state() === 'pending') {
            try {
                token.abort();
            } catch (error) {
                // Ignore these errors
            }
        }
    }
    function xhrCompleted(token) {
        return !(token !== undefined && token.state() === 'pending');
    }
    function removeElement(array, element) {
        var index = array.indexOf(element);
        if (index !== -1) {
            array.splice(index, 1);
        }
    }
    function smooth(observable, initialValue, targetValue, steps, formatFunction) {
        var diff, stepSize, decimals, execute, current = initialValue;
        if (initialValue === undefined) {
            if (formatFunction && formatFunction.call) {
                observable(formatFunction(targetValue));
            } else {
                observable(targetValue);
            }
        } else {
            diff = targetValue - initialValue;
            if (diff !== 0) {
                decimals = Math.max((initialValue.toString().split('.')[1] || []).length, (targetValue.toString().split('.')[1] || []).length);
                stepSize = ceil(diff / steps, decimals);
                stepSize = stepSize === 0 ? 1 : stepSize;
                execute = function() {
                    if (Math.abs(targetValue - current) > Math.abs(stepSize)) {
                        current += stepSize;
                        if (formatFunction && formatFunction.call) {
                            observable(formatFunction(current));
                        } else {
                            observable(current);
                        }
                        window.setTimeout(execute, 75);
                    } else if (formatFunction && formatFunction.call) {
                        observable(formatFunction(targetValue));
                    } else {
                        observable(targetValue);
                    }
                };
                window.setTimeout(execute, 75);
            }
        }
    }
    function crossFiller(newKeyList, objectList, objectLoader, key, clean) {
        //               Arr.        Obs. Arr    Function      Obs.
        var i, j, currentKeyList = [], loadedObject;
        for (i = 0; i < objectList().length; i += 1) {
            currentKeyList.push(objectList()[i][key]());
        }
        for (i = 0; i < newKeyList.length; i += 1) {
            if ($.inArray(newKeyList[i], currentKeyList) === -1) {
                // One of the new keys is not yet in our current key list. This means
                // we'll have to load the object.
                loadedObject = objectLoader(newKeyList[i]);
                if (loadedObject !== undefined) {
                    objectList.push(loadedObject);
                }
            }
        }
        if (clean !== false) {
            for (i = 0; i < currentKeyList.length; i += 1) {
                if ($.inArray(currentKeyList[i], newKeyList) === -1) {
                    // One of the existing keys is not in the new key list anymore. This means
                    // we'll have to remove the object
                    for (j = 0; j < objectList().length; j += 1) {
                        if (objectList()[j][key]() === currentKeyList[i]) {
                            objectList.splice(j, 1);
                            break;
                        }
                    }
                }
            }
        }
    }
    function numberSort(itemA, itemB) {
        if ((itemA === undefined || itemA === null) && (itemB !== undefined && itemB !== null)) {
            return -1;
        }
        if ((itemA === undefined || itemA === null) && (itemB === undefined || itemB === null)) {
            return 0;
        }
        if ((itemA !== undefined && itemA !== null) && (itemB === undefined || itemB === null)) {
            return 1;
        }
        var regexAlpha = /[\d]+/g,
        regexNumber = /[^\d]+/g,
        partA = itemA.replace(regexAlpha, ''),
        partB = itemB.replace(regexAlpha, '');
        if (partA === partB) {
            partA = parseInt(itemA.replace(regexNumber, ''), 10);
            partB = parseInt(itemB.replace(regexNumber, ''), 10);
            return partA === partB ? 0 : (partA > partB ? 1 : -1);
        }
        return partA > partB ? 1 : -1;
    }
    function advancedSort(list, properties) {
        list.sort(function(a, b) {
            var i, result;
            for (i = 0; i < properties.length; i += 1) {
                result = numberSort(a[properties[i]](), b[properties[i]]());
                if (result !== 0) {
                    return result;
                }
            }
            return 0;
        });
    }
    function validate(nodes) {
        var i, node, check, checkAndRedirect;
        check = function(node) {
            return $.ajax(node + '/api/?timestamp=' + (new Date().getTime()), {
                type: 'GET',
                contentType: 'application/json',
                dataType: 'json',
                timeout: 5000,
                headers: { Accept: 'application/json' }
            });
        };
        checkAndRedirect = function(node) {
            check(node)
                .done(function() {
                    window.location.href = node;
                });
        };
        check('https://' + window.location.hostname)
            .fail(function() {
                for (i = 0; i < nodes.length; i += 1) {
                    node = nodes[i];
                    checkAndRedirect('https://' + node);
                }
                window.setTimeout(function() {
                    location.reload(true);
                }, 5000);
            });
    }
    function overlap(array1, array2) {
        var i, j;
        for (i = 0; i < array1.length; i += 1) {
            for (j = 0; j < array2.length; j += 1) {
                if (array1[i] === array2[j]) {
                    return true;
                }
            }
        }
        return false;
    }

    return {
        getTimestamp     : getTimestamp,
        formatBytes      : formatBytes,
        formatSpeed      : formatSpeed,
        formatRatio      : formatRatio,
        formatShort      : formatShort,
        formatNumber     : formatNumber,
        formatPercentage : formatPercentage,
        padRight         : padRight,
        padLeft          : padLeft,
        tryGet           : tryGet,
        trySet           : trySet,
        lower            : lower,
        alert            : alert,
        alertInfo        : alertInfo,
        alertSuccess     : alertSuccess,
        alertError       : alertError,
        keys             : keys,
        xhrAbort         : xhrAbort,
        xhrCompleted     : xhrCompleted,
        removeElement    : removeElement,
        smooth           : smooth,
        round            : round,
        ceil             : ceil,
        buildString      : buildString,
        setDecimals      : setDecimals,
        crossFiller      : crossFiller,
        deg2rad          : deg2rad,
        numberSort       : numberSort,
        advancedSort     : advancedSort,
        validate         : validate,
        overlap          : overlap
    };
});
<commit_msg>OVS-1573 - Updates for Alba discovery process<commit_after>// Copyright 2014 CloudFounders NV
//
// 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.
/*global define, window, document, location */
define(['jquery', 'jqp/pnotify'], function($) {
    "use strict";
    function getTimestamp() {
        return new Date().getTime();
    }
    function buildString(value, times) {
        var i, returnvalue = '';
        for (i = 0; i < times; i += 1) {
            returnvalue += value.toString();
        }
        return returnvalue;
    }
    function deg2rad(deg) {
		return deg * Math.PI / 180;
	}
    function setDecimals(value, decimals) {
        decimals = decimals || 2;
        var parts = [];
        if (isNaN(value)) {
            parts = ["0"];
        } else {
            parts = value.toString().split('.');
        }

        if (decimals <= 0) {
            return parts[0];
        }

        if (parts.length === 1) {
            parts.push(buildString('0', decimals));
        }
        while (parts[1].length < decimals) {
            parts[1] = parts[1] + '0';
        }
        return parts[0] + '.' + parts[1];
    }
    function round(value, decimals) {
        decimals = decimals || 0;
        if (decimals === 0) {
            return Math.round(value);
        }
        var factor = Math.pow(10, decimals);
        return Math.round(value * factor) / factor;
    }
    function ceil(value, decimals) {
        decimals = decimals || 0;
        if (decimals === 0) {
            return Math.ceil(value);
        }
        var factor = Math.pow(10, decimals);
        return Math.ceil(value * factor) / factor;
    }
    function formatBytes(value) {
        var units, counter;
        units = ['b', 'kib', 'mib', 'gib', 'tib'];
        counter = 0;
        while (value >= 1000) {
            value = value / 1024;
            counter += 1;
        }
        return setDecimals(round(value, 2), 2) + ' ' + $.t('ovs:generic.' + units[counter]);
    }
    function formatSpeed(value) {
        var units, counter;
        units = ['b', 'kib', 'mib', 'gib', 'tib'];
        counter = 0;
        while (value >= 1000) {
            value = value / 1024;
            counter += 1;
        }
        return setDecimals(round(value, 2), 2) + ' ' + $.t('ovs:generic.' + units[counter] + 's');
    }
    function formatRatio(value) {
        return setDecimals(round(value, 2), 2) + ' %';
    }
    function formatShort(value) {
        var units, counter, returnValue;
        units = ['k', 'm', 'g', 't'];
        counter = 0;
        while (value >= 1000) {
            value = value / 1000;
            counter += 1;
        }
        returnValue = setDecimals(round(value, 2), 2);
        if (counter > 0) {
            returnValue += ' ' + $.t('ovs:generic.' + units[counter - 1]);
        }
        return returnValue;
    }
    function formatNumber(value) {
        if (value !== undefined) {
            value = round(value).toString();
            var regex = /(\d+)(\d{3})/;
            while (regex.test(value)) {
                value = value.replace(regex, '$1' + $.t('ovs:generic.thousandseparator') + '$2');
            }
            return value;
        }
        return undefined;
    }
    function formatPercentage(value) {
        value = Math.round(value * 10000) / 100;
        return formatNumber(value) + ' %';
    }
    function padRight(value, character, length) {
        while (value.length < length) {
            value += character;
        }
        return value;
    }
    function padLeft(value, character, length) {
        while (value.length < length) {
            value = character + value;
        }
        return value;
    }
    function tryGet(object, key, fallback) {
        if (object !== undefined && object.hasOwnProperty(key)) {
            return object[key];
        }
        return fallback;
    }
    function trySet(observable, object, key, formatFunction) {
        if (object !== undefined && object.hasOwnProperty(key)) {
            if (formatFunction !== undefined && formatFunction.call) {
                observable(formatFunction(object[key]));
            } else {
                observable(object[key]);
            }
        }
    }
    function lower(value) {
        return value.toLowerCase();
    }
    function alert(title, message, type) {
        var data = {
            title: title,
            text: message,
            nonblock: true,
            delay: 3000
        };
        if (type !== undefined) {
            data.type = type;
        }
        return $.pnotify(data);
    }
    function alertInfo(title, message) {
        return alert(title, message, 'info');
    }
    function alertSuccess(title, message) {
        return alert(title, message, 'success');
    }
    function alertError(title, message) {
        return alert(title, message, 'error');
    }
    function keys(object) {
        var allKeys = [], key;
        for (key in object) {
            if (object.hasOwnProperty(key)) {
                allKeys.push(key);
            }
        }
        return allKeys;
    }
    function xhrAbort(token) {
        if (token !== undefined && token.state() === 'pending') {
            try {
                token.abort();
            } catch (error) {
                // Ignore these errors
            }
        }
    }
    function xhrCompleted(token) {
        return !(token !== undefined && token.state() === 'pending');
    }
    function removeElement(array, element) {
        var index = array.indexOf(element);
        if (index !== -1) {
            array.splice(index, 1);
        }
    }
    function smooth(observable, initialValue, targetValue, steps, formatFunction) {
        var diff, stepSize, decimals, execute, current = initialValue;
        if (initialValue === undefined) {
            if (formatFunction && formatFunction.call) {
                observable(formatFunction(targetValue));
            } else {
                observable(targetValue);
            }
        } else {
            diff = targetValue - initialValue;
            if (diff !== 0) {
                decimals = Math.max((initialValue.toString().split('.')[1] || []).length, (targetValue.toString().split('.')[1] || []).length);
                stepSize = ceil(diff / steps, decimals);
                stepSize = stepSize === 0 ? 1 : stepSize;
                execute = function() {
                    if (Math.abs(targetValue - current) > Math.abs(stepSize)) {
                        current += stepSize;
                        if (formatFunction && formatFunction.call) {
                            observable(formatFunction(current));
                        } else {
                            observable(current);
                        }
                        window.setTimeout(execute, 75);
                    } else if (formatFunction && formatFunction.call) {
                        observable(formatFunction(targetValue));
                    } else {
                        observable(targetValue);
                    }
                };
                window.setTimeout(execute, 75);
            }
        }
    }
    function crossFiller(newKeyList, objectList, objectLoader, key, clean) {
        //               Arr.        Obs. Arr    Function      Obs.
        var i, j, currentKeyList = [], loadedObject;
        for (i = 0; i < objectList().length; i += 1) {
            currentKeyList.push(objectList()[i][key]());
        }
        for (i = 0; i < newKeyList.length; i += 1) {
            if ($.inArray(newKeyList[i], currentKeyList) === -1) {
                // One of the new keys is not yet in our current key list. This means
                // we'll have to load the object.
                loadedObject = objectLoader(newKeyList[i]);
                if (loadedObject !== undefined) {
                    objectList.push(loadedObject);
                }
            }
        }
        if (clean !== false) {
            for (i = 0; i < currentKeyList.length; i += 1) {
                if ($.inArray(currentKeyList[i], newKeyList) === -1) {
                    // One of the existing keys is not in the new key list anymore. This means
                    // we'll have to remove the object
                    for (j = 0; j < objectList().length; j += 1) {
                        if (objectList()[j][key]() === currentKeyList[i]) {
                            objectList.splice(j, 1);
                            break;
                        }
                    }
                }
            }
        }
    }
    function syncObservableArray(newArray, objectList, key, clean) {
        var i, j, newKeyList = [], currentKeyList = [];
        for (i = 0; i < objectList().length; i += 1) {
            currentKeyList.push(objectList()[i].key);
        }
        for (i = 0; i < newArray.length; i += 1) {
            newKeyList.push(newArray[i].key);
        }
        for (i = 0; i < newKeyList.length; i += 1) {
            if ($.inArray(newKeyList[i], currentKeyList) === -1) {
                // One of the new keys is not yet in our current key list. This means
                // we'll have to load the object.
                objectList.push(newArray[i]);
            }
        }
        if (clean !== false) {
            for (i = 0; i < currentKeyList.length; i += 1) {
                if ($.inArray(currentKeyList[i], newKeyList) === -1) {
                    // One of the existing keys is not in the new key list anymore. This means
                    // we'll have to remove the object
                    for (j = 0; j < objectList().length; j += 1) {
                        if (objectList()[j].key === currentKeyList[i]) {
                            objectList.splice(j, 1);
                            break;
                        }
                    }
                }
            }
        }
    }
    function numberSort(itemA, itemB) {
        if ((itemA === undefined || itemA === null) && (itemB !== undefined && itemB !== null)) {
            return -1;
        }
        if ((itemA === undefined || itemA === null) && (itemB === undefined || itemB === null)) {
            return 0;
        }
        if ((itemA !== undefined && itemA !== null) && (itemB === undefined || itemB === null)) {
            return 1;
        }
        var regexAlpha = /[\d]+/g,
        regexNumber = /[^\d]+/g,
        partA = itemA.replace(regexAlpha, ''),
        partB = itemB.replace(regexAlpha, '');
        if (partA === partB) {
            partA = parseInt(itemA.replace(regexNumber, ''), 10);
            partB = parseInt(itemB.replace(regexNumber, ''), 10);
            return partA === partB ? 0 : (partA > partB ? 1 : -1);
        }
        return partA > partB ? 1 : -1;
    }
    function advancedSort(list, properties) {
        list.sort(function(a, b) {
            var i, result;
            for (i = 0; i < properties.length; i += 1) {
                result = numberSort(a[properties[i]](), b[properties[i]]());
                if (result !== 0) {
                    return result;
                }
            }
            return 0;
        });
    }
    function validate(nodes) {
        var i, node, check, checkAndRedirect;
        check = function(node) {
            return $.ajax(node + '/api/?timestamp=' + (new Date().getTime()), {
                type: 'GET',
                contentType: 'application/json',
                dataType: 'json',
                timeout: 5000,
                headers: { Accept: 'application/json' }
            });
        };
        checkAndRedirect = function(node) {
            check(node)
                .done(function() {
                    window.location.href = node;
                });
        };
        check('https://' + window.location.hostname)
            .fail(function() {
                for (i = 0; i < nodes.length; i += 1) {
                    node = nodes[i];
                    checkAndRedirect('https://' + node);
                }
                window.setTimeout(function() {
                    location.reload(true);
                }, 5000);
            });
    }
    function overlap(array1, array2) {
        var i, j;
        for (i = 0; i < array1.length; i += 1) {
            for (j = 0; j < array2.length; j += 1) {
                if (array1[i] === array2[j]) {
                    return true;
                }
            }
        }
        return false;
    }

    return {
        getTimestamp             : getTimestamp,
        formatBytes              : formatBytes,
        formatSpeed              : formatSpeed,
        formatRatio              : formatRatio,
        formatShort              : formatShort,
        formatNumber             : formatNumber,
        formatPercentage         : formatPercentage,
        padRight                 : padRight,
        padLeft                  : padLeft,
        tryGet                   : tryGet,
        trySet                   : trySet,
        lower                    : lower,
        alert                    : alert,
        alertInfo                : alertInfo,
        alertSuccess             : alertSuccess,
        alertError               : alertError,
        keys                     : keys,
        xhrAbort                 : xhrAbort,
        xhrCompleted             : xhrCompleted,
        removeElement            : removeElement,
        smooth                   : smooth,
        round                    : round,
        ceil                     : ceil,
        buildString              : buildString,
        setDecimals              : setDecimals,
        crossFiller              : crossFiller,
        syncObservableArray      : syncObservableArray,
        deg2rad                  : deg2rad,
        numberSort               : numberSort,
        advancedSort             : advancedSort,
        validate                 : validate,
        overlap                  : overlap
    };
});
<|endoftext|>


<commit_before>'use strict';
/*jshint expr: true*/
/*global describe, it, afterEach, beforeEach*/

var expect = require('chai').expect,
    path = require('path'),
    mkdirp = require('mkdirp'),
    rimraf = require('rimraf'),
    bufferEqual = require('buffer-equal'),
    mpq = require('../');

function getDataPath(filename) {
    filename = filename || '';
    return path.join('./test/temp/', filename);
}

describe('archive operations', function() {
    beforeEach(function() {
        rimraf.sync(getDataPath());
        mkdirp.sync(getDataPath());
    });

    afterEach(function() {
        rimraf.sync(getDataPath());
    });

    it('can create and open archives', function() {
        var archivePath = getDataPath('abc.mpq');
        var archive = mpq.createArchive(archivePath);
        expect(archive).to.exist;
        expect(archive.flush()).to.be.true;
        archive.close();
        archive = mpq.openArchive(archivePath);
        expect(archive).to.exist;
        archive.close();
    });

    it('can create, remove, and rename files within an archive', function() {
        var archivePath = getDataPath('abc.mpq');
        var filePath_0 = "foo/bar_0.txt";
        var filePath_1 = "foo/bar_1.txt";

        var archive = mpq.createArchive(archivePath);
        expect(archive).to.exist;

        expect(archive.hasFile(filePath_0)).to.be.false;
        expect(archive.createFile(filePath_0, 1024)).to.exist;

        expect(archive.hasFile(filePath_0)).to.be.true;
        expect(archive.hasFile(filePath_1)).to.be.false;
        expect(archive.renameFile(filePath_0, filePath_1)).to.be.true;
        expect(archive.hasFile(filePath_0)).to.be.false;
        expect(archive.hasFile(filePath_1)).to.be.true;

        expect(archive.removeFile(filePath_1)).to.be.true;
        expect(archive.hasFile(filePath_0)).to.be.false;
        expect(archive.hasFile(filePath_1)).to.be.false;

        archive.flush();
        archive.close();
    });
});

describe('file operations', function() {
    beforeEach(function() {
        rimraf.sync(getDataPath());
        mkdirp.sync(getDataPath());
    });

    afterEach(function() {
        rimraf.sync(getDataPath());
    });

    function createArchive() {
        var archivePath = getDataPath('abc.mpq');
        var archive = mpq.createArchive(archivePath);
        expect(archive).to.exist;
        return archive;
    }

    function getRandomIntInclusive(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    it('can create and open files within an archive', function() {
        var archive = createArchive();
        var filePath = "foo/bar/hoge";
        var fileSize = 2048;
        var file = archive.createFile(filePath, fileSize);
        expect(file).to.exist;

        expect(file.getSize()).to.equal(fileSize);

        var otherFile = archive.openFile(filePath);
        expect(otherFile).to.exist;
        expect(otherFile.getSize()).to.equal(fileSize);

        archive.close();
    });

    it('can read and write files within an archive', function() {
        var archive = createArchive();
        var filePath = "foo/bar/hoge";
        var fileSize = 1024;

        var file = archive.createFile(filePath, fileSize);
        expect(file).to.exist;
        expect(file.getSize()).to.equal(fileSize);

        var bytes = [];
        for (var i = 0; i < fileSize; i++) {
            bytes.push(getRandomIntInclusive(0, 0xFF));
        }

        var buffer = new Buffer(bytes);
        expect(buffer.length).to.equal(fileSize);
        expect(file.write(buffer)).to.be.true;
        expect(file.finish()).to.be.true;

        file = archive.openFile(filePath);
        expect(file).to.exist;
        expect(file.getSize()).to.equal(fileSize);

        var otherBuffer = file.read();
        expect(otherBuffer).to.exist;
        expect(otherBuffer.length).to.equal(fileSize);

        expect(bufferEqual(buffer, otherBuffer)).to.be.true;

        archive.close();
    });
});
<commit_msg>File close fixes for tests.<commit_after>'use strict';
/*jshint expr: true*/
/*global describe, it, afterEach, beforeEach*/

var expect = require('chai').expect,
    path = require('path'),
    mkdirp = require('mkdirp'),
    rimraf = require('rimraf'),
    bufferEqual = require('buffer-equal'),
    mpq = require('../');

function getDataPath(filename) {
    filename = filename || '';
    return path.join('./test/temp/', filename);
}

describe('archive operations', function() {
    beforeEach(function() {
        rimraf.sync(getDataPath());
        mkdirp.sync(getDataPath());
    });

    afterEach(function() {
        rimraf.sync(getDataPath());
    });

    it('can create and open archives', function() {
        var archivePath = getDataPath('abc.mpq');
        var archive = mpq.createArchive(archivePath);
        expect(archive).to.exist;
        expect(archive.flush()).to.be.true;
        archive.close();
        archive = mpq.openArchive(archivePath);
        expect(archive).to.exist;
        archive.close();
    });

    it('can create, remove, and rename files within an archive', function() {
        var archivePath = getDataPath('abc.mpq');
        var filePath_0 = "foo/bar_0.txt";
        var filePath_1 = "foo/bar_1.txt";

        var archive = mpq.createArchive(archivePath);
        expect(archive).to.exist;

        expect(archive.hasFile(filePath_0)).to.be.false;
        expect(archive.createFile(filePath_0, 1024)).to.exist;

        expect(archive.hasFile(filePath_0)).to.be.true;
        expect(archive.hasFile(filePath_1)).to.be.false;
        expect(archive.renameFile(filePath_0, filePath_1)).to.be.true;
        expect(archive.hasFile(filePath_0)).to.be.false;
        expect(archive.hasFile(filePath_1)).to.be.true;

        expect(archive.removeFile(filePath_1)).to.be.true;
        expect(archive.hasFile(filePath_0)).to.be.false;
        expect(archive.hasFile(filePath_1)).to.be.false;

        archive.flush();
        archive.close();
    });
});

describe('file operations', function() {
    beforeEach(function() {
        rimraf.sync(getDataPath());
        mkdirp.sync(getDataPath());
    });

    afterEach(function() {
        rimraf.sync(getDataPath());
    });

    function createArchive() {
        var archivePath = getDataPath('abc.mpq');
        var archive = mpq.createArchive(archivePath);
        expect(archive).to.exist;
        return archive;
    }

    function getRandomIntInclusive(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    it('can create and open files within an archive', function() {
        var archive = createArchive();
        var filePath = "foo/bar/hoge";
        var fileSize = 2048;
        var file = archive.createFile(filePath, fileSize);
        expect(file).to.exist;

        expect(file.getSize()).to.equal(fileSize);

        var otherFile = archive.openFile(filePath);
        expect(otherFile).to.exist;
        expect(otherFile.getSize()).to.equal(fileSize);
        otherFile.close();

        archive.close();
    });

    it('can read and write files within an archive', function() {
        var archive = createArchive();
        var filePath = "foo/bar/hoge";
        var fileSize = 1024;

        var file = archive.createFile(filePath, fileSize);
        expect(file).to.exist;
        expect(file.getSize()).to.equal(fileSize);

        var bytes = [];
        for (var i = 0; i < fileSize; i++) {
            bytes.push(getRandomIntInclusive(0, 0xFF));
        }

        var buffer = new Buffer(bytes);
        expect(buffer.length).to.equal(fileSize);
        expect(file.write(buffer)).to.be.true;
        expect(file.close()).to.be.true;

        file = archive.openFile(filePath);
        expect(file).to.exist;
        expect(file.getSize()).to.equal(fileSize);

        var otherBuffer = file.read();
        expect(otherBuffer).to.exist;
        expect(otherBuffer.length).to.equal(fileSize);
        file.close();

        expect(bufferEqual(buffer, otherBuffer)).to.be.true;

        archive.close();
    });
});
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { browserHistory } from 'react-router';
import { contextTypes } from '../../../utils/decorators/withContext.js';
import { connect } from 'react-redux';
import { util as storeUtil } from '../../../store.js';
import moment from 'moment';

import enhanceWithClickOutside from 'react-click-outside';
import LeftNav from 'material-ui/lib/left-nav';
import MenuItem from 'material-ui/lib/menus/menu-item';
import Divider from 'material-ui/lib/divider';
import Badge from 'material-ui/lib/badge';

//using @connect decorator breaks enhanceWithClickOutside
class Navigation extends Component {
  static contextTypes = contextTypes;
  static propTypes = {
    matches: PropTypes.object.isRequired,
    toggleNav: PropTypes.func.isRequired,
    navOpen: PropTypes.bool.isRequired,
    isNavOpening: PropTypes.bool.isRequired,
  }

  handleClickOutside() {
    if (this.props.navOpen && !this.props.isNavOpening) {
      this.props.toggleNav(false);
    }
  }

  handleClickCloseMenuButton = () => this.props.toggleNav(false);

  _goto(url) {
    this.props.toggleNav(false);
    browserHistory.push(url);
  }

  render() {
    const t = this.context.t;
    const matchesToday = storeUtil.matches.getTodayMatches();

    return (
      <LeftNav open={this.props.navOpen} width={200}>
        <MenuItem onTouchTap={this._goto.bind(this, t.route('matches'))}>{t('nav.matches')}</MenuItem>
        {matchesToday.size ? (
          <MenuItem onTouchTap={this._goto.bind(this, t.route('matchesToday'))} style={{}}>
            {t('nav.matchesToday')}
            <Badge badgeContent={matchesToday.size} secondary={true} badgeStyle={{padding: 0, top: 5, left: 5}} />
          </MenuItem>
        ) : null}
        <MenuItem onTouchTap={this._goto.bind(this, t.route('players'))}>{t('nav.players')}</MenuItem>
        <Divider />
        <MenuItem onTouchTap={this._goto.bind(this, t.route('links'))}>{t('nav.links')}</MenuItem>
        <MenuItem onTouchTap={this._goto.bind(this, t.route('facts'))}>{t('nav.facts')}</MenuItem>
        <MenuItem onTouchTap={this.handleClickCloseMenuButton}>{t('nav.closeMenu')}</MenuItem>
      </LeftNav>
    );
  }
}

export default enhanceWithClickOutside(Navigation);<commit_msg>headernavigation cleanup<commit_after>import React, { Component, PropTypes } from 'react';
import { browserHistory } from 'react-router';
import { contextTypes } from '../../../utils/decorators/withContext.js';
import { util as storeUtil } from '../../../store.js';

import enhanceWithClickOutside from 'react-click-outside';
import LeftNav from 'material-ui/lib/left-nav';
import MenuItem from 'material-ui/lib/menus/menu-item';
import Divider from 'material-ui/lib/divider';
import Badge from 'material-ui/lib/badge';

//using @connect decorator breaks enhanceWithClickOutside
class Navigation extends Component {
  static contextTypes = contextTypes;
  static propTypes = {
    toggleNav: PropTypes.func.isRequired,
    navOpen: PropTypes.bool.isRequired,
    isNavOpening: PropTypes.bool.isRequired,
  }

  handleClickOutside() {
    if (this.props.navOpen && !this.props.isNavOpening) {
      this.props.toggleNav(false);
    }
  }

  handleClickCloseMenuButton = () => this.props.toggleNav(false);

  _goto(url) {
    this.props.toggleNav(false);
    browserHistory.push(url);
  }

  render() {
    const t = this.context.t;
    const matchesToday = storeUtil.matches.getTodayMatches();

    return (
      <LeftNav open={this.props.navOpen} width={200}>
        <MenuItem onTouchTap={this._goto.bind(this, t.route('matches'))}>{t('nav.matches')}</MenuItem>
        {matchesToday.size ? (
          <MenuItem onTouchTap={this._goto.bind(this, t.route('matchesToday'))} style={{}}>
            {t('nav.matchesToday')}
            <Badge badgeContent={matchesToday.size} secondary={true} badgeStyle={{padding: 0, top: 5, left: 5}} />
          </MenuItem>
        ) : null}
        <MenuItem onTouchTap={this._goto.bind(this, t.route('players'))}>{t('nav.players')}</MenuItem>
        <Divider />
        <MenuItem onTouchTap={this._goto.bind(this, t.route('links'))}>{t('nav.links')}</MenuItem>
        <MenuItem onTouchTap={this._goto.bind(this, t.route('facts'))}>{t('nav.facts')}</MenuItem>
        <MenuItem onTouchTap={this.handleClickCloseMenuButton}>{t('nav.closeMenu')}</MenuItem>
      </LeftNav>
    );
  }
}

export default enhanceWithClickOutside(Navigation);<|endoftext|>


<commit_before>function rowdyMenuBar() {
  const directive = {
    link: link,
    restrict: 'EA',
    template: `

            <rowdy-menu-button data="{{button}}" ng-repeat="button in iconButtons">

            <rowdy-menu-button data="{{button}}" ng-repeat="button in menuButtons">

    `,
  };
  return directive;

  function link(scope, element, attrs) {
    scope.menuButtons = [
      {
        name: 'Products',
        subNav: [
          {
            name: 'Beer',
            sref: 'app'
          },
          {
            name: 'Kombucha',
            sref: 'app'
          }
        ]
      },
      {
        name: 'About',
        sref: 'app.about',
      },
      {
        name: 'Taproom',
        subNav: [
          {
            name: 'News',
            sref: 'app'
          },
          {
            name: 'Event',
            sref: 'app'
          }
        ]
      },
      {
        name: 'Store',
        sref: 'app.store',
      }
    ];

    //pulled out log in and cart buttons because they need to be in a different div
    scope.iconButtons = [
      {
        name: 'Log In',
        sref: 'app.login',
        iconClass: 'fa-user',
      },
      {
        name: 'Shopping Cart',
        sref: 'app.shoppingCart',
        iconClass: 'fa-shopping-cart',
      },
    ];
  }
}

angular
  .module('RowdyMermaid-site.widgets')
  .directive('rowdyMenuBar', rowdyMenuBar);
<commit_msg>remove menubar.directive .... again<commit_after><|endoftext|>


<commit_before>// Pre-run
import chai from 'chai';
import { givenAsync } from 'mocha-testdata';

import attemptLyricsWikia from '../../../build/main/features/core/lyrics/source_lyricsWikia';
import attemptMetroLyrics from '../../../build/main/features/core/lyrics/source_metroLyrics';

import lyricsSourceSpec from './_lyricsSource_spec';
import { validSongs, invalidSongs } from '../testdata/lyrics';

// Actual Test Imports
const resolveLyrics = require('../../../build/main/features/core/lyrics').resolveLyrics;

chai.should();

// Mock expected globals
global.PlaybackAPI = {
  on: () => {},
};

describe('Lyrics Resolver', () => {
  givenAsync(...validSongs).it('should resolve when given a valid song object', (done, song) => {
    resolveLyrics(song)
      .then((lyrics) => {
        lyrics.should.be.a('string');
        done();
      })
      .catch(() => done(new Error(`Failed to fetch lyrics for song: ${song.title}`)));
  });

  givenAsync(...invalidSongs).it('should fail when given an invalid song object', (done, song) => {
    resolveLyrics(song)
      .then((lyrics) => {
        lyrics.should.be.equal(null);
        done();
      })
      .catch(() => done());
  });

  givenAsync(...validSongs).it('should not contain any script tags when resolved', (done, song) => {
    resolveLyrics(song)
      .then((lyrics) => {
        /<script/g.test(lyrics).should.be.equal(false);
        done();
      })
      .catch(() => done(new Error('Failed to fetch lyrics in this test')));
  });

  lyricsSourceSpec(attemptLyricsWikia, (song) => `${song.artist}:${song.title}`, 'Lyrics Wikia');
  lyricsSourceSpec(attemptMetroLyrics, (song) =>
    `${song.title.toLowerCase().replace(/ /g, '-')}-lyrics-${song.artist.toLowerCase().replace(/ /g, '-')}`
  , 'Metro Lyrics');
});
<commit_msg>Fix tests<commit_after>// Pre-run
import chai from 'chai';
import { givenAsync } from 'mocha-testdata';

import attemptLyricsWikia from '../../../build/main/features/core/lyrics/source_lyricsWikia';
import attemptMetroLyrics from '../../../build/main/features/core/lyrics/source_metroLyrics';

import lyricsSourceSpec from './_lyricsSource_spec';
import { validSongs, invalidSongs } from '../testdata/lyrics';

chai.should();

// Mock expected globals
global.PlaybackAPI = {
  on: () => {},
};

// Actual Test Imports
const resolveLyrics = require('../../../build/main/features/core/lyrics').resolveLyrics; // eslint-disable-line

describe('Lyrics Resolver', () => {
  givenAsync(...validSongs).it('should resolve when given a valid song object', (done, song) => {
    resolveLyrics(song)
      .then((lyrics) => {
        lyrics.should.be.a('string');
        done();
      })
      .catch(() => done(new Error(`Failed to fetch lyrics for song: ${song.title}`)));
  });

  givenAsync(...invalidSongs).it('should fail when given an invalid song object', (done, song) => {
    resolveLyrics(song)
      .then((lyrics) => {
        lyrics.should.be.equal(null);
        done();
      })
      .catch(() => done());
  });

  givenAsync(...validSongs).it('should not contain any script tags when resolved', (done, song) => {
    resolveLyrics(song)
      .then((lyrics) => {
        /<script/g.test(lyrics).should.be.equal(false);
        done();
      })
      .catch(() => done(new Error('Failed to fetch lyrics in this test')));
  });

  lyricsSourceSpec(attemptLyricsWikia, (song) => `${song.artist}:${song.title}`, 'Lyrics Wikia');
  lyricsSourceSpec(attemptMetroLyrics, (song) =>
    `${song.title.toLowerCase().replace(/ /g, '-')}-lyrics-${song.artist.toLowerCase().replace(/ /g, '-')}`
  , 'Metro Lyrics');
});
<|endoftext|>


<commit_before>import React from 'react'

const isComponent = (element = {}): boolean =>
  React.isValidElement(element) && typeof element.type !== 'string'

export const recursiveCloneChildren = (children?: React.Children,
  calculateProps: (React.Children) => {}) => {
  return React.Children.map(children, (child) => {
    return child ? React.cloneElement(
      child,
      isComponent(child)
        ? calculateProps(child)
        : { children: recursiveCloneChildren(child.props.children, calculateProps) },
    ) : null
  })
}
<commit_msg>Only Dupe Children if they exist<commit_after>import React from 'react'

const isComponent = (element = {}): boolean =>
  React.isValidElement(element) && typeof element.type !== 'string'

export const recursiveCloneChildren = (children?: React.Children,
  calculateProps: (React.Children) => {}) => {
  return React.Children.map(children, (child) => {
    return child ? React.cloneElement(
      child,
      isComponent(child)
        ? calculateProps(child)
        : {
          children: child.props
            ? recursiveCloneChildren(child.props.children, calculateProps)
            : null,
        },
    ) : null
  })
}
<|endoftext|>


<commit_before>/*
 * Copyright 2016 Crown Copyright
 *
 * 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('app').controller('AppController',
    [ '$scope', '$mdDialog', '$http', '$location', 'settings', 'graph', 'raw', 'table',
    function($scope, $mdDialog, $http, $location, settings, graph, raw, table){

    $scope.settings = settings;
    $scope.rawData = raw;
    $scope.graph = graph;
    $scope.table = table;
    $scope.operations = [];

    $scope.graphData = {entities: {}, edges: {}};

    $scope.selectedElementTabIndex = 0;
    $scope.selectedEntities = {};
    $scope.selectedEdges = {};

    $scope.buildQueryStep = 0;
    $scope.expandEntities = [];
    $scope.expandEdges = [];
    $scope.expandEntitiesContent = {};
    $scope.expandEdgesContent = {};
    $scope.inOutFlag = "BOTH";
    $scope.editingOperations = false;

    $scope.buildQuery = function() {
        $scope.openGraph();
        $scope.showBuildQuery = true;
        $scope.buildQueryTab = 0;
    }

    $scope.goToStep = function(stepId) {
        $scope.buildQueryStep = stepId - 1;
        if(stepId > 2) {
            executeBuildQueryCounts();
        }
    }

    $scope.redraw = function() {
        if($scope.showGraph) {
            $scope.selectedEntities = {};
            $scope.selectedEdges = {};
            graph.redraw();
       }
    };

    $scope.initialise = function() {
        $scope.openGraph();

        var updateResultsListener = function() {
            updateGraphData(raw.results);
            table.update(raw.results);
            if(!$scope.$$phase) {
               $scope.$apply();
            }
        }

        var updateScope = function() {
            if(!$scope.$$phase) {
               $scope.$apply();
            }
        }

        raw.initialise(updateResultsListener, updateScope);
    };

    function addSeedDialogController($scope, $mdDialog) {
        $scope.addSeedCancel = function() {
          $mdDialog.cancel();
        };

        $scope.addSeedAdd = function() {
          var seed = {vertexType: $scope.addSeedVertexType, vertex: $scope.addSeedVertex};
           $scope.addSeedVertexType = '';
           $scope.addSeedVertex = '';
          $mdDialog.hide(seed);
        };
      }

    $scope.addSeedPrompt = function(ev) {
        $mdDialog.show({
              scope: $scope,
              preserveScope: true,
              controller: addSeedDialogController,
              templateUrl: 'app/graph/addSeedDialog.html',
              parent: angular.element(document.body),
              targetEvent: ev,
              clickOutsideToClose:true,
              fullscreen: $scope.customFullscreen
            })
            .then(function(seed) {
              $scope.addSeed(seed.vertexType, seed.vertex);
            });
      };

    var getVertexTypeFromEntityGroup = function(group) {
        for(var entityGroup in raw.schema.entities) {
            if(entityGroup === group) {
                return raw.schema.entities[entityGroup].vertex;
            }
        }
    }

    var getVertexTypesFromEdgeGroup = function(group) {
        for(var edgeGroup in raw.schema.edges) {
            if(edgeGroup === group) {
               return [raw.schema.edges[edgeGroup].source, raw.schema.edges[edgeGroup].destination];
            }
        }
    }

    var updateRelatedEntities = function() {
        $scope.relatedEntities = [];
        for(id in $scope.selectedEntities) {
            var vertexType = $scope.selectedEntities[id][0].vertexType;
            for(var entityGroup in raw.schema.entities) {
                var entity = raw.schema.entities[entityGroup];
                if(entity.vertex === vertexType
                    && $scope.relatedEntities.indexOf(entityGroup) === -1) {
                    $scope.relatedEntities.push(entityGroup);
                }
            }
        }
    }

    var updateRelatedEdges = function() {
        $scope.relatedEdges = [];
        for(id in $scope.selectedEntities) {
            var vertexType = $scope.selectedEntities[id][0].vertexType;
            for(var edgeGroup in raw.schema.edges) {
                var edge = raw.schema.edges[edgeGroup];
                if((edge.source === vertexType || edge.destination === vertexType)
                    && $scope.relatedEdges.indexOf(edgeGroup) === -1) {
                    $scope.relatedEdges.push(edgeGroup);
                }
            }
        }
    }

    $scope.addSeed = function(vertex, value) {
        graph.addSeed(vertex, value);
    }

    arrayContainsValue = function(arr, value) {
        var jsonValue = JSON.stringify(value);
        for(var i in arr) {
            if(JSON.stringify(arr[i]) === jsonValue) {
                return true;
            }
        }

        return false;
    }

    $scope.addFilterFunction = function(expandElementContent, element) {
        if(!expandElementContent[element]) {
            expandElementContent[element] = {};
        }

        if(!expandElementContent[element].filters) {
            expandElementContent[element].filters = [];
        }

        expandElementContent[element].filters.push({});
    }

    createBuildQueryOperation = function() {
        var operation = createOperation();
        var jsonVertex;
        for(var vertex in $scope.selectedEntities) {
            try {
               jsonVertex = JSON.parse(vertex);
            } catch(err) {
               jsonVertex = vertex;
            }
            operation.seeds.push({
                      "class": "uk.gov.gchq.gaffer.operation.data.EntitySeed",
                      "vertex": jsonVertex
                   });
        }

        for(var i in $scope.expandEntities) {
            var entity = $scope.expandEntities[i];
            operation.view.entities[entity] = {groupBy: []};

            var filterFunctions = convertFilterFunctions($scope.expandEntitiesContent[entity], raw.schema.entities[entity]);
            if(filterFunctions.length > 0) {
                operation.view.entities[entity].preAggregationFilterFunctions = filterFunctions;
            }
        }

        for(var i in $scope.expandEdges) {
            var edge = $scope.expandEdges[i];
            operation.view.edges[edge] = {groupBy: []};

            var filterFunctions = convertFilterFunctions($scope.expandEdgesContent[edge], raw.schema.edges[edge]);
            if(filterFunctions.length > 0) {
                operation.view.edges[edge].preAggregationFilterFunctions = filterFunctions;
            }
        }

        operation.includeIncomingOutGoing = $scope.inOutFlag;
        return operation;
    }

    var convertFilterFunctions = function(expandElementContent, elementDefinition) {
        var filterFunctions = [];
        if(expandElementContent && expandElementContent.filters) {
            for(var index in expandElementContent.filters) {
                var filter = expandElementContent.filters[index];
                if(filter.property && filter['function']) {
                    var functionJson = {
                        "function": {
                            class: filter['function']
                        },
                        selection: [ filter.property ]
                    };

                    for(var i in filter.availableFunctionParameters) {
                        if(filter.parameters[i]) {
                            functionJson["function"][filter.availableFunctionParameters[i]] = JSON.parse(filter.parameters[i]);
                        }
                    }

                    filterFunctions.push(functionJson);
                }
            }
        }
        return filterFunctions;
    }

    $scope.clearResults = function() {
        raw.clearResults();
        $scope.selectedEntities = {};
        $scope.selectedEdges = {};
        $scope.graphData = {entities: {}, edges: {}};
        table.clear();
        graph.clear();
    }

    $scope.updateGraph = function() {
        graph.update($scope.graphData);
    }

    var updateGraphData = function(results) {
        $scope.graphData = {entities: {}, edges: {}};
        for (var i in results.entities) {
            var entity = clone(results.entities[i]);
            var id = entity.vertex;
            entity.vertexType = getVertexTypeFromEntityGroup(entity.group);
            if(id in $scope.graphData.entities) {
                if(!arrayContainsValue($scope.graphData.entities[id], entity)) {
                    $scope.graphData.entities[id].push(entity);
                }
            } else {
                $scope.graphData.entities[id] = [entity];
            }
        }

        for (var i in results.edges) {
            var edge = clone(results.edges[i]);
            var vertexTypes = getVertexTypesFromEdgeGroup(edge.group);
            edge.sourceType = vertexTypes[0];
            edge.destinationType = vertexTypes[1];
            var id = edge.source + "|" + edge.destination + "|" + edge.directed + "|" + edge.group;
            if(id in $scope.graphData.edges) {
                if(!arrayContainsValue($scope.graphData.edges[id], edge)) {
                    $scope.graphData.edges[id].push(edge);
                }
            } else {
                $scope.graphData.edges[id] = [edge];
            }
        }
        $scope.updateGraph();
    }

    var clone = function(obj) {
        return JSON.parse(JSON.stringify(obj));
    }

    var createOperation = function() {
        return {
            class: "uk.gov.gchq.gaffer.operation.impl.get.GetElements",
            resultLimit:  settings.resultLimit,
            deduplicate: true,
            seeds: [],
            view: {
                entities: {},
                edges: {}
            }
        };
    }

    $scope.addOperation = function() {
        $scope.operations.push(createOperation());
    };

    $scope.resetBuildQuery = function() {
        $scope.expandEdges = [];
        $scope.expandEntities = [];
        $scope.showBuildQuery = false;
        $scope.buildQueryStep = 0;
        $scope.expandQueryCounts = undefined;
        $scope.expandEntitiesContent = {};
        $scope.expandEdgesContent = {};
    };

    $scope.executeBuildQuery = function() {
        var operation = createBuildQueryOperation();
        $scope.operations.push(operation);
        $scope.resetBuildQuery();
        raw.execute(JSON.stringify({operations: [operation]}));
    };

    var createCountOperation = function() {
        return {
            class: "uk.gov.gchq.gaffer.operation.impl.CountGroups",
            limit: (settings.resultLimit - 1)
        };
    }

    var executeBuildQueryCounts = function() {
        var operations = {operations: [createBuildQueryOperation(), createCountOperation()]};
        var onSuccess = function(data) {
            if(!data.limitHit) {
                var total = 0;
                for(var i in data.entityGroups) {
                    total += data.entityGroups[i];
                }
                for(var i in data.edgeGroups) {
                    total += data.edgeGroups[i];
                }
                data.total = total;
            }
            $scope.expandQueryCounts = data;
        }
        $scope.expandQueryCounts = undefined;
        raw.execute(JSON.stringify(operations), onSuccess);
    };

    $scope.executeAll = function() {
        $scope.clearResults();
        $scope.resetBuildQuery();
       for(var i in $scope.operations) {
           raw.execute(JSON.stringify({operations: [$scope.operations[i]]}));
       }
    }

  graph.onGraphElementSelect(function(element){
     $scope.selectedElementTabIndex = 0;
      var _id = element.id();
      for (var id in $scope.graphData.entities) {
            if(_id == id) {
                $scope.selectedEntities[id] = $scope.graphData.entities[id];
                $scope.selectedEntitiesCount = Object.keys($scope.selectedEntities).length;
                updateRelatedEntities();
                updateRelatedEdges();
                if(!$scope.$$phase) {
                    $scope.$apply();
                  }
                return;
            }
        };
      for (var id in $scope.graphData.edges) {
          if(_id == id) {
              $scope.selectedEdges[id] = $scope.graphData.edges[id];
              $scope.selectedEdgesCount = Object.keys($scope.selectedEdges).length;
              if(!$scope.$$phase) {
                  $scope.$apply();
                }
              return;
          }
      };

      $scope.selectedEntities[_id] = [{vertexType: element.data().vertexType, vertex: _id}];
      $scope.selectedEntitiesCount = Object.keys($scope.selectedEntities).length;
      updateRelatedEntities();
      updateRelatedEdges();

      if(!$scope.$$phase) {
        $scope.$apply();
      }
  });

  graph.onGraphElementUnselect(function(element){
      $scope.selectedElementTabIndex = 0;
      if(element.id() in $scope.selectedEntities) {
        delete $scope.selectedEntities[element.id()];
        $scope.selectedEntitiesCount = Object.keys($scope.selectedEntities).length;
        updateRelatedEntities();
        updateRelatedEdges();
      } else if(element.id() in $scope.selectedEdges) {
        delete $scope.selectedEdges[element.id()];
        $scope.selectedEdgesCount = Object.keys($scope.selectedEdges).length;
      }

      $scope.$apply();
  });

  $scope.toggle = function(item, list) {
    var idx = list.indexOf(item);
    if(idx > -1) {
        list.splice(idx, 1);
    } else {
        list.push(item);
    }
  }

  $scope.exists = function(item, list) {
    return list.indexOf(item) > -1;
  }

  $scope.onSelectedPropertyChange = function(group, selectedElement) {
    raw.functions(group, selectedElement.property, function(data) {
        selectedElement.availableFunctions = data
        $scope.$apply();
    });
    selectedElement.function = '';
  }

  $scope.onSelectedFunctionChange = function(group, selectedElement) {
    raw.functionParameters(selectedElement['function'], function(data) {
        selectedElement.availableFunctionParameters = data;
        $scope.$apply();
    });

    var elementDef = raw.schema.entities[group];
    if(!elementDef) {
         elementDef = raw.schema.edges[group];
    }
    var propertyClass = raw.schema.types[elementDef.properties[selectedElement.property]].class;
    if("java.lang.String" !== propertyClass
        && "java.lang.Boolean" !== propertyClass
        && "java.lang.Integer" !== propertyClass) {
        selectedElement.propertyClass = propertyClass;
    }

    selectedElement.parameters = {};
  }

  var switchTabs = function(tabFlag) {
      $scope.showRaw = false;
      $scope.showGraph = false;
      $scope.showResultsTable = false;
      $scope.showSettings = false;
      $scope[tabFlag] = true;
  };

  $scope.openRaw = function() {
     switchTabs('showRaw');
  };

  $scope.openGraph = function() {
      if(!$scope.graphDataGraphLoaded) {
          graph.load()
               .then(function(){
                 $scope.graphDataGraphLoaded = true;
               });
       }
     switchTabs('showGraph');
  };

  $scope.openResultsTable = function() {
    switchTabs('showResultsTable');
  };

  $scope.openSettings = function() {
     switchTabs('showSettings');
  };

  $scope.editOperations = function() {
    $scope.operationsForEdit = [];
    for(var i in $scope.operations) {
        $scope.operationsForEdit.push(JSON.stringify($scope.operations[i], null, 2));
    }
    $scope.editingOperations = true;
  }

  $scope.saveOperations = function() {
      $scope.operations = [];
      for(var i in $scope.operationsForEdit) {
          try {
            $scope.operations.push(JSON.parse($scope.operationsForEdit[i]));
          } catch(e) {
            console.log('Invalid json: ' + $scope.operationsForEdit[i]);
          }
      }
      $scope.editingOperations = false;
   }

  $scope.initialise();
} ]);
<commit_msg>gh-724 - string seeds are now automatically quoted<commit_after>/*
 * Copyright 2016 Crown Copyright
 *
 * 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('app').controller('AppController',
    [ '$scope', '$mdDialog', '$http', '$location', 'settings', 'graph', 'raw', 'table',
    function($scope, $mdDialog, $http, $location, settings, graph, raw, table){

    $scope.settings = settings;
    $scope.rawData = raw;
    $scope.graph = graph;
    $scope.table = table;
    $scope.operations = [];

    $scope.graphData = {entities: {}, edges: {}};

    $scope.selectedElementTabIndex = 0;
    $scope.selectedEntities = {};
    $scope.selectedEdges = {};

    $scope.buildQueryStep = 0;
    $scope.expandEntities = [];
    $scope.expandEdges = [];
    $scope.expandEntitiesContent = {};
    $scope.expandEdgesContent = {};
    $scope.inOutFlag = "BOTH";
    $scope.editingOperations = false;

    $scope.buildQuery = function() {
        $scope.openGraph();
        $scope.showBuildQuery = true;
        $scope.buildQueryTab = 0;
    }

    $scope.goToStep = function(stepId) {
        $scope.buildQueryStep = stepId - 1;
        if(stepId > 2) {
            executeBuildQueryCounts();
        }
    }

    $scope.redraw = function() {
        if($scope.showGraph) {
            $scope.selectedEntities = {};
            $scope.selectedEdges = {};
            graph.redraw();
       }
    };

    $scope.initialise = function() {
        $scope.openGraph();

        var updateResultsListener = function() {
            updateGraphData(raw.results);
            table.update(raw.results);
            if(!$scope.$$phase) {
               $scope.$apply();
            }
        }

        var updateScope = function() {
            if(!$scope.$$phase) {
               $scope.$apply();
            }
        }

        raw.initialise(updateResultsListener, updateScope);
    };

    function addSeedDialogController($scope, $mdDialog) {
        $scope.addSeedCancel = function() {
          $mdDialog.cancel();
        };

        $scope.addSeedAdd = function() {
          try {
             JSON.parse($scope.addSeedVertex);
          } catch(err) {
             // Try adding quotes
             $scope.addSeedVertex = "\"" + $scope.addSeedVertex + "\"";

             try {
               JSON.parse($scope.addSeedVertex);
             } catch(err) {
               alert("Error: vertex is not valid - " + $scope.addSeedVertex);
             }
          }

          var seed = {vertexType: $scope.addSeedVertexType, vertex: $scope.addSeedVertex};
           $scope.addSeedVertexType = '';
           $scope.addSeedVertex = '';
          $mdDialog.hide(seed);
        };
      }

    $scope.addSeedPrompt = function(ev) {
        $mdDialog.show({
              scope: $scope,
              preserveScope: true,
              controller: addSeedDialogController,
              templateUrl: 'app/graph/addSeedDialog.html',
              parent: angular.element(document.body),
              targetEvent: ev,
              clickOutsideToClose:true,
              fullscreen: $scope.customFullscreen
            })
            .then(function(seed) {
              $scope.addSeed(seed.vertexType, seed.vertex);
            });
      };

    var getVertexTypeFromEntityGroup = function(group) {
        for(var entityGroup in raw.schema.entities) {
            if(entityGroup === group) {
                return raw.schema.entities[entityGroup].vertex;
            }
        }
    }

    var getVertexTypesFromEdgeGroup = function(group) {
        for(var edgeGroup in raw.schema.edges) {
            if(edgeGroup === group) {
               return [raw.schema.edges[edgeGroup].source, raw.schema.edges[edgeGroup].destination];
            }
        }
    }

    var updateRelatedEntities = function() {
        $scope.relatedEntities = [];
        for(id in $scope.selectedEntities) {
            var vertexType = $scope.selectedEntities[id][0].vertexType;
            for(var entityGroup in raw.schema.entities) {
                var entity = raw.schema.entities[entityGroup];
                if(entity.vertex === vertexType
                    && $scope.relatedEntities.indexOf(entityGroup) === -1) {
                    $scope.relatedEntities.push(entityGroup);
                }
            }
        }
    }

    var updateRelatedEdges = function() {
        $scope.relatedEdges = [];
        for(id in $scope.selectedEntities) {
            var vertexType = $scope.selectedEntities[id][0].vertexType;
            for(var edgeGroup in raw.schema.edges) {
                var edge = raw.schema.edges[edgeGroup];
                if((edge.source === vertexType || edge.destination === vertexType)
                    && $scope.relatedEdges.indexOf(edgeGroup) === -1) {
                    $scope.relatedEdges.push(edgeGroup);
                }
            }
        }
    }

    $scope.addSeed = function(vertex, value) {
        graph.addSeed(vertex, value);
    }

    arrayContainsValue = function(arr, value) {
        var jsonValue = JSON.stringify(value);
        for(var i in arr) {
            if(JSON.stringify(arr[i]) === jsonValue) {
                return true;
            }
        }

        return false;
    }

    $scope.addFilterFunction = function(expandElementContent, element) {
        if(!expandElementContent[element]) {
            expandElementContent[element] = {};
        }

        if(!expandElementContent[element].filters) {
            expandElementContent[element].filters = [];
        }

        expandElementContent[element].filters.push({});
    }

    createBuildQueryOperation = function() {
        var operation = createOperation();
        var jsonVertex;
        for(var vertex in $scope.selectedEntities) {
            try {
               jsonVertex = JSON.parse(vertex);
            } catch(err) {
               jsonVertex = vertex;
            }
            operation.seeds.push({
                      "class": "uk.gov.gchq.gaffer.operation.data.EntitySeed",
                      "vertex": jsonVertex
                   });
        }

        for(var i in $scope.expandEntities) {
            var entity = $scope.expandEntities[i];
            operation.view.entities[entity] = {groupBy: []};

            var filterFunctions = convertFilterFunctions($scope.expandEntitiesContent[entity], raw.schema.entities[entity]);
            if(filterFunctions.length > 0) {
                operation.view.entities[entity].preAggregationFilterFunctions = filterFunctions;
            }
        }

        for(var i in $scope.expandEdges) {
            var edge = $scope.expandEdges[i];
            operation.view.edges[edge] = {groupBy: []};

            var filterFunctions = convertFilterFunctions($scope.expandEdgesContent[edge], raw.schema.edges[edge]);
            if(filterFunctions.length > 0) {
                operation.view.edges[edge].preAggregationFilterFunctions = filterFunctions;
            }
        }

        operation.includeIncomingOutGoing = $scope.inOutFlag;
        return operation;
    }

    var convertFilterFunctions = function(expandElementContent, elementDefinition) {
        var filterFunctions = [];
        if(expandElementContent && expandElementContent.filters) {
            for(var index in expandElementContent.filters) {
                var filter = expandElementContent.filters[index];
                if(filter.property && filter['function']) {
                    var functionJson = {
                        "function": {
                            class: filter['function']
                        },
                        selection: [ filter.property ]
                    };

                    for(var i in filter.availableFunctionParameters) {
                        if(filter.parameters[i]) {
                            functionJson["function"][filter.availableFunctionParameters[i]] = JSON.parse(filter.parameters[i]);
                        }
                    }

                    filterFunctions.push(functionJson);
                }
            }
        }
        return filterFunctions;
    }

    $scope.clearResults = function() {
        raw.clearResults();
        $scope.selectedEntities = {};
        $scope.selectedEdges = {};
        $scope.graphData = {entities: {}, edges: {}};
        table.clear();
        graph.clear();
    }

    $scope.updateGraph = function() {
        graph.update($scope.graphData);
    }

    var parseVertex = function(vertex) {
        try {
             JSON.parse(vertex);
        } catch(err) {
             // Try adding quotes
             vertex = "\"" + vertex + "\"";
        }

        return vertex;
    }

    var updateGraphData = function(results) {
        $scope.graphData = {entities: {}, edges: {}};
        for (var i in results.entities) {
            var entity = clone(results.entities[i]);
            entity.vertex = parseVertex(entity.vertex);
            var id = entity.vertex;
            entity.vertexType = getVertexTypeFromEntityGroup(entity.group);
            if(id in $scope.graphData.entities) {
                if(!arrayContainsValue($scope.graphData.entities[id], entity)) {
                    $scope.graphData.entities[id].push(entity);
                }
            } else {
                $scope.graphData.entities[id] = [entity];
            }
        }

        for (var i in results.edges) {
            var edge = clone(results.edges[i]);
            edge.source = parseVertex(edge.source);
            edge.destination = parseVertex(edge.destination);

            var vertexTypes = getVertexTypesFromEdgeGroup(edge.group);
            edge.sourceType = vertexTypes[0];
            edge.destinationType = vertexTypes[1];
            var id = edge.source + "|" + edge.destination + "|" + edge.directed + "|" + edge.group;
            if(id in $scope.graphData.edges) {
                if(!arrayContainsValue($scope.graphData.edges[id], edge)) {
                    $scope.graphData.edges[id].push(edge);
                }
            } else {
                $scope.graphData.edges[id] = [edge];
            }
        }
        $scope.updateGraph();
    }

    var clone = function(obj) {
        return JSON.parse(JSON.stringify(obj));
    }

    var createOperation = function() {
        return {
            class: "uk.gov.gchq.gaffer.operation.impl.get.GetElements",
            resultLimit:  settings.resultLimit,
            deduplicate: true,
            seeds: [],
            view: {
                entities: {},
                edges: {}
            }
        };
    }

    $scope.addOperation = function() {
        $scope.operations.push(createOperation());
    };

    $scope.resetBuildQuery = function() {
        $scope.expandEdges = [];
        $scope.expandEntities = [];
        $scope.showBuildQuery = false;
        $scope.buildQueryStep = 0;
        $scope.expandQueryCounts = undefined;
        $scope.expandEntitiesContent = {};
        $scope.expandEdgesContent = {};
    };

    $scope.executeBuildQuery = function() {
        var operation = createBuildQueryOperation();
        $scope.operations.push(operation);
        $scope.resetBuildQuery();
        raw.execute(JSON.stringify({operations: [operation]}));
    };

    var createCountOperation = function() {
        return {
            class: "uk.gov.gchq.gaffer.operation.impl.CountGroups",
            limit: (settings.resultLimit - 1)
        };
    }

    var executeBuildQueryCounts = function() {
        var operations = {operations: [createBuildQueryOperation(), createCountOperation()]};
        var onSuccess = function(data) {
            if(!data.limitHit) {
                var total = 0;
                for(var i in data.entityGroups) {
                    total += data.entityGroups[i];
                }
                for(var i in data.edgeGroups) {
                    total += data.edgeGroups[i];
                }
                data.total = total;
            }
            $scope.expandQueryCounts = data;
        }
        $scope.expandQueryCounts = undefined;
        raw.execute(JSON.stringify(operations), onSuccess);
    };

    $scope.executeAll = function() {
        $scope.clearResults();
        $scope.resetBuildQuery();
       for(var i in $scope.operations) {
           raw.execute(JSON.stringify({operations: [$scope.operations[i]]}));
       }
    }

  graph.onGraphElementSelect(function(element){
     $scope.selectedElementTabIndex = 0;
      var _id = element.id();
      for (var id in $scope.graphData.entities) {
            if(_id == id) {
                $scope.selectedEntities[id] = $scope.graphData.entities[id];
                $scope.selectedEntitiesCount = Object.keys($scope.selectedEntities).length;
                updateRelatedEntities();
                updateRelatedEdges();
                if(!$scope.$$phase) {
                    $scope.$apply();
                  }
                return;
            }
        };
      for (var id in $scope.graphData.edges) {
          if(_id == id) {
              $scope.selectedEdges[id] = $scope.graphData.edges[id];
              $scope.selectedEdgesCount = Object.keys($scope.selectedEdges).length;
              if(!$scope.$$phase) {
                  $scope.$apply();
                }
              return;
          }
      };

      $scope.selectedEntities[_id] = [{vertexType: element.data().vertexType, vertex: _id}];
      $scope.selectedEntitiesCount = Object.keys($scope.selectedEntities).length;
      updateRelatedEntities();
      updateRelatedEdges();

      if(!$scope.$$phase) {
        $scope.$apply();
      }
  });

  graph.onGraphElementUnselect(function(element){
      $scope.selectedElementTabIndex = 0;
      if(element.id() in $scope.selectedEntities) {
        delete $scope.selectedEntities[element.id()];
        $scope.selectedEntitiesCount = Object.keys($scope.selectedEntities).length;
        updateRelatedEntities();
        updateRelatedEdges();
      } else if(element.id() in $scope.selectedEdges) {
        delete $scope.selectedEdges[element.id()];
        $scope.selectedEdgesCount = Object.keys($scope.selectedEdges).length;
      }

      $scope.$apply();
  });

  $scope.toggle = function(item, list) {
    var idx = list.indexOf(item);
    if(idx > -1) {
        list.splice(idx, 1);
    } else {
        list.push(item);
    }
  }

  $scope.exists = function(item, list) {
    return list.indexOf(item) > -1;
  }

  $scope.onSelectedPropertyChange = function(group, selectedElement) {
    raw.functions(group, selectedElement.property, function(data) {
        selectedElement.availableFunctions = data
        $scope.$apply();
    });
    selectedElement.function = '';
  }

  $scope.onSelectedFunctionChange = function(group, selectedElement) {
    raw.functionParameters(selectedElement['function'], function(data) {
        selectedElement.availableFunctionParameters = data;
        $scope.$apply();
    });

    var elementDef = raw.schema.entities[group];
    if(!elementDef) {
         elementDef = raw.schema.edges[group];
    }
    var propertyClass = raw.schema.types[elementDef.properties[selectedElement.property]].class;
    if("java.lang.String" !== propertyClass
        && "java.lang.Boolean" !== propertyClass
        && "java.lang.Integer" !== propertyClass) {
        selectedElement.propertyClass = propertyClass;
    }

    selectedElement.parameters = {};
  }

  var switchTabs = function(tabFlag) {
      $scope.showRaw = false;
      $scope.showGraph = false;
      $scope.showResultsTable = false;
      $scope.showSettings = false;
      $scope[tabFlag] = true;
  };

  $scope.openRaw = function() {
     switchTabs('showRaw');
  };

  $scope.openGraph = function() {
      if(!$scope.graphDataGraphLoaded) {
          graph.load()
               .then(function(){
                 $scope.graphDataGraphLoaded = true;
               });
       }
     switchTabs('showGraph');
  };

  $scope.openResultsTable = function() {
    switchTabs('showResultsTable');
  };

  $scope.openSettings = function() {
     switchTabs('showSettings');
  };

  $scope.editOperations = function() {
    $scope.operationsForEdit = [];
    for(var i in $scope.operations) {
        $scope.operationsForEdit.push(JSON.stringify($scope.operations[i], null, 2));
    }
    $scope.editingOperations = true;
  }

  $scope.saveOperations = function() {
      $scope.operations = [];
      for(var i in $scope.operationsForEdit) {
          try {
            $scope.operations.push(JSON.parse($scope.operationsForEdit[i]));
          } catch(e) {
            console.log('Invalid json: ' + $scope.operationsForEdit[i]);
          }
      }
      $scope.editingOperations = false;
   }

  $scope.initialise();
} ]);
<|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  WebView
} from 'react-native';

import Relay from 'react-relay';

Relay.injectNetworkLayer(
  new Relay.DefaultNetworkLayer('http://localhost:3000/graphql')
);

import { Reducer } from 'react-native-router-flux';

import { Router, Scene, Actions } from 'react-native-router-flux';

import RelayComponentRenderer from './RelayComponentRenderer';
import PageOne from './PageOne';
import PageTwo from './PageTwo';

const reducerCreate = params=>{
    const defaultReducer = Reducer(params);
    return (state, action)=>{
        console.log("ACTION:", action);
        return defaultReducer(state, action);
    }
};

class App extends Component {
  render() {
    // return <WebView  source={{uri: 'http://localhost:3000/'}}/>
    return (
      <Router createReducer={reducerCreate} sceneStyle={{flex: 1}} wrapBy={RelayComponentRenderer}>
        <Scene key="root">
          <Scene
            key="pageOne"
            component={PageOne}
            title="PageOne"
            initial={true}
            queries={{viewer: () => Relay.QL`query { viewer } `,}}
          />

          <Scene
            key="pageTwo"
            component={PageTwo}
            title="PageTwo"
            queries={{node: () => Relay.QL`query { node(id: $nodeID) } `,}}
          />

        </Scene>
      </Router>
    )
  }
}

export default () => {
  return (
    <View style={styles.container}>
      <App />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'stretch',
    backgroundColor: '#F5FCFF',
    borderWidth: 1,
  },
});
<commit_msg>Not needed style removed<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  WebView
} from 'react-native';

import Relay from 'react-relay';

Relay.injectNetworkLayer(
  new Relay.DefaultNetworkLayer('http://localhost:3000/graphql')
);

import { Reducer } from 'react-native-router-flux';

import { Router, Scene, Actions } from 'react-native-router-flux';

import RelayComponentRenderer from './RelayComponentRenderer';
import PageOne from './PageOne';
import PageTwo from './PageTwo';

const reducerCreate = params=>{
    const defaultReducer = Reducer(params);
    return (state, action)=>{
        console.log("ACTION:", action);
        return defaultReducer(state, action);
    }
};

class App extends Component {
  render() {
    // return <WebView  source={{uri: 'http://localhost:3000/'}}/>
    return (
      <Router createReducer={reducerCreate} sceneStyle={{flex: 1}} wrapBy={RelayComponentRenderer}>
        <Scene key="root">
          <Scene
            key="pageOne"
            component={PageOne}
            title="PageOne"
            initial={true}
            queries={{viewer: () => Relay.QL`query { viewer } `,}}
          />

          <Scene
            key="pageTwo"
            component={PageTwo}
            title="PageTwo"
            queries={{node: () => Relay.QL`query { node(id: $nodeID) } `,}}
          />

        </Scene>
      </Router>
    )
  }
}

export default () => {
  return (
    <View style={styles.container}>
      <App />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'stretch',
    backgroundColor: '#F5FCFF',
  },
});
<|endoftext|>