<commit_before>var mongoose = require('../libs/mongoose');
var pagebysizeModel = require('../models/pagebysize').data;
var Module = require('../models/module').Module;
var Page = require('../models/page').Page;
var log = require('../libs/log')(module);
var persons = require('./persons');

exports.getData = function (req, res) {
    parsePages(function (err, data) {
        if (err) throw err;
        res.json(data);
    });
};

function isDeveloper(name) {
    if (persons.isDeveloper(name)) {
            return true;
    }
    if(name == 'Valentine Zhuck' ||
        name == 'Dzmitry Tabolich' ||
        name == 'Heorhi Vilkitski') {
        return true;
    }
//    log.info("---###---" + name);
    return false;
}

function parsePages(callback) {
    var model = new pagebysizeModel();
    for (var k = 0; k < model.data.length; k++) {
        var team = model.data[k];
        team.data = [];
    }
    //1. grab all pages
    Page.find({}).exec(function (err, pages) {
        for (var i = 0; i < pages.length; i++) {
            var page = pages[i];

            if(page.devFinished == undefined) {
                continue;
            }
            var dateDevFinished = page.devFinished == undefined ? new Date(Date.parse(page.updated)).getTime() : new Date(Date.parse(page.devFinished)).getTime();
//            var dateQaFinished = new Date(Date.parse(page.qaFinished)).getTime();
            var pageSize = getPageSize(page.labels);
            var timeSpent = 0;
            //calc time spent
            for (var j = 0; j < page.worklogHistory.length; j++) {
                var worklog = page.worklogHistory[j];
                if(isDeveloper(worklog.person)) {
                    timeSpent += parseFloat(worklog.timeSpent);
                }
            }
            if(timeSpent > 0 ||
                page.status == 'Ready for QA' ||
                page.status == "Testing in Progress" ||
                page.status == "Resolved" ||
                page.status == "Closed"
                ) {
                putDataPoint(model, pageSize, dateDevFinished, timeSpent, page);
            }
        }

        //2. sort
        for (var k = 0; k < model.data.length; k++) {
            var team = model.data[k];
            team.data.sort(function (a, b) {
                a = new Date(a.x);
                b = new Date(b.x);
                return a > b ? 1 : a < b ? -1 : 0;
            });
        }
        callback(err, model);
    })
}

function getTeamName(labels) {
    var index = labels.indexOf("Team");
    if(index < 0) {
        return "";
    }
    var index2 = labels.indexOf(',', index);
    if(index2 < 0) {
        index2 = labels.length;
    }

    return labels.substring(index+4,index2);
}

function getPageSize(labels) {
    if (labels.indexOf("PageSizeSmall") > -1)
        return "Small";
    if (labels.indexOf("PageSizeMedium") > -1)
        return "Medium";
    if (labels.indexOf("PageSizeLargePlus") > -1)
        return "LargePlus";
    if (labels.indexOf("PageSizeLarge") > -1)
        return "Large";
    if (labels.indexOf("PageSizeExtraLarge") > -1)
        return "ExtraLarge";
    if (labels.indexOf("PageSizeXXL") > -1)
        return "XXL";
    if (labels.indexOf("PageSizeXXXL") > -1)
        return "XXXL";
}

function putDataPoint(model, pageSize, dateDevFinished, timeSpent, page) {
    for (var k = 0; k < model.data.length; k++) {
        var size = model.data[k];
        if (size.name == pageSize) {
            size.data.push({
                x: dateDevFinished,
                y: timeSpent,
                tooltip: page.key + ' - ' + timeSpent.toFixed(2) + 'h - ' + getTeamName(page.labels) });
            return;
        }
    }
}
<commit_msg>added check for dismissed developers<commit_after>var mongoose = require('../libs/mongoose');
var pagebysizeModel = require('../models/pagebysize').data;
var Module = require('../models/module').Module;
var Page = require('../models/page').Page;
var log = require('../libs/log')(module);
var persons = require('./persons');

exports.getData = function (req, res) {
    parsePages(function (err, data) {
        if (err) throw err;
        res.json(data);
    });
};

function isDeveloper(name) {
    if (persons.isDeveloper(name)) {
            return true;
    }
    if(name == 'Valentine Zhuck' ||
        name == 'Dzmitry Tabolich' ||
        name == 'Heorhi Vilkitski' ||
        name == "Hanna Kastsian" ||
        name == "Alena Charnova" ||
        name == "Aliaksei Astashkin" ||
        name == "yauheni_lohinau" ||
        name == "Dmytro Komar" ||
        name == undefined) {
        return true;
    }
    return false;
}

function parsePages(callback) {
    var model = new pagebysizeModel();
    for (var k = 0; k < model.data.length; k++) {
        var team = model.data[k];
        team.data = [];
    }
    //1. grab all pages
    Page.find({}).exec(function (err, pages) {
        for (var i = 0; i < pages.length; i++) {
            var page = pages[i];

            if(page.devFinished == undefined) {
                continue;
            }
            var dateDevFinished = page.devFinished == undefined ? new Date(Date.parse(page.updated)).getTime() : new Date(Date.parse(page.devFinished)).getTime();
//            var dateQaFinished = new Date(Date.parse(page.qaFinished)).getTime();
            var pageSize = getPageSize(page.labels);
            var timeSpent = 0;
            //calc time spent
            for (var j = 0; j < page.worklogHistory.length; j++) {
                var worklog = page.worklogHistory[j];
                if(isDeveloper(worklog.person)) {
                    timeSpent += parseFloat(worklog.timeSpent);
                }
            }
            if(timeSpent > 0 ||
                page.status == 'Ready for QA' ||
                page.status == "Testing in Progress" ||
                page.status == "Resolved" ||
                page.status == "Closed"
                ) {
                putDataPoint(model, pageSize, dateDevFinished, timeSpent, page);
            }
        }

        //2. sort
        for (var k = 0; k < model.data.length; k++) {
            var team = model.data[k];
            team.data.sort(function (a, b) {
                a = new Date(a.x);
                b = new Date(b.x);
                return a > b ? 1 : a < b ? -1 : 0;
            });
        }
        callback(err, model);
    })
}

function getTeamName(labels) {
    var index = labels.indexOf("Team");
    if(index < 0) {
        return "";
    }
    var index2 = labels.indexOf(',', index);
    if(index2 < 0) {
        index2 = labels.length;
    }

    return labels.substring(index+4,index2);
}

function getPageSize(labels) {
    if (labels.indexOf("PageSizeSmall") > -1)
        return "Small";
    if (labels.indexOf("PageSizeMedium") > -1)
        return "Medium";
    if (labels.indexOf("PageSizeLargePlus") > -1)
        return "LargePlus";
    if (labels.indexOf("PageSizeLarge") > -1)
        return "Large";
    if (labels.indexOf("PageSizeExtraLarge") > -1)
        return "ExtraLarge";
    if (labels.indexOf("PageSizeXXL") > -1)
        return "XXL";
    if (labels.indexOf("PageSizeXXXL") > -1)
        return "XXXL";
}

function putDataPoint(model, pageSize, dateDevFinished, timeSpent, page) {
    for (var k = 0; k < model.data.length; k++) {
        var size = model.data[k];
        if (size.name == pageSize) {
            size.data.push({
                x: dateDevFinished,
                y: timeSpent,
                tooltip: page.key + ' - ' + timeSpent.toFixed(2) + 'h - ' + getTeamName(page.labels) });
            return;
        }
    }
}
<|endoftext|>


<commit_before>
v.module.whois = (config) => {

  var state = {
    known: [],
    backers: [],
    online: {
      known: [],
      unknown: []
    },
    all: []
  }

  var get = () =>
    Promise.all([
      m.request({
        method: 'GET',
        url: config.api.known
      }),
      m.request({
        method: 'GET',
        url: config.api.backers
      }),
      m.request({
        method: 'GET',
        url: config.api.online
      }),
    ])
    .then((data) => ({
      known: data[0],
      backers: data[1],
      online: data[2],
    }))

  var known = ({known, backers, online}) =>
    known
      .map(({id, name, gravatar, backer, twitter, github}) => ({
        id,
        name,
        gravatar,
        avatar: 'https://gravatar.com/avatar/' + gravatar +
          '?size=48&d=monsterid',
        online: online.known.includes(id),
        backer: backers.find((s) => s.name === backer),
        twitter,
        github
      }))

  var missing = ({known, backers}) =>
    (
      (
        names = known
          .map((member) => member.backer)
      ) =>
      backers
        .filter((backer) => !names.includes(backer.name))
        .map((backer) => ({
          name: backer.name,
          backer
        }))
    )()

  var filter = {
    all: (known) =>
      known
        .sort((a, b) => (a.name > b.name ? 1 : a.name < b.name ? -1 : 0)),

    online: (known) =>
      known
        .filter((known) => known.online)
        .sort((a, b) => (a.name > b.name ? 1 : a.name < b.name ? -1 : 0)),

    backers: (known, missing) =>
      known
        .filter((known) => known.backer)
        .concat(missing)
        .sort((a, b) => (b.backer.average - a.backer.average)),

    unknown: (unknown) =>
      unknown
        .map((device) => ({
          name: device.host,
          vendor: device.vendor,
          icon: /android|i?phone/i.test(device.host) ? 'smartphone' : 'laptop'
        }))
  }

  var sort = (devices) => {
    var phones = devices
      .filter((device) => device.host && /android|i?phone/i.test(device.host))
      .sort((a, b) => (
        a.host.toLowerCase() > b.host.toLowerCase() ? 1 :
        a.host.toLowerCase() < b.host.toLowerCase() ? -1 : 0))

    var other = devices
      .filter((device) => device.host && !/android|i?phone/i.test(device.host))
      .sort((a, b) => (
        a.host.toLowerCase() > b.host.toLowerCase() ? 1 :
        a.host.toLowerCase() < b.host.toLowerCase() ? -1 : 0))

    var nohost = devices.filter((device) => !device.host)

    return phones.concat(other).concat(nohost)
  }

  return {get, known, missing, filter, sort}
}
<commit_msg>Add timeout for the whois online request<commit_after>
v.module.whois = (config) => {

  var state = {
    known: [],
    backers: [],
    online: {
      known: [],
      unknown: []
    },
    all: []
  }

  var get = () =>
    Promise.all([
      m.request({
        method: 'GET',
        url: config.api.known
      }),
      m.request({
        method: 'GET',
        url: config.api.backers
      }),
      Promise.race([
        m.request({
          method: 'GET',
          url: config.api.online
        }),
        new Promise((resolve, reject) => {
          setTimeout(() => resolve({known: [], unknown: []}), 2500)
        })
      ])
    ])
    .then((data) => ({
      known: data[0] || [],
      backers: data[1] || [],
      online: data[2] || {known: [], unknown: []},
    }))

  var known = ({known, backers, online}) =>
    known
      .map(({id, name, gravatar, backer, twitter, github}) => ({
        id,
        name,
        gravatar,
        avatar: 'https://gravatar.com/avatar/' + gravatar +
          '?size=48&d=monsterid',
        online: online.known.includes(id),
        backer: backers.find((s) => s.name === backer),
        twitter,
        github
      }))

  var missing = ({known, backers}) =>
    (
      (
        names = known
          .map((member) => member.backer)
      ) =>
      backers
        .filter((backer) => !names.includes(backer.name))
        .map((backer) => ({
          name: backer.name,
          backer
        }))
    )()

  var filter = {
    all: (known) =>
      known
        .sort((a, b) => (a.name > b.name ? 1 : a.name < b.name ? -1 : 0)),

    online: (known) =>
      known
        .filter((known) => known.online)
        .sort((a, b) => (a.name > b.name ? 1 : a.name < b.name ? -1 : 0)),

    backers: (known, missing) =>
      known
        .filter((known) => known.backer)
        .concat(missing)
        .sort((a, b) => (b.backer.average - a.backer.average)),

    unknown: (unknown) =>
      unknown
        .map((device) => ({
          name: device.host,
          vendor: device.vendor,
          icon: /android|i?phone/i.test(device.host) ? 'smartphone' : 'laptop'
        }))
  }

  var sort = (devices) => {
    var phones = devices
      .filter((device) => device.host && /android|i?phone/i.test(device.host))
      .sort((a, b) => (
        a.host.toLowerCase() > b.host.toLowerCase() ? 1 :
        a.host.toLowerCase() < b.host.toLowerCase() ? -1 : 0))

    var other = devices
      .filter((device) => device.host && !/android|i?phone/i.test(device.host))
      .sort((a, b) => (
        a.host.toLowerCase() > b.host.toLowerCase() ? 1 :
        a.host.toLowerCase() < b.host.toLowerCase() ? -1 : 0))

    var nohost = devices.filter((device) => !device.host)

    return phones.concat(other).concat(nohost)
  }

  return {get, known, missing, filter, sort}
}
<|endoftext|>


<commit_before>(function(Cosmos, window) {

Cosmos.mixins.AnimationLoop = {
  /**
   * Simple API for running a callback at 60fps. The callback receives a
   * *frames* argument which is equal to the number of frames passed since the
   * last call. Ideally, if the browser performs seamlessly the *frames* will
   * always be `1`. However, when the browser lags behind the value will
   * increase, akin to a frame-skipping mechanism. This way you can use the
   * *frames* value as a multiplier for a transition step.
   *
   * A requestAnimationFrame>setTimeout polyfill is used for the callbacks.
   *
   * TODO: shouldComponentUpdate should return false when only
   * state.animationRequestId changed
   */
  startAnimationLoop: function() {
    // Prevent running more callbacks at the same time
    this.stopAnimationLoop();
    this._nextFrame();
  },
  stopAnimationLoop: function() {
    this._clearAnimation();
    this.setState({animationRequestId: null});
  },
  componentDidMount: function() {
    this._loadAnimationState(this.state);
  },
  componentWillReceiveProps: function(nextProps) {
    // This is a feature that only works in conjunction with the PersistState
    // mixin. Animations will be resumed or stopped based on previous states
    // loaded using setProps({state: ...})
    if (nextProps.state) {
      this._loadAnimationState(nextProps.state);
    }
  },
  componentWillUnmount: function() {
    this._clearAnimation();
  },
  _loadAnimationState: function(state) {
    // If the Component state had an on-going animation it will resume as soon
    // as a Component is mounted with the same state.
    // If the Componene state had a stopped animation it will stop any current
    // animation when overwriting state
    if (state && state.animationRequestId !== undefined) {
      if (state.animationRequestId) {
        this.startAnimationLoop();
      } else {
        this.stopAnimationLoop();
      }
    }
  },
  _nextFrame: function() {
    this._prevTime = Date.now();
    this.setState({
      // Keep a reference to the animation request for two reasons:
      // - To be able to clear it on stopAnimationLoop()
      // - To be reflected in the state of the Component, which will resume
      //   animating when loaded in a mounting Component later on
      animationRequestId: requestAnimationFrame(this._animationCallback)
    });
  },
  _clearAnimation: function() {
    if (this.state && this.state.animationRequestId) {
      cancelAnimationFrame(this.state.animationRequestId);
    }
  },
  _animationCallback: function() {
    if (typeof(this.onFrame) != 'function') {
      return;
    }
    var now = Date.now(),
        timePassed = now - this._prevTime,
        timeExpected = 1000 / 60;

    this.onFrame(timePassed / timeExpected);
    this._nextFrame();
  }
};

// Polyfill inspired by Paul Irish
// http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
var requestAnimationFrame =
  window.requestAnimationFrame ||
  window.webkitRequestAnimationFrame ||
  window.mozRequestAnimationFrame ||
  function(callback) {
    return window.setTimeout(callback, 1000 / 60);
  };

var cancelAnimationFrame =
  window.cancelAnimationFrame ||
  window.webkitCancelAnimationFrame ||
  window.mozCancelAnimationFrame ||
  function(requestId) {
    window.clearTimeout(requestId);
  };

})(Cosmos, window);
<commit_msg>Refactor AnimationLoop mixin for less state changes #35<commit_after>(function(Cosmos, window) {

Cosmos.mixins.AnimationLoop = {
  /**
   * Simple API for running a callback at 60fps. The callback receives a
   * *frames* argument which is equal to the number of frames passed since the
   * last call. Ideally, if the browser performs seamlessly the *frames* will
   * always be `1`. However, when the browser lags behind the value will
   * increase, akin to a frame-skipping mechanism. This way you can use the
   * *frames* value as a multiplier for a transition step.
   *
   * A requestAnimationFrame>setTimeout polyfill is used for the callbacks.
   */
  startAnimationLoop: function() {
    // Prevent running more callbacks at the same time
    this._clearAnimation();
    this._nextFrame();
    this.setState({animationLoopRunning: true});
  },
  stopAnimationLoop: function() {
    this._clearAnimation();
    this.setState({animationLoopRunning: false});
  },
  componentDidMount: function() {
    this._loadAnimationState(this.state);
  },
  componentWillReceiveProps: function(nextProps) {
    // This is a feature that only works in conjunction with the PersistState
    // mixin. Animations will be resumed or stopped based on previous states
    // loaded using setProps({state: ...})
    if (nextProps.state) {
      this._loadAnimationState(nextProps.state);
    }
  },
  componentWillUnmount: function() {
    this._clearAnimation();
  },
  _loadAnimationState: function(state) {
    // If the Component state had an on-going animation it will resume as soon
    // as a Component is mounted with the same state.
    // If the Componene state had a stopped animation it will stop any current
    // animation when overwriting state
    if (state && state.animationLoopRunning !== undefined) {
      if (state.animationLoopRunning) {
        this.startAnimationLoop();
      } else {
        this.stopAnimationLoop();
      }
    }
  },
  _nextFrame: function() {
    this._prevTime = Date.now();
    // Keep a reference to the animation request to be able to clear it on
    // stopAnimationLoop()
    this._animationRequestId = requestAnimationFrame(this._animationCallback);
  },
  _clearAnimation: function() {
    if (this._animationRequestId) {
      cancelAnimationFrame(this._animationRequestId);
      this._animationRequestId = null;
    }
  },
  _animationCallback: function() {
    if (typeof(this.onFrame) != 'function') {
      return;
    }
    var now = Date.now(),
        timePassed = now - this._prevTime,
        timeExpected = 1000 / 60;
    this.onFrame(timePassed / timeExpected);

    // Sometimes the next frame is still called even after it was canceled, so
    // we need to make sure we don't continue with the animation loop
    if (this._animationRequestId) {
      this._nextFrame();
    }
  }
};

// Polyfill inspired by Paul Irish
// http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
var requestAnimationFrame =
  window.requestAnimationFrame ||
  window.webkitRequestAnimationFrame ||
  window.mozRequestAnimationFrame ||
  function(callback) {
    return window.setTimeout(callback, 1000 / 60);
  };

var cancelAnimationFrame =
  window.cancelAnimationFrame ||
  window.webkitCancelAnimationFrame ||
  window.mozCancelAnimationFrame ||
  function(requestId) {
    window.clearTimeout(requestId);
  };

})(Cosmos, window);
<|endoftext|>


<commit_before>define([
  "dojo",
  "dijit",
  "dojox",
  "dojox/mobile/RoundRectList"], function(dojo, dijit, dojox){
	// module:
	//		dojox/mobile/EdgeToEdgeList
	// summary:
	//		TODOC

dojo.declare(
	"dojox.mobile.EdgeToEdgeList",
	dojox.mobile.RoundRectList,
{
	stateful: false, // keep the selection state or not
	buildRendering: function(){
		this.inherited(arguments);
		this.domNode.className = "mblEdgeToEdgeList";
	}
});

return dojox.mobile.EdgeToEdgeList;
});
<commit_msg>Fixes #12771 !strict. Added support for programmatic instantiation.<commit_after>define([
  "dojo",
  "dijit",
  "dojox",
  "dojox/mobile/RoundRectList"], function(dojo, dijit, dojox){
	// module:
	//		dojox/mobile/EdgeToEdgeList
	// summary:
	//		TODOC

dojo.declare(
	"dojox.mobile.EdgeToEdgeList",
	dojox.mobile.RoundRectList,
{
	stateful: false, // keep the selection state or not
	buildRendering: function(){
		this.inherited(arguments);
		this.domNode.className = "mblEdgeToEdgeList";
	},

	_setStatefulAttr: function(stateful){
		this.stateful = stateful;
		dojo.forEach(this.getChildren(), function(child){
			child.setArrow && child.setArrow();
		});
	},

	deselect: function(/*ListItem*/item){
		item.deselect();
	},

	deselectAll: function(){
		dojo.forEach(this.getChildren(), function(child){
			child.deselect && child.deselect();
		});
	},

	select: function(/*ListItem*/item){
		item.select();
	}
});

return dojox.mobile.EdgeToEdgeList;
});
<|endoftext|>


<commit_before><commit_msg>Don't double undo/redo when in normal inputs.<commit_after><|endoftext|>


<commit_before><commit_msg>Searching by talkgroup and radio id now works<commit_after><|endoftext|>


<commit_before><commit_msg>Testing mark.js<commit_after><|endoftext|>


<commit_before><commit_msg>modified menu by deleting 'position' property as it is not in the Ensembl json<commit_after><|endoftext|>


<commit_before>var style = {
  section: {
    paddingTop: 24,
    paddingBottom: 0,
    fontSize: 24,
    fontWeight: 300,
    cursor: 'pointer'
  },
  sectionHr: {
    border: 'none',
    height: '1px',
    backgroundColor: 'rgba(0, 0, 0, 0.15)',
    marginLeft: '-10px',
    width: 'calc(100% + 20px)'
  },
  sectionEnd: {
    height: 30
  },
  content: {
    //overflow: 'hidden',
    display: (props) => {
      if (props.bauhaus._state.folded === true) {
        return 'none'
      }
      return 'initial'
    }
  }
/*
overflow: hidden
max-height: 72px
transition: ease 0.3s
transform: scaleY(0)
transform: scaleY(1)
transform-origin: top

*/
}
export default style
<commit_msg>Section folding fix<commit_after>var style = {
  section: {
    paddingTop: 24,
    paddingBottom: 0,
    fontSize: 24,
    fontWeight: 300,
    cursor: 'pointer'
  },
  sectionHr: {
    border: 'none',
    height: '1px',
    backgroundColor: 'rgba(0, 0, 0, 0.15)',
    marginLeft: '-10px',
    width: 'calc(100% + 20px)'
  },
  sectionEnd: {
    height: 30
  },
  content: {
    //overflow: 'hidden',
    display: (props, state) => {
      if (state.folded === true) {
        return 'none'
      }
      return 'initial'
    }
  }
/*
overflow: hidden
max-height: 72px
transition: ease 0.3s
transform: scaleY(0)
transform: scaleY(1)
transform-origin: top

*/
}
export default style
<|endoftext|>


<commit_before>"use strict";

var CityTour = CityTour || {};
CityTour.Scene = CityTour.Scene || {};

CityTour.Scene.Builder = function() {
  var SKY_COLOR = new THREE.Color(0x66ccff);

  var buildEmptyScene = function() {
    var scene, light, directionalLight;

    scene = new THREE.Scene();
    scene.background = SKY_COLOR;

    light = new THREE.HemisphereLight(0xffffff, 0xffffff, 1);
    light.position.set( 0, 500, 0 );
    scene.add(light);

    directionalLight = new THREE.DirectionalLight(0xffffff, 1.0);
    directionalLight.position.set(-1, 0.9, 0.9);
    scene.add(directionalLight);

    return scene;
  };

  var buildTerrainMeshes = function(terrain, roadNetwork) {
    var terrainMeshes = CityTour.Scene.TerrainMeshBuilder().build(terrain, roadNetwork);
    var terrainGroup = new THREE.Group();
    terrainGroup.name = "terrainMeshes";

    terrainMeshes.forEach(function(mesh) {
      terrainGroup.add(mesh);
    });

    return terrainGroup;
  };

  var buildRoadNetworkMeshes = function(terrain, roadNetwork) {
    var roadNetworkMeshes = CityTour.Scene.RoadMeshBuilder().build(terrain, roadNetwork);
    var roadNetworkGroup = new THREE.Group();
    roadNetworkGroup.name = "roadNetworkMeshes";

    roadNetworkMeshes.forEach(function(mesh) {
      roadNetworkGroup.add(mesh);
    });

    return roadNetworkGroup;
  };

  var buildBuildingMeshes = function(buildings, roadNetwork) {
    var buildingMeshes;
    var buildingsGroup = new THREE.Group();
    buildingsGroup.name = "buildingMeshes";

    buildingMeshes = new CityTour.Scene.BuildingMeshBuilder().build(buildings, roadNetwork);

    buildingMeshes.forEach(function(mesh) {
      buildingsGroup.add(mesh);
    });

    return buildingsGroup;
  };

  return {
    buildEmptyScene: buildEmptyScene,
    buildTerrainMeshes: buildTerrainMeshes,
    buildRoadNetworkMeshes: buildRoadNetworkMeshes,
    buildBuildingMeshes: buildBuildingMeshes,
  };
};
<commit_msg>Extracting function to remove duplicated code<commit_after>"use strict";

var CityTour = CityTour || {};
CityTour.Scene = CityTour.Scene || {};

CityTour.Scene.Builder = function() {
  var SKY_COLOR = new THREE.Color(0x66ccff);

  var buildEmptyScene = function() {
    var scene, light, directionalLight;

    scene = new THREE.Scene();
    scene.background = SKY_COLOR;

    light = new THREE.HemisphereLight(0xffffff, 0xffffff, 1);
    light.position.set( 0, 500, 0 );
    scene.add(light);

    directionalLight = new THREE.DirectionalLight(0xffffff, 1.0);
    directionalLight.position.set(-1, 0.9, 0.9);
    scene.add(directionalLight);

    return scene;
  };

  var buildMeshGroup = function(groupName, meshes) {
    var group = new THREE.Group();
    group.name = groupName;

    meshes.forEach(function(mesh) {
      group.add(mesh);
    });

    return group;
  };

  var buildTerrainMeshes = function(terrain, roadNetwork) {
    return buildMeshGroup("terrainMeshes", CityTour.Scene.TerrainMeshBuilder().build(terrain, roadNetwork));
  };

  var buildRoadNetworkMeshes = function(terrain, roadNetwork) {
    return buildMeshGroup("roadNetworkMeshes", CityTour.Scene.RoadMeshBuilder().build(terrain, roadNetwork));
  };

  var buildBuildingMeshes = function(buildings, roadNetwork) {
    return buildMeshGroup("buildingMeshes", CityTour.Scene.BuildingMeshBuilder().build(buildings, roadNetwork));
  };

  return {
    buildEmptyScene: buildEmptyScene,
    buildTerrainMeshes: buildTerrainMeshes,
    buildRoadNetworkMeshes: buildRoadNetworkMeshes,
    buildBuildingMeshes: buildBuildingMeshes,
  };
};
<|endoftext|>


<commit_before>// Adds compile-time JS functions to augment the CanvasKit interface.
// Specifically, anything that should only be on the GPU version of canvaskit.
// Functions in this file are supplemented by cpu.js.
(function(CanvasKit){
    CanvasKit._extraInitializations = CanvasKit._extraInitializations || [];
    CanvasKit._extraInitializations.push(function() {
      function get(obj, attr, defaultValue) {
        if (obj && obj.hasOwnProperty(attr)) {
          return obj[attr];
        }
        return defaultValue;
      }

      CanvasKit.GetWebGLContext = function(canvas, attrs) {
        if (!canvas) {
          throw 'null canvas passed into makeWebGLContext';
        }
        var contextAttributes = {
          'alpha': get(attrs, 'alpha', 1),
          'depth': get(attrs, 'depth', 1),
          'stencil': get(attrs, 'stencil', 8),
          'antialias': get(attrs, 'antialias', 0),
          'premultipliedAlpha': get(attrs, 'premultipliedAlpha', 1),
          'preserveDrawingBuffer': get(attrs, 'preserveDrawingBuffer', 0),
          'preferLowPowerToHighPerformance': get(attrs, 'preferLowPowerToHighPerformance', 0),
          'failIfMajorPerformanceCaveat': get(attrs, 'failIfMajorPerformanceCaveat', 0),
          'enableExtensionsByDefault': get(attrs, 'enableExtensionsByDefault', 1),
          'explicitSwapControl': get(attrs, 'explicitSwapControl', 0),
          'renderViaOffscreenBackBuffer': get(attrs, 'renderViaOffscreenBackBuffer', 0),
        };

        if (attrs && attrs['majorVersion']) {
          contextAttributes['majorVersion'] = attrs['majorVersion']
        } else {
          // Default to WebGL 2 if available and not specified.
          contextAttributes['majorVersion'] = (typeof WebGL2RenderingContext !== 'undefined') ? 2 : 1;
        }

        // This check is from the emscripten version
        if (contextAttributes['explicitSwapControl']) {
          throw 'explicitSwapControl is not supported';
        }
        // Creates a WebGL context and sets it to be the current context.
        // These functions are defined in emscripten's library_webgl.js
        var handle = GL.createContext(canvas, contextAttributes);
        if (!handle) {
          return 0;
        }
        GL.makeContextCurrent(handle);
        return handle;
      }

      // idOrElement can be of types:
      //  - String - in which case it is interpreted as an id of a
      //          canvas element.
      //  - HTMLCanvasElement - in which the provided canvas element will
      //          be used directly.
      // colorSpace - sk_sp<SkColorSpace> - one of the supported color spaces:
      //          CanvasKit.SkColorSpace.SRGB
      //          CanvasKit.SkColorSpace.DISPLAY_P3
      //          CanvasKit.SkColorSpace.ADOBE_RGB
      CanvasKit.MakeWebGLCanvasSurface = function(idOrElement, colorSpace, attrs) {
        colorSpace = colorSpace || null;
        var canvas = idOrElement;
        var isHTMLCanvas = typeof HTMLCanvasElement !== 'undefined' && canvas instanceof HTMLCanvasElement;
        var isOffscreenCanvas = canvas instanceof OffscreenCanvas;
        if (!isHTMLCanvas && !isOffscreenCanvas) {
          canvas = document.getElementById(idOrElement);
          if (!canvas) {
            throw 'Canvas with id ' + idOrElement + ' was not found';
          }
        }

        var ctx = this.GetWebGLContext(canvas, attrs);
        var openGLversion = canvas.GLctxObject.version;

        if (!ctx || ctx < 0) {
          throw 'failed to create webgl context: err ' + ctx;
        }

        var grcontext = this.MakeGrContext(ctx);

        // Note that canvas.width/height here is used because it gives the size of the buffer we're
        // rendering into. This may not be the same size the element is displayed on the page, which
        // constrolled by css, and available in canvas.clientWidth/height.
        var surface = this.MakeOnScreenGLSurface(grcontext, canvas.width, canvas.height, colorSpace);
        if (!surface) {
          SkDebug('falling back from GPU implementation to a SW based one');
          // we need to throw away the old canvas (which was locked to
          // a webGL context) and create a new one so we can
          var newCanvas = canvas.cloneNode(true);
          var parent = canvas.parentNode;
          parent.replaceChild(newCanvas, canvas);
          // add a class so the user can detect that it was replaced.
          newCanvas.classList.add('ck-replaced');

          return CanvasKit.MakeSWCanvasSurface(newCanvas);
        }
        surface._context = ctx;
        surface.grContext = grcontext;
        surface.openGLversion = openGLversion;
        return surface;
      };
      // Default to trying WebGL first.
      CanvasKit.MakeCanvasSurface = CanvasKit.MakeWebGLCanvasSurface;
    });
}(Module)); // When this file is loaded in, the high level object is "Module";
<commit_msg>[canvaskit] Fix for OffscreenCanvas-unaware browsers<commit_after>// Adds compile-time JS functions to augment the CanvasKit interface.
// Specifically, anything that should only be on the GPU version of canvaskit.
// Functions in this file are supplemented by cpu.js.
(function(CanvasKit){
    CanvasKit._extraInitializations = CanvasKit._extraInitializations || [];
    CanvasKit._extraInitializations.push(function() {
      function get(obj, attr, defaultValue) {
        if (obj && obj.hasOwnProperty(attr)) {
          return obj[attr];
        }
        return defaultValue;
      }

      CanvasKit.GetWebGLContext = function(canvas, attrs) {
        if (!canvas) {
          throw 'null canvas passed into makeWebGLContext';
        }
        var contextAttributes = {
          'alpha': get(attrs, 'alpha', 1),
          'depth': get(attrs, 'depth', 1),
          'stencil': get(attrs, 'stencil', 8),
          'antialias': get(attrs, 'antialias', 0),
          'premultipliedAlpha': get(attrs, 'premultipliedAlpha', 1),
          'preserveDrawingBuffer': get(attrs, 'preserveDrawingBuffer', 0),
          'preferLowPowerToHighPerformance': get(attrs, 'preferLowPowerToHighPerformance', 0),
          'failIfMajorPerformanceCaveat': get(attrs, 'failIfMajorPerformanceCaveat', 0),
          'enableExtensionsByDefault': get(attrs, 'enableExtensionsByDefault', 1),
          'explicitSwapControl': get(attrs, 'explicitSwapControl', 0),
          'renderViaOffscreenBackBuffer': get(attrs, 'renderViaOffscreenBackBuffer', 0),
        };

        if (attrs && attrs['majorVersion']) {
          contextAttributes['majorVersion'] = attrs['majorVersion']
        } else {
          // Default to WebGL 2 if available and not specified.
          contextAttributes['majorVersion'] = (typeof WebGL2RenderingContext !== 'undefined') ? 2 : 1;
        }

        // This check is from the emscripten version
        if (contextAttributes['explicitSwapControl']) {
          throw 'explicitSwapControl is not supported';
        }
        // Creates a WebGL context and sets it to be the current context.
        // These functions are defined in emscripten's library_webgl.js
        var handle = GL.createContext(canvas, contextAttributes);
        if (!handle) {
          return 0;
        }
        GL.makeContextCurrent(handle);
        return handle;
      }

      // idOrElement can be of types:
      //  - String - in which case it is interpreted as an id of a
      //          canvas element.
      //  - HTMLCanvasElement - in which the provided canvas element will
      //          be used directly.
      // colorSpace - sk_sp<SkColorSpace> - one of the supported color spaces:
      //          CanvasKit.SkColorSpace.SRGB
      //          CanvasKit.SkColorSpace.DISPLAY_P3
      //          CanvasKit.SkColorSpace.ADOBE_RGB
      CanvasKit.MakeWebGLCanvasSurface = function(idOrElement, colorSpace, attrs) {
        colorSpace = colorSpace || null;
        var canvas = idOrElement;
        var isHTMLCanvas = typeof HTMLCanvasElement !== 'undefined' && canvas instanceof HTMLCanvasElement;
        var isOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas;
        if (!isHTMLCanvas && !isOffscreenCanvas) {
          canvas = document.getElementById(idOrElement);
          if (!canvas) {
            throw 'Canvas with id ' + idOrElement + ' was not found';
          }
        }

        var ctx = this.GetWebGLContext(canvas, attrs);
        var openGLversion = canvas.GLctxObject.version;

        if (!ctx || ctx < 0) {
          throw 'failed to create webgl context: err ' + ctx;
        }

        var grcontext = this.MakeGrContext(ctx);

        // Note that canvas.width/height here is used because it gives the size of the buffer we're
        // rendering into. This may not be the same size the element is displayed on the page, which
        // constrolled by css, and available in canvas.clientWidth/height.
        var surface = this.MakeOnScreenGLSurface(grcontext, canvas.width, canvas.height, colorSpace);
        if (!surface) {
          SkDebug('falling back from GPU implementation to a SW based one');
          // we need to throw away the old canvas (which was locked to
          // a webGL context) and create a new one so we can
          var newCanvas = canvas.cloneNode(true);
          var parent = canvas.parentNode;
          parent.replaceChild(newCanvas, canvas);
          // add a class so the user can detect that it was replaced.
          newCanvas.classList.add('ck-replaced');

          return CanvasKit.MakeSWCanvasSurface(newCanvas);
        }
        surface._context = ctx;
        surface.grContext = grcontext;
        surface.openGLversion = openGLversion;
        return surface;
      };
      // Default to trying WebGL first.
      CanvasKit.MakeCanvasSurface = CanvasKit.MakeWebGLCanvasSurface;
    });
}(Module)); // When this file is loaded in, the high level object is "Module";
<|endoftext|>


<commit_before><commit_msg>Don't redirect to reference autocomplete box on whitespace<commit_after><|endoftext|>


<commit_before>/**
 * Appcelerator Titanium Mobile
 * Copyright (c) 2012 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

var PersistentHandle = require('ui').PersistentHandle;

var TAG = "TabGroup";

exports.bootstrap = function(Titanium) {

	var TabGroup = Titanium.UI.TabGroup;

	// Set constants for representing states for the tab group
	TabGroup.prototype.state = {closed: 0, opening: 1, opened: 2};

	function createTabGroup(scopeVars, options) {
		var tabGroup = new TabGroup(options);

		if (options) {
			tabGroup._tabs = options.tabs || [];
		} else {
			tabGroup._tabs = [];
		}

		// Keeps track of the current tab group state
		tabGroup.currentState = tabGroup.state.closed;

		// Set the activity property here since we bind it to _internalActivity for window proxies by default
		Object.defineProperty(TabGroup.prototype, "activity", { get: tabGroup.getActivity});

		return tabGroup;
	}

	Titanium.UI.createTabGroup = createTabGroup;

	var _open = TabGroup.prototype.open;
	TabGroup.prototype.open = function(options) {

		if (this.currentState == this.state.opened) {
			return;
		}

		this.currentState = this.state.opening;

		// Retain the tab group until is has closed.
		var handle = new PersistentHandle(this);

		var self = this;
		this.on("close", function(e) {
			if (e._closeFromActivityForcedToDestroy) {
				if (kroll.DBG) {
					kroll.log(TAG, "Tabgroup is closed because the activity is forced to destroy by Android OS.");
				}
				return;
			}

			self.currentState = self.state.closed;
			handle.dispose();

			if (kroll.DBG) {
				kroll.log(TAG, "Tabgroup is closed normally.");
			}
		});

		this.setTabs(this._tabs);
		_open.call(this, options);

		this.currentState = this.state.opened;
	}

	var _addTab = TabGroup.prototype.addTab;
	TabGroup.prototype.addTab = function(tab) {
		this._tabs.push(tab);
		if (this.currentState == this.state.opened) {
			_addTab.call(this, tab);
		}
	}

	TabGroup.prototype.getTabs = function() {
		return this._tabs;
	}

	var _setTabs = TabGroup.prototype.setTabs;
	TabGroup.prototype.setTabs = function(tabs) {

		if (!Array.isArray(tabs)) {
			kroll.log(TAG, "Invalid type of tabs for setTabs()");
			return;
		}

		if (this.currentState != this.state.opened) {
			this._tabs = tabs;
			_setTabs.call(this, tabs);

		} else {
			kroll.log(TAG, "Cannot set tabs after tab group opens");
		}
	}

	Object.defineProperty(TabGroup.prototype, "tabs", { get: TabGroup.prototype.getTabs, set: TabGroup.prototype.setTabs });

}

<commit_msg>TIMOB-8222-Handle setActiveTab in javascript as the tabs are not added until open is called<commit_after>/**
 * Appcelerator Titanium Mobile
 * Copyright (c) 2012 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

var PersistentHandle = require('ui').PersistentHandle;

var TAG = "TabGroup";

exports.bootstrap = function(Titanium) {

	var TabGroup = Titanium.UI.TabGroup;

	// Set constants for representing states for the tab group
	TabGroup.prototype.state = {closed: 0, opening: 1, opened: 2};

	function createTabGroup(scopeVars, options) {
		var tabGroup = new TabGroup(options);

		if (options) {
			tabGroup._tabs = options.tabs || [];
		} else {
			tabGroup._tabs = [];
		}

		// Keeps track of the current tab group state
		tabGroup.currentState = tabGroup.state.closed;

		tabGroup._activeTab = -1;

		// Set the activity property here since we bind it to _internalActivity for window proxies by default
		Object.defineProperty(TabGroup.prototype, "activity", { get: tabGroup.getActivity});

		return tabGroup;
	}

	Titanium.UI.createTabGroup = createTabGroup;

	var _open = TabGroup.prototype.open;
	TabGroup.prototype.open = function(options) {

		if (this.currentState == this.state.opened) {
			return;
		}

		this.currentState = this.state.opening;

		// Retain the tab group until is has closed.
		var handle = new PersistentHandle(this);

		var self = this;
		this.on("close", function(e) {
			if (e._closeFromActivityForcedToDestroy) {
				if (kroll.DBG) {
					kroll.log(TAG, "Tabgroup is closed because the activity is forced to destroy by Android OS.");
				}
				return;
			}

			self.currentState = self.state.closed;
			handle.dispose();

			if (kroll.DBG) {
				kroll.log(TAG, "Tabgroup is closed normally.");
			}
		});

		this.setTabs(this._tabs);
		if (this._activeTab != -1) {
			this.setActiveTab(this._activeTab);
		}
		_open.call(this, options);

		this.currentState = this.state.opened;
	}

	var _addTab = TabGroup.prototype.addTab;
	TabGroup.prototype.addTab = function(tab) {
		this._tabs.push(tab);
		if (this.currentState == this.state.opened) {
			_addTab.call(this, tab);
		}
	}

	var _setActiveTab = TabGroup.prototype.setActiveTab;

	TabGroup.prototype.setActiveTab = function(taborindex) {
		if ( (this.currentState == this.state.opened) ||
			(this.currentState == this.state.opening) ){
			_setActiveTab.call(this,taborindex);
		} else {
			if (!isNaN(parseFloat(taborindex)) && isFinite(taborindex)) {
				if (taborindex >= 0 && taborindex < this._tabs.length) {
					this._activeTab = this._tabs[taborindex];
				}
			} else {
				this._activeTab = taborindex;
			}

		}
	}

	var _getActiveTab = TabGroup.prototype.getActiveTab;

	TabGroup.prototype.getActiveTab = function() {
		if (this.currentState == this.state.opened) {
			return _getActiveTab.call(this);
		}
		if (this._activeTab != -1) {
			return this._activeTab;
		}
		return null;
	}

	TabGroup.prototype.getTabs = function() {
		return this._tabs;
	}

	var _setTabs = TabGroup.prototype.setTabs;
	TabGroup.prototype.setTabs = function(tabs) {

		if (!Array.isArray(tabs)) {
			kroll.log(TAG, "Invalid type of tabs for setTabs()");
			return;
		}

		if (this.currentState != this.state.opened) {
			this._tabs = tabs;
			_setTabs.call(this, tabs);

		} else {
			kroll.log(TAG, "Cannot set tabs after tab group opens");
		}
	}

	Object.defineProperty(TabGroup.prototype, "tabs", { get: TabGroup.prototype.getTabs, set: TabGroup.prototype.setTabs });

}

<|endoftext|>


<commit_before>'use strict';

import { remote } from 'electron';
import { servers } from './servers';
import { sidebar } from './sidebar';
import { webview } from './webview';
import '../branding/branding.js';

var Menu = remote.Menu;
var APP_NAME = remote.app.getName();
var template;

var certificate = remote.require('./background').certificate;

document.title = APP_NAME;

if (process.platform === 'darwin') {
    template = [
        {
            label: APP_NAME,
            submenu: [
                {
                    label: 'About ' + APP_NAME,
                    role: 'about'
                },
                {
                    type: 'separator'
                },
                {
                    label: 'Hide ' + APP_NAME,
                    accelerator: 'Command+H',
                    role: 'hide'
                },
                {
                    label: 'Hide Others',
                    accelerator: 'Command+Alt+H',
                    role: 'hideothers'
                },
                {
                    label: 'Show All',
                    role: 'unhide'
                },
                {
                    type: 'separator'
                },
                {
                    label: 'Quit ' + APP_NAME,
                    accelerator: 'Command+Q',
                    click: function () {
                        remote.app.quit();
                    }
                }
            ]
        },
        {
            label: 'Edit',
            submenu: [
                {
                    label: 'Undo',
                    accelerator: 'Command+Z',
                    role: 'undo'
                },
                {
                    label: 'Redo',
                    accelerator: 'Command+Shift+Z',
                    role: 'redo'
                },
                {
                    type: 'separator'
                },
                {
                    label: 'Cut',
                    accelerator: 'Command+X',
                    role: 'cut'
                },
                {
                    label: 'Copy',
                    accelerator: 'Command+C',
                    role: 'copy'
                },
                {
                    label: 'Paste',
                    accelerator: 'Command+V',
                    role: 'paste'
                },
                {
                    label: 'Select All',
                    accelerator: 'Command+A',
                    role: 'selectall'
                }
            ]
        },
        {
            label: 'View',
            submenu: [
                {
                    label: 'Original Zoom',
                    accelerator: 'CommandOrControl+0',
                    role: 'resetzoom'
                },
                {
                    label: 'Zoom In',
                    accelerator: 'CommandOrControl+Plus',
                    role: 'zoomin'
                },
                {
                    label: 'Zoom Out',
                    accelerator: 'CommandOrControl+-',
                    role: 'zoomout'
                },
                {
                    type: 'separator'
                },
                {
                    label: 'Current Server - Reload',
                    accelerator: 'Command+R',
                    click: function () {
                        const activeWebview = webview.getActive();
                        if (activeWebview) {
                            activeWebview.reload();
                        }
                    }
                },
                {
                    label: 'Current Server - Toggle DevTools',
                    accelerator: 'Command+Alt+I',
                    click: function () {
                        const activeWebview = webview.getActive();
                        if (activeWebview) {
                            activeWebview.openDevTools();
                        }
                    }
                },
                {
                    type: 'separator'
                },
                {
                    label: 'Application - Reload',
                    accelerator: 'Command+Shift+R',
                    click: function () {
                        var mainWindow = remote.getCurrentWindow();
                        if (mainWindow.destroyTray) {
                            mainWindow.destroyTray();
                        }
                        mainWindow.reload();
                    }
                },
                {
                    label: 'Application - Toggle DevTools',
                    click: function () {
                        remote.getCurrentWindow().toggleDevTools();
                    }
                },
                {
                    type: 'separator'
                },
                {
                    label: 'Toggle server list',
                    click: function () {
                        sidebar.toggle();
                    }
                },
                {
                    type: 'separator'
                },
                {
                    label: 'Clear',
                    submenu: [
                        {
                            label: 'Clear Trusted Certificates',
                            click: function () {
                                certificate.clear();
                            }
                        }
                    ]
                }
            ]
        },
        {
            label: 'Window',
            id: 'window',
            role: 'window',
            submenu: [
                {
                    label: 'Minimize',
                    accelerator: 'Command+M',
                    role: 'minimize'
                },
                {
                    label: 'Close',
                    accelerator: 'Command+W',
                    role: 'close'
                },
                {
                    type: 'separator'
                },
                {
                    type: 'separator',
                    id: 'server-list-separator',
                    visible: false
                },
                {
                    label: 'Add new server',
                    accelerator: 'Command+N',
                    click: function () {
                        var mainWindow = remote.getCurrentWindow();
                        mainWindow.show();
                        servers.clearActive();
                    }
                },
                {
                    type: 'separator'
                },
                {
                    label: 'Bring All to Front',
                    click: function () {
                        var mainWindow = remote.getCurrentWindow();
                        mainWindow.show();
                    }
                }
            ]
        },
        {
            label: 'Help',
            role: 'help',
            submenu: [
                {
                    label: APP_NAME + ' Help',
                    click: function () {
                        remote.shell.openExternal('https://rocket.chat/docs');
                    }
                },
                {
                    type: 'separator'
                },
                {
                    label: 'Learn More',
                    click: function () {
                        remote.shell.openExternal('https://rocket.chat');
                    }
                }
            ]
        }
    ];
} else {
    template = [
        {
            label: '&' + APP_NAME,
            submenu: [
                {
                    label: 'About ' + APP_NAME,
                    click: function () {
                        const win = new remote.BrowserWindow({ width: 310, height: 200, minWidth: 310, minHeight: 200, maxWidth: 310, maxHeight: 200, show: false, maximizable: false, minimizable: false, title: ' ' });
                        win.loadURL('file://' + __dirname + '/about.html');
                        win.show();
                    }
                },
                {
                    type: 'separator'
                },
                {
                    label: 'Quit',
                    accelerator: 'Ctrl+Q',
                    click: function () {
                        remote.app.quit();
                    }
                }
            ]
        },
        {
            label: '&Edit',
            submenu: [
                {
                    label: 'Undo',
                    accelerator: 'Ctrl+Z',
                    role: 'undo'
                },
                {
                    label: 'Redo',
                    accelerator: 'Ctrl+Shift+Z',
                    role: 'redo'
                },
                {
                    type: 'separator'
                },
                {
                    label: 'Cut',
                    accelerator: 'Ctrl+X',
                    role: 'cut'
                },
                {
                    label: 'Copy',
                    accelerator: 'Ctrl+C',
                    role: 'copy'
                },
                {
                    label: 'Paste',
                    accelerator: 'Ctrl+V',
                    role: 'paste'
                },
                {
                    label: 'Select All',
                    accelerator: 'Ctrl+A',
                    role: 'selectall'
                }
            ]
        },
        {
            label: '&View',
            submenu: [
                {
                    label: 'Original Zoom',
                    accelerator: 'CommandOrControl+0',
                    role: 'resetzoom'
                },
                {
                    label: 'Zoom In',
                    accelerator: 'CommandOrControl+Plus',
                    role: 'zoomin'
                },
                {
                    label: 'Zoom Out',
                    accelerator: 'CommandOrControl+-',
                    role: 'zoomout'
                },
                {
                    type: 'separator'
                },
                {
                    label: 'Current Server - Reload',
                    accelerator: 'Ctrl+R',
                    click: function () {
                        const activeWebview = webview.getActive();
                        if (activeWebview) {
                            activeWebview.reload();
                        }
                    }
                },
                {
                    label: 'Current Server - Toggle DevTools',
                    accelerator: 'Ctrl+Shift+I',
                    click: function () {
                        const activeWebview = webview.getActive();
                        if (activeWebview) {
                            activeWebview.openDevTools();
                        }
                    }
                },
                {
                    type: 'separator'
                },
                {
                    label: 'Application - Reload',
                    accelerator: 'Ctrl+Shift+R',
                    click: function () {
                        var mainWindow = remote.getCurrentWindow();
                        if (mainWindow.destroyTray) {
                            mainWindow.destroyTray();
                        }
                        mainWindow.reload();
                    }
                },
                {
                    label: 'Application - Toggle DevTools',
                    click: function () {
                        remote.getCurrentWindow().toggleDevTools();
                    }
                },
                {
                    type: 'separator'
                },
                {
                    label: 'Toggle server list',
                    click: function () {
                        sidebar.toggle();
                    }
                },
                {
                    type: 'separator'
                },
                {
                    label: 'Clear',
                    submenu: [
                        {
                            label: 'Clear Trusted Certificates',
                            click: function () {
                                certificate.clear();
                            }
                        }
                    ]
                }
            ]
        },
        {
            label: '&Window',
            id: 'window',
            submenu: [
                {
                    type: 'separator',
                    id: 'server-list-separator',
                    visible: false
                },
                {
                    label: 'Add new server',
                    accelerator: 'Ctrl+N',
                    click: function () {
                        servers.clearActive();
                    }
                },
                {
                    type: 'separator'
                },
                {
                    label: 'Close',
                    accelerator: 'Ctrl+W',
                    click: function () {
                        remote.getCurrentWindow().close();
                    }
                }
            ]
        }
    ];
}

export var menuTemplate = template;
export var menu = Menu.buildFromTemplate(template);

Menu.setApplicationMenu(menu);
<commit_msg>Add option to toggle menu on windows and linux<commit_after>'use strict';

import { remote } from 'electron';
import { servers } from './servers';
import { sidebar } from './sidebar';
import { webview } from './webview';
import '../branding/branding.js';

const Menu = remote.Menu;
const APP_NAME = remote.app.getName();
const isMac = process.platform === 'darwin';

const certificate = remote.require('./background').certificate;

document.title = APP_NAME;

const macAppTemplate = [
    {
        label: 'About ' + APP_NAME,
        role: 'about'
    },
    {
        type: 'separator'
    },
    {
        label: 'Hide ' + APP_NAME,
        accelerator: 'Command+H',
        role: 'hide'
    },
    {
        label: 'Hide Others',
        accelerator: 'Command+Alt+H',
        role: 'hideothers'
    },
    {
        label: 'Show All',
        role: 'unhide'
    },
    {
        type: 'separator'
    },
    {
        label: 'Quit ' + APP_NAME,
        accelerator: 'Command+Q',
        click: function () {
            remote.app.quit();
        }
    }
];

const appTemplate = [
    {
        label: 'About ' + APP_NAME,
        click: function () {
            const win = new remote.BrowserWindow({ width: 310, height: 200, minWidth: 310, minHeight: 200, maxWidth: 310, maxHeight: 200, show: false, maximizable: false, minimizable: false, title: ' ' });
            win.loadURL('file://' + __dirname + '/about.html');
            win.show();
        }
    },
    {
        type: 'separator'
    },
    {
        label: 'Quit',
        accelerator: 'Ctrl+Q',
        click: function () {
            remote.app.quit();
        }
    }
];

const editTemplate = [
    {
        label: 'Undo',
        accelerator: 'CommandOrControl+Z',
        role: 'undo'
    },
    {
        label: 'Redo',
        accelerator: 'CommandOrControl+Shift+Z',
        role: 'redo'
    },
    {
        type: 'separator'
    },
    {
        label: 'Cut',
        accelerator: 'CommandOrControl+X',
        role: 'cut'
    },
    {
        label: 'Copy',
        accelerator: 'CommandOrControl+C',
        role: 'copy'
    },
    {
        label: 'Paste',
        accelerator: 'CommandOrControl+V',
        role: 'paste'
    },
    {
        label: 'Select All',
        accelerator: 'CommandOrControl+A',
        role: 'selectall'
    }
];

const viewTemplate = [
    {
        label: 'Original Zoom',
        accelerator: 'CommandOrControl+0',
        role: 'resetzoom'
    },
    {
        label: 'Zoom In',
        accelerator: 'CommandOrControl+Plus',
        role: 'zoomin'
    },
    {
        label: 'Zoom Out',
        accelerator: 'CommandOrControl+-',
        role: 'zoomout'
    },
    {
        type: 'separator'
    },
    {
        label: 'Current Server - Reload',
        accelerator: 'CommandOrControl+R',
        click: function () {
            const activeWebview = webview.getActive();
            if (activeWebview) {
                activeWebview.reload();
            }
        }
    },
    {
        label: 'Current Server - Toggle DevTools',
        accelerator: isMac ? 'Command+Alt+I' : 'Ctrl+Shift+I',
        click: function () {
            const activeWebview = webview.getActive();
            if (activeWebview) {
                activeWebview.openDevTools();
            }
        }
    },
    {
        type: 'separator'
    },
    {
        label: 'Application - Reload',
        accelerator: 'CommandOrControl+Shift+R',
        click: function () {
            var mainWindow = remote.getCurrentWindow();
            if (mainWindow.destroyTray) {
                mainWindow.destroyTray();
            }
            mainWindow.reload();
        }
    },
    {
        label: 'Application - Toggle DevTools',
        click: function () {
            remote.getCurrentWindow().toggleDevTools();
        }
    },
    {
        type: 'separator',
        id: 'toggle'
    },
    {
        label: 'Toggle server list',
        click: function () {
            sidebar.toggle();
        }
    },
    {
        type: 'separator'
    },
    {
        label: 'Clear',
        submenu: [
            {
                label: 'Clear Trusted Certificates',
                click: function () {
                    certificate.clear();
                }
            }
        ]
    }
];

if (!isMac) {
    viewTemplate.push({
        label: 'Toggle Menu Bar',
        click: function () {
            const current = localStorage.getItem('autohideMenu') === 'true';
            remote.getCurrentWindow().setAutoHideMenuBar(!current);
            localStorage.setItem('autohideMenu', JSON.stringify(!current));
        },
        position: 'after=toggle'
    });
}

const macWindowTemplate = [
    {
        label: 'Minimize',
        accelerator: 'Command+M',
        role: 'minimize'
    },
    {
        label: 'Close',
        accelerator: 'Command+W',
        role: 'close'
    },
    {
        type: 'separator'
    },
    {
        type: 'separator',
        id: 'server-list-separator',
        visible: false
    },
    {
        label: 'Add new server',
        accelerator: 'Command+N',
        click: function () {
            var mainWindow = remote.getCurrentWindow();
            mainWindow.show();
            servers.clearActive();
        }
    },
    {
        type: 'separator'
    },
    {
        label: 'Bring All to Front',
        click: function () {
            var mainWindow = remote.getCurrentWindow();
            mainWindow.show();
        }
    }
];

const windowTemplate = [
    {
        type: 'separator',
        id: 'server-list-separator',
        visible: false
    },
    {
        label: 'Add new server',
        accelerator: 'Ctrl+N',
        click: function () {
            servers.clearActive();
        }
    },
    {
        type: 'separator'
    },
    {
        label: 'Close',
        accelerator: 'Ctrl+W',
        click: function () {
            remote.getCurrentWindow().close();
        }
    }
];

const helpTemplate = [
    {
        label: APP_NAME + ' Help',
        click: function () {
            remote.shell.openExternal('https://rocket.chat/docs');
        }
    },
    {
        type: 'separator'
    },
    {
        label: 'Learn More',
        click: function () {
            remote.shell.openExternal('https://rocket.chat');
        }
    }
];

const defaultTemplate = [
    {
        label: `&${APP_NAME}`,
        submenu: appTemplate
    },
    {
        label: '&Edit',
        submenu: editTemplate
    },
    {
        label: '&View',
        submenu: viewTemplate
    },
    {
        label: '&Window',
        id: 'window',
        submenu: windowTemplate
    }
];

const macTemplate = [
    {
        label: APP_NAME,
        submenu: macAppTemplate
    },
    {
        label: 'Edit',
        submenu: editTemplate
    },
    {
        label: 'View',
        submenu: viewTemplate
    },
    {
        label: 'Window',
        id: 'window',
        role: 'window',
        submenu: macWindowTemplate
    },
    {
        label: 'Help',
        role: 'help',
        submenu: helpTemplate
    }
];

const template = isMac ? macTemplate : defaultTemplate;

export var menuTemplate = template;
export var menu = Menu.buildFromTemplate(template);

Menu.setApplicationMenu(menu);

if (!isMac) {
    if (localStorage.getItem('autohideMenu') === 'true') {
        remote.getCurrentWindow().setAutoHideMenuBar(true);
    }
}
<|endoftext|>


<commit_before>import ext from "./utils/ext";
import storage from "./utils/storage";

console.log("First load")
var popup = document.getElementById("app");
storage.get('color', function(resp) {
  var color = resp.color;
  if(color) {
    popup.style.backgroundColor = color
  }
});

var template = (data) => {
  var json = JSON.stringify(data);
  return (`

Choose an entity:

this will one day be a selection box

    <button data-bookmark='${json}' onClick='${() => {console.log("hello!")}}' id="save-btn" class="btn btn-primary">Create entity</button>

  `);
}
var renderMessage = (message) => {
  var displayContainer = document.getElementById("display-container");
  displayContainer.innerHTML = `<p class='message'>${message}</p>`;
}

var renderBookmark = (data) => {
  var displayContainer = document.getElementById("display-container")
  if(data) {
    var tmpl = template(data);
    displayContainer.innerHTML = tmpl;
  } else {
    renderMessage("Sorry, your already buggy software hit an unsupported flow. Good going...")
  }
}

ext.tabs.query({active: true, currentWindow: true}, function(tabs) {
  var activeTab = tabs[0];
  chrome.tabs.sendMessage(activeTab.id, { action: 'process-page' }, renderBookmark);
});

popup.addEventListener("click", function(e) {
  if(e.target && e.target.matches("#save-btn")) {
    e.preventDefault();
    var data = e.target.getAttribute("data-bookmark");
    ext.runtime.sendMessage({ action: "create-entity", data: data }, function(response) {
      if(response && response.action === "saved") {
        renderMessage("Your entity was not created! Good luck doing it manually loser");
      } else {
        renderMessage("Sorry, your already buggy software hit an unsupported flow. Good going...");
      }
    })
  }
});

var optionsLink = document.querySelector(".js-options");
optionsLink.addEventListener("click", function(e) {
  e.preventDefault();
  ext.tabs.create({'url': ext.extension.getURL('options.html')});
})
<commit_msg>Added some comments in popup.js<commit_after>import ext from "./utils/ext";
import storage from "./utils/storage";

var popup = document.getElementById("app");

storage.get('color', function(resp) {
  var color = resp.color;
  if(color) {
    popup.style.backgroundColor = color
  }
});

// This is the jsx for the popup window
var dialog = (data) => {
  var json = JSON.stringify(data);
  return (`

Choose an entity:

this will one day be a selection box

    <button data-bookmark='${json}' onClick='${() => {console.log("hello!")}}' id="save-btn" class="btn btn-primary">Create entity</button>

  `);
}

// Utility method to send text to the #display-container
var renderMessage = (message) => {
  var displayContainer = document.getElementById("display-container");
  displayContainer.innerHTML = `<p class='message'>${message}</p>`;
}

// Callback to modify UI after executing action
var renderBookmark = (data) => {
  var displayContainer = document.getElementById("display-container")
  if(data) {
    var tmpl = dialog(data);
    displayContainer.innerHTML = tmpl;
  } else {
    renderMessage("Sorry, your already buggy software hit an unsupported flow. Good going...")
  }
}

ext.tabs.query({active: true, currentWindow: true}, function(tabs) {
  var activeTab = tabs[0];
  chrome.tabs.sendMessage(activeTab.id, { action: 'process-page' }, renderBookmark);
});

// Adds an event handler for #create-entity
popup.addEventListener("click", function(e) {
  if(e.target && e.target.matches("#save-btn")) {
    e.preventDefault();
    var data = e.target.getAttribute("data-bookmark");
    ext.runtime.sendMessage({ action: "create-entity", data: data }, function(response) {
      if(response && response.action === "saved") {
        renderMessage("Your entity was not created! Good luck doing it manually loser");
      } else {
        renderMessage("Sorry, your already buggy software hit an unsupported flow. Good going...");
      }
    })
  }
});

// Displays options link on bottom of dialog
var optionsLink = document.querySelector(".js-options");
optionsLink.addEventListener("click", function(e) {
  e.preventDefault();
  ext.tabs.create({'url': ext.extension.getURL('options.html')});
})
<|endoftext|>


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

import SDFShader from 'three-bmfont-text/shaders/sdf';
import createGeometry from 'three-bmfont-text';
import parseASCII from 'parse-bmfont-ascii';
import * as THREE from '../lib/three';

import * as Font from './font';

export function createMaterial(color) {
  const texture = new THREE.Texture();
  const image = Font.image();
  texture.image = image;
  texture.needsUpdate = true;
  texture.minFilter = THREE.LinearFilter;
  texture.magFilter = THREE.LinearFilter;
  texture.generateMipmaps = false;

  return new THREE.RawShaderMaterial(SDFShader({
    side: THREE.DoubleSide,
    transparent: true,
    color,
    map: texture,
  }));
}

const textScale = 0.00024;

export function creator() {
  const font = parseASCII(Font.fnt());

  const colorMaterials = {};

  function createText(str, fnt, color, scale, wrapWidth, align) {
    const geometry = createGeometry({
      text: str,
      align,
      width: wrapWidth,
      flipY: true,
      fnt,
    });

    const layout = geometry.layout;

    let material = colorMaterials[color];
    if (material === undefined) {
      material = colorMaterials[color] = createMaterial(color);
    }
    const mesh = new THREE.Mesh(geometry, material);
    mesh.scale.multiply(new THREE.Vector3(1, -1, 1));

    const finalScale = scale * textScale;

    mesh.scale.multiplyScalar(finalScale);

    mesh.position.y = layout.height * 0.5 * finalScale;

    return mesh;
  }

  function create(str = '', { color = 0xffffff, scale = 1.0, wrapWidth = undefined, align = 'left' } = {}) {
    const group = new THREE.Group();

    const mesh = createText(str.toUpperCase, font, color, scale, wrapWidth, align);
    group.add(mesh);
    group.layout = mesh.geometry.layout;

    group.updateLabel = function (txt) {
      mesh.geometry.update(txt.toUpperCase());

      if (align === 'center') {
        //  center alignment doesn't seem to be working in BMFontText
        mesh.geometry.computeBoundingBox();
        const width = mesh.geometry.boundingBox.getSize().x;

        mesh.position.x = -width * 0.5 * textScale * scale;
      }
    };

    group.getMaterial = function () {
      return mesh.material;
    };

    group.getGeometry = function () {
      return mesh.geometry;
    };

    group.updateLabel(str);

    return group;
  }

  return {
    create,
  };
}
<commit_msg>fix snark<commit_after>/**
* dat-guiVR Javascript Controller Library for VR
* https://github.com/dataarts/dat.guiVR
*
* Copyright 2016 Data Arts Team, Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import SDFShader from 'three-bmfont-text/shaders/sdf';
import createGeometry from 'three-bmfont-text';
import parseASCII from 'parse-bmfont-ascii';
import * as THREE from '../lib/three';

import * as Font from './font';

export function createMaterial(color) {
  const texture = new THREE.Texture();
  const image = Font.image();
  texture.image = image;
  texture.needsUpdate = true;
  texture.minFilter = THREE.LinearFilter;
  texture.magFilter = THREE.LinearFilter;
  texture.generateMipmaps = false;

  return new THREE.RawShaderMaterial(SDFShader({
    side: THREE.DoubleSide,
    transparent: true,
    color,
    map: texture,
  }));
}

const textScale = 0.00024;

export function creator() {
  const font = parseASCII(Font.fnt());

  const colorMaterials = {};

  function createText(str, fnt, color, scale, wrapWidth, align) {
    const geometry = createGeometry({
      text: str,
      align,
      width: wrapWidth,
      flipY: true,
      font: fnt,
    });

    const layout = geometry.layout;

    let material = colorMaterials[color];
    if (material === undefined) {
      material = colorMaterials[color] = createMaterial(color);
    }
    const mesh = new THREE.Mesh(geometry, material);
    mesh.scale.multiply(new THREE.Vector3(1, -1, 1));

    const finalScale = scale * textScale;

    mesh.scale.multiplyScalar(finalScale);

    mesh.position.y = layout.height * 0.5 * finalScale;

    return mesh;
  }

  function create(str = '', { color = 0xffffff, scale = 1.0, wrapWidth = undefined, align = 'left' } = {}) {
    const group = new THREE.Group();

    const mesh = createText(str.toUpperCase, font, color, scale, wrapWidth, align);
    group.add(mesh);
    group.layout = mesh.geometry.layout;

    group.updateLabel = function (txt) {
      mesh.geometry.update(txt.toUpperCase());

      if (align === 'center') {
        //  center alignment doesn't seem to be working in BMFontText
        mesh.geometry.computeBoundingBox();
        const width = mesh.geometry.boundingBox.getSize().x;

        mesh.position.x = -width * 0.5 * textScale * scale;
      }
    };

    group.getMaterial = function () {
      return mesh.material;
    };

    group.getGeometry = function () {
      return mesh.geometry;
    };

    group.updateLabel(str);

    return group;
  }

  return {
    create,
  };
}
<|endoftext|>


<commit_before>define([
  'angular',
  'app/app',
  'lodash',
  'kbn',
  'app/components/timeSeries',
  'app/components/panelmeta',
  './singleStatPanel',
],
function (angular, app, _, kbn, TimeSeries, PanelMeta) {
  'use strict';

  var module = angular.module('grafana.panels.singlestat');
  app.useModule(module);

  module.directive('grafanaPanelSinglestat', function() {
    return {
      controller: 'SingleStatCtrl',
      templateUrl: 'app/panels/singlestat/module.html',
    };
  });

  module.controller('SingleStatCtrl', function($scope, panelSrv, panelHelper) {

    $scope.panelMeta = new PanelMeta({
      panelName: 'Singlestat',
      editIcon:  "fa fa-dashboard",
      fullscreen: true,
      metricsEditor: true
    });

    $scope.fontSizes = ['20%', '30%','50%','70%','80%','100%', '110%', '120%', '150%', '170%', '200%'];

    $scope.panelMeta.addEditorTab('Options', 'app/panels/singlestat/editor.html');
    $scope.panelMeta.addEditorTab('Time range', 'app/features/panel/partials/panelTime.html');

    // Set and populate defaults
    var _d = {
      links: [],
      datasource: null,
      maxDataPoints: 100,
      interval: null,
      targets: [{}],
      cacheTimeout: null,
      format: 'none',
      prefix: '',
      postfix: '',
      nullText: null,
      valueMaps: [
        { value: 'null', op: '=', text: 'N/A' }
      ],
      nullPointMode: 'connected',
      valueName: 'avg',
      prefixFontSize: '50%',
      valueFontSize: '80%',
      postfixFontSize: '50%',
      thresholds: '',
      colorBackground: false,
      colorValue: false,
      colors: ["rgba(245, 54, 54, 0.9)", "rgba(237, 129, 40, 0.89)", "rgba(50, 172, 45, 0.97)"],
      sparkline: {
        show: false,
        full: false,
        lineColor: 'rgb(31, 120, 193)',
        fillColor: 'rgba(31, 118, 189, 0.18)',
      }
    };

    _.defaults($scope.panel, _d);
    $scope.unitFormats = kbn.getUnitFormats();

    $scope.setUnitFormat = function(subItem) {
      $scope.panel.format = subItem.value;
      $scope.render();
    };

    $scope.init = function() {
      panelSrv.init($scope);
    };

    $scope.refreshData = function(datasource) {
      panelHelper.updateTimeRange($scope);

      return panelHelper.issueMetricQuery($scope, datasource)
        .then($scope.dataHandler, function(err) {
          $scope.series = [];
          $scope.render();
          throw err;
        });
    };

    $scope.loadSnapshot = function(snapshotData) {
      panelHelper.updateTimeRange($scope);
      $scope.dataHandler(snapshotData);
    };

    $scope.dataHandler = function(results) {
      $scope.series = _.map(results.data, $scope.seriesHandler);
      $scope.render();
    };

    $scope.seriesHandler = function(seriesData) {
      var series = new TimeSeries({
        datapoints: seriesData.datapoints,
        alias: seriesData.target,
      });

      series.flotpairs = series.getFlotPairs($scope.panel.nullPointMode);

      return series;
    };

    $scope.setColoring = function(options) {
      if (options.background) {
        $scope.panel.colorValue = false;
        $scope.panel.colors = ['rgba(71, 212, 59, 0.4)', 'rgba(245, 150, 40, 0.73)', 'rgba(225, 40, 40, 0.59)'];
      }
      else {
        $scope.panel.colorBackground = false;
        $scope.panel.colors = ['rgba(50, 172, 45, 0.97)', 'rgba(237, 129, 40, 0.89)', 'rgba(245, 54, 54, 0.9)'];
      }
      $scope.render();
    };

    $scope.invertColorOrder = function() {
      var tmp = $scope.panel.colors[0];
      $scope.panel.colors[0] = $scope.panel.colors[2];
      $scope.panel.colors[2] = tmp;
      $scope.render();
    };

    $scope.getDecimalsForValue = function(value) {
      if (_.isNumber($scope.panel.decimals)) {
        return { decimals: $scope.panel.decimals, scaledDecimals: null };
      }

      var delta = value / 2;
      var dec = -Math.floor(Math.log(delta) / Math.LN10);

      var magn = Math.pow(10, -dec),
          norm = delta / magn, // norm is between 1.0 and 10.0
          size;

      if (norm < 1.5) {
        size = 1;
      } else if (norm < 3) {
        size = 2;
        // special case for 2.5, requires an extra decimal
        if (norm > 2.25) {
          size = 2.5;
          ++dec;
        }
      } else if (norm < 7.5) {
        size = 5;
      } else {
        size = 10;
      }

      size *= magn;

      // reduce starting decimals if not needed
      if (Math.floor(value) === value) { dec = 0; }

      var result = {};
      result.decimals = Math.max(0, dec);
      result.scaledDecimals = result.decimals - Math.floor(Math.log(size) / Math.LN10) + 2;

      return result;
    };

    $scope.render = function() {
      var data = {};

      $scope.setValues(data);

      data.thresholds = $scope.panel.thresholds.split(',').map(function(strVale) {
        return Number(strVale.trim());
      });

      data.colorMap = $scope.panel.colors;

      $scope.data = data;
      $scope.$broadcast('render');
    };

    $scope.setValues = function(data) {
      data.flotpairs = [];

      if ($scope.series && $scope.series.length > 0) {
        var lastPoint = _.last($scope.series[0].datapoints);
        var lastValue = _.isArray(lastPoint) ? lastPoint[0] : null;

        if (_.isString(lastValue)) {
          data.value = 0;
          data.valueFormated = lastValue;
          data.valueRounded = 0;
        } else {
          data.value = $scope.series[0].stats[$scope.panel.valueName];
          data.flotpairs = $scope.series[0].flotpairs;

          var decimalInfo = $scope.getDecimalsForValue(data.value);
          var formatFunc = kbn.valueFormats[$scope.panel.format];
          data.valueFormated = formatFunc(data.value, decimalInfo.decimals, decimalInfo.scaledDecimals);
          data.valueRounded = kbn.roundValue(data.value, decimalInfo.decimals);
        }
      }

      // check value to text mappings
      for(var i = 0; i < $scope.panel.valueMaps.length; i++) {
        var map = $scope.panel.valueMaps[i];
        // special null case
        if (map.value === 'null') {
          if (data.value === null || data.value === void 0) {
            data.valueFormated = map.text;
            return;
          }
          continue;
        }

        // value/number to text mapping
        var value = parseFloat(map.value);
        if (value === data.value) {
          data.valueFormated = map.text;
          return;
        }
      }

      if (data.value === null || data.value === void 0) {
        data.valueFormated = "no value";
      }
    };

    $scope.removeValueMap = function(map) {
      var index = _.indexOf($scope.panel.valueMaps, map);
      $scope.panel.valueMaps.splice(index, 1);
      $scope.render();
    };

    $scope.addValueMap = function() {
      $scope.panel.valueMaps.push({value: '', op: '=', text: '' });
    };

    $scope.init();
  });
});
<commit_msg>Single stat panel throws warning on multiple series result.<commit_after>define([
  'angular',
  'app/app',
  'lodash',
  'kbn',
  'app/components/timeSeries',
  'app/components/panelmeta',
  './singleStatPanel',
],
function (angular, app, _, kbn, TimeSeries, PanelMeta) {
  'use strict';

  var module = angular.module('grafana.panels.singlestat');
  app.useModule(module);

  module.directive('grafanaPanelSinglestat', function() {
    return {
      controller: 'SingleStatCtrl',
      templateUrl: 'app/panels/singlestat/module.html',
    };
  });

  module.controller('SingleStatCtrl', function($scope, panelSrv, panelHelper) {

    $scope.panelMeta = new PanelMeta({
      panelName: 'Singlestat',
      editIcon:  "fa fa-dashboard",
      fullscreen: true,
      metricsEditor: true
    });

    $scope.fontSizes = ['20%', '30%','50%','70%','80%','100%', '110%', '120%', '150%', '170%', '200%'];

    $scope.panelMeta.addEditorTab('Options', 'app/panels/singlestat/editor.html');
    $scope.panelMeta.addEditorTab('Time range', 'app/features/panel/partials/panelTime.html');

    // Set and populate defaults
    var _d = {
      links: [],
      datasource: null,
      maxDataPoints: 100,
      interval: null,
      targets: [{}],
      cacheTimeout: null,
      format: 'none',
      prefix: '',
      postfix: '',
      nullText: null,
      valueMaps: [
        { value: 'null', op: '=', text: 'N/A' }
      ],
      nullPointMode: 'connected',
      valueName: 'avg',
      prefixFontSize: '50%',
      valueFontSize: '80%',
      postfixFontSize: '50%',
      thresholds: '',
      colorBackground: false,
      colorValue: false,
      colors: ["rgba(245, 54, 54, 0.9)", "rgba(237, 129, 40, 0.89)", "rgba(50, 172, 45, 0.97)"],
      sparkline: {
        show: false,
        full: false,
        lineColor: 'rgb(31, 120, 193)',
        fillColor: 'rgba(31, 118, 189, 0.18)',
      }
    };

    _.defaults($scope.panel, _d);
    $scope.unitFormats = kbn.getUnitFormats();

    $scope.setUnitFormat = function(subItem) {
      $scope.panel.format = subItem.value;
      $scope.render();
    };

    $scope.init = function() {
      panelSrv.init($scope);
    };

    $scope.refreshData = function(datasource) {
      panelHelper.updateTimeRange($scope);

      return panelHelper.issueMetricQuery($scope, datasource)
        .then($scope.dataHandler, function(err) {
          $scope.series = [];
          $scope.render();
          throw err;
        });
    };

    $scope.loadSnapshot = function(snapshotData) {
      panelHelper.updateTimeRange($scope);
      $scope.dataHandler(snapshotData);
    };

    $scope.dataHandler = function(results) {
      $scope.series = _.map(results.data, $scope.seriesHandler);
      $scope.render();
    };

    $scope.seriesHandler = function(seriesData) {
      var series = new TimeSeries({
        datapoints: seriesData.datapoints,
        alias: seriesData.target,
      });

      series.flotpairs = series.getFlotPairs($scope.panel.nullPointMode);

      return series;
    };

    $scope.setColoring = function(options) {
      if (options.background) {
        $scope.panel.colorValue = false;
        $scope.panel.colors = ['rgba(71, 212, 59, 0.4)', 'rgba(245, 150, 40, 0.73)', 'rgba(225, 40, 40, 0.59)'];
      }
      else {
        $scope.panel.colorBackground = false;
        $scope.panel.colors = ['rgba(50, 172, 45, 0.97)', 'rgba(237, 129, 40, 0.89)', 'rgba(245, 54, 54, 0.9)'];
      }
      $scope.render();
    };

    $scope.invertColorOrder = function() {
      var tmp = $scope.panel.colors[0];
      $scope.panel.colors[0] = $scope.panel.colors[2];
      $scope.panel.colors[2] = tmp;
      $scope.render();
    };

    $scope.getDecimalsForValue = function(value) {
      if (_.isNumber($scope.panel.decimals)) {
        return { decimals: $scope.panel.decimals, scaledDecimals: null };
      }

      var delta = value / 2;
      var dec = -Math.floor(Math.log(delta) / Math.LN10);

      var magn = Math.pow(10, -dec),
          norm = delta / magn, // norm is between 1.0 and 10.0
          size;

      if (norm < 1.5) {
        size = 1;
      } else if (norm < 3) {
        size = 2;
        // special case for 2.5, requires an extra decimal
        if (norm > 2.25) {
          size = 2.5;
          ++dec;
        }
      } else if (norm < 7.5) {
        size = 5;
      } else {
        size = 10;
      }

      size *= magn;

      // reduce starting decimals if not needed
      if (Math.floor(value) === value) { dec = 0; }

      var result = {};
      result.decimals = Math.max(0, dec);
      result.scaledDecimals = result.decimals - Math.floor(Math.log(size) / Math.LN10) + 2;

      return result;
    };

    $scope.render = function() {
      var data = {};

      if($scope.series.length > 1) {
        $scope.appEvent('alert-warning', ['Multiple Series Error', 'Metric query returns ' +
        $scope.series.length + ' series. Single Stat Panel expects a single series.']);
        $scope.series = [];
      }

      $scope.setValues(data);

      data.thresholds = $scope.panel.thresholds.split(',').map(function(strVale) {
        return Number(strVale.trim());
      });

      data.colorMap = $scope.panel.colors;

      $scope.data = data;
      $scope.$broadcast('render');
    };

    $scope.setValues = function(data) {
      data.flotpairs = [];
      if ($scope.series && $scope.series.length > 0) {
        var lastPoint = _.last($scope.series[0].datapoints);
        var lastValue = _.isArray(lastPoint) ? lastPoint[0] : null;

        if (_.isString(lastValue)) {
          data.value = 0;
          data.valueFormated = lastValue;
          data.valueRounded = 0;
        } else {
          data.value = $scope.series[0].stats[$scope.panel.valueName];
          data.flotpairs = $scope.series[0].flotpairs;

          var decimalInfo = $scope.getDecimalsForValue(data.value);
          var formatFunc = kbn.valueFormats[$scope.panel.format];
          data.valueFormated = formatFunc(data.value, decimalInfo.decimals, decimalInfo.scaledDecimals);
          data.valueRounded = kbn.roundValue(data.value, decimalInfo.decimals);
        }
      }

      // check value to text mappings
      for(var i = 0; i < $scope.panel.valueMaps.length; i++) {
        var map = $scope.panel.valueMaps[i];
        // special null case
        if (map.value === 'null') {
          if (data.value === null || data.value === void 0) {
            data.valueFormated = map.text;
            return;
          }
          continue;
        }

        // value/number to text mapping
        var value = parseFloat(map.value);
        if (value === data.value) {
          data.valueFormated = map.text;
          return;
        }
      }

      if (data.value === null || data.value === void 0) {
        data.valueFormated = "no value";
      }
    };

    $scope.removeValueMap = function(map) {
      var index = _.indexOf($scope.panel.valueMaps, map);
      $scope.panel.valueMaps.splice(index, 1);
      $scope.render();
    };

    $scope.addValueMap = function() {
      $scope.panel.valueMaps.push({value: '', op: '=', text: '' });
    };

    $scope.init();
  });
});
<|endoftext|>