<commit_before>exports.mod = function(context, server)
{
	this.core$cmd = function(prefix, target, command, params, $core)
	{
		if(command === 'helloworld') $core._privmsg(target, 'Hello, ' + prefix.nick + '!');
	}
}
<commit_msg>Implemented help in mod helloworld.<commit_after>exports.mod = function(context, server)
{
	this.help$register = function()
	{
		server.do('help$register', 'helloworld');
	}

	this._help = function(topic, params)
	{
		switch(topic)
		{
			case 'helloworld':
				return 'Prints a hello message.';
				break;
		}
	}

	this.core$cmd = function(prefix, target, command, params, $core)
	{
		if(command === 'helloworld') $core._privmsg(target, 'Hello, ' + prefix.nick + '!');
	}
}
<|endoftext|>


<commit_before>import React from "react";
import ReactDOM from "react-dom";

import loaded from "./loaded";

import App from "./App";

const error = message => {
  if (console && console.error) {
    console.error(message);
  }
};

function startInterface(config) {
  if (!config) {
    error(
      'global value "sj" not found, please check the code snippet for your Sajari search interface'
    );
    return;
  }
  if (!config.project) {
    error("project value in config not set, must be set");
  }
  if (!config.collection) {
    error("collection value in config not set, must be set");
  }
  if (!config.pipeline) {
    error("pipeline value in config not set, must be set");
  }

  let renderTarget = null;
  if (config.overlay) {
    // Create a container to render the overlay into
    const overlayContainer = document.createElement("div");
    overlayContainer.id = "sj-overlay-holder";
    document.body.appendChild(overlayContainer);

    renderTarget = overlayContainer;
  } else if (config.attachSearchBox && config.attachSearchResponse) {
    renderTarget = config.attachSearchBox;
  } else {
    error(
      "no render mode found, need to specify either overlay or attachSearchBox and attachSearchResponse in config"
    );
    return;
  }

  ReactDOM.render(<App config={config} />, renderTarget);
}

loaded(window, () => startInterface(window._sjui.config));
<commit_msg>site-search-overlay: fix incorrect error message<commit_after>import React from "react";
import ReactDOM from "react-dom";

import loaded from "./loaded";

import App from "./App";

const error = message => {
  if (console && console.error) {
    console.error(message);
  }
};

function startInterface(config) {
  if (!config) {
    error(
      'global value "_sjui" not found, please check the code snippet for your Sajari search interface'
    );
    return;
  }
  if (!config.project) {
    error("project value in config not set, must be set");
  }
  if (!config.collection) {
    error("collection value in config not set, must be set");
  }
  if (!config.pipeline) {
    error("pipeline value in config not set, must be set");
  }

  let renderTarget = null;
  if (config.overlay) {
    // Create a container to render the overlay into
    const overlayContainer = document.createElement("div");
    overlayContainer.id = "sj-overlay-holder";
    document.body.appendChild(overlayContainer);

    renderTarget = overlayContainer;
  } else if (config.attachSearchBox && config.attachSearchResponse) {
    renderTarget = config.attachSearchBox;
  } else {
    error(
      "no render mode found, need to specify either overlay or attachSearchBox and attachSearchResponse in config"
    );
    return;
  }

  ReactDOM.render(<App config={config} />, renderTarget);
}

loaded(window, () => startInterface(window._sjui.config));
<|endoftext|>


<commit_before>/**
 * The game engine.
 */

// SDK imports
import ui.View;
import ui.ImageView as ImageView;

// User imports
import src.GameElements.Enemy as Enemy;
import src.GameElements.User as User;
import src.GameElements.HexaGrid as HexaGrid;

exports = Class(ui.View, function (supr) {
    this.init = function (opts) {

        this._config = JSON.parse(CACHE['resources/conf/config.json']);

        opts = merge(opts, {
            x: 0,
            y: 0,
            width: this._config.screenWidth,
            height: this._config.screenHeight,
        });

        supr(this, 'init', [opts]);

        this.build();
    };

    this.build = function () {

        this._input = false;

        // Background
        this._bg = new ImageView({
            superview: this,
            image: 'resources/images/bg2.jpg',
            width: this._config.screenWidth,
            height: this._config.screenHeight,
            x: 0,
            y: 0
        });

        this._user = new User();
        this._hexagrid = new HexaGrid();
        this._enemy = new Enemy();

        this.addSubview( this._user );
        this.addSubview( this._hexagrid );
        this.addSubview( this._enemy );

        this.on('game1:start', start_game_flow.bind(this));

        this.on('InputStart', function (event, point) {
            if (!this._hexagrid.getGridState()) {
                return;
            }

            this._input = true;
            this._user.inputDown(point);
        });

        this.on('InputSelect', function (event, point) {
            if (!this._hexagrid.getGridState()) {
                return;
            }

            this._input = false;
            this._user.inputUp(point);
        });

        this.on('InputMove', function (event, point) {
            if (!this._hexagrid.getGridState()) {
                return;
            }

            if (this._input) {
                this._user.inputDown(point);
            }
        });

        // Game setup
        this._config.ballLength = 3;

        this._user.config(this._config);
        this._enemy.config(this._config);
        this._hexagrid.config(this._config);

        this._user.emit('user:start');
        this._enemy.emit('enemy:start');
        this._hexagrid.emit('hexagrid:start');
    };
});

/**
 * Game play.
 */
function start_game_flow () {

    // Reset game.
    this._user.resetGame();
    this._enemy.resetGame();
    this._hexagrid.resetGame();

    this._startTime = Date.now();
    window.requestAnimationFrame(tick.bind(this));
}

/**
 * Game tick.
 */
function tick () {
    // Game over. The user lost.
    if (!this._hexagrid.getGridState()) {
        this._enemy.gameOver();

        setTimeout(bind(this, function () {
            this.emit('gamescreen1:end');
        }), 4000);

        return;
    }

    var timestamp = Date.now();
    var progress = timestamp - this._startTime;

    this._user.progress(progress);
    this._enemy.progress(progress);
    this._hexagrid.progress(progress);

    this._user.emit('user:tick');
    this._enemy.emit('enemy:tick');
    this._hexagrid.emit('hexagrid:tick');

    // Check, if the fired ball hit the hexagrid.
    var firedBall = this._user.getFiredBall();
    if (firedBall) {
        var ballHit = this._hexagrid.checkHit(firedBall);
        this._user.firedHit(ballHit);
    }

    this._startTime = timestamp;
    window.requestAnimationFrame(tick.bind(this));
}
<commit_msg>Game over development<commit_after>/**
 * The game engine.
 */

// SDK imports
import ui.View;
import ui.ImageView as ImageView;

// User imports
import src.GameElements.Enemy as Enemy;
import src.GameElements.User as User;
import src.GameElements.HexaGrid as HexaGrid;

exports = Class(ui.View, function (supr) {
    this.init = function (opts) {

        this._config = JSON.parse(CACHE['resources/conf/config.json']);

        opts = merge(opts, {
            x: 0,
            y: 0,
            width: this._config.screenWidth,
            height: this._config.screenHeight,
        });

        supr(this, 'init', [opts]);

        this.build();
    };

    this.build = function () {

        this._input = false;

        // Background
        this._bg = new ImageView({
            superview: this,
            image: 'resources/images/bg2.jpg',
            width: this._config.screenWidth,
            height: this._config.screenHeight,
            x: 0,
            y: 0
        });

        this._user = new User();
        this._hexagrid = new HexaGrid();
        this._enemy = new Enemy();

        this.addSubview( this._user );
        this.addSubview( this._hexagrid );
        this.addSubview( this._enemy );

        this.on('game1:start', start_game_flow.bind(this));

        this.on('InputStart', function (event, point) {
            if (this.gameOver()) {
                return;
            }

            this._input = true;
            this._user.inputDown(point);
        });

        this.on('InputSelect', function (event, point) {
            if (this.gameOver()) {
                return;
            }

            this._input = false;
            this._user.inputUp(point);
        });

        this.on('InputMove', function (event, point) {
            if (this.gameOver()) {
                return;
            }

            if (this._input) {
                this._user.inputDown(point);
            }
        });

        // Game setup
        this._config.ballLength = 3;

        this._user.config(this._config);
        this._enemy.config(this._config);
        this._hexagrid.config(this._config);

        this._user.emit('user:start');
        this._enemy.emit('enemy:start');
        this._hexagrid.emit('hexagrid:start');
    };

    this.gameOver = function () {
        return !this._hexagrid.getGridState();
    };
});

/**
 * Game play.
 */
function start_game_flow () {

    // Reset game.
    this._user.resetGame();
    this._enemy.resetGame();
    this._hexagrid.resetGame();

    this._startTime = Date.now();
    window.requestAnimationFrame(tick.bind(this));
}

/**
 * Game tick.
 */
function tick () {
    // Game over. The user lost.
    if (this.gameOver()) {
        this._enemy.gameOver();

        setTimeout(bind(this, function () {
            this.emit('gamescreen1:end');
        }), 4000);

        return;
    }

    var timestamp = Date.now();
    var progress = timestamp - this._startTime;

    this._user.progress(progress);
    this._enemy.progress(progress);
    this._hexagrid.progress(progress);

    this._user.emit('user:tick');
    this._enemy.emit('enemy:tick');
    this._hexagrid.emit('hexagrid:tick');

    // Check, if the fired ball hit the hexagrid.
    var firedBall = this._user.getFiredBall();
    if (firedBall) {
        var ballHit = this._hexagrid.checkHit(firedBall);
        this._user.firedHit(ballHit);
    }

    this._startTime = timestamp;
    window.requestAnimationFrame(tick.bind(this));
}
<|endoftext|>


<commit_before>import { expect } from 'chai';

import { updateCellSource, executeCell } from '../../../src/notebook/actions';
import { liveStore, dispatchQueuePromise, waitForOutputs } from '../../utils';

describe('agendas.executeCell', function() {
  this.timeout(5000);
  it('produces the right output', () => {
    return liveStore((kernel, dispatch, store) => {
      const cellId = store.getState().document.getIn(['notebook', 'cellOrder', 0]);
      const source = 'print("a")';
      dispatch(updateCellSource(cellId, source));

      // TODO: Remove hack
      // HACK: Wait 100ms before executing a cell because kernel ready and idle
      // aren't enough.  There must be another signal that we need to listen to.
      return (new Promise(resolve => setTimeout(resolve, 100)))
        .then(() => dispatch(executeCell(kernel.channels, cellId, source, true, undefined)))
        .then(() => dispatchQueuePromise(dispatch))
        .then(() => waitForOutputs(store, cellId))
        .then(() => {
          const output = store.getState().document.getIn(['notebook', 'cellMap', cellId, 'outputs', 0]).toJS();
          expect(output.name).to.equal('stdout');
          expect(output.text).to.equal('a\n');
          expect(output.output_type).to.equal('stream');
        });
    });
  });
});
<commit_msg>Retry tests if race condition ensues<commit_after>import { expect } from 'chai';

import { updateCellSource, executeCell } from '../../../src/notebook/actions';
import { liveStore, dispatchQueuePromise, waitForOutputs } from '../../utils';

describe('agendas.executeCell', function() {
  this.timeout(5000);
  this.retries(5);
  it('produces the right output', () => {
    return liveStore((kernel, dispatch, store) => {
      const cellId = store.getState().document.getIn(['notebook', 'cellOrder', 0]);
      const source = 'print("a")';
      dispatch(updateCellSource(cellId, source));

      return Promise.resolve()
        .then(() => dispatch(executeCell(kernel.channels, cellId, source, true, undefined)))
        .then(() => dispatchQueuePromise(dispatch))
        .then(() => waitForOutputs(store, cellId))
        .then(() => {
          const output = store.getState().document.getIn(['notebook', 'cellMap', cellId, 'outputs', 0]).toJS();
          expect(output.name).to.equal('stdout');
          expect(output.text).to.equal('a\n');
          expect(output.output_type).to.equal('stream');
        });
    });
  });
});
<|endoftext|>


<commit_before>"use strict"

angular.module('medialibrary').controller("FileListCtrl", ["$scope", "$rootScope", "$routeParams", "$route", "$filter", "apiStorage", "apiAuth", "LocalFiles", "$log", "storageAPILoader", "fileInfo", "FileList",
	function ($scope, $rootScope, $routeParams, $route, $filter, apiStorage, apiAuth, LocalFiles, $log, storageAPILoader, fileInfo, FileList) {

	var MEDIA_LIBRARY_URL = 'http://commondatastorage.googleapis.com/';

	$rootScope.bucketName = 'risemedialibrary-' + $routeParams.companyId;
	$rootScope.bucketUrl = MEDIA_LIBRARY_URL + $rootScope.bucketName + '/';
	$rootScope.requireBucketCreation = false;

	$scope.mediaFiles = fileInfo.files || [];

  if(fileInfo.authError) {
    $scope.authenticationError = true;
  }

  else if(fileInfo.notFound) {
    $rootScope.actionsDisabled = false;
    $rootScope.requireBucketCreation = true;
  }

  else {
    $rootScope.actionsDisabled = false;
    $rootScope.librarySize = 0;
    $scope.selectAll = false;
    if(fileInfo.local) {
      $rootScope.actionsDisabled = true;
    }
  }

	$scope.orderByAttribute = 'lastModified';

  $scope.fileExtOrderFunction = function(file) {
    return file.name.split('.').pop();
  };

  $scope.fileSizeOrderFunction = function(file) {
    return Number(file.size);
  };

	$scope.reverseSort = true;

	$rootScope.updateList = function() {
		if ($rootScope.authStatus !== 1) {
      return;
    }
    FileList($routeParams.companyId).then($route.reload());
	};

	function onGetFiles(resp) {
    if (resp && resp.files) {
    	$scope.mediaFiles = resp.files;
    }
    else {
    	$scope.mediaFiles = [];
    }
	}

  function getLibrarySize(mediaFiles) {
    var size = 0;
    for ( var i = 0; i < mediaFiles.length; ++i ) {
      size += parseInt(mediaFiles[ i ].size);
    }
    return size;
  }

	$scope.$watch('mediaFiles', function(items) {
    if(items) {
      var checkedCount = 0;
      items.forEach(function(item) {
        if (item.checked) {
          checkedCount++;
        }
        $rootScope.librarySize = getLibrarySize(items);
      });
      $rootScope.$broadcast('CheckedCountChange', checkedCount);
    }
    else {
      $rootScope.librarySize = 0;
    }

	}, true);
/*
 *     Scope $watch won't work within a bootstrap modal unless it's an object
 *     property that is being changed.  See the following issue:
 *     https://github.com/angular-ui/bootstrap/issues/1680
 *
	$scope.$watch('selectAll', function(v) {

	    for ( var i = 0; i < $scope.mediaFiles.length; ++i ) {
	        $scope.mediaFiles[ i ].checked = v;
	    }

	});

        */

	$scope.selectAllCheckboxes = function() {
    $scope.selectAll = !$scope.selectAll;

    for ( var i = 0; i < $scope.mediaFiles.length; ++i ) {
        $scope.mediaFiles[ i ].checked = $scope.selectAll;
    }
	};

	$scope.$on('FileSelectAction', function(event, file) {

		if (!file) {
			file = getSelectedFile();
		}

		if (file) {
			var fileUrl = $rootScope.bucketUrl + file.name;
			var data = { params: fileUrl };
			gadgets.rpc.call('', 'rscmd_saveSettings', null, data);
		}
	});

	$scope.$on('FileDownloadAction', function(event, file) {
		if (!file) {
			file = getSelectedFile();
		}
		$scope.selectedFile = file;
		if ($scope.selectedFile) {
			apiStorage.getFileUrl($routeParams.companyId, encodeURIComponent($scope.selectedFile)).then(onFileUrlResponse);
		}
	});

	function onFileUrlResponse(response) {
		window.location.assign(response);
	}

	$scope.$on('FileDeleteAction', function(event) {
		var selectedFiles = getSelectedFiles();
		if (confirm('Are you sure you want to delete the ' + selectedFiles.length + ' files selected?')) {
			apiStorage.deleteFiles($routeParams.companyId, selectedFiles).then(onGetFiles);
		}
	});

	$scope.$on('NewFolderAction', function(event) {
          var folderName = prompt('new folder');
          if (folderName) {
            apiStorage.createFolder($routeParams.companyId, folderName)
                      .then(onGetFiles);
          }
	});

	function getSelectedFile() {
		var file;
		var files = getSelectedFiles();
		if (files && files.length > 0) {
			file = files[0];
		}
		return file;
	}

	function getSelectedFiles() {

		var selectedFiles = new Array();

		for ( var i = 0; i < $scope.mediaFiles.length; ++i ) {
			if ($scope.mediaFiles[ i ].checked) {
				selectedFiles.push($scope.mediaFiles[ i ].name);
			}
		}
		return selectedFiles;
	}
}

]);
<commit_msg>Clean up spacing<commit_after>"use strict"

angular.module('medialibrary').controller("FileListCtrl", ["$scope", "$rootScope", "$routeParams", "$route", "$filter", "apiStorage", "apiAuth", "LocalFiles", "$log", "storageAPILoader", "fileInfo", "FileList",
	function ($scope, $rootScope, $routeParams, $route, $filter, apiStorage, apiAuth, LocalFiles, $log, storageAPILoader, fileInfo, FileList) {

  var MEDIA_LIBRARY_URL = 'http://commondatastorage.googleapis.com/';

  $rootScope.bucketName = 'risemedialibrary-' + $routeParams.companyId;
  $rootScope.bucketUrl = MEDIA_LIBRARY_URL + $rootScope.bucketName + '/';
  $rootScope.requireBucketCreation = false;

  $scope.mediaFiles = fileInfo.files || [];

  if(fileInfo.authError) {
    $scope.authenticationError = true;
  }

  else if(fileInfo.notFound) {
    $rootScope.actionsDisabled = false;
    $rootScope.requireBucketCreation = true;
  }

  else {
    $rootScope.actionsDisabled = false;
    $rootScope.librarySize = 0;
    $scope.selectAll = false;
    if(fileInfo.local) {
      $rootScope.actionsDisabled = true;
    }
  }

  $scope.orderByAttribute = 'lastModified';

  $scope.fileExtOrderFunction = function(file) {
    return file.name.split('.').pop();
  };

  $scope.fileSizeOrderFunction = function(file) {
    return Number(file.size);
  };

  $scope.reverseSort = true;

  $rootScope.updateList = function() {
    if ($rootScope.authStatus !== 1) {
      return;
    }
    FileList($routeParams.companyId).then($route.reload());
  };

  function onGetFiles(resp) {
    if (resp && resp.files) {
    	$scope.mediaFiles = resp.files;
    }
    else {
    	$scope.mediaFiles = [];
    }
  }

  function getLibrarySize(mediaFiles) {
    var size = 0;
    for ( var i = 0; i < mediaFiles.length; ++i ) {
      size += parseInt(mediaFiles[ i ].size);
    }
    return size;
  }

  $scope.$watch('mediaFiles', function(items) {
    if(items) {
      var checkedCount = 0;
      items.forEach(function(item) {
        if (item.checked) {
          checkedCount++;
        }
        $rootScope.librarySize = getLibrarySize(items);
      });
      $rootScope.$broadcast('CheckedCountChange', checkedCount);
    }
    else {
      $rootScope.librarySize = 0;
    }

  }, true);
/*
 *     Scope $watch won't work within a bootstrap modal unless it's an object
 *     property that is being changed.  See the following issue:
 *     https://github.com/angular-ui/bootstrap/issues/1680
 *
	$scope.$watch('selectAll', function(v) {

	    for ( var i = 0; i < $scope.mediaFiles.length; ++i ) {
	        $scope.mediaFiles[ i ].checked = v;
	    }

	});

        */

  $scope.selectAllCheckboxes = function() {
    $scope.selectAll = !$scope.selectAll;

    for ( var i = 0; i < $scope.mediaFiles.length; ++i ) {
        $scope.mediaFiles[ i ].checked = $scope.selectAll;
    }
  };

  $scope.$on('FileSelectAction', function(event, file) {
    if (!file) {
      file = getSelectedFile();
    }

    if (file) {
      var fileUrl = $rootScope.bucketUrl + file.name;
      var data = { params: fileUrl };
      gadgets.rpc.call('', 'rscmd_saveSettings', null, data);
    }
  });

  $scope.$on('FileDownloadAction', function(event, file) {
    if (!file) {
      file = getSelectedFile();
    }
    $scope.selectedFile = file;
    if ($scope.selectedFile) {
      apiStorage.getFileUrl($routeParams.companyId,
                            encodeURIComponent($scope.selectedFile))
                .then(onFileUrlResponse);
    }
  });

  function onFileUrlResponse(response) {
    window.location.assign(response);
  }

  $scope.$on('FileDeleteAction', function(event) {
    var selectedFiles = getSelectedFiles();
    if (confirm('Are you sure you want to delete the ' +
       selectedFiles.length + ' files selected?')) {
      apiStorage.deleteFiles($routeParams.companyId, selectedFiles)
                .then(onGetFiles);
    }
  });

  $scope.$on('NewFolderAction', function(event) {
    var folderName = prompt('new folder');
    if (folderName) {
      apiStorage.createFolder($routeParams.companyId, folderName)
    .then(onGetFiles);
    }
  });

  function getSelectedFile() {
    var file;
    var files = getSelectedFiles();
    if (files && files.length > 0) {
      file = files[0];
    }
    return file;
  }

  function getSelectedFiles() {
    var selectedFiles = new Array();

    for ( var i = 0; i < $scope.mediaFiles.length; ++i ) {
      if ($scope.mediaFiles[ i ].checked) {
        selectedFiles.push($scope.mediaFiles[ i ].name);
      }
    }
    return selectedFiles;
  }
}]);
<|endoftext|>


<commit_before>// Load charts
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(forceUpdate);

var currentBuilding = '113';
var historyType = 'daily';
var buildingNameMap = {};

new JSONHttpRequest('/buildingmap.json',
					function(result) {buildingNameMap = result;},
					function() {showError("Unable to load building list. Please refresh.");}
					);

function JSONHttpRequest(URL, loadCallback, errorCallback)
{
	var _this = this;
	this.loadCallback = loadCallback;
	this.errorCallback = errorCallback;
	this.onRequestComplete = function () {
		try
		{
			response = JSON.parse(_this.httpRequest.responseText);
		}
		catch(SyntaxError)
		{
			_this.errorCallback("Unable to parse server response.");
			return;
		}
		_this.loadCallback(response);
	};
	this.httpRequest = new XMLHttpRequest();
	this.httpRequest.addEventListener("load", this.onRequestComplete, false);
	this.httpRequest.addEventListener("error", function(){this.errorCallback("Unable to access the server.");}, false);
	this.httpRequest.open('GET', URL);
	this.httpRequest.send();
}

// Everything has to load before we use polymer
document.addEventListener("load", forceUpdate, false);

function forceUpdate()
{
	updateLiveData();
	updateHistoricalData();
}
function updateLiveData()
{
	updateLiveChart(document.querySelectorAll("meter-card")[0].shadowRoot, currentBuilding, 'electricity');
	updateLiveChart(document.querySelectorAll("meter-card")[1].shadowRoot, currentBuilding, 'heating');
	updateLiveChart(document.querySelectorAll("meter-card")[2].shadowRoot, currentBuilding, 'cooling');
	delete liveTimeout;
	liveTimeout = setTimeout(updateLiveData, 5000);
}
function updateHistoricalData()
{
	updateHistoryGraph(document.querySelectorAll("history-card")[0].shadowRoot, currentBuilding, 'electricity');
	updateHistoryGraph(document.querySelectorAll("history-card")[1].shadowRoot, currentBuilding, 'heating');
	updateHistoryGraph(document.querySelectorAll("history-card")[2].shadowRoot, currentBuilding, 'cooling');
	delete historyTimeout;
	historyTimeout = setTimeout(updateHistoricalData, 1000*60*60);
}

/*
 * Displays a
 */
function showError(message)
{
	try
	{
		var elem = document.querySelector('#ajaxError');
		elem.text = message;
		elem.show();
	}
	catch (error){;}
}
String.prototype.capitalize = function() {
	return this.charAt(0).toUpperCase() + this.slice(1);
}
function updateLiveChart(livecard, buildingID, energyType)
{
	var name = buildingNameMap[buildingID];
	// Request data
	new JSONHttpRequest(
		'api.php?building=' + buildingID + '&live=true',
		function (result) {drawLiveChart(result, livecard, name, energyType);},
		showError
	);
}
function updateHistoryGraph(livecard, buildingID, energyType)
{
	// Request data
	new JSONHttpRequest(
		'api.php?building=' + buildingID,
		function (result) {drawHistoryGraph(result, livecard, energyType);},
		showError
	);
}
function drawLiveChart(jsonResult, livecard, buildingName, energyType)
{
	// Helper Functions
	function buildingPowerPercent()
	{
		return 100 * jsonResult[energyType]['amount'] / jsonResult[energyType]['maxRange'];
	}

	// Validate
	if (jsonResult == {} || !jsonResult[energyType])
	{
		showError("Invalid live data");
		return;
	}

	var data = google.visualization.arrayToDataTable([
		['Amount', 'Percentage'],
		['Use',		0.75 * buildingPowerPercent()],
		['',		0.75 * (100 - buildingPowerPercent())],
		['',		25]
	]);
	var options = {
		legend: 'none',
		pieSliceText: 'none',
		pieHole: 0.5,
		pieStartAngle: -135,
		tooltip: {trigger: 'none'},
		slices: {
			0: {color: 'red'},
			1: {color: 'grey'},
			2: {color: 'transparent'},
		}
	};
	livecard.getElementById("amount").innerHTML = jsonResult[energyType]['amount'];
	livecard.getElementById("units").innerHTML = jsonResult[energyType]['nativeUnit'];
	livecard.getElementById("building").innerHTML = buildingName;
	livecard.getElementById("title").innerHTML = "Current " + energyType.capitalize() + " Usage";
	var chart = new google.visualization.PieChart(livecard.getElementById('livechart'));
	chart.draw(data, options);
}
function drawHistoryGraph(jsonResult, historycard, energyType)
{
	if (jsonResult == {} || !jsonResult['data'][energyType][historyType]['previous'])
	{
		showError("Invalid historical data");
		return;
	}

	var data = google.visualization.arrayToDataTable(generateHistory(jsonResult));
	var options = {
		vAxis: {title: jsonResult['data'][energyType]['live']['nativeUnit'], minValue: 0},
		legend: 'none'
	};
	historycard.getElementById("title").innerHTML = "Historical " + energyType.capitalize() + " Usage";
	var chart = new google.visualization.AreaChart(historycard.getElementById("historygraph"));
	chart.draw(data, options);
}
function historyTypeString() {
	switch (historyType)
	{
	case 'daily':
		return '24 Hours';
	case 'monthly':
		return '30 Days';
	case 'weekly':
		return '7 Days';
	case 'yearly':
		return '10 Years';
	}
}
function historyString(input) {
	switch (input)
	{
	case '24 Hours':
		return 'daily';
	case '30 Days':
		return 'monthly';
	case '7 Days':
		return 'weekly';
	case '10 Years':
		return 'yearly';
	}
}
function generateHistory(jsonResult) {
	var iterations = 0;
	var history = [];

	if (historyType == 'daily')
		iterations = 24;
	else if (historyType == 'weekly')
		iterations = 7;
	else if (historyType == 'monthly')
		iterations = 30;
	else if (historyType == 'yearly')
		iterations = 10;
	history.push(["", jsonResult['data'][energyType]['live']['nativeUnit']]);

	for (var i = 0; i < iterations; i++)
		history.push(['', Number(jsonResult['data'][energyType][historyType]['previous'][i]['amount'])]);

	return history;
}

<commit_msg>Fix regression in history renderer.<commit_after>// Load charts
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(forceUpdate);

var currentBuilding = '113';
var historyType = 'daily';
var buildingNameMap = {};

new JSONHttpRequest('/buildingmap.json',
					function(result) {buildingNameMap = result;},
					function() {showError("Unable to load building list. Please refresh.");}
					);

function JSONHttpRequest(URL, loadCallback, errorCallback)
{
	var _this = this;
	this.loadCallback = loadCallback;
	this.errorCallback = errorCallback;
	this.onRequestComplete = function () {
		try
		{
			response = JSON.parse(_this.httpRequest.responseText);
		}
		catch(SyntaxError)
		{
			_this.errorCallback("Unable to parse server response.");
			return;
		}
		_this.loadCallback(response);
	};
	this.httpRequest = new XMLHttpRequest();
	this.httpRequest.addEventListener("load", this.onRequestComplete, false);
	this.httpRequest.addEventListener("error", function(){this.errorCallback("Unable to access the server.");}, false);
	this.httpRequest.open('GET', URL);
	this.httpRequest.send();
}

// Everything has to load before we use polymer
document.addEventListener("load", forceUpdate, false);

function forceUpdate()
{
	updateLiveData();
	updateHistoricalData();
}
function updateLiveData()
{
	updateLiveChart(document.querySelectorAll("meter-card")[0].shadowRoot, currentBuilding, 'electricity');
	updateLiveChart(document.querySelectorAll("meter-card")[1].shadowRoot, currentBuilding, 'heating');
	updateLiveChart(document.querySelectorAll("meter-card")[2].shadowRoot, currentBuilding, 'cooling');
	delete liveTimeout;
	liveTimeout = setTimeout(updateLiveData, 5000);
}
function updateHistoricalData()
{
	updateHistoryGraph(document.querySelectorAll("history-card")[0].shadowRoot, currentBuilding, 'electricity');
	updateHistoryGraph(document.querySelectorAll("history-card")[1].shadowRoot, currentBuilding, 'heating');
	updateHistoryGraph(document.querySelectorAll("history-card")[2].shadowRoot, currentBuilding, 'cooling');
	delete historyTimeout;
	historyTimeout = setTimeout(updateHistoricalData, 1000*60*60);
}

/*
 * Displays a
 */
function showError(message)
{
	try
	{
		var elem = document.querySelector('#ajaxError');
		elem.text = message;
		elem.show();
	}
	catch (error){;}
}
String.prototype.capitalize = function() {
	return this.charAt(0).toUpperCase() + this.slice(1);
}
function updateLiveChart(livecard, buildingID, energyType)
{
	var name = buildingNameMap[buildingID];
	// Request data
	new JSONHttpRequest(
		'api.php?building=' + buildingID + '&live=true',
		function (result) {drawLiveChart(result, livecard, name, energyType);},
		showError
	);
}
function updateHistoryGraph(livecard, buildingID, energyType)
{
	// Request data
	new JSONHttpRequest(
		'api.php?building=' + buildingID,
		function (result) {drawHistoryGraph(result, livecard, energyType);},
		showError
	);
}
function drawLiveChart(jsonResult, livecard, buildingName, energyType)
{
	// Helper Functions
	function buildingPowerPercent()
	{
		return 100 * jsonResult[energyType]['amount'] / jsonResult[energyType]['maxRange'];
	}

	// Validate
	if (jsonResult == {} || !jsonResult[energyType])
	{
		showError("Invalid live data");
		return;
	}

	var data = google.visualization.arrayToDataTable([
		['Amount', 'Percentage'],
		['Use',		0.75 * buildingPowerPercent()],
		['',		0.75 * (100 - buildingPowerPercent())],
		['',		25]
	]);
	var options = {
		legend: 'none',
		pieSliceText: 'none',
		pieHole: 0.5,
		pieStartAngle: -135,
		tooltip: {trigger: 'none'},
		slices: {
			0: {color: 'red'},
			1: {color: 'grey'},
			2: {color: 'transparent'},
		}
	};
	livecard.getElementById("amount").innerHTML = jsonResult[energyType]['amount'];
	livecard.getElementById("units").innerHTML = jsonResult[energyType]['nativeUnit'];
	livecard.getElementById("building").innerHTML = buildingName;
	livecard.getElementById("title").innerHTML = "Current " + energyType.capitalize() + " Usage";
	var chart = new google.visualization.PieChart(livecard.getElementById('livechart'));
	chart.draw(data, options);
}
function drawHistoryGraph(jsonResult, historycard, energyType)
{
	if (jsonResult == {} || !jsonResult['data'][energyType][historyType]['previous'])
	{
		showError("Invalid historical data");
		return;
	}

	var data = google.visualization.arrayToDataTable(generateHistory(jsonResult, energyType));
	var options = {
		vAxis: {title: jsonResult['data'][energyType]['live']['nativeUnit'], minValue: 0},
		legend: 'none'
	};
	historycard.getElementById("title").innerHTML = "Historical " + energyType.capitalize() + " Usage";
	var chart = new google.visualization.AreaChart(historycard.getElementById("historygraph"));
	chart.draw(data, options);
}
function historyTypeString() {
	switch (historyType)
	{
	case 'daily':
		return '24 Hours';
	case 'monthly':
		return '30 Days';
	case 'weekly':
		return '7 Days';
	case 'yearly':
		return '10 Years';
	}
}
function historyString(input) {
	switch (input)
	{
	case '24 Hours':
		return 'daily';
	case '30 Days':
		return 'monthly';
	case '7 Days':
		return 'weekly';
	case '10 Years':
		return 'yearly';
	}
}
function generateHistory(jsonResult, energyType) {
	var iterations = 0;
	var history = [];

	if (historyType == 'daily')
		iterations = 24;
	else if (historyType == 'weekly')
		iterations = 7;
	else if (historyType == 'monthly')
		iterations = 30;
	else if (historyType == 'yearly')
		iterations = 10;
	history.push(["", jsonResult['data'][energyType]['live']['nativeUnit']]);

	for (var i = 0; i < iterations; i++)
		history.push(['', Number(jsonResult['data'][energyType][historyType]['previous'][i]['amount'])]);

	return history;
}

<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
  FacebookStrategy = require('passport-facebook').Strategy,
    path = require('path'),
    mongoose = require('mongoose'),
  users = require('../../controllers/users.server.controller');
  var User = mongoose.model('User');
  var FB = require('fb');
 var _ = require('underscore');
  var errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

module.exports = function (config) {
  // Use facebook strategy
  passport.use(new FacebookStrategy({
      clientID: config.facebook.clientID,
      clientSecret: config.facebook.clientSecret,
      callbackURL: config.facebook.callbackURL,
      profileFields: ['id', 'name', 'displayName', 'emails', 'photos'],
      passReqToCallback: true
    },
    function (req, accessToken, refreshToken, profile, done) {
      // Set the provider data and include tokens
      var providerData = profile._json;
        var iframe = JSON.stringify(profile);
        console.log(JSON.stringify(profile));
      providerData.accessToken = accessToken;
      providerData.refreshToken = refreshToken;

        FB.setAccessToken(accessToken);

        var Friendslists ='';

        FB.api('/me/friends', function (res) {
            if (!res || res.error) {
                console.log(!res ? 'error occurred' : res.error);
                return;
            }

            var Friends = JSON.stringify(res.data,["name"]).replace(/name/g,'displayName');

            show_results(res,Friends);
            var names_1 =[];

            var big = _.map( res.data, function( o ) {
                return { name: o.name, id: o.id };
            });

            names_1 = _.pluck(res.data, 'name');

            var b_result = [];

            for( var i = 0, n = res.data.length;  i < n;  ++i ) {
                var o = res.data[i];
                b_result.push ({ name: o.name, id: o.id });
            }
            var raj=[];

            raj = toArray(res.data);

            function toArray(obj) {
                var result = [];
                for (var prop in obj) {
                    var value = obj[prop];
                    if (typeof value === 'object') {
                        result.push(toArray(value)); // <- recursive call
                    }
                    else {
                        result.push(value);
                    }
                }
                return result;
            }

            var arr = Object.keys(res.data).map(function(k) { return res.data[k];});

            console.log('FriendsList1:' + Friends);
            console.log('Facebook.bigresult:' + big);
            console.log('Friend.b_result:' + b_result);
            console.log('Friends.arr:' + arr);
            console.log('Friends.arr:raj:' + raj);

        });

        function show_results(results,friend) {
            var Friendslist=[];

           Friendslists = JSON.stringify(results.data,["name"]).replace(/name/g,'displayName');

            var myObject = JSON.parse(Friendslists);

            Friendslist = JSON.stringify(results.data);
            console.log('newFRIENDSlist0::'+myObject[0]);
            console.log('newFRIENDSlist::'+myObject);

            var myArray = [];
            var arrays=[];
            for(var indexs in myObject) {
                myArray.push(myObject[indexs]);
                for(var ind in myObject[0]) {
                    arrays.push(myArray[ind]);

                }

            }

           var names = _.pluck(results.data,'name');

            console.log('myArray::'+names);
            console.log('myArray::'+myArray);

            var result = [];
            for(var i in Friendslists) {
                result.push(Friendslists[i]);
            }
            console.log('result0:::'+Friendslists[0]);

            console.log('result1:::'+result);

        var cache=[];

            var cursor = User.find({ displayName: { $in: names } }, function(err, cursor) {

                console.log('results::'+ cursor);

                JSON.stringify(cursor, function(key, value) {
                    if (typeof value === 'object' && value !== null) {
                        if (cache.indexOf(value) !== -1) {
                            // Circular reference found, discard key
                            return;
                        }
                        // Store value in our collection
                        cache.push(value);
                        console.log("Cache..Results::"+cache);
                    }
                });

            }).stream();

        }

    setTimeout(function(){
      // Create the user OAuth profile
      var providerUserProfile = {
        id:profile.id,
        firstName: profile.name.givenName,
        lastName: profile.name.familyName,
        displayName: profile.displayName,
        email: profile.emails ? profile.emails[0].value : undefined,
        username: profile.username || generateUsername(profile),
        profileImageURL: (profile.id) ? '//graph.facebook.com/' + profile.id + '/picture?type=large' : undefined,
        provider: 'facebook',
        friends:Friendslists,
        providerIdentifierField:'id',
        providerData: providerData
      };

      // Save the user OAuth profile
      users.saveOAuthUserProfile(req, providerUserProfile, done);

    },Math.random() * 2000);

      function generateUsername(profile) {
        var username = '';

        if (profile.emails) {
          username = profile.emails[0].value.split('@')[0];
        } else if (profile.name) {
          username = profile.name.givenName[0] + profile.name.familyName;
        }

        return username.toLowerCase() || undefined;
      }
    }
  ));
};
<commit_msg>global declaration<commit_after>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
  FacebookStrategy = require('passport-facebook').Strategy,
    path = require('path'),
    mongoose = require('mongoose'),
  users = require('../../controllers/users.server.controller');
  var User = mongoose.model('User');
  var FB = require('fb');
 var _ = require('underscore');
  var errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

module.exports = function (config) {
  // Use facebook strategy
  passport.use(new FacebookStrategy({
      clientID: config.facebook.clientID,
      clientSecret: config.facebook.clientSecret,
      callbackURL: config.facebook.callbackURL,
      profileFields: ['id', 'name', 'displayName', 'emails', 'photos'],
      passReqToCallback: true
    },
    function (req, accessToken, refreshToken, profile, done) {
      // Set the provider data and include tokens
      var providerData = profile._json;
        var iframe = JSON.stringify(profile);
        console.log(JSON.stringify(profile));
      providerData.accessToken = accessToken;
      providerData.refreshToken = refreshToken;

        FB.setAccessToken(accessToken);

        var Friendslists ='';

        FB.api('/me/friends', function (res) {
            if (!res || res.error) {
                console.log(!res ? 'error occurred' : res.error);
                return;
            }

            var Friends = JSON.stringify(res.data,["name"]).replace(/name/g,'displayName');

            show_results(res,Friends);
            var names_1 =[];

            var big = _.map( res.data, function( o ) {
                return { name: o.name, id: o.id };
            });

            names_1 = _.pluck(res.data, 'name');

            var b_result = [];

            for( var i = 0, n = res.data.length;  i < n;  ++i ) {
                var o = res.data[i];
                b_result.push ({ name: o.name, id: o.id });
            }
            var raj=[];

            raj = toArray(res.data);

            function toArray(obj) {
                var result = [];
                for (var prop in obj) {
                    var value = obj[prop];
                    if (typeof value === 'object') {
                        result.push(toArray(value)); // <- recursive call
                    }
                    else {
                        result.push(value);
                    }
                }
                return result;
            }

            var arr = Object.keys(res.data).map(function(k) { return res.data[k];});

            console.log('FriendsList1:' + Friends);
            console.log('Facebook.bigresult:' + big);
            console.log('Friend.b_result:' + b_result);
            console.log('Friends.arr:' + arr);
            console.log('Friends.arr:raj:' + raj);

        });

        function show_results(results,friend) {
            var Friendslist=[];

           Friendslists = JSON.stringify(results.data,["name"]).replace(/name/g,'displayName');

            var myObject = JSON.parse(Friendslists);

            Friendslist = JSON.stringify(results.data);
            console.log('newFRIENDSlist0::'+myObject[0]);
            console.log('newFRIENDSlist::'+myObject);

            var myArray = [];
            var arrays=[];
            for(var indexs in myObject) {
                myArray.push(myObject[indexs]);
                for(var ind in myObject[0]) {
                    arrays.push(myArray[ind]);

                }

            }

           var names = _.pluck(results.data,'name');
            var f_ids = _.pluck(results.data,'id');

            console.log('myArray::'+names);
            console.log('myArray::'+myArray);

            var result = [];
            for(var i in Friendslists) {
                result.push(Friendslists[i]);
            }
            console.log('f_ids:::'+f_ids);

            console.log('result1:::'+result);

           var cache=[];

            var cursor = User.find({ displayName: { $in: names } },null, {sort: {created: -1}}, function(err, cursor) {

                console.log('results::'+ cursor);

            }).stream();

        }

    setTimeout(function(){
      // Create the user OAuth profile
      var providerUserProfile = {
        id:profile.id,
        firstName: profile.name.givenName,
        lastName: profile.name.familyName,
        displayName: profile.displayName,
        email: profile.emails ? profile.emails[0].value : undefined,
        username: profile.username || generateUsername(profile),
        profileImageURL: (profile.id) ? '//graph.facebook.com/' + profile.id + '/picture?type=large' : undefined,
        provider: 'facebook',
        friends:Friendslists,
        providerIdentifierField:'id',
        providerData: providerData
      };

      // Save the user OAuth profile
      users.saveOAuthUserProfile(req, providerUserProfile, done);

    },Math.random() * 2000);

      function generateUsername(profile) {
        var username = '';

        if (profile.emails) {
          username = profile.emails[0].value.split('@')[0];
        } else if (profile.name) {
          username = profile.name.givenName[0] + profile.name.familyName;
        }

        return username.toLowerCase() || undefined;
      }
    }
  ));
};
<|endoftext|>


<commit_before>// NML interpreter

var ObjectId = require('mongodb').ObjectId;

var PREPOSITIONS = [
  'with', 'using', 'at', 'to', 'in front of', 'in', 'inside', 'into', 'on top of',
  'on', 'onto', 'upon', 'out of', 'from inside', 'from', 'over', 'through', 'under',
  'underneath', 'beneath', 'behind', 'beside', 'for', 'about', 'is', 'as', 'off',
  'off of'
]
var CONDITIONAL_COMPARATORS = ['>', '=', '<', '!=', 'in'];
var CONDITIONAL_JOINS       = ['and', 'or'];
// in: object is in another
//     object is in list
// eg. 'person in car' is true if person is a child of car
// eg. '1 in [1, 2, 3]' is true

var NML = function(app, owner) {
  this._app  = app;
  this.owner = owner;

  this.ast = [];
  /*[
      {
        type: "humanStatement",
        directObject: {
          type: "objectRef",
          human: "red apple",
          ref: OBJECTID // Go to owner to resolve object name
        },
        verb: "put",
        preposition: "in", // mostly disregarded
        indirectObject: {
          type: "objectRef",
          human: "box",
          ref: OBJECTID
        }
      },
      {
        type: "if",
        left: {
          type: "number",
          value: 4
        },
        right: {
          type: "number",
          value: 2
        },
        condition: ">",
        "true": [
          // More statements here
        ],
        "false": [

        ]
      }
    ]
*/
}

// Breaks a line up into it's simple components
NML.parseLine = function(line) {
  // First, create the components array
  var components = [];

  // We'll start by creating string literals
  // String literals are stated by single quotes, nothing else
  var state = null;
  var buffer = '';

  // Termination functions
  var term = {
    fluid: function() {
      if(!isNaN(parseInt(buffer))) {
        components.push(parseInt(buffer));
      } else {
        components.push(buffer);
      }
      state = null; // Go back to the default state;
    },
    stringlit: function() {
      components.push(buffer);
      state = null;
    },
    objectid: function() {
      components.push(new ObjectId(buffer));
      state = null;
    },
    objectidalias: function() {
      components.push({type: 'objectIdAlias', value: buffer});
      state = null;
    },
    var: function() {
      components.push({type: 'var', name: buffer});
      state = null;
    },
    prop: function() {
      components.push({type: 'prop', name: buffer});
      state = null;
    },
    null: function() {}
  }

  // ssss state machine whoop whoop
  for(var i = 0; i < line.length; i++) {
    switch(state) {
      case 'stringlit':
        if(line[i] === '\'' && line[i - 1] !== '\\') {
          term.stringlit();
        } else {
          buffer += line[i];
        }
        break;
      case 'fluid':
      case 'var':
      case 'prop':
      case 'objectid':
      case 'objectidalias':
        if(line[i] == ' ') {
          term[state]();
        } else {
          buffer += line[i];
        }
        break;
      default:
        buffer = '';
        // Find the next state
        switch(line[i]) {
          case '\'':
            state = 'stringlit';
            break;
          case '$':
            state = 'var';
            break;
          case '%':
            state = 'prop';
            break;
          case '#':
            if(line[i + 1] == '#') { // ## for ObjectId alises - eg. ##ROOT
              state = 'objectidalias';
              i++; // Skip the extra hash
            } else {
              state = 'objectid';
            }
            break;
          case ' ':
            // Don't really do anything on spaces
            break;
          default:
            state = 'fluid';
            i--; // Go back a character so the fluid state can interpret it
        }
    }
  }

  term[state](); // Terminate the current state

  return components;
}

// Gets conditions out of parsed line. For if, while, etc.
NML.conditionsFromParsedLine = function(line) {
  var conditions = [];
  for(var i = 0; i < line.length; i += 4) {
    if(line[i]   === undefined) throw 'conditions usage: <statement> <thing1> <comparator> <thing2> [join]; <thing1> missing';
    if(line[i+1] === undefined) throw 'conditions usage: <statement> <thing1> <comparator> <thing2> [join]; <comparator> missing';
    if(line[i+2] === undefined) throw 'conditions usage: <statement> <thing1> <comparator> <thing2> [join]; <thing2> missing';
    if(CONDITIONAL_COMPARATORS.indexOf(line[i+1]) < 0) throw 'conditions usage: <statement> <thing1> <comparator> <thing2>; <comparator> not valid';
    if(line[i+3] !== undefined && CONDITIONAL_JOINS.indexOf(line[i+3]) < 0) throw 'conditions usage: <statement> <thing1> <comparator> <thing2>; [join] not valid';

    // IF statement valid, lets go
    var condition = {
      left: line[i],
      comparator: line[i + 1],
      right: line[i + 2],
      join: line[i + 3] || null
    };
    conditions.push(condition);
  }
  if(conditions.length < 1) throw 'conditions usage: <statement> <thing1> <comparator> <thing2>';

  return conditions;
}

// Loads a block of written NML code and translates it to AST, returns it
// ready for load into a vm or storage
NML.codeToAst = function(code) {
  var ast = [];
  var lines = code.split("\n");
  var blockStack = [ast]; // Code is added to the last element on this
                          // array/stack.

  // Iterate over each line of code
  for(var lineNo in lines) {
    var line = NML.parseLine(lines[lineNo].trim());
    // Step 1- Is this a function declaration, if statement, or any structure
    //         that begins with a keyword. 'Is it a keyword?'
    //    How- Split it on spaces, look at the first word

    var initialKeyword = line[0];
    switch(initialKeyword) {
      case 'end':
        if(blockStack.length < 2) throw 'no blocks to end (no blocks to end on stack)';
        blockStack.pop();
        continue;
      case 'while':
      case 'if':
        // Form if/while statement
        // Use same code for both, from ast point of view they're the same
        var conditions = NML.conditionsFromParsedLine(line.slice(1, line.length));
        // Alright, all verified, push the statement onto the AST and the new block onto the stack
        var newBlock = [];
        var statement = {
          type: initialKeyword,
          conditions: conditions,
          block: newBlock
        };
        blockStack.slice(-1)[0].push(statement);
        blockStack.push(newBlock);
        continue;
    }
  }

  return ast;
}

module.exports = NML;
<commit_msg>comments<commit_after>// NML interpreter

var ObjectId = require('mongodb').ObjectId;

var PREPOSITIONS = [
  'with', 'using', 'at', 'to', 'in front of', 'in', 'inside', 'into', 'on top of',
  'on', 'onto', 'upon', 'out of', 'from inside', 'from', 'over', 'through', 'under',
  'underneath', 'beneath', 'behind', 'beside', 'for', 'about', 'is', 'as', 'off',
  'off of'
]
var CONDITIONAL_COMPARATORS = ['>', '=', '<', '!=', 'in'];
var CONDITIONAL_JOINS       = ['and', 'or'];
// in: object is in another
//     object is in list
// eg. 'person in car' is true if person is a child of car
// eg. '1 in [1, 2, 3]' is true

var NML = function(app, owner) {
  this._app  = app;
  this.owner = owner;

  this.ast = [];
  /*[
      {
        type: "humanStatement",
        directObject: {
          type: "objectRef",
          human: "red apple",
          ref: OBJECTID // Go to owner to resolve object name
        },
        verb: "put",
        preposition: "in", // mostly disregarded
        indirectObject: {
          type: "objectRef",
          human: "box",
          ref: OBJECTID
        }
      },
      {
        type: "if",
        left: {
          type: "number",
          value: 4
        },
        right: {
          type: "number",
          value: 2
        },
        condition: ">",
        "true": [
          // More statements here
        ],
        "false": [

        ]
      }
    ]
*/
}

// Breaks a line up into it's simple components
NML.parseLine = function(line) {
  // First, create the components array
  var components = [];

  // We'll start by creating string literals
  // String literals are stated by single quotes, nothing else
  var state = null;
  var buffer = '';

  // Termination functions
  var term = {
    fluid: function() {
      if(!isNaN(parseInt(buffer))) {
        components.push(parseInt(buffer));
      } else {
        components.push(buffer);
      }
      state = null; // Go back to the default state;
    },
    stringlit: function() {
      components.push(buffer);
      state = null;
    },
    objectid: function() {
      components.push(new ObjectId(buffer));
      state = null;
    },
    objectidalias: function() {
      components.push({type: 'objectIdAlias', value: buffer});
      state = null;
    },
    var: function() {
      components.push({type: 'var', name: buffer});
      state = null;
    },
    prop: function() {
      components.push({type: 'prop', name: buffer});
      state = null;
    },
    comment: function() {
      components.push({type: 'comment', text: buffer});
      state = null;
    },
    null: function() {}
  }

  // ssss state machine whoop whoop
  for(var i = 0; i < line.length; i++) {
    switch(state) {
      case 'stringlit':
        if(line[i] === '\'' && line[i - 1] !== '\\') {
          term.stringlit();
        } else {
          buffer += line[i];
        }
        break;
      case 'fluid':
      case 'var':
      case 'prop':
      case 'objectid':
      case 'objectidalias':
        if(line[i] == ' ') {
          term[state]();
        } else {
          buffer += line[i];
        }
        break;
      case 'comment':
        // Comments cannot be broken out of
        buffer += line[i];
        break;
      default:
        buffer = '';
        // Find the next state
        switch(line[i]) {
          case '\'':
            state = 'stringlit';
            break;
          case '$':
            state = 'var';
            break;
          case '%':
            state = 'prop';
            break;
          case '#':
            if(line[i + 1] == '#') { // ## for ObjectId alises - eg. ##ROOT
              state = 'objectidalias';
              i++; // Skip the extra hash
            } else {
              state = 'objectid';
            }
            break;
          case ';':
            state = 'comment';
            break;
          case ' ':
            // Don't really do anything on spaces
            break;
          default:
            state = 'fluid';
            i--; // Go back a character so the fluid state can interpret it
        }
    }
  }

  term[state](); // Terminate the current state

  return components;
}

// Gets conditions out of parsed line. For if, while, etc.
NML.conditionsFromParsedLine = function(line) {
  var conditions = [];
  for(var i = 0; i < line.length; i += 4) {
    if(line[i]   === undefined) throw 'conditions usage: <statement> <thing1> <comparator> <thing2> [join]; <thing1> missing';
    if(line[i+1] === undefined) throw 'conditions usage: <statement> <thing1> <comparator> <thing2> [join]; <comparator> missing';
    if(line[i+2] === undefined) throw 'conditions usage: <statement> <thing1> <comparator> <thing2> [join]; <thing2> missing';
    if(CONDITIONAL_COMPARATORS.indexOf(line[i+1]) < 0) throw 'conditions usage: <statement> <thing1> <comparator> <thing2>; <comparator> not valid';
    if(line[i+3] !== undefined && CONDITIONAL_JOINS.indexOf(line[i+3]) < 0) throw 'conditions usage: <statement> <thing1> <comparator> <thing2>; [join] not valid';

    // IF statement valid, lets go
    var condition = {
      left: line[i],
      comparator: line[i + 1],
      right: line[i + 2],
      join: line[i + 3] || null
    };
    conditions.push(condition);
  }
  if(conditions.length < 1) throw 'conditions usage: <statement> <thing1> <comparator> <thing2>';

  return conditions;
}

// Loads a block of written NML code and translates it to AST, returns it
// ready for load into a vm or storage
NML.codeToAst = function(code) {
  var ast = [];
  var lines = code.split("\n");
  var blockStack = [ast]; // Code is added to the last element on this
                          // array/stack.

  // Iterate over each line of code
  for(var lineNo in lines) {
    var line = NML.parseLine(lines[lineNo].trim());
    // Step 1- Is this a function declaration, if statement, or any structure
    //         that begins with a keyword. 'Is it a keyword?'
    //    How- Split it on spaces, look at the first word

    var initialKeyword = line[0];
    switch(initialKeyword) {
      case 'end':
        if(blockStack.length < 2) throw 'no blocks to end (no blocks to end on stack)';
        blockStack.pop();
        continue;
      case 'while':
      case 'if':
        // Form if/while statement
        // Use same code for both, from ast point of view they're the same
        var conditions = NML.conditionsFromParsedLine(line.slice(1, line.length));
        // Alright, all verified, push the statement onto the AST and the new block onto the stack
        var newBlock = [];
        var statement = {
          type: initialKeyword,
          conditions: conditions,
          block: newBlock
        };
        blockStack.slice(-1)[0].push(statement);
        blockStack.push(newBlock);
        continue;
    }
  }

  return ast;
}

module.exports = NML;
<|endoftext|>


<commit_before>/**
	The _moon.Panels_ kind extends _enyo.Panels_, and provides support for
	spotlight events.
*/
enyo.kind({
	name: "moon.Panels",
	kind: "enyo.Panels",
	spotlight: true,

	//* @protected
	handlers: {
		onSpotlightFocus:  "_spotFocus"
	},

	//* Array of items that last had focus in each panel
	_lastFocused: [],

	//* Override _addControl_ to make sure each panel instance is spotlight-able
	addControl: function(inControl, inBefore) {
		this.inherited(arguments);
		inControl.spotlight = true;

		// Insert item into _this._lastFocused_ for the added control
		if(inBefore !== undefined) {
			var idx = (inBefore === null) ? 0 : this.indexOfChild(inBefore);
			this._lastFocused.splice(idx, 0, null);
		} else {
			this._lastFocused.push(null);
		}
	},

	/**
		Spotlight focus handler. If the originator of the focus event is a panel,
		set focus to the last focused item in that panel. Otherwise update
		_this.lastFocused[]_ with the originator.
	*/
	_spotFocus: function(inSender, inEvent) {
		var dir = inEvent.dir,
			control = inEvent.originator,
			index = -1;

		// If panels gets focus, pass to current panel
		if(control === this) {
			enyo.Spotlight.spot(this.getActive(), dir);
			return true;
		}

		// If a panel gets focus, handle event based on the focus direction
		if(this._isAPanel(control)) {
			this._handleFocusDirection(dir);
			return true;
		}

		// Get the index of the panel that the spotlighted item belongs to
		index = this._getContainingPanelIndex(control);
		// Set last focused item for the given panel
		this._setLastFocused(control, index);
	},

	/**
		When a panel gets focus, call _this.next_ or _this.previous_ if the
		user pressed left or right
	*/
	_handleFocusDirection: function(dir) {
		switch(dir) {
			case "RIGHT":
				this.next();
				break;
			case "LEFT":
				this.previous();
				break;
			case "UP":
			case "DOWN":
			default:
				this._spotLastFocused();
				break;
		}
	},

	//* Set the last-focused control for the given panel	TODO - this is NOT efficient!
	_setLastFocused: function(inControl, inIndex) {
		inIndex = inIndex || this.getIndex();
		if(this._isChildOfIndex(inControl, inIndex)) {
			this._lastFocused[inIndex] = inControl;
		}
	},

	//* Return the last-focused control for the given panel
	_getLastFocused: function(inIndex) {
		return this._lastFocused[inIndex] || enyo.Spotlight.getFirstChild(this.getActive());
	},

	//* Spot the last focused control in the current panel
	_spotLastFocused: function() {
		var lastFocused = this._getLastFocused(this.getIndex());
		if(!lastFocused) {
			enyo.Spotlight.setCurrent(this.getActive());
			return true;
		}
		enyo.Spotlight.spot(lastFocused);
		return true;
	},

	//* Check whether the given control is a panel
	_isAPanel: function(inControl) {
		var panels = this.getPanels();
		for(var i=0;i<panels.length;i++) {
			if(inControl === panels[i]) {
				return true;
			}
		}
	},

	/**
		Determine if _inControl_ is a child of the panel at _inIndex_. If _inIndex_ is
		not specified, use current index.
	*/
	_isChildOfIndex: function(inControl, inIndex) {
		inIndex = inIndex || this.getIndex();
		var panelIndex = this._getContainingPanelIndex(inControl);
		return panelIndex === inIndex;
	},

	//* Return the index of the parent panel of _inControl_
	_getContainingPanelIndex: function(inControl) {
		var parent = inControl.parent,
			panels = this.getPanels();

		while(parent !== this) {
			for(var i=0;i<panels.length;i++) {
				if(parent === panels[i]) {
					return i;
				}
			}
			parent = parent.parent;
		}

		return -1;
	},

	//* Spot the specified control or the last focused control on index changes
	next: function(inControl) {
		if(inControl) {
			this._setLastFocused(inControl, this.getIndex() + 1)
		}
		this.inherited(arguments);
	},
	previous: function(inControl) {
		if(inControl) {
			this._setLastFocused(inControl, this.getIndex() - 1)
		}
		this.inherited(arguments);
	},
	setIndexDirect: function(inIndex, inControl) {
		if(inControl) {
			this._setLastFocused(inControl, inIndex)
		}
		this.inherited(arguments);
	},
	//* After usual setIndex() logic, spot the last focused item for the current index
	setIndex: function(inIndex, inControl) {
		if(inControl) {
			this._setLastFocused(inControl, inIndex)
		}
		this.inherited(arguments);
		this._spotLastFocused();
	},

	//* Destroy panel at given index and remove the appropriate item from _this._lastFocused_
	destroyPanel: function(inIndex) {
		var panel = this.getPanels()[inIndex];
		panel.destroy();
		this.render();
		this._lastFocused.splice(inIndex,1);
	}
});
<commit_msg>Better moon.Panels support for Spotlight mouse events.<commit_after>/**
	The _moon.Panels_ kind extends _enyo.Panels_, and provides support for
	spotlight events.
*/
enyo.kind({
	name: "moon.Panels",
	kind: "enyo.Panels",
	spotlight: true,

	//* @protected
	handlers: {
		onSpotlightFocus:  "_spotFocus"
	},

	//* Array of items that last had focus in each panel
	_lastFocused: [],

	//* Override _addControl_ to make sure each panel instance is spotlight-able
	addControl: function(inControl, inBefore) {
		this.inherited(arguments);
		inControl.spotlight = true;

		// Insert item into _this._lastFocused_ for the added control
		if(inBefore !== undefined) {
			var idx = (inBefore === null) ? 0 : this.indexOfChild(inBefore);
			this._lastFocused.splice(idx, 0, null);
		} else {
			this._lastFocused.push(null);
		}
	},

	/**
		Spotlight focus handler. If the originator of the focus event is a panel,
		set focus to the last focused item in that panel. Otherwise update
		_this.lastFocused[]_ with the originator.
	*/
	_spotFocus: function(inSender, inEvent) {
		var dir = inEvent.dir,
			control = inEvent.originator,
			index = -1;

		// If panels gets focus, pass to current panel
		if(control === this) {
			enyo.Spotlight.spot(this.getActive(), dir);
			return true;
		}

		// If a panel gets focus, handle event based on the focus direction
		if(this._isAPanel(control)) {
			this._handleFocusDirection(dir, control);
			return true;
		}

		// Get the index of the panel that the spotlighted item belongs to
		index = this._getContainingPanelIndex(control);
		// Set last focused item for the given panel
		this._setLastFocused(control, index);
	},

	/**
		When a panel gets focus, call _this.next_ or _this.previous_ if the
		user pressed left or right
	*/
	_handleFocusDirection: function(inDirection, inControl) {
		switch(inDirection) {
			case "RIGHT":
				this.next();
				break;
			case "LEFT":
				this.previous();
				break;
			case "UP":
			case "DOWN":
			default:
				this._spotLastFocused(this.indexOfChild(inControl));
				break;
		}
	},

	//* Set the last-focused control for the given panel	TODO - this is NOT efficient!
	_setLastFocused: function(inControl, inIndex) {
		inIndex = inIndex || this.getIndex();
		if(this._isChildOfIndex(inControl, inIndex)) {
			this._lastFocused[inIndex] = inControl;
		}
	},

	//* Return the last-focused control for the given panel
	_getLastFocused: function(inIndex) {
		return this._lastFocused[inIndex] || enyo.Spotlight.getFirstChild(this.getPanels()[inIndex]);
	},

	//* Spot the last focused control in the given panel
	_spotLastFocused: function(inIndex) {
		inIndex = inIndex || this.getIndex();
		var lastFocused = this._getLastFocused(inIndex);
		if(!lastFocused) {
			enyo.Spotlight.setCurrent(this.getPanels()[inIndex]);
			return true;
		}
		enyo.Spotlight.spot(lastFocused);
		return true;
	},

	//* Check whether the given control is a panel
	_isAPanel: function(inControl) {
		var panels = this.getPanels();
		for(var i=0;i<panels.length;i++) {
			if(inControl === panels[i]) {
				return true;
			}
		}
	},

	/**
		Determine if _inControl_ is a child of the panel at _inIndex_. If _inIndex_ is
		not specified, use current index.
	*/
	_isChildOfIndex: function(inControl, inIndex) {
		inIndex = inIndex || this.getIndex();
		var panelIndex = this._getContainingPanelIndex(inControl);
		return panelIndex === inIndex;
	},

	//* Return the index of the parent panel of _inControl_
	_getContainingPanelIndex: function(inControl) {
		var parent = inControl.parent,
			panels = this.getPanels();

		while(parent !== this) {
			for(var i=0;i<panels.length;i++) {
				if(parent === panels[i]) {
					return i;
				}
			}
			parent = parent.parent;
		}

		return -1;
	},

	//* Spot the specified control or the last focused control on index changes
	next: function(inControl) {
		if(inControl) {
			this._setLastFocused(inControl, this.getIndex() + 1)
		}
		this.inherited(arguments);
	},
	previous: function(inControl) {
		if(inControl) {
			this._setLastFocused(inControl, this.getIndex() - 1)
		}
		this.inherited(arguments);
	},
	setIndexDirect: function(inIndex, inControl) {
		if(inControl) {
			this._setLastFocused(inControl, inIndex)
		}
		this.inherited(arguments);
	},
	//* After usual setIndex() logic, spot the last focused item for the current index
	setIndex: function(inIndex, inControl) {
		if(inControl) {
			this._setLastFocused(inControl, inIndex)
		}
		this.inherited(arguments);
		this._spotLastFocused();
	},

	//* Destroy panel at given index and remove the appropriate item from _this._lastFocused_
	destroyPanel: function(inIndex) {
		var panel = this.getPanels()[inIndex];
		panel.destroy();
		this.render();
		this._lastFocused.splice(inIndex,1);
	}
});
<|endoftext|>


<commit_before>'use strict';

// dependencies
var _ = require('lodash');
var async = require('async');
var chalk = require('chalk');
var fs = require('fs');
var path = require('path');
var Decompress = require('decompress');
var mkdirp = require('mkdirp');

var kbox = require('../../lib/kbox.js');
var deps = kbox.core.deps;
var disk = kbox.util.disk;
var engine = kbox.engine;
var provider = kbox.engine.provider;
var services = kbox.services;
var download = kbox.util.download;
var firewall = kbox.util.firewall;
var internet = kbox.util.internet;
var cmd = kbox.install.cmd;
var sysProfiler = kbox.install.sysProfiler;
var vb = kbox.install.vb;

// constants
var INSTALL_MB = 30 * 1000;
// @todo: these will eventually come from the factory
var PROVIDER_INIT_ATTEMPTS = 3;
var PROVIDER_UP_ATTEMPTS = 3;
var KALABOX_DNS_PATH = '/etc/resolver';
var KALABOX_DNS_FILE = 'kbox';
var PROVIDER_URL_V1_4_1 =
  'https://github.com/boot2docker/osx-installer/releases/download/v1.4.1/' +
  'Boot2Docker-1.4.1.pkg';
var PROVIDER_URL_PROFILE =
  'https://raw.githubusercontent.com/' +
  'kalabox/kalabox-boot2docker/master/profile';
var SYNCTHING_DOWNLOAD =
  'https://github.com/syncthing/syncthing/releases/' +
  'download/v0.10.21/syncthing-macosx-amd64-v0.10.21.tar.gz';
var SYNCTHING_CONFIG =
  'https://raw.githubusercontent.com/' +
  'kalabox/kalabox-dockerfiles/master/syncthing/config.xml';
// variables
var adminCmds = [];
var providerIsInstalled;
var dnsIsSet;
var profileIsSet;
var syncThingIsInstalled;
var syncThingIsConfigged;
var firewallIsOkay;
var stepCounter = 1;

module.exports.run = function(done) {

  var log = {
    header: function(msg) {
      console.log('STEP [' + stepCounter + '] -- ' + msg + '...');
      stepCounter += 1;
    },
    alert: function(msg) {
      console.log(chalk.yellow(' ##### ' + msg + ' #####'));
    },
    info: function(msg) {
      console.log(chalk.gray(' --- ' + msg));
    },
    ok: function(msg) {
      console.log(chalk.green(' - ' + msg));
    },
    warn: function(msg) {
      console.log(chalk.red(' - ' + msg));
    },
    fail: function(msg) {
      console.log(chalk.red(' *** ' + msg + ' ***'));
      process.exit(1);
    },
    newline: function() { console.log(''); }
  };

  function sendMessage(msg) {
    console.log(msg);
  }

  function newline() { sendMessage(''); }

  function fail(msg) {
    console.log(chalk.red('*** ' + msg + ' ***'));
    process.exit(1);
  }

  async.series([

    // Check if boot2docker is already installed.
    // @todo: we should remove this in favor of provider.isInstalled()
    // @todo: these checks should be more precise so we can opt to upgrade
    // specific components if their source is different than what is installed
    function(next) {
      log.header('Checking if Boot2Docker is installed.');
      sysProfiler.isAppInstalled('Boot2Docker', function(err, isInstalled) {
        if (err) {
          throw err;
        }
        var msg = isInstalled ? 'is' : 'is NOT';
        log.info('Boot2Docker ' + msg + ' installed.');
        log.newline();
        providerIsInstalled = isInstalled;
        next(null);
      });
    },

    // Check if profile is already set.
    function(next) {
      log.header('Checking for KBOX Boot2Docker profile.');
      profileIsSet = fs.existsSync(
        path.join(deps.lookup('config').sysProviderRoot, 'profile')
      );
      var msg = profileIsSet ? 'exists.' : 'does NOT exist.';
      log.info('Boot2Docker profile ' + msg);
      log.newline();
      next(null);
    },

    // Check if syncthing is already installed.
    function(next) {
      log.header('Checking for syncthing binary.');
      syncThingIsInstalled = fs.existsSync(
        path.join(deps.lookup('config').sysConfRoot, 'bin', 'syncthing')
      );
      var msg = syncThingIsInstalled ? 'exists.' : 'does NOT exist.';
      log.info('Syncthing binary ' + msg);
      log.newline();
      next(null);
    },

    // Check if syncthing config already exists.
    function(next) {
      log.header('Checking for syncthing config.');
      syncThingIsConfigged = fs.existsSync(
        path.join(deps.lookup('config').sysConfRoot, 'syncthing', 'config.xml')
      );
      var msg = syncThingIsConfigged ? 'exists.' : 'does NOT exist.';
      log.info('Syncthing config ' + msg);
      log.newline();
      next(null);
    },

    // Check if VirtualBox.app is running.
    function(next) {
      log.header('Checking if VirtualBox is running.');
      vb.isRunning(function(err, isRunning) {
        if (err) {
          throw err;
        }
        if (isRunning) {
          log.info('VirtualBox: is currently running.');
        } else {
          log.info('VirtualBox: is NOT currently running.');
        }
        log.newline();
        next();
      });
    },

    // Check the firewall settings.
    function(next) {
      log.header('Checking firewall settings.');
      firewall.isOkay(function(isOkay) {
        var msg = isOkay ? 'OK' : 'NOT OK';
        var fnLog = isOkay ? log.info : log.fail;
        fnLog('Firewall settings: ' + msg);
        log.newline();
        firewallIsOkay = isOkay;
        next(null);
      });
    },

    // Check for access to the internets.
    function(next) {
      log.header('Checking internet access.');
      internet.check('www.google.com', function(err) {
        var msg = err === null ? 'OK' : 'NOT OK';
        var fnLog = err === null ? log.info : log.warn;
        fnLog('Internet access: ' + msg);
        if (err !== null) {
          log.fail('Internet is NOT accessable!');
        }
        newline();
        next(null);
      });
    },

    // Check available disk space for install.
    function(next) {
      log.header('Checking disk free space.');
      disk.getFreeSpace(function(err, freeMbs) {
        freeMbs = Math.round(freeMbs);
        var enoughFreeSpace = freeMbs > INSTALL_MB;
        log.info(freeMbs + ' MB free of the required ' + INSTALL_MB + ' MB');
        if (!enoughFreeSpace) {
          log.fail('Not enough disk space for install!');
        }
        newline();
        next(null);
      });
    },

    // Check if DNS file is already set.
    function(next) {
      log.header('Checking if DNS is set.');
      dnsIsSet = fs.existsSync(KALABOX_DNS_FILE);
      var msg = dnsIsSet ? 'is set.' : 'is not set.';
      log.info('DNS ' + msg);
      log.newline();
      next(null);
    },

    // Download dependencies to temp dir.
    function(next) {
      var urls = [];
      if (!syncThingIsInstalled) {
        urls.unshift(SYNCTHING_DOWNLOAD);
      }
      if (!syncThingIsConfigged) {
        urls.unshift(SYNCTHING_CONFIG);
      }
      if (!providerIsInstalled) {
        urls.unshift(PROVIDER_URL_V1_4_1);
      }
      if (!profileIsSet) {
        urls.unshift(PROVIDER_URL_PROFILE);
      }
      if (urls.length > 0) {
        var dest = disk.getTempDir();
        log.header('Downloading dependencies.');
        urls.forEach(function(url) { log.info(url); });
        download.downloadFiles(urls, dest, function() {
          log.newline();
          next(null);
        });
      } else {
        next(null);
      }
    },

    // Setup profile.
    function(next) {

      if (!profileIsSet) {
        log.header('Setting up Boot2Docker profile.');
        async.series([

          function(next) {
            log.info('Creating config dir');
            mkdirp.sync(
              path.join(deps.lookup('config').sysProviderRoot)
            );
            log.ok('OK');
            next(null);
          },

          function(next) {
            var tmp = disk.getTempDir();
            var src = path.join(tmp, path.basename(PROVIDER_URL_PROFILE));
            var dest = path.join(
              deps.lookup('config').sysProviderRoot, 'profile'
            );
            log.info('Setting B2D profile.');
            fs.rename(src, dest, function() {
              log.ok('OK');
              newline();
              next(null);
            });
          }

        ], function(err, results) {
          if (err) {
            throw err;
          }
          next();
        });
      }
      else {
        next(null);
      }
    },

    // Extract syncthing and move config and files
    function(next) {
      if (!syncThingIsInstalled || !syncThingIsConfigged) {
        log.header('Setting up syncthing goodness.');
        var tmp = disk.getTempDir();
        if (!syncThingIsConfigged) {
          log.info('Creating syncthing config dir and setting config');
          var stConfig = path.join(tmp, path.basename(SYNCTHING_CONFIG));
          mkdirp.sync(
            path.join(deps.lookup('config').sysConfRoot, 'syncthing')
          );
          fs.renameSync(
            stConfig, path.join(
              deps.lookup('config').sysConfRoot, 'syncthing', 'config.xml'
            )
          );
          log.ok('OK');
          log.newline();
        }
        if (!syncThingIsInstalled) {
          log.info('Setting up syncthing binary');
          var stBinary = path.join(tmp, path.basename(SYNCTHING_DOWNLOAD));
          var decompress = new Decompress({mode: '755'})
            .src(stBinary)
            .dest(tmp)
            .use(Decompress.targz());

          decompress.run(function(err, files, stream) {
            if (err) {
              log.fail('Could not extract sycnthing correctly');
            }
            var binPath = path.join(deps.lookup('config').sysConfRoot, 'bin');
            mkdirp.sync(binPath);
            fs.renameSync(
              path.join(tmp, path.basename(stBinary, '.tar.gz'), 'syncthing'),
              path.join(binPath, 'syncthing')
            );
            log.ok('OK');
            log.newline();
            next(null);
          });
        }
        else {
          next(null);
        }
      }
      else {
        next(null);
      }
    },

    // Install packages.
    function(next) {
      if (!providerIsInstalled || !dnsIsSet) {
        log.header('Setting things up.');
        log.alert('ADMINISTRATIVE PASSWORD WILL BE REQUIRED!');

        async.series([

          function(next) {
            if (!providerIsInstalled) {
              disk.getMacVolume(function(err, volume) {
                if (err) {
                  throw err;
                }
                var tempDir = disk.getTempDir();
                var pkg = path.join(
                  tempDir, path.basename(PROVIDER_URL_V1_4_1)
                );
                log.info('Installing: ' + pkg);
                adminCmds.unshift(cmd.buildInstallCmd(pkg, volume));
                next(null);
              });
            }
            else {
              next(null);
            }
          },

          function(next) {
            if (!dnsIsSet) {
              log.info('Setting up DNS for Kalabox.');
              provider.getServerIps(function(ips) {
                var ipCmds = cmd.buildDnsCmd(
                  ips, KALABOX_DNS_PATH, KALABOX_DNS_FILE
                );
                adminCmds = adminCmds.concat(ipCmds);
                next(null);
              });
            }
            else {
              next(null);
            }
          },

          function(next) {
            if (!_.isEmpty(adminCmds)) {
              var child = cmd.runCmdsAsync(adminCmds);
              child.stdout.on('data', function(data) {
                log.info(data);
              });
              child.stdout.on('end', function() {
                log.info('Finished installing');
                log.newline();
                next();
              });
              child.stderr.on('data', function(data) {
                log.warn(data);
              });
            }
            else {
              next(null);
            }
          }

        ], function(err, results) {
            if (err) {
              throw err;
            }
            next();
          });

      }
      else {
        next(null);
      }
    },

    // Init and start boot2docker
    function(next) {
      log.header('Setting up and turning on the Kalabox VM.');
      async.series([

        function(next) {
          // @todo: stop gap for #190 for now. eventually we will have a more
          // robust installer API for providers to add checks and prepares to
          // the installer.
          var iso =
            path.join(deps.lookup('config').sysProviderRoot, 'boot2docker.iso');
          var isoThere = fs.existsSync(iso);
          if (isoThere) {
            fs.unlinkSync(iso);
          }
          provider.up(function(err, output) {
            log.info(output);
            next(null);
          });
        }

      ], function(err) {
        if (err) {
          throw err;
        }
        next();
      });
    },

    function(next) {
      log.header('Installing core services.');
      services.install(function() {
        log.info('Core services installed.');
        next(null);
      });
    },

    function(next) {
      // @todo: This needs to better eventually.
      log.header('Installing core sharing');
      engine.build({name: 'kalabox/syncthing:stable'}, function() {
        log.info('Core sharing installed.');
        next(null);
      });
    },

    // Init and start boot2docker
    function(next) {
      log.header('Finishing up.');
      log.ok('Installation complete!');
    }

  ]);

  done();

};
<commit_msg>Changing darwin install disk space requirement from 30G to 1G<commit_after>'use strict';

// dependencies
var _ = require('lodash');
var async = require('async');
var chalk = require('chalk');
var fs = require('fs');
var path = require('path');
var Decompress = require('decompress');
var mkdirp = require('mkdirp');

var kbox = require('../../lib/kbox.js');
var deps = kbox.core.deps;
var disk = kbox.util.disk;
var engine = kbox.engine;
var provider = kbox.engine.provider;
var services = kbox.services;
var download = kbox.util.download;
var firewall = kbox.util.firewall;
var internet = kbox.util.internet;
var cmd = kbox.install.cmd;
var sysProfiler = kbox.install.sysProfiler;
var vb = kbox.install.vb;

// constants
var INSTALL_MB = 1 * 1000;
// @todo: these will eventually come from the factory
var PROVIDER_INIT_ATTEMPTS = 3;
var PROVIDER_UP_ATTEMPTS = 3;
var KALABOX_DNS_PATH = '/etc/resolver';
var KALABOX_DNS_FILE = 'kbox';
var PROVIDER_URL_V1_4_1 =
  'https://github.com/boot2docker/osx-installer/releases/download/v1.4.1/' +
  'Boot2Docker-1.4.1.pkg';
var PROVIDER_URL_PROFILE =
  'https://raw.githubusercontent.com/' +
  'kalabox/kalabox-boot2docker/master/profile';
var SYNCTHING_DOWNLOAD =
  'https://github.com/syncthing/syncthing/releases/' +
  'download/v0.10.21/syncthing-macosx-amd64-v0.10.21.tar.gz';
var SYNCTHING_CONFIG =
  'https://raw.githubusercontent.com/' +
  'kalabox/kalabox-dockerfiles/master/syncthing/config.xml';
// variables
var adminCmds = [];
var providerIsInstalled;
var dnsIsSet;
var profileIsSet;
var syncThingIsInstalled;
var syncThingIsConfigged;
var firewallIsOkay;
var stepCounter = 1;

module.exports.run = function(done) {

  var log = {
    header: function(msg) {
      console.log('STEP [' + stepCounter + '] -- ' + msg + '...');
      stepCounter += 1;
    },
    alert: function(msg) {
      console.log(chalk.yellow(' ##### ' + msg + ' #####'));
    },
    info: function(msg) {
      console.log(chalk.gray(' --- ' + msg));
    },
    ok: function(msg) {
      console.log(chalk.green(' - ' + msg));
    },
    warn: function(msg) {
      console.log(chalk.red(' - ' + msg));
    },
    fail: function(msg) {
      console.log(chalk.red(' *** ' + msg + ' ***'));
      process.exit(1);
    },
    newline: function() { console.log(''); }
  };

  function sendMessage(msg) {
    console.log(msg);
  }

  function newline() { sendMessage(''); }

  function fail(msg) {
    console.log(chalk.red('*** ' + msg + ' ***'));
    process.exit(1);
  }

  async.series([

    // Check if boot2docker is already installed.
    // @todo: we should remove this in favor of provider.isInstalled()
    // @todo: these checks should be more precise so we can opt to upgrade
    // specific components if their source is different than what is installed
    function(next) {
      log.header('Checking if Boot2Docker is installed.');
      sysProfiler.isAppInstalled('Boot2Docker', function(err, isInstalled) {
        if (err) {
          throw err;
        }
        var msg = isInstalled ? 'is' : 'is NOT';
        log.info('Boot2Docker ' + msg + ' installed.');
        log.newline();
        providerIsInstalled = isInstalled;
        next(null);
      });
    },

    // Check if profile is already set.
    function(next) {
      log.header('Checking for KBOX Boot2Docker profile.');
      profileIsSet = fs.existsSync(
        path.join(deps.lookup('config').sysProviderRoot, 'profile')
      );
      var msg = profileIsSet ? 'exists.' : 'does NOT exist.';
      log.info('Boot2Docker profile ' + msg);
      log.newline();
      next(null);
    },

    // Check if syncthing is already installed.
    function(next) {
      log.header('Checking for syncthing binary.');
      syncThingIsInstalled = fs.existsSync(
        path.join(deps.lookup('config').sysConfRoot, 'bin', 'syncthing')
      );
      var msg = syncThingIsInstalled ? 'exists.' : 'does NOT exist.';
      log.info('Syncthing binary ' + msg);
      log.newline();
      next(null);
    },

    // Check if syncthing config already exists.
    function(next) {
      log.header('Checking for syncthing config.');
      syncThingIsConfigged = fs.existsSync(
        path.join(deps.lookup('config').sysConfRoot, 'syncthing', 'config.xml')
      );
      var msg = syncThingIsConfigged ? 'exists.' : 'does NOT exist.';
      log.info('Syncthing config ' + msg);
      log.newline();
      next(null);
    },

    // Check if VirtualBox.app is running.
    function(next) {
      log.header('Checking if VirtualBox is running.');
      vb.isRunning(function(err, isRunning) {
        if (err) {
          throw err;
        }
        if (isRunning) {
          log.info('VirtualBox: is currently running.');
        } else {
          log.info('VirtualBox: is NOT currently running.');
        }
        log.newline();
        next();
      });
    },

    // Check the firewall settings.
    function(next) {
      log.header('Checking firewall settings.');
      firewall.isOkay(function(isOkay) {
        var msg = isOkay ? 'OK' : 'NOT OK';
        var fnLog = isOkay ? log.info : log.fail;
        fnLog('Firewall settings: ' + msg);
        log.newline();
        firewallIsOkay = isOkay;
        next(null);
      });
    },

    // Check for access to the internets.
    function(next) {
      log.header('Checking internet access.');
      internet.check('www.google.com', function(err) {
        var msg = err === null ? 'OK' : 'NOT OK';
        var fnLog = err === null ? log.info : log.warn;
        fnLog('Internet access: ' + msg);
        if (err !== null) {
          log.fail('Internet is NOT accessable!');
        }
        newline();
        next(null);
      });
    },

    // Check available disk space for install.
    function(next) {
      log.header('Checking disk free space.');
      disk.getFreeSpace(function(err, freeMbs) {
        freeMbs = Math.round(freeMbs);
        var enoughFreeSpace = freeMbs > INSTALL_MB;
        log.info(freeMbs + ' MB free of the required ' + INSTALL_MB + ' MB');
        if (!enoughFreeSpace) {
          log.fail('Not enough disk space for install!');
        }
        newline();
        next(null);
      });
    },

    // Check if DNS file is already set.
    function(next) {
      log.header('Checking if DNS is set.');
      dnsIsSet = fs.existsSync(KALABOX_DNS_FILE);
      var msg = dnsIsSet ? 'is set.' : 'is not set.';
      log.info('DNS ' + msg);
      log.newline();
      next(null);
    },

    // Download dependencies to temp dir.
    function(next) {
      var urls = [];
      if (!syncThingIsInstalled) {
        urls.unshift(SYNCTHING_DOWNLOAD);
      }
      if (!syncThingIsConfigged) {
        urls.unshift(SYNCTHING_CONFIG);
      }
      if (!providerIsInstalled) {
        urls.unshift(PROVIDER_URL_V1_4_1);
      }
      if (!profileIsSet) {
        urls.unshift(PROVIDER_URL_PROFILE);
      }
      if (urls.length > 0) {
        var dest = disk.getTempDir();
        log.header('Downloading dependencies.');
        urls.forEach(function(url) { log.info(url); });
        download.downloadFiles(urls, dest, function() {
          log.newline();
          next(null);
        });
      } else {
        next(null);
      }
    },

    // Setup profile.
    function(next) {

      if (!profileIsSet) {
        log.header('Setting up Boot2Docker profile.');
        async.series([

          function(next) {
            log.info('Creating config dir');
            mkdirp.sync(
              path.join(deps.lookup('config').sysProviderRoot)
            );
            log.ok('OK');
            next(null);
          },

          function(next) {
            var tmp = disk.getTempDir();
            var src = path.join(tmp, path.basename(PROVIDER_URL_PROFILE));
            var dest = path.join(
              deps.lookup('config').sysProviderRoot, 'profile'
            );
            log.info('Setting B2D profile.');
            fs.rename(src, dest, function() {
              log.ok('OK');
              newline();
              next(null);
            });
          }

        ], function(err, results) {
          if (err) {
            throw err;
          }
          next();
        });
      }
      else {
        next(null);
      }
    },

    // Extract syncthing and move config and files
    function(next) {
      if (!syncThingIsInstalled || !syncThingIsConfigged) {
        log.header('Setting up syncthing goodness.');
        var tmp = disk.getTempDir();
        if (!syncThingIsConfigged) {
          log.info('Creating syncthing config dir and setting config');
          var stConfig = path.join(tmp, path.basename(SYNCTHING_CONFIG));
          mkdirp.sync(
            path.join(deps.lookup('config').sysConfRoot, 'syncthing')
          );
          fs.renameSync(
            stConfig, path.join(
              deps.lookup('config').sysConfRoot, 'syncthing', 'config.xml'
            )
          );
          log.ok('OK');
          log.newline();
        }
        if (!syncThingIsInstalled) {
          log.info('Setting up syncthing binary');
          var stBinary = path.join(tmp, path.basename(SYNCTHING_DOWNLOAD));
          var decompress = new Decompress({mode: '755'})
            .src(stBinary)
            .dest(tmp)
            .use(Decompress.targz());

          decompress.run(function(err, files, stream) {
            if (err) {
              log.fail('Could not extract sycnthing correctly');
            }
            var binPath = path.join(deps.lookup('config').sysConfRoot, 'bin');
            mkdirp.sync(binPath);
            fs.renameSync(
              path.join(tmp, path.basename(stBinary, '.tar.gz'), 'syncthing'),
              path.join(binPath, 'syncthing')
            );
            log.ok('OK');
            log.newline();
            next(null);
          });
        }
        else {
          next(null);
        }
      }
      else {
        next(null);
      }
    },

    // Install packages.
    function(next) {
      if (!providerIsInstalled || !dnsIsSet) {
        log.header('Setting things up.');
        log.alert('ADMINISTRATIVE PASSWORD WILL BE REQUIRED!');

        async.series([

          function(next) {
            if (!providerIsInstalled) {
              disk.getMacVolume(function(err, volume) {
                if (err) {
                  throw err;
                }
                var tempDir = disk.getTempDir();
                var pkg = path.join(
                  tempDir, path.basename(PROVIDER_URL_V1_4_1)
                );
                log.info('Installing: ' + pkg);
                adminCmds.unshift(cmd.buildInstallCmd(pkg, volume));
                next(null);
              });
            }
            else {
              next(null);
            }
          },

          function(next) {
            if (!dnsIsSet) {
              log.info('Setting up DNS for Kalabox.');
              provider.getServerIps(function(ips) {
                var ipCmds = cmd.buildDnsCmd(
                  ips, KALABOX_DNS_PATH, KALABOX_DNS_FILE
                );
                adminCmds = adminCmds.concat(ipCmds);
                next(null);
              });
            }
            else {
              next(null);
            }
          },

          function(next) {
            if (!_.isEmpty(adminCmds)) {
              var child = cmd.runCmdsAsync(adminCmds);
              child.stdout.on('data', function(data) {
                log.info(data);
              });
              child.stdout.on('end', function() {
                log.info('Finished installing');
                log.newline();
                next();
              });
              child.stderr.on('data', function(data) {
                log.warn(data);
              });
            }
            else {
              next(null);
            }
          }

        ], function(err, results) {
            if (err) {
              throw err;
            }
            next();
          });

      }
      else {
        next(null);
      }
    },

    // Init and start boot2docker
    function(next) {
      log.header('Setting up and turning on the Kalabox VM.');
      async.series([

        function(next) {
          // @todo: stop gap for #190 for now. eventually we will have a more
          // robust installer API for providers to add checks and prepares to
          // the installer.
          var iso =
            path.join(deps.lookup('config').sysProviderRoot, 'boot2docker.iso');
          var isoThere = fs.existsSync(iso);
          if (isoThere) {
            fs.unlinkSync(iso);
          }
          provider.up(function(err, output) {
            log.info(output);
            next(null);
          });
        }

      ], function(err) {
        if (err) {
          throw err;
        }
        next();
      });
    },

    function(next) {
      log.header('Installing core services.');
      services.install(function() {
        log.info('Core services installed.');
        next(null);
      });
    },

    function(next) {
      // @todo: This needs to better eventually.
      log.header('Installing core sharing');
      engine.build({name: 'kalabox/syncthing:stable'}, function() {
        log.info('Core sharing installed.');
        next(null);
      });
    },

    // Init and start boot2docker
    function(next) {
      log.header('Finishing up.');
      log.ok('Installation complete!');
    }

  ]);

  done();

};
<|endoftext|>