<commit_before>
var myApp = angular.module('configAuditViewer', ['ngAnimate']);

myApp.service('ServerDataService', ['$http', function($http) {
  this.getData = function(jsonFile) {
     return $http.get(jsonFile);
  }
}]);

myApp.service('ClientDataService', ['$q', function($q) {

  this.getData = function(fileList) {
    return new Promise(function(resolve, reject) {
      var environments = []
      var readers = []
        for (var f = 0; f < fileList.length; f++) {
          var file = fileList[f];
          readers.push(new FileReader());
          readers[f].onload = function(e) {
            try {
              environments.push(JSON.parse(this.result));
            } catch (e) {
              reject('Invalid json file')
            }
            if (environments.length == fileList.length) {
              resolve(environments);
            }
          }
          readers[f].readAsText(file, 'UTF-8');
        }
      }
    )
  }

}]);

myApp.controller('ConfigAuditController', ['$scope', '$log', 'ServerDataService', 'ClientDataService', function($scope, $log, ServerDataService, ClientDataService) {

  this.files = [];
  this.errorMessage = '';
  this.comparisonObjectBuilder = [];
  this.comparisonObject = [];
  this.environments = [];
  this.loading = false;
  self = this;

  this.getConfigFilesFromJson = function(jsonFile, index) {
    self.files[index] = [];
    self.errorMessages[index] = '';
    ServerDataService.getData(jsonFile).then(function(response) {
      self.files[index] = response.data;
      self.getComparisonObject();
    }, function(errResponse) {
      $log.error('error getting data: ' + JSON.stringify(errResponse));
      self.errorMessage = errResponse.data;
      self.getComparisonObject();
    });
  };

  this.uploadFiles = function() {
    var fileList = $scope.files;
    this.environments = [];
    ClientDataService.getData(fileList).then(function(response) {
      self.environments = response;
      self.getComparisonObject();
      $scope.$apply();
    }, function(errResponse) {
      $log.error(errResponse);
      self.errorMessage = errResponse;
      self.environments = [];
      self.getComparisonObject();
      $scope.$apply();
    });
  }

  this.getComparisonObject = function() {
    allFiles = function(environments) {
      var allFilesBuilder = [];
      for (var i = 0; i < environments.length; i++ ) {
        for (var j = 0; j < environments[i].length; j ++) {
          var file = {relativePath: environments[i][j].relativePath, fileName: environments[i][j].fileName}
          if (!listContainsFile(allFilesBuilder, file)) {
            allFilesBuilder.push(file);
          }
        }
      }
      return allFilesBuilder;
    }

    function listContainsFile(fileList, file) {
      for (var f = 0; f < fileList.length; f ++) {
        if (fileList[f].fileName == file.fileName && fileList[f].relativePath == file.relativePath) {
          return true;
        }
      }
      return false;
    }

    function indexOfFileInEnv(environmentFiles, file) {
      for (var f = 0; f < environmentFiles.length; f ++) {
        if (environmentFiles[f].fileName == file.fileName && environmentFiles[f].relativePath == file.relativePath) {
          return f;
        }
      }
      return -1;
    }

    function indexOfOverrideLevelInFile(file, overrideLevel) {
      for (var o = 0; o < file.overrideLevels.length; o ++) {
        if (file.overrideLevels[o].levelDescription == overrideLevel.levelDescription) {
          return o;
        }
      }
      return -1;
    }

    function fileContainsOverrideLevel(file, overrideLevel) {
      for (var o = 0; o < file.overrideLevels.length; o++ ) {
        if (file.overrideLevels[o].levelDescription == overrideLevel.levelDescription) {
          return true;
        }
      }
      return false;
    }

    function overrideLevelContainsKey(overrideLevel, key) {
      for (var k = 0; k < overrideLevel.keyValues.length; k++ ) {
        if (overrideLevel.keyValues[k].key == key) {
          return true;
        }
      }
      return false;
    }

    function envOverrideLevelContainsKey(overrideLevel, key) {
      for (var k = 0; k < overrideLevel.keyValuePairs.length; k++ ) {
        if (overrideLevel.keyValuePairs[k].key == key) {
          return true;
        }
      }
      return false;
    }

    function valueOfKeyInEnvOverride(key, overrideLevel) {
      for (var k = 0; k < overrideLevel.keyValuePairs.length; k++ ) {
        if (overrideLevel.keyValuePairs[k].key == key) {
          return overrideLevel.keyValuePairs[k].value;
        }
      }
      return null;
    }

    this.comparisonObjectBuilder = allFiles(this.environments);

    // find the override levels in each file.
    for (var i = 0; i < this.comparisonObjectBuilder.length; i++ ) {
      this.comparisonObjectBuilder[i].existsInEnvironment = [];
      this.comparisonObjectBuilder[i].overrideLevels = [];
      this.comparisonObjectBuilder[i].highlight = false;
      this.comparisonObjectBuilder[i].show = false;
      for (var j = 0; j < this.environments.length; j++ ) {
        var indexOfFile = indexOfFileInEnv(this.environments[j], (this.comparisonObjectBuilder[i]))
        this.comparisonObjectBuilder[i].existsInEnvironment[j] = (indexOfFile != -1)
        if (this.comparisonObjectBuilder[i].existsInEnvironment[j]) {
          for (var ovrLvl = 0; ovrLvl < this.environments[j][indexOfFile].overrideLevels.length; ovrLvl++ ) {
            if (!fileContainsOverrideLevel(this.comparisonObjectBuilder[i], (this.environments[j][indexOfFile].overrideLevels[ovrLvl]))) {
              var overrideLevel = {show: true, highlight: false, levelDescription: this.environments[j][indexOfFile].overrideLevels[ovrLvl].levelDescription, existsInEnvironment: [], keyValues: []}
              this.comparisonObjectBuilder[i].overrideLevels.push(overrideLevel);
            }
            var coOvrLvl = indexOfOverrideLevelInFile(this.comparisonObjectBuilder[i], this.environments[j][indexOfFile].overrideLevels[ovrLvl])
            var coOverrideLevel = this.comparisonObjectBuilder[i].overrideLevels[coOvrLvl]
            for (var k = 0; k < this.environments[j][indexOfFile].overrideLevels[ovrLvl].keyValuePairs.length; k++ ) {
              var key = {key: this.environments[j][indexOfFile].overrideLevels[ovrLvl].keyValuePairs[k].key, existsInEnvironment: [], valueInEnvironment: []}
              if (!overrideLevelContainsKey(coOverrideLevel, key.key)) {
                coOverrideLevel.keyValues.push(key);
              }
            }
          }
        }
      }
    }

    // for each environment, check whether the override and key values exist, and record that along with what they are.
    for (var coF = 0; coF < this.comparisonObjectBuilder.length; coF++ ) {
      var coFile = this.comparisonObjectBuilder[coF];
      for (var envE = 0; envE < this.environments.length; envE++ ) {
        var environment = this.environments[envE];
        if (coFile.existsInEnvironment[envE]) {
          for (var coO = 0; coO < coFile.overrideLevels.length; coO++ ) {
            var envFile = environment[indexOfFileInEnv(environment, coFile)];
            var coOverrideLevel = coFile.overrideLevels[coO];
            coOverrideLevel.existsInEnvironment[envE] = fileContainsOverrideLevel(envFile, coOverrideLevel);
            if (coOverrideLevel.existsInEnvironment[envE]) {
              var envOverrideLevel = envFile.overrideLevels[indexOfOverrideLevelInFile(envFile, coOverrideLevel)];
              for (var coK = 0; coK < coOverrideLevel.keyValues.length; coK++ ) {
                var coKey = coOverrideLevel.keyValues[coK];
                coKey.existsInEnvironment[envE] = envOverrideLevelContainsKey(envOverrideLevel, coKey.key);
                if (coOverrideLevel.existsInEnvironment[envE]) {
                  coKey.valueInEnvironment[envE] = valueOfKeyInEnvOverride(coKey.key, envOverrideLevel);
                }
              }
            }
          }
        } else {
          for (var coO = 0; coO < coFile.overrideLevels.length; coO++ ) {
            var coOverrideLevel = coFile.overrideLevels[coO];
            coOverrideLevel.existsInEnvironment[envE] = false;
          }
        }
      }
    }

    // Where something doesn't exist in an environment, populate the value's existence with 'false'.
    for (var envE = 0; envE < this.environments.length; envE++ ) {
      for (var coF = 0; coF < this.comparisonObjectBuilder.length; coF++ ) {
        var file = this.comparisonObjectBuilder[coF];
        for (var coO = 0; coO < file.overrideLevels.length; coO++ ) {
          var overrideLevel = file.overrideLevels[coO];
          if (!overrideLevel.existsInEnvironment[envE]) {
            for (var coK = 0; coK < overrideLevel.keyValues.length; coK++ ) {
              overrideLevel.keyValues[coK].existsInEnvironment[envE] = false;
              overrideLevel.keyValues[coK].valueInEnvironment[envE] = "";
            }
          }
        }
      }
    }

    this.comparisonObject = this.comparisonObjectBuilder;

  };

  this.isNotEmpty = function(arrayElement) {
    return (arrayElement.length > 0)
  };

  this.matchingValuesForKey = function(keyValues) {
    if (keyValues.existsInEnvironment.length == 0) {
      return true;
    } else {
      for (var i = 0; i < keyValues.valueInEnvironment.length; i++ ) {
        if ((!keyValues.existsInEnvironment[i]) || keyValues.valueInEnvironment[i] != keyValues.valueInEnvironment[0]) {
          return false;
        }
      }
    }
    return true;
  }

  this.environmentCount = function() {
    return this.environments.length;
  }

  this.evenOdd = function(number) {
    if (number % 2 == 0) {
      return "even";
    } else {
      return "odd";
    }
  }

  this.overrideLevelColor = function(overrideLevel) {
    for (var env = 0; env < overrideLevel.existsInEnvironment.length; env++ ) {
      if (overrideLevel.existsInEnvironment[env] != true) {
        return "absence";
      }
    }
    for (var k = 0; k < overrideLevel.keyValues.length; k++ ) {
      var key = overrideLevel.keyValues[k];
      if (!this.matchingValuesForKey(key)) {
        return "difference";
      }
    }
    return "match";
  }

  this.configFileColor = function(configFile) {
    for (var env = 0; env < configFile.existsInEnvironment.length; env++ ) {
      if (configFile.existsInEnvironment[env] != true) {
        return "absence";
      }
    }
    for (var o = 0; o < configFile.overrideLevels.length; o++ ) {
      var overrideLevel = configFile.overrideLevels[o];
      if (this.overrideLevelColor(overrideLevel) != "match") {
        return "difference";
      }
    }
    return "match";
  }

  this.openOrClosed = function(configLevel) {
    if (configLevel.show) {
      return "open"
    } else {
      return "closed"
    }
  }

  this.valueColor = function(keyValue) {
    if (keyValue.existsInEnvironment.length == 0) {
      return "matching";
    } else {
      for (var i = 0; i < keyValue.valueInEnvironment.length; i++ ) {
        if (!keyValue.existsInEnvironment[i]) {
          return "absence"
        } else if (keyValue.valueInEnvironment[i] != keyValue.valueInEnvironment[0]) {
          return "difference";
        }
      }
    }
    return "matching";
  }

}]);

myApp.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function(){
                scope.configViewer.loading=true;
                scope.$apply();
                scope.configViewer.comparisonObject = [];
                modelSetter(scope, element[0].files);
                scope.$apply(scope.configViewer.uploadFiles());
                scope.configViewer.loading=false;
            });
        }
    };
}]);<commit_msg>Better loading visuals<commit_after>
var myApp = angular.module('configAuditViewer', ['ngAnimate']);

myApp.service('ServerDataService', ['$http', function($http) {
  this.getData = function(jsonFile) {
     return $http.get(jsonFile);
  }
}]);

myApp.service('ClientDataService', ['$q', function($q) {

  this.getData = function(fileList) {
    return new Promise(function(resolve, reject) {
      var environments = []
      var readers = []
        for (var f = 0; f < fileList.length; f++) {
          var file = fileList[f];
          readers.push(new FileReader());
          readers[f].onload = function(e) {
            try {
              environments.push(JSON.parse(this.result));
            } catch (e) {
              reject('Invalid json file')
            }
            if (environments.length == fileList.length) {
              resolve(environments);
            }
          }
          readers[f].readAsText(file, 'UTF-8');
        }
      }
    )
  }

}]);

myApp.controller('ConfigAuditController', ['$scope', '$log', 'ServerDataService', 'ClientDataService', function($scope, $log, ServerDataService, ClientDataService) {

  this.files = [];
  this.errorMessage = '';
  this.comparisonObjectBuilder = [];
  this.comparisonObject = [];
  this.environments = [];
  this.loading = false;
  self = this;

  this.getConfigFilesFromJson = function(jsonFile, index) {
    self.files[index] = [];
    self.errorMessages[index] = '';
    ServerDataService.getData(jsonFile).then(function(response) {
      self.files[index] = response.data;
      self.getComparisonObject();
    }, function(errResponse) {
      $log.error('error getting data: ' + JSON.stringify(errResponse));
      self.errorMessage = errResponse.data;
      self.getComparisonObject();
    });
  };

  this.uploadFiles = function() {
    var fileList = $scope.files;
    this.environments = [];
    ClientDataService.getData(fileList).then(function(response) {
      self.environments = response;
      self.getComparisonObject();
      self.loading=false;
      $scope.$apply();
    }, function(errResponse) {
      $log.error(errResponse);
      self.errorMessage = errResponse;
      self.environments = [];
      self.getComparisonObject();
      self.loading=false;
      $scope.$apply();
    });
  }

  this.getComparisonObject = function() {
    allFiles = function(environments) {
      var allFilesBuilder = [];
      for (var i = 0; i < environments.length; i++ ) {
        for (var j = 0; j < environments[i].length; j ++) {
          var file = {relativePath: environments[i][j].relativePath, fileName: environments[i][j].fileName}
          if (!listContainsFile(allFilesBuilder, file)) {
            allFilesBuilder.push(file);
          }
        }
      }
      return allFilesBuilder;
    }

    function listContainsFile(fileList, file) {
      for (var f = 0; f < fileList.length; f ++) {
        if (fileList[f].fileName == file.fileName && fileList[f].relativePath == file.relativePath) {
          return true;
        }
      }
      return false;
    }

    function indexOfFileInEnv(environmentFiles, file) {
      for (var f = 0; f < environmentFiles.length; f ++) {
        if (environmentFiles[f].fileName == file.fileName && environmentFiles[f].relativePath == file.relativePath) {
          return f;
        }
      }
      return -1;
    }

    function indexOfOverrideLevelInFile(file, overrideLevel) {
      for (var o = 0; o < file.overrideLevels.length; o ++) {
        if (file.overrideLevels[o].levelDescription == overrideLevel.levelDescription) {
          return o;
        }
      }
      return -1;
    }

    function fileContainsOverrideLevel(file, overrideLevel) {
      for (var o = 0; o < file.overrideLevels.length; o++ ) {
        if (file.overrideLevels[o].levelDescription == overrideLevel.levelDescription) {
          return true;
        }
      }
      return false;
    }

    function overrideLevelContainsKey(overrideLevel, key) {
      for (var k = 0; k < overrideLevel.keyValues.length; k++ ) {
        if (overrideLevel.keyValues[k].key == key) {
          return true;
        }
      }
      return false;
    }

    function envOverrideLevelContainsKey(overrideLevel, key) {
      for (var k = 0; k < overrideLevel.keyValuePairs.length; k++ ) {
        if (overrideLevel.keyValuePairs[k].key == key) {
          return true;
        }
      }
      return false;
    }

    function valueOfKeyInEnvOverride(key, overrideLevel) {
      for (var k = 0; k < overrideLevel.keyValuePairs.length; k++ ) {
        if (overrideLevel.keyValuePairs[k].key == key) {
          return overrideLevel.keyValuePairs[k].value;
        }
      }
      return null;
    }

    this.comparisonObjectBuilder = allFiles(this.environments);

    // find the override levels in each file.
    for (var i = 0; i < this.comparisonObjectBuilder.length; i++ ) {
      this.comparisonObjectBuilder[i].existsInEnvironment = [];
      this.comparisonObjectBuilder[i].overrideLevels = [];
      this.comparisonObjectBuilder[i].highlight = false;
      this.comparisonObjectBuilder[i].show = false;
      for (var j = 0; j < this.environments.length; j++ ) {
        var indexOfFile = indexOfFileInEnv(this.environments[j], (this.comparisonObjectBuilder[i]))
        this.comparisonObjectBuilder[i].existsInEnvironment[j] = (indexOfFile != -1)
        if (this.comparisonObjectBuilder[i].existsInEnvironment[j]) {
          for (var ovrLvl = 0; ovrLvl < this.environments[j][indexOfFile].overrideLevels.length; ovrLvl++ ) {
            if (!fileContainsOverrideLevel(this.comparisonObjectBuilder[i], (this.environments[j][indexOfFile].overrideLevels[ovrLvl]))) {
              var overrideLevel = {show: true, highlight: false, levelDescription: this.environments[j][indexOfFile].overrideLevels[ovrLvl].levelDescription, existsInEnvironment: [], keyValues: []}
              this.comparisonObjectBuilder[i].overrideLevels.push(overrideLevel);
            }
            var coOvrLvl = indexOfOverrideLevelInFile(this.comparisonObjectBuilder[i], this.environments[j][indexOfFile].overrideLevels[ovrLvl])
            var coOverrideLevel = this.comparisonObjectBuilder[i].overrideLevels[coOvrLvl]
            for (var k = 0; k < this.environments[j][indexOfFile].overrideLevels[ovrLvl].keyValuePairs.length; k++ ) {
              var key = {key: this.environments[j][indexOfFile].overrideLevels[ovrLvl].keyValuePairs[k].key, existsInEnvironment: [], valueInEnvironment: []}
              if (!overrideLevelContainsKey(coOverrideLevel, key.key)) {
                coOverrideLevel.keyValues.push(key);
              }
            }
          }
        }
      }
    }

    // for each environment, check whether the override and key values exist, and record that along with what they are.
    for (var coF = 0; coF < this.comparisonObjectBuilder.length; coF++ ) {
      var coFile = this.comparisonObjectBuilder[coF];
      for (var envE = 0; envE < this.environments.length; envE++ ) {
        var environment = this.environments[envE];
        if (coFile.existsInEnvironment[envE]) {
          for (var coO = 0; coO < coFile.overrideLevels.length; coO++ ) {
            var envFile = environment[indexOfFileInEnv(environment, coFile)];
            var coOverrideLevel = coFile.overrideLevels[coO];
            coOverrideLevel.existsInEnvironment[envE] = fileContainsOverrideLevel(envFile, coOverrideLevel);
            if (coOverrideLevel.existsInEnvironment[envE]) {
              var envOverrideLevel = envFile.overrideLevels[indexOfOverrideLevelInFile(envFile, coOverrideLevel)];
              for (var coK = 0; coK < coOverrideLevel.keyValues.length; coK++ ) {
                var coKey = coOverrideLevel.keyValues[coK];
                coKey.existsInEnvironment[envE] = envOverrideLevelContainsKey(envOverrideLevel, coKey.key);
                if (coOverrideLevel.existsInEnvironment[envE]) {
                  coKey.valueInEnvironment[envE] = valueOfKeyInEnvOverride(coKey.key, envOverrideLevel);
                }
              }
            }
          }
        } else {
          for (var coO = 0; coO < coFile.overrideLevels.length; coO++ ) {
            var coOverrideLevel = coFile.overrideLevels[coO];
            coOverrideLevel.existsInEnvironment[envE] = false;
          }
        }
      }
    }

    // Where something doesn't exist in an environment, populate the value's existence with 'false'.
    for (var envE = 0; envE < this.environments.length; envE++ ) {
      for (var coF = 0; coF < this.comparisonObjectBuilder.length; coF++ ) {
        var file = this.comparisonObjectBuilder[coF];
        for (var coO = 0; coO < file.overrideLevels.length; coO++ ) {
          var overrideLevel = file.overrideLevels[coO];
          if (!overrideLevel.existsInEnvironment[envE]) {
            for (var coK = 0; coK < overrideLevel.keyValues.length; coK++ ) {
              overrideLevel.keyValues[coK].existsInEnvironment[envE] = false;
              overrideLevel.keyValues[coK].valueInEnvironment[envE] = "";
            }
          }
        }
      }
    }

    this.comparisonObject = this.comparisonObjectBuilder;

  };

  this.isNotEmpty = function(arrayElement) {
    return (arrayElement.length > 0)
  };

  this.matchingValuesForKey = function(keyValues) {
    if (keyValues.existsInEnvironment.length == 0) {
      return true;
    } else {
      for (var i = 0; i < keyValues.valueInEnvironment.length; i++ ) {
        if ((!keyValues.existsInEnvironment[i]) || keyValues.valueInEnvironment[i] != keyValues.valueInEnvironment[0]) {
          return false;
        }
      }
    }
    return true;
  }

  this.environmentCount = function() {
    return this.environments.length;
  }

  this.evenOdd = function(number) {
    if (number % 2 == 0) {
      return "even";
    } else {
      return "odd";
    }
  }

  this.overrideLevelColor = function(overrideLevel) {
    for (var env = 0; env < overrideLevel.existsInEnvironment.length; env++ ) {
      if (overrideLevel.existsInEnvironment[env] != true) {
        return "absence";
      }
    }
    for (var k = 0; k < overrideLevel.keyValues.length; k++ ) {
      var key = overrideLevel.keyValues[k];
      if (!this.matchingValuesForKey(key)) {
        return "difference";
      }
    }
    return "match";
  }

  this.configFileColor = function(configFile) {
    for (var env = 0; env < configFile.existsInEnvironment.length; env++ ) {
      if (configFile.existsInEnvironment[env] != true) {
        return "absence";
      }
    }
    for (var o = 0; o < configFile.overrideLevels.length; o++ ) {
      var overrideLevel = configFile.overrideLevels[o];
      if (this.overrideLevelColor(overrideLevel) != "match") {
        return "difference";
      }
    }
    return "match";
  }

  this.openOrClosed = function(configLevel) {
    if (configLevel.show) {
      return "open"
    } else {
      return "closed"
    }
  }

  this.valueColor = function(keyValue) {
    if (keyValue.existsInEnvironment.length == 0) {
      return "matching";
    } else {
      for (var i = 0; i < keyValue.valueInEnvironment.length; i++ ) {
        if (!keyValue.existsInEnvironment[i]) {
          return "absence"
        } else if (keyValue.valueInEnvironment[i] != keyValue.valueInEnvironment[0]) {
          return "difference";
        }
      }
    }
    return "matching";
  }

}]);

myApp.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function(){
              if (element[0].files.length > 0) {
                scope.configViewer.loading=true;
                scope.configViewer.comparisonObject = [];
                scope.$apply();
                modelSetter(scope, element[0].files);
                scope.configViewer.uploadFiles();
              }
            });
        }
    };
}]);<|endoftext|>


<commit_before>// Declare app level module which depends on views, and components
app = angular.module('cliffhanger', [
    'ui.bootstrap'
    , 'ui.checkbox'
    , 'ngRoute'
    , 'ngTagsInput'
    , 'ngSanitize'
    , 'ngCsv'
    , 'cliffhanger.version',

    //My modules
    'cliffhanger.dashboard'
    , 'cliffhanger.datasets'
    , 'cliffhanger.compare'
    , 'cliffhanger.queries'
    , 'cliffhanger.query_wizard'
    , 'cliffhanger.tags'

]).
config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
    //set up URL mapping/routing
    $locationProvider.hashPrefix('');
    $routeProvider.otherwise({
        redirectTo: '/'
    });
}]).run(function ($rootScope) {
    //set base Url for the REST API
    //$rootScope.baseUrl = 'http://localhost:8080/cliffhanger'; //development
    $rootScope.baseUrl = 'http://hangingonbyanicepick.eastus2.cloudapp.azure.com:8080/cliffhanger-0.1'; //production
}).directive('prevent-default', function ($rootScope) {
    var linkFn = function (scope, element, attrs) {
        $(element).on("click", function (event) {
            event.preventDefault();
        });
    };
    return {
        restrict: 'A',
        link: linkFn
    }
});<commit_msg>just swith the backend<commit_after>// Declare app level module which depends on views, and components
app = angular.module('cliffhanger', [
    'ui.bootstrap'
    , 'ui.checkbox'
    , 'ngRoute'
    , 'ngTagsInput'
    , 'ngSanitize'
    , 'ngCsv'
    , 'cliffhanger.version',

    //My modules
    'cliffhanger.dashboard'
    , 'cliffhanger.datasets'
    , 'cliffhanger.compare'
    , 'cliffhanger.queries'
    , 'cliffhanger.query_wizard'
    , 'cliffhanger.tags'

]).
config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
    //set up URL mapping/routing
    $locationProvider.hashPrefix('');
    $routeProvider.otherwise({
        redirectTo: '/'
    });
}]).run(function ($rootScope) {
    //set base Url for the REST API
    $rootScope.baseUrl = 'http://localhost:8080/cliffhanger'; //development
    //$rootScope.baseUrl = 'http://hangingonbyanicepick.eastus2.cloudapp.azure.com:8080/cliffhanger-0.1'; //production
}).directive('prevent-default', function ($rootScope) {
    var linkFn = function (scope, element, attrs) {
        $(element).on("click", function (event) {
            event.preventDefault();
        });
    };
    return {
        restrict: 'A',
        link: linkFn
    }
});<|endoftext|>


<commit_before>'use strict';

require('angular/angular');
require('angular-route');
require('angular-cookies');
require('angular-base64');

var sextant = angular.module('sextant', [
	'ngRoute',
	'base64',
	'ngCookies'
]);

// Services
require('./js/services/http-service')(sextant);

// Models

// Controllers
require('./js/controllers/account-controller')(sextant);
require('./js/controllers/session-controller')(sextant);
require('./js/controllers/tracking-code-controller')(sextant);
require('./js/controllers/data-controller')(sextant);
require('./js/directives/controllers/events-bar-graph-controller')(sextant);
require('./js/directives/controllers/header-controller')(sextant);
require('./js/directives/controllers/page-graph-controller')(sextant);

// Directives

require('./js/directives/visit-summary-directive')(sextant);
require('./js/directives/visit-details-directive')(sextant);
require('./js/directives/d3-events-bar-graph-directive')(sextant);
require('./js/directives/header-directive')(sextant);
require('./js/directives/footer-directive')(sextant);
require('./js/directives/page-graph-directive')(sextant);

// Routes
sextant.config([ '$routeProvider', '$locationProvider',
	function($routeProvider, $locationProvider) {
		$routeProvider
			.when('/login', {
				templateUrl: 'views/gateway-view.html',
				controller: 'sessionController'
			})
			.when('/dashboard', {
				templateUrl: 'views/dashboard-view.html',
				controller: 'dataController'
			})
			.when('/init', {
				templateUrl: 'views/tracking-code-view.html',
				controller: 'trackingCodeController'
			})
			.otherwise({
				redirectTo: '/login'
			});

} ]);<commit_msg>Removed unused  dependency<commit_after>'use strict';

require('angular/angular');
require('angular-route');
require('angular-cookies');
require('angular-base64');

var sextant = angular.module('sextant', [
	'ngRoute',
	'base64',
	'ngCookies'
]);

// Services
require('./js/services/http-service')(sextant);

// Models

// Controllers
require('./js/controllers/account-controller')(sextant);
require('./js/controllers/session-controller')(sextant);
require('./js/controllers/tracking-code-controller')(sextant);
require('./js/controllers/data-controller')(sextant);
require('./js/directives/controllers/events-bar-graph-controller')(sextant);
require('./js/directives/controllers/header-controller')(sextant);
require('./js/directives/controllers/page-graph-controller')(sextant);

// Directives

require('./js/directives/visit-summary-directive')(sextant);
require('./js/directives/visit-details-directive')(sextant);
require('./js/directives/d3-events-bar-graph-directive')(sextant);
require('./js/directives/header-directive')(sextant);
require('./js/directives/footer-directive')(sextant);
require('./js/directives/page-graph-directive')(sextant);

// Routes
sextant.config([ '$routeProvider', '$locationProvider',
	function($routeProvider) {
		$routeProvider
			.when('/login', {
				templateUrl: 'views/gateway-view.html',
				controller: 'sessionController'
			})
			.when('/dashboard', {
				templateUrl: 'views/dashboard-view.html',
				controller: 'dataController'
			})
			.when('/init', {
				templateUrl: 'views/tracking-code-view.html',
				controller: 'trackingCodeController'
			})
			.otherwise({
				redirectTo: '/login'
			});
} ]);<|endoftext|>


<commit_before>function MenuItem(descr) {
    this.setup(descr);
};
MenuItem.prototype.setup = function (descr) {
    for (var property in descr) {
        this[property] = descr[property];
    }
}

MenuItem.prototype.hitBox = false;
MenuItem.prototype.selected = false;

function Menu(descr) {
    this.setup(descr);
};

Menu.prototype.setup = function (descr) {
    for (var property in descr) {
        this[property] = descr[property];
    }
}

Menu.prototype.inMenu = function(x,y) {
     return (this.initialized &&  util.circInBox(x,y,0,this.hitBox[0],this.hitBox[1]));
    }

Menu.prototype.titleHeight = 50;
Menu.prototype.itemHeight = 25;
Menu.prototype.margin_bottom = 5;

//Must take in context to compute properties
Menu.prototype.init = function (ctx) {
    ctx.save();
    ctx.textAlign = "center";
    ctx.textBaseline = "top";
    ctx.font = this.itemHeight+"px " +this.font;
    var offsetFromTitle = this.height/2 - (this.itemHeight + this.margin_bottom)*this.items.length/2;
    ctx.textBaseline = "middle";
    for(var i = 0; i < this.items.length; i++){
        this.items[i] = new MenuItem(this.items[i]);
        this.items[i].location = [this.location[0],this.location[1] + offsetFromTitle + i*(this.itemHeight + this.margin_bottom)];
        var wiOText = ctx.measureText(this.items[i].text).width
        this.items[i].width = wiOText < this.width ? wiOText : this.width;
        var loc = this.items[i].location;
        var w = this.items[i].width
        var h = this.itemHeight;
        this.items[i].hitBox = [[loc[0]-w/2,loc[1]-h/2],[loc[0]+w/2,loc[1]+h/2]];
    }
    ctx.restore();

    this.hitBox = [[this.location[0] - this.width/2, this.location[1]], [this.location[0]+this.width/2, this.location[1]+this.height]]
    this.initialized = true;
}

Menu.prototype.initialized = false;

Menu.prototype.items = [];

Menu.prototype.fill = "lime";
Menu.prototype.stroke = "lime";
Menu.prototype.font = "Quantico";
Menu.prototype.height = 0;
Menu.prototype.width = 0;

Menu.prototype.render = function(ctx) {
        if (!this.initialized) { this.init(ctx);}
        ctx.save();
        ctx.fillStyle = this.fill;
        ctx.strokeStyle = this.stroke;
        ctx.textAlign = "center";
        ctx.textBaseline = "top";
        if(this.title){
            ctx.font = this.titleHeight+"px " +this.font;
            ctx.fillText(this.title, this.location[0],this.location[1],this.width);
        }
        ctx.font = this.itemHeight+"px " +this.font;
        ctx.textBaseline = "middle";
        for(var i = 0; i < this.items.length; i++) {
            var item = this.items[i];
            var loc = item.location;
            var w = item.width;
            var h = this.itemHeight;
            ctx.fillText(item.text,loc[0],loc[1],this.width);
            if (item.selected) {
                util.strokeBox(ctx,item.hitBox[0][0],item.hitBox[0][1],w,h);
            }
        }
        if(g_settings.enableDebug) util.strokeBox(ctx,this.hitBox[0][0],this.hitBox[0][1],this.width,this.height);
        ctx.restore();
    };

Menu.prototype.update = function (du) {
};

Menu.prototype.onSelected = function (item) {
    item.action(this.state);
}

Menu.prototype.handleMouse = function (evt, type) {
	var pos = util.findPos(g_canvas);
	g_mouse = [evt.clientX - pos.x,evt.clientY - pos.y];
        if (this.inMenu(g_mouse[0],g_mouse[1])){
            if (type === "down"){

            } else if (type === "move") {
                for (var i = 0; i < this.items.length; i++){
                    var item = this.items[i];
                    item.selected = false;
                    if (util.circInBox(g_mouse[0],g_mouse[1],0,item.hitBox[0],item.hitBox[1])) {
                        item.selected = true;
                    }
                }
            } else if (type === "up") {
                for (var i = 0; i < this.items.length; i++){
                    var item = this.items[i];
                    if (item.selected){
                        this.onSelected(item);
                        break;
                    }
                }
            }
	    }
};

var mainMenu = new State({
    "render" : function (ctx){
	this.menu.render(ctx);
	},
    "handleMouse" : function(evt,type) {
	this.menu.handleMouse(evt,type);
	},
    "update" : function(du) {
	this.menu.update(du);
	},
    "init" : function () {
	this.menu = new Menu({
	"state" : this,
	"title" : "JERBAL SPACE PROGRAM",
	"items": [ {
		"text": "Quick Start",
		"state" : "simulation"
		},
		{ "text": "Part Design",
		  "state" : "partsDesigner"
		},
		{ "text": "Ship Design",
		  "state" : "shipDesigner"
		}
	],
	    "location": [g_canvas.width/2,0],
	"titleHeight" : 50,
	"itemHeight" : 42,
	"width" : g_canvas.width,
	"height" : g_canvas.height,
	"margin_bottom" : 5,
	"onSelected" : function (item) {
	     stateManager.switchState(item.state);
	}
	});
	}
    });
<commit_msg>Update Menu.js<commit_after>function MenuItem(descr) {
    this.setup(descr);
};
MenuItem.prototype.setup = function (descr) {
    for (var property in descr) {
        this[property] = descr[property];
    }
}

MenuItem.prototype.hitBox = false;
MenuItem.prototype.selected = false;

function Menu(descr) {
    this.setup(descr);
};

Menu.prototype.setup = function (descr) {
    for (var property in descr) {
        this[property] = descr[property];
    }
}

Menu.prototype.inMenu = function(x,y) {
     return (this.initialized &&  util.circInBox(x,y,0,this.hitBox[0],this.hitBox[1]));
    }

Menu.prototype.titleHeight = 50;
Menu.prototype.itemHeight = 25;
Menu.prototype.margin_bottom = 5;

//Must take in context to compute properties
Menu.prototype.init = function (ctx) {
    ctx.save();
    ctx.textAlign = "center";
    ctx.textBaseline = "top";
    ctx.font = this.itemHeight+"px " +this.font;
    var offsetFromTitle = this.height/2 - (this.itemHeight + this.margin_bottom)*this.items.length/2;
    ctx.textBaseline = "middle";
    for(var i = 0; i < this.items.length; i++){
        this.items[i] = new MenuItem(this.items[i]);
        this.items[i].location = [this.location[0],this.location[1] + offsetFromTitle + i*(this.itemHeight + this.margin_bottom)];
        var wiOText = ctx.measureText(this.items[i].text).width
        this.items[i].width = wiOText < this.width ? wiOText : this.width;
        var loc = this.items[i].location;
        var w = this.items[i].width
        var h = this.itemHeight;
        this.items[i].hitBox = [[loc[0]-w/2,loc[1]-h/2],[loc[0]+w/2,loc[1]+h/2]];
    }
    ctx.restore();

    this.hitBox = [[this.location[0] - this.width/2, this.location[1]], [this.location[0]+this.width/2, this.location[1]+this.height]]
    this.initialized = true;
}

Menu.prototype.initialized = false;

Menu.prototype.items = [];

Menu.prototype.fill = "lime";
Menu.prototype.stroke = "lime";
Menu.prototype.font = "VT323";
Menu.prototype.height = 0;
Menu.prototype.width = 0;

Menu.prototype.render = function(ctx) {
        if (!this.initialized) { this.init(ctx);}
        ctx.save();
        ctx.fillStyle = this.fill;
        ctx.strokeStyle = this.stroke;
        ctx.textAlign = "center";
        ctx.textBaseline = "top";
        if(this.title){
            ctx.font = this.titleHeight+"px " +this.font;
            ctx.fillText(this.title, this.location[0],this.location[1],this.width);
        }
        ctx.font = this.itemHeight+"px " +this.font;
        ctx.textBaseline = "middle";
        for(var i = 0; i < this.items.length; i++) {
            var item = this.items[i];
            var loc = item.location;
            var w = item.width;
            var h = this.itemHeight;
            ctx.fillText(item.text,loc[0],loc[1],this.width);
            if (item.selected) {
                util.strokeBox(ctx,item.hitBox[0][0],item.hitBox[0][1],w,h);
            }
        }
        if(g_settings.enableDebug) util.strokeBox(ctx,this.hitBox[0][0],this.hitBox[0][1],this.width,this.height);
        ctx.restore();
    };

Menu.prototype.update = function (du) {
};

Menu.prototype.onSelected = function (item) {
    item.action(this.state);
}

Menu.prototype.handleMouse = function (evt, type) {
	var pos = util.findPos(g_canvas);
	g_mouse = [evt.clientX - pos.x,evt.clientY - pos.y];
        if (this.inMenu(g_mouse[0],g_mouse[1])){
            if (type === "down"){

            } else if (type === "move") {
                for (var i = 0; i < this.items.length; i++){
                    var item = this.items[i];
                    item.selected = false;
                    if (util.circInBox(g_mouse[0],g_mouse[1],0,item.hitBox[0],item.hitBox[1])) {
                        item.selected = true;
                    }
                }
            } else if (type === "up") {
                for (var i = 0; i < this.items.length; i++){
                    var item = this.items[i];
                    if (item.selected){
                        this.onSelected(item);
                        break;
                    }
                }
            }
	    }
};

var mainMenu = new State({
    "render" : function (ctx){
	this.menu.render(ctx);
	},
    "handleMouse" : function(evt,type) {
	this.menu.handleMouse(evt,type);
	},
    "update" : function(du) {
	this.menu.update(du);
	},
    "init" : function () {
	this.menu = new Menu({
	"state" : this,
	"title" : "JERBAL SPACE PROGRAM",
	"items": [ {
		"text": "Quick Start",
		"state" : "simulation"
		},
		{ "text": "Part Design",
		  "state" : "partsDesigner"
		},
		{ "text": "Ship Design",
		  "state" : "shipDesigner"
		}
	],
	    "location": [g_canvas.width/2,0],
	"titleHeight" : 50,
	"itemHeight" : 42,
	"width" : g_canvas.width,
	"height" : g_canvas.height,
	"margin_bottom" : 5,
	"onSelected" : function (item) {
	     stateManager.switchState(item.state);
	}
	});
	}
    });
<|endoftext|>


<commit_before>var editor = ace.edit('game-rb-editor');
editor.setTheme('ace/theme/monokai');
editor.getSession().setFoldStyle('manual');
editor.getSession().setMode("ace/mode/ruby");
editor.getSession().setTabSize(2);
editor.getSession().setUseSoftTabs(true);
editor.getSession().setUseWrapMode(true);
editor.setDisplayIndentGuides(false);
editor.setHighlightActiveLine(true);
editor.setShowPrintMargin(false);
editor.setShowInvisibles(true);

var addToTerminal = function(value, type) {
    if (type === 'output' && value.indexOf('()') > -1) return;
    var classes = 'outputs outputs-' + type;
    value = value.replace(/&/g, '&')
                 .replace(/>/g, '>')
                 .replace(/</g, '<')
                 .replace(/"/g, '"')
                 .replace(/'/g, ''')
                 .replace(/\n/g, '
');
    terminalOutputs.innerHTML += '
' + value + '
';
    terminalInput.scrollIntoView();
};

var handleterminalInput = function(event) {
    var key = event.which || event.keyCode;
    if (key == 13) {
        event.preventDefault();
        socket.emit('terminalInput', { input: terminalInput.value });
        addToTerminal(terminalInput.value, 'input');
        terminalInput.value = '';
    }
};

var handleFileLoad = function() {
    var currentFileContent = editor.getValue();
    socket.emit('fileLoad', { input: currentFileContent });
    addToTerminal('Loading game...', 'status');
};

var handleFileSave = function() {
    var currentFileContent = editor.getValue();
    socket.emit('fileSave', { fileContent: currentFileContent });
    addToTerminal('Saving game code...', 'status');
};

var socket = io('http://localhost:8888/ruby'),
    terminal = document.getElementById('terminal'),
    terminalOutputs = document.getElementById('terminal-outputs'),
    terminalInput = document.getElementById('terminal-input'),
    sourceActionSave = document.getElementById('source-action-save'),
    sourceActionLoad = document.getElementById('source-action-load');

terminal.addEventListener('click', function(e) { terminalInput.focus() }, false);
sourceActionSave.addEventListener('click', handleFileSave, false );
sourceActionLoad.addEventListener('click', handleFileLoad, false);

socket.on('connect', function() {
    addToTerminal('Server connected', 'status');
    terminalInput.addEventListener('keypress', handleterminalInput, false);
});

socket.on('disconnect', function() {
    addToTerminal('Server disconnected', 'status');
    terminalInput.removeEventListener('keypress', handleterminalInput, false);
});

socket.on('ready', function(data) {
    addToTerminal(data.output, 'status');
    editor.setValue(data.fileContent);
    editor.gotoLine(0);
});

socket.on('terminalOutput', function(data) {
    if (data.output.indexOf('Error') > -1) addToTerminal(data.output, 'error');
    else addToTerminal(data.output, 'output');
});

socket.on('terminalError', function(data) {
    addToTerminal(data.output, 'error');
});

socket.on('fileSaved', function(data) {
    addToTerminal(data.output, 'status');
});

socket.on('fileLoaded', function(data) {
    addToTerminal(data.output, 'status');
});
<commit_msg>Disable save and load buttons when server disconnects<commit_after>var editor = ace.edit('game-rb-editor');
editor.setTheme('ace/theme/monokai');
editor.getSession().setFoldStyle('manual');
editor.getSession().setMode("ace/mode/ruby");
editor.getSession().setTabSize(2);
editor.getSession().setUseSoftTabs(true);
editor.getSession().setUseWrapMode(true);
editor.setDisplayIndentGuides(false);
editor.setHighlightActiveLine(true);
editor.setShowPrintMargin(false);
editor.setShowInvisibles(true);

var addToTerminal = function(value, type) {
    if (type === 'output' && value.indexOf('()') > -1) return;
    var classes = 'outputs outputs-' + type;
    value = value.replace(/&/g, '&')
                 .replace(/>/g, '>')
                 .replace(/</g, '<')
                 .replace(/"/g, '"')
                 .replace(/'/g, ''')
                 .replace(/\n/g, '
');
    terminalOutputs.innerHTML += '
' + value + '
';
    terminalInput.scrollIntoView();
};

var handleterminalInput = function(event) {
    var key = event.which || event.keyCode;
    if (key == 13) {
        event.preventDefault();
        socket.emit('terminalInput', { input: terminalInput.value });
        addToTerminal(terminalInput.value, 'input');
        terminalInput.value = '';
    }
};

var handleFileLoad = function() {
    var currentFileContent = editor.getValue();
    socket.emit('fileLoad', { input: currentFileContent });
    addToTerminal('Loading game...', 'status');
};

var handleFileSave = function() {
    var currentFileContent = editor.getValue();
    socket.emit('fileSave', { fileContent: currentFileContent });
    addToTerminal('Saving game code...', 'status');
};

var socket = io('http://localhost:8888/ruby'),
    terminal = document.getElementById('terminal'),
    terminalOutputs = document.getElementById('terminal-outputs'),
    terminalInput = document.getElementById('terminal-input'),
    sourceActionSave = document.getElementById('source-action-save'),
    sourceActionLoad = document.getElementById('source-action-load');

terminal.addEventListener('click', function(e) { terminalInput.focus() }, false);

socket.on('connect', function() {
    addToTerminal('Server connected', 'status');
    terminalInput.addEventListener('keypress', handleterminalInput, false);
    sourceActionSave.addEventListener('click', handleFileSave, false );
    sourceActionLoad.addEventListener('click', handleFileLoad, false);
});

socket.on('disconnect', function() {
    addToTerminal('Server disconnected', 'status');
    terminalInput.removeEventListener('keypress', handleterminalInput, false);
    sourceActionSave.removeEventListener('click', handleFileSave, false );
    sourceActionLoad.removeEventListener('click', handleFileLoad, false);
});

socket.on('ready', function(data) {
    addToTerminal(data.output, 'status');
    editor.setValue(data.fileContent);
    editor.gotoLine(0);
});

socket.on('terminalOutput', function(data) {
    if (data.output.indexOf('Error') > -1) addToTerminal(data.output, 'error');
    else addToTerminal(data.output, 'output');
});

socket.on('terminalError', function(data) {
    addToTerminal(data.output, 'error');
});

socket.on('fileSaved', function(data) {
    addToTerminal(data.output, 'status');
});

socket.on('fileLoaded', function(data) {
    addToTerminal(data.output, 'status');
});
<|endoftext|>


<commit_before>'use strict';

angular.module('chatApp', [])

.controller('ChatCtrl', function($scope, $http) {

   $scope.chatChannel = "chatApp";
   $scope.messageLimit = 50;
   $scope.defaultUsername = "Guest";

   $scope.currentConnectionStatus = 0;
   $scope.errorMessage;
   $scope.loggedIn = false;

   PUBNUB.subscribe({
      channel: $scope.chatChannel,
      restore: false,

      callback: function() { },

      disconnect: function() {
         $scope.$apply(function(){
            $scope.currentConnectionStatus = 0;
         });
      },

      reconnect: function() {
         $scope.$apply(function(){
            $scope.currentConnectionStatus = 1;
         });
      },

      connect: function() {
         $scope.$apply(function(){
            $scope.currentConnectionStatus = 2;
         });
      }
   });

   $scope.attemptLogin = function() {
      $scope.errorMessage = "";

      if (!$scope.message.username) {
         $scope.errorMessage = "you must enter a username.";
         return;
      }

      if (!$scope.currentConnectionStatus) {
         $scope.errorMessage = "you're not connect to our chat room yet.";
         return;
      }

      $scope.loggedIn = true;
   };

});<commit_msg>Add function to post a message to the channel<commit_after>'use strict';

angular.module('chatApp', [])

.controller('ChatCtrl', function($scope, $http) {

   $scope.chatChannel = "chatApp";
   $scope.messageLimit = 50;
   $scope.defaultUsername = "Guest";

   $scope.currentConnectionStatus = 0;
   $scope.errorMessage;
   $scope.loggedIn = false;

   PUBNUB.subscribe({
      channel: $scope.chatChannel,
      restore: false,

      callback: function() { },

      disconnect: function() {
         $scope.$apply(function(){
            $scope.currentConnectionStatus = 0;
         });
      },

      reconnect: function() {
         $scope.$apply(function(){
            $scope.currentConnectionStatus = 1;
         });
      },

      connect: function() {
         $scope.$apply(function(){
            $scope.currentConnectionStatus = 2;
         });
      }
   });

   $scope.attemptLogin = function() {
      $scope.errorMessage = "";

      if (!$scope.message.username) {
         $scope.errorMessage = "you must enter a username.";
         return;
      }

      if (!$scope.currentConnectionStatus) {
         $scope.errorMessage = "you're not connect to our chat room yet.";
         return;
      }

      $scope.loggedIn = true;
   };

   $scope.postMessage = function() {

   };

});<|endoftext|>


<commit_before>
var app = angular.module('app', ['ngAnimate', 'ngMaterial']);

app.filter('regex', function() {
    return function(input, field, regex) {
        var patt = new RegExp(regex);
        var out = [];

        if(input) {
            for (var i = 0; i < input.length; i++){
                if(patt.test(input[i][field])) {
                    out.push(input[i]);
                }
            }
        }

        return out;
    };
});

app.directive('devtools', function() {

    return {
        restrict: 'E',
        replace: true,
        template: '

',
        scope: {
            'src': '@',
        },
        link: function ($scope, element, attr) {

        }
    }

});

app.controller('home', function ($scope, $http, $location) {

    $scope.filter = '^page$';
    $scope.targetsFilterSelectedIndex = 1;
    $scope.targets = [];
    $scope.devtoolsUrl = '';

    // make it possible to run the app in a browser environment
    if(typeof require === 'function') {
        $scope.gui = require('nw.gui');
        $scope.win = $scope.gui.Window.get();

        var nativeMenuBar = new $scope.gui.Menu({ type: "menubar" });
        nativeMenuBar.createMacBuiltin('chrome devtools app');

        $scope.win.menu = nativeMenuBar;
    }

    $scope.debug = function() {
        $scope.win.showDevTools();
    }

    $scope.connect = function(target) {

        if(!target.devtoolsFrontendUrl) {
            return;
        }

        var frontendUrl = target.devtoolsFrontendUrl.replace('/devtools/', '');

        $scope.devtoolsUrl = 'devtools/front_end/' + frontendUrl
    }

    $scope.setTargetFilter = function(filter) {

        switch(filter) {
            case 'apps':
                $scope.filter = '^apps$';
                $scope.targetsFilterSelectedIndex = 0;
                break;
            case 'pages':
                $scope.filter = '^page$';
                $scope.targetsFilterSelectedIndex = 1;
                break;
            case 'background_page':
                $scope.filter = '^background_page$';
                $scope.targetsFilterSelectedIndex = 2;
                break;
        }

    }

    $scope.discover = function() {
        var req = $http.get('http://localhost:9222/json');
        // var req = $http.get('/json.json');

        req.success(function(data, status, headers, config) {
            $scope.targets = data;
        });

        req.catch(function() {

        });
    }

    $scope.showTargets = function() {
        $scope.devtoolsUrl = '';
    }

    $scope.discover();

});
<commit_msg>Updated app name in menu bars. <commit_after>
var app = angular.module('app', ['ngAnimate', 'ngMaterial']);

app.filter('regex', function() {
    return function(input, field, regex) {
        var patt = new RegExp(regex);
        var out = [];

        if(input) {
            for (var i = 0; i < input.length; i++){
                if(patt.test(input[i][field])) {
                    out.push(input[i]);
                }
            }
        }

        return out;
    };
});

app.directive('devtools', function() {

    return {
        restrict: 'E',
        replace: true,
        template: '

',
        scope: {
            'src': '@',
        },
        link: function ($scope, element, attr) {

        }
    }

});

app.controller('home', function ($scope, $http, $location) {

    $scope.filter = '^page$';
    $scope.targetsFilterSelectedIndex = 1;
    $scope.targets = [];
    $scope.devtoolsUrl = '';

    // make it possible to run the app in a browser environment
    if(typeof require === 'function') {
        $scope.gui = require('nw.gui');
        $scope.win = $scope.gui.Window.get();

        var nativeMenuBar = new $scope.gui.Menu({ type: "menubar" });
        nativeMenuBar.createMacBuiltin('Chrome DevTools');

        $scope.win.menu = nativeMenuBar;
    }

    $scope.debug = function() {
        $scope.win.showDevTools();
    }

    $scope.connect = function(target) {

        if(!target.devtoolsFrontendUrl) {
            return;
        }

        var frontendUrl = target.devtoolsFrontendUrl.replace('/devtools/', '');

        $scope.devtoolsUrl = 'devtools/front_end/' + frontendUrl
    }

    $scope.setTargetFilter = function(filter) {

        switch(filter) {
            case 'apps':
                $scope.filter = '^apps$';
                $scope.targetsFilterSelectedIndex = 0;
                break;
            case 'pages':
                $scope.filter = '^page$';
                $scope.targetsFilterSelectedIndex = 1;
                break;
            case 'background_page':
                $scope.filter = '^background_page$';
                $scope.targetsFilterSelectedIndex = 2;
                break;
        }

    }

    $scope.discover = function() {
        var req = $http.get('http://localhost:9222/json');
        // var req = $http.get('/json.json');

        req.success(function(data, status, headers, config) {
            $scope.targets = data;
        });

        req.catch(function() {

        });
    }

    $scope.showTargets = function() {
        $scope.devtoolsUrl = '';
    }

    $scope.discover();

});
<|endoftext|>


<commit_before>// Module dependencies
var fs = require('fs'),
    path = require('path'),
    express = require('express'),
    engines = require('consolidate'),
    logger = require('./lib/logger'),
    settings = require('./config/settings');

module.exports = function() {
    // Main app
    var app = express();

    var env = process.env.NODE_ENV || 'development';
    if ('production' === env) {
        app.use(express.errorHandler());
        // a custom "verbose errors" setting which can be used in the templates via settings['verbose errors']
        app.disable('verbose errors'); // disable verbose errors in production
    }
    if ('development' === env) {
        app.use(express.errorHandler({
            dumpExceptions: true,
            showStack: true
        }));

        // a custom "verbose errors" setting which can be used in the templates via settings['verbose errors']
        app.enable('verbose errors'); // enable verbose errors in development
    }

    logger.init(settings.winston);

    var log = logger();

    // Register app.locals (app.helper):
    logger.registerAppHelper(app);

    // Define view engine with its options
    for (var i = 0; i < settings.view.engines.length; ++i) {
        var extension = settings.view.engines[i].extension;
        var template = settings.view.engines[i].template;
        app.engine(extension, engines[template]);
    }
    app.set('view engine', settings.view.defaultExtension);
    app.set('views', path.join(__dirname, 'views'));

    // Enables reverse proxy support
    app.enable('trust proxy');
    app.enable('jsonp callback');

    /**
     * Auto-load bundled middleware
     */
    var middleware = {};

    fs.readdirSync(__dirname + '/lib/middleware').forEach(function(filename) {
        if ( ! /\.js$/.test(filename)) {
            return;
        }
        var name = path.basename(filename, '.js');
        middleware[name] = require('./lib/middleware/' + name);
    });

    /**
     * Multihost
     */
    var _ = require('underscore');
    _.each(settings.multihost.index, function(options) {

        /**
         * Modules are cached after the first time they are loaded.
         * The cached module must be invalidated to ensure data-independence
         * in a multi-host environment.
         */
        var server_path = path.join(settings.multihost.path, options.server);
        if (require.cache[server_path]) {
            delete require.cache[server_path];
        }
        var server = require(server_path);
        if ( ! server) {
            log.error('The multi-host server does not exist: %s', server_path);
            return;
        }

        app.use(middleware.multihost({
            hosts: options.hosts,
            route: options.route,
            server: server(options.hosts, options.route)
        }));

        log.info('Attached a multi-host server: %j', options);

    });

    // Log errors
    app.use(function(err, req, res, next) {
        console.log(err.stack);
        next(err);
    });

    // Client errors
    app.use(function(err, req, res, next) {
        if (req.xhr) {
            res.send(500, {
                error: 'Something blew up!'
            });
        } else {
            next(err);
        }
    });

    // 404 status
    app.use(function(req, res, next) {
        res.status(404);

        // respond with html page
        if (req.accepts('html')) {
            res.render('404.hogan', { url: req.url });
            return;
        }

        // respond with json
        if (req.accepts('json')) {
            res.send({ error: 'Not found' });
            return;
        }

        // default to plain-text. send()
        res.type('txt').send('Not found');
    });

    // error-handling middleware, take the same form
    // as regular middleware, however they require an
    // arity of 4, aka the signature (err, req, res, next).
    // when connect has an error, it will invoke ONLY error-handling
    // middleware.

    // If we were to next() here any remaining non-error-handling
    // middleware would then be executed, or if we next(err) to
    // continue passing the error, only error-handling middleware
    // would remain being executed, however here
    // we simply respond with an error page.
    app.use(function(err, req, res, next) {
        // we may use properties of the error object
        // here and next(err) appropriately, or if
        // we possibly recovered from the error, simply next().
        res.status(err.status || 500);
        res.render('500.jade', { error: err });
    });

    return app;
};
<commit_msg>Removed unnecessary underscore module from app.js<commit_after>// Module dependencies
var fs = require('fs'),
    path = require('path'),
    express = require('express'),
    engines = require('consolidate'),
    logger = require('./lib/logger'),
    settings = require('./config/settings');

module.exports = function() {
    // Main app
    var app = express();

    var env = process.env.NODE_ENV || 'development';
    if ('production' === env) {
        app.use(express.errorHandler());
        // a custom "verbose errors" setting which can be used in the templates via settings['verbose errors']
        app.disable('verbose errors'); // disable verbose errors in production
    }
    if ('development' === env) {
        app.use(express.errorHandler({
            dumpExceptions: true,
            showStack: true
        }));

        // a custom "verbose errors" setting which can be used in the templates via settings['verbose errors']
        app.enable('verbose errors'); // enable verbose errors in development
    }

    logger.init(settings.winston);

    var log = logger();

    // Register app.locals (app.helper):
    logger.registerAppHelper(app);

    // Define view engine with its options
    for (var i = 0; i < settings.view.engines.length; ++i) {
        var extension = settings.view.engines[i].extension;
        var template = settings.view.engines[i].template;
        app.engine(extension, engines[template]);
    }
    app.set('view engine', settings.view.defaultExtension);
    app.set('views', path.join(__dirname, 'views'));

    // Enables reverse proxy support
    app.enable('trust proxy');
    app.enable('jsonp callback');

    /**
     * Auto-load bundled middleware
     */
    var middleware = {};

    fs.readdirSync(__dirname + '/lib/middleware').forEach(function(filename) {
        if ( ! /\.js$/.test(filename)) {
            return;
        }
        var name = path.basename(filename, '.js');
        middleware[name] = require('./lib/middleware/' + name);
    });

    /**
     * Multihost
     */
    for (var i = 0; i < settings.multihost.index.length; ++i) {
        var options = settings.multihost.index[i];

        /**
         * Modules are cached after the first time they are loaded.
         * The cached module must be invalidated to ensure data-independence
         * in a multi-host environment.
         */
        var server_path = path.join(settings.multihost.path, options.server);
        if (require.cache[server_path]) {
            delete require.cache[server_path];
        }
        var server = require(server_path);
        if ( ! server) {
            log.error('The multi-host server does not exist: %s', server_path);
            return;
        }

        app.use(middleware.multihost({
            hosts: options.hosts,
            route: options.route,
            server: server(options.hosts, options.route)
        }));

        log.info('Attached a multi-host server: %j', options);
    }

    // Log errors
    app.use(function(err, req, res, next) {
        console.log(err.stack);
        next(err);
    });

    // Client errors
    app.use(function(err, req, res, next) {
        if (req.xhr) {
            res.send(500, {
                error: 'Something blew up!'
            });
        } else {
            next(err);
        }
    });

    // 404 status
    app.use(function(req, res, next) {
        res.status(404);

        // respond with html page
        if (req.accepts('html')) {
            res.render('404.hogan', { url: req.url });
            return;
        }

        // respond with json
        if (req.accepts('json')) {
            res.send({ error: 'Not found' });
            return;
        }

        // default to plain-text. send()
        res.type('txt').send('Not found');
    });

    // error-handling middleware, take the same form
    // as regular middleware, however they require an
    // arity of 4, aka the signature (err, req, res, next).
    // when connect has an error, it will invoke ONLY error-handling
    // middleware.

    // If we were to next() here any remaining non-error-handling
    // middleware would then be executed, or if we next(err) to
    // continue passing the error, only error-handling middleware
    // would remain being executed, however here
    // we simply respond with an error page.
    app.use(function(err, req, res, next) {
        // we may use properties of the error object
        // here and next(err) appropriately, or if
        // we possibly recovered from the error, simply next().
        res.status(err.status || 500);
        res.render('500.jade', { error: err });
    });

    return app;
};
<|endoftext|>


<commit_before>'use strict';

//Start by defining the main module and adding the module dependencies
angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies);

// Setting HTML5 Location Mode
angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider',
	function($locationProvider) {
		$locationProvider.hashPrefix('!');
	}
]);

window.auth = {};
window.auth.sistcoop = {};

window.realm;

//Then define the init function for starting up the application
angular.element(document).ready(function() {
	//Fixing facebook bug with redirect
	if (window.location.hash === '#_=_') window.location.hash = '#!';

	//Then init the app
	//angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]);

	var consoleIndex = window.location.href.indexOf('/console');
	if (consoleIndex == -1) {
		alert('Invalid url.');
		return;
	}

	var consoleBaseUrl = window.location.href;
	consoleBaseUrl = consoleBaseUrl.substring(0, consoleBaseUrl.indexOf('/console'));

	window.realm = consoleBaseUrl.split('/')[3];
	var sucursal;
	var agencia;
	var keycloak;
	if(realm === 'master') {
		sucursal = realm;
		agencia = realm;
		keycloak = new Keycloak({
			url: 'http://192.168.1.50:8080/auth',
			realm: 'sistcoop-master',
			clientId: 'sistcoop'
		});

		window.realm = 'sistcoop-master';

	} else if(realm === 'sucursales'){
		sucursal = consoleBaseUrl.split('/')[4];
		agencia = consoleBaseUrl.split('/')[6];
		keycloak = new Keycloak({
			url: 'http://192.168.1.50:8080/auth',
			realm: 'sistcoop-default',
			clientId: 'sistcoop'
		});

		window.realm = 'sistcoop-default';

	} else {
		alert('Invalid realm.');
		return;
	}

	keycloak.init({onLoad: 'login-required'}).success(function () {

		var sistcoop = new Sistcoop({
			url: 'http://localhost:8080/rrhh',
			username: keycloak.idTokenParsed.preferred_username,
			sucursal: sucursal,
			agencia: agencia,
			token: keycloak.token
		});

		sistcoop.init({onLoad: 'login-required'}).success(function () {
			window.auth.authz = keycloak;
			window.auth.sistcoop = sistcoop;
			angular.module('mean').factory('Auth', function () {
				return auth;
			});
			angular.module('mean').constant('REALM', window.realm);

			//Then init the app
			angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]);

		}).error(function () {
			alert('No se pudo verificar el origen de sucursal y agencia para el usuario');
		});
	}).error(function () {
		window.location.reload();
	});

});

angular.module('mean').controller('KeycloakController',
	function ($scope, Auth) {

		$scope.logout = function(){
			Auth.authz.logout();
		};
		$scope.accountManagement = function(){
			Auth.authz.accountManagement();
		};

		$scope.user = {
			username: Auth.authz.idTokenParsed.preferred_username,
			roles: []
		};

		$scope.loadRoles = function () {
			var realmRoles = Auth.authz.realmAccess.roles;
			for (var i = 0; i < realmRoles.length; i++) {
				$scope.user.roles.push(realmRoles[i]);
			}
		};
		$scope.loadRoles();

	}
);

var resourceRequests = 0;
var loadingTimer = -1;

angular.module('mean').factory('authInterceptor', function ($q, Auth) {
	return {
		request: function (config) {
			if (!config.url.match(/.html$/)) {
				var deferred = $q.defer();
				if (Auth.authz.token) {
					Auth.authz.updateToken(5).success(function () {
						config.headers = config.headers || {};
						config.headers.Authorization = 'Bearer ' + Auth.authz.token;

						deferred.resolve(config);
					}).error(function () {
						location.reload();
					});
				}
				return deferred.promise;
			} else {
				return config;
			}
		}
	};
});

angular.module('mean').factory('spinnerInterceptor', function ($q, $window, $rootScope, $location) {
	return function (promise) {
		return promise.then(function (response) {
			resourceRequests--;
			if (resourceRequests == 0) {
				if (loadingTimer != -1) {
					window.clearTimeout(loadingTimer);
					loadingTimer = -1;
				}
				$('#loading').hide();
			}
			return response;
		}, function (response) {
			resourceRequests--;
			if (resourceRequests == 0) {
				if (loadingTimer != -1) {
					window.clearTimeout(loadingTimer);
					loadingTimer = -1;
				}
				$('#loading').hide();
			}

			return $q.reject(response);
		});
	};
});

angular.module('mean').factory('errorInterceptor', function ($q, $window, $rootScope, $location, Auth) {
	return function (promise) {
		return promise.then(function (response) {
			return response;
		}, function (response) {
			if (response.status == 401) {
				Auth.authz.logout();
			} else if (response.status == 403) {
				$location.path('/forbidden');
			} else if (response.status == 404) {
				$location.path('/notfound');
			} else if (response.status) {
				if (response.data && response.data.errorMessage) {
					alert(response.data.errorMessage);
				} else {
					alert.error("An unexpected server error has occurred");
				}
			}
			return $q.reject(response);
		});
	};
});

angular.module('mean').config(function ($httpProvider) {
	$httpProvider.interceptors.push('errorInterceptor');

	var spinnerFunction = function (data, headersGetter) {
		if (resourceRequests == 0) {
			loadingTimer = window.setTimeout(function () {
				$('#loading').show();
				loadingTimer = -1;
			}, 500);
		}
		resourceRequests++;
		return data;
	};
	$httpProvider.defaults.transformRequest.push(spinnerFunction);

	$httpProvider.interceptors.push('spinnerInterceptor');
	$httpProvider.interceptors.push('authInterceptor');

});
<commit_msg>change to openshift cloud server<commit_after>'use strict';

//Start by defining the main module and adding the module dependencies
angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies);

// Setting HTML5 Location Mode
angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider',
	function($locationProvider) {
		$locationProvider.hashPrefix('!');
	}
]);

window.auth = {};
window.auth.sistcoop = {};

window.realm;

//Then define the init function for starting up the application
angular.element(document).ready(function() {
	//Fixing facebook bug with redirect
	if (window.location.hash === '#_=_') window.location.hash = '#!';

	//Then init the app
	//angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]);

	var consoleIndex = window.location.href.indexOf('/console');
	if (consoleIndex == -1) {
		alert('Invalid url.');
		return;
	}

	var consoleBaseUrl = window.location.href;
	consoleBaseUrl = consoleBaseUrl.substring(0, consoleBaseUrl.indexOf('/console'));

	window.realm = consoleBaseUrl.split('/')[3];
	var sucursal;
	var agencia;
	var keycloak;
	if(realm === 'master') {
		sucursal = realm;
		agencia = realm;
		keycloak = new Keycloak({
			url: 'https://keycloak-softgreen.rhcloud.com/auth',
			realm: 'sistcoop-master',
			clientId: 'sistcoop'
		});

		window.realm = 'sistcoop-master';

	} else if(realm === 'sucursales'){
		sucursal = consoleBaseUrl.split('/')[4];
		agencia = consoleBaseUrl.split('/')[6];
		keycloak = new Keycloak({
			url: 'https://keycloak-softgreen.rhcloud.com/auth',
			realm: 'sistcoop-default',
			clientId: 'sistcoop'
		});

		window.realm = 'sistcoop-default';

	} else {
		alert('Invalid realm.');
		return;
	}

	keycloak.init({onLoad: 'login-required'}).success(function () {

		var sistcoop = new Sistcoop({
			url: 'http://localhost:8080/rrhh',
			username: keycloak.idTokenParsed.preferred_username,
			sucursal: sucursal,
			agencia: agencia,
			token: keycloak.token
		});

		sistcoop.init({onLoad: 'login-required'}).success(function () {
			window.auth.authz = keycloak;
			window.auth.sistcoop = sistcoop;
			angular.module('mean').factory('Auth', function () {
				return auth;
			});
			angular.module('mean').constant('REALM', window.realm);

			//Then init the app
			angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]);

		}).error(function () {
			alert('No se pudo verificar el origen de sucursal y agencia para el usuario');
		});
	}).error(function () {
		window.location.reload();
	});

});

angular.module('mean').controller('KeycloakController',
	function ($scope, Auth) {

		$scope.logout = function(){
			Auth.authz.logout();
		};
		$scope.accountManagement = function(){
			Auth.authz.accountManagement();
		};

		$scope.user = {
			username: Auth.authz.idTokenParsed.preferred_username,
			roles: []
		};

		$scope.loadRoles = function () {
			var realmRoles = Auth.authz.realmAccess.roles;
			for (var i = 0; i < realmRoles.length; i++) {
				$scope.user.roles.push(realmRoles[i]);
			}
		};
		$scope.loadRoles();

	}
);

var resourceRequests = 0;
var loadingTimer = -1;

angular.module('mean').factory('authInterceptor', function ($q, Auth) {
	return {
		request: function (config) {
			if (!config.url.match(/.html$/)) {
				var deferred = $q.defer();
				if (Auth.authz.token) {
					Auth.authz.updateToken(5).success(function () {
						config.headers = config.headers || {};
						config.headers.Authorization = 'Bearer ' + Auth.authz.token;

						deferred.resolve(config);
					}).error(function () {
						location.reload();
					});
				}
				return deferred.promise;
			} else {
				return config;
			}
		}
	};
});

angular.module('mean').factory('spinnerInterceptor', function ($q, $window, $rootScope, $location) {
	return function (promise) {
		return promise.then(function (response) {
			resourceRequests--;
			if (resourceRequests == 0) {
				if (loadingTimer != -1) {
					window.clearTimeout(loadingTimer);
					loadingTimer = -1;
				}
				$('#loading').hide();
			}
			return response;
		}, function (response) {
			resourceRequests--;
			if (resourceRequests == 0) {
				if (loadingTimer != -1) {
					window.clearTimeout(loadingTimer);
					loadingTimer = -1;
				}
				$('#loading').hide();
			}

			return $q.reject(response);
		});
	};
});

angular.module('mean').factory('errorInterceptor', function ($q, $window, $rootScope, $location, Auth) {
	return function (promise) {
		return promise.then(function (response) {
			return response;
		}, function (response) {
			if (response.status == 401) {
				Auth.authz.logout();
			} else if (response.status == 403) {
				$location.path('/forbidden');
			} else if (response.status == 404) {
				$location.path('/notfound');
			} else if (response.status) {
				if (response.data && response.data.errorMessage) {
					alert(response.data.errorMessage);
				} else {
					alert.error("An unexpected server error has occurred");
				}
			}
			return $q.reject(response);
		});
	};
});

angular.module('mean').config(function ($httpProvider) {
	$httpProvider.interceptors.push('errorInterceptor');

	var spinnerFunction = function (data, headersGetter) {
		if (resourceRequests == 0) {
			loadingTimer = window.setTimeout(function () {
				//$('#loading').show();
				loadingTimer = -1;
			}, 500);
		}
		resourceRequests++;
		return data;
	};
	$httpProvider.defaults.transformRequest.push(spinnerFunction);

	$httpProvider.interceptors.push('spinnerInterceptor');
	$httpProvider.interceptors.push('authInterceptor');

});
<|endoftext|>


<commit_before>"use strict";
var path = require('path')
  , rimraf = require('rimraf')
  , UUID = require('uuid-js')
  , fs = require('fs')
  , sock = '/tmp/instruments_sock';
  , instruments = require('../instruments/instruments');

var IOS = function(rest, app, udid, verbose, removeTraceDir) {
  this.rest = rest;
  this.app = app;
  this.udid = udid;
  this.verbose = verbose;
  this.instruments = null;
  this.queue = [];
  this.progress = 0;
  this.removeTraceDir = removeTraceDir;
  this.onStop = function(code, traceDir) {};
};

IOS.prototype.start = function(cb) {
  var me = this;

  var onLaunch = function() {
    console.log('Instruments launched. Starting poll loop for new commands.');
    me.instruments.setDebug(true);
    cb(null, me);
  };

  var onExit = function(code, traceDir) {
    this.instruments = null;
    if (me.removeTraceDir && traceDir) {
      rimraf(traceDir, function() {
        me.onStop(code);
      });
    } else {
      me.onStop(code, traceDir);
    }
  };

  if (this.instruments === null) {
    this.instruments = instruments(
      path.resolve(__dirname, '../' + this.app)
      , this.udid
      , path.resolve(__dirname, 'uiauto/bootstrap.js')
      , path.resolve(__dirname, 'uiauto/Automation.tracetemplate')
      , sock
      , onLaunch
      , onExit
    );
  }

};

IOS.prototype.stop = function(cb) {
  var me = this;
  if (cb) {
    this.onStop = cb;
  }

  this.instruments.shutdown();
  me.queue = [];
  me.progress = 0;
};

IOS.prototype.proxy = function(command, cb) {
  // was thinking we should use a queue for commands instead of writing to a file
  this.push([command, cb]);
  console.log('Pushed command to appium work queue: ' + command);
};

IOS.prototype.push = function(elem) {
  this.queue.push(elem);
  var me = this;

  var next = function() {
    if (me.queue.length <= 0 || me.progress > 0) {
      return;
    }

    var target = me.queue.shift();
    me.progress++;

    me.instruments.sendCommand(target[0], function(result) {
      if (typeof target[1] === 'function') {
        if (result === 'undefined') {
          target[1]();
        } else {
          try {
            var jsonresult = JSON.parse(result);
            target[1](jsonresult);
          } catch (e) {
            target[1](result);
          }
        }
      }

      // maybe there's moar work to do
      me.progress--;
      next();
    });
  };

  next();
};

IOS.prototype.findElements = function(selector, cb) {
  var me = this;
  var findElement = function(value, ctx, many, cb) {
    var ext = many ? 's' : '';

    var command = [ctx, ".findElement", ext, "AndSetKey", ext, "('", value, "')"].join("");

    me.proxy(command, function(json) {
      json = many ? json : json[0];
      cb(null, json);
    });
  };

  findElement(selector, 'wd_frame', true, function(err, res) {
    cb(null, res);
  });
};

IOS.prototype.setValue = function(elementId, value, cb) {
  var command = ["elements['", elementId, "'].setValue('", value, "')"].join('');

  this.proxy(command, function(json) {
    cb(null, json);
  });
};

IOS.prototype.click = function(elementId, cb) {
  var command = ["elements['", elementId, "'].tap()"].join('');

  this.proxy(command, function(json) {
    cb(null, json);
  });
};

IOS.prototype.getText = function(elementId, cb) {
  var command = ["elements['", elementId, "'].getText()"].join('');

  this.proxy(command, function(json) {
    cb(null, json);
  });
};

IOS.prototype.keys = function(elementId, keys, cb) {
  var command = ["sendKeysToActiveElement('", keys ,"')"].join('');

  this.proxy(command, function(json) {
    cb(null, json);
  });
};

IOS.prototype.elementDisplayed = function(elementId, cb) {
  var command = ["elements['", elementId, "'].isDisplayed()"].join('');

  this.proxy(command, function(json) {
    cb(null, json);
  });
};

IOS.prototype.elementEnabled = function(elementId, cb) {
  var command = ["elements['", elementId, "'].isEnabled()"].join('');

  this.proxy(command, function(json) {
    cb(null, json);
  });
};

IOS.prototype.getPageSource = function(cb) {
  this.proxy("wd_frame.getPageSource()", function(json) {
    cb(null, json);
  });
};

IOS.prototype.getAlertText = function(cb) {
  this.proxy("target.frontMostApp().alert().name()", function(json) {
    cb(null, json);
  });
};

IOS.prototype.postAcceptAlert = function(cb) {
  this.proxy("target.frontMostApp().alert().defaultButton().tap()", function(json) {
    cb(null, json);
  });
};

IOS.prototype.postDismissAlert = function(cb) {
  this.proxy("target.frontMostApp().alert().cancelButton().tap()", function(json) {
    cb(null, json);
  });
};
module.exports = function(rest, app, udid, verbose, removeTraceDir) {
  return new IOS(rest, app, udid, verbose, removeTraceDir);
};
<commit_msg>fixing the build: syntax err<commit_after>"use strict";
var path = require('path')
  , rimraf = require('rimraf')
  , UUID = require('uuid-js')
  , fs = require('fs')
  , sock = '/tmp/instruments_sock'
  , instruments = require('../instruments/instruments');

var IOS = function(rest, app, udid, verbose, removeTraceDir) {
  this.rest = rest;
  this.app = app;
  this.udid = udid;
  this.verbose = verbose;
  this.instruments = null;
  this.queue = [];
  this.progress = 0;
  this.removeTraceDir = removeTraceDir;
  this.onStop = function(code, traceDir) {};
};

IOS.prototype.start = function(cb) {
  var me = this;

  var onLaunch = function() {
    console.log('Instruments launched. Starting poll loop for new commands.');
    me.instruments.setDebug(true);
    cb(null, me);
  };

  var onExit = function(code, traceDir) {
    this.instruments = null;
    if (me.removeTraceDir && traceDir) {
      rimraf(traceDir, function() {
        me.onStop(code);
      });
    } else {
      me.onStop(code, traceDir);
    }
  };

  if (this.instruments === null) {
    this.instruments = instruments(
      path.resolve(__dirname, '../' + this.app)
      , this.udid
      , path.resolve(__dirname, 'uiauto/bootstrap.js')
      , path.resolve(__dirname, 'uiauto/Automation.tracetemplate')
      , sock
      , onLaunch
      , onExit
    );
  }

};

IOS.prototype.stop = function(cb) {
  var me = this;
  if (cb) {
    this.onStop = cb;
  }

  this.instruments.shutdown();
  me.queue = [];
  me.progress = 0;
};

IOS.prototype.proxy = function(command, cb) {
  // was thinking we should use a queue for commands instead of writing to a file
  this.push([command, cb]);
  console.log('Pushed command to appium work queue: ' + command);
};

IOS.prototype.push = function(elem) {
  this.queue.push(elem);
  var me = this;

  var next = function() {
    if (me.queue.length <= 0 || me.progress > 0) {
      return;
    }

    var target = me.queue.shift();
    me.progress++;

    me.instruments.sendCommand(target[0], function(result) {
      if (typeof target[1] === 'function') {
        if (result === 'undefined') {
          target[1]();
        } else {
          try {
            var jsonresult = JSON.parse(result);
            target[1](jsonresult);
          } catch (e) {
            target[1](result);
          }
        }
      }

      // maybe there's moar work to do
      me.progress--;
      next();
    });
  };

  next();
};

IOS.prototype.findElements = function(selector, cb) {
  var me = this;
  var findElement = function(value, ctx, many, cb) {
    var ext = many ? 's' : '';

    var command = [ctx, ".findElement", ext, "AndSetKey", ext, "('", value, "')"].join("");

    me.proxy(command, function(json) {
      json = many ? json : json[0];
      cb(null, json);
    });
  };

  findElement(selector, 'wd_frame', true, function(err, res) {
    cb(null, res);
  });
};

IOS.prototype.setValue = function(elementId, value, cb) {
  var command = ["elements['", elementId, "'].setValue('", value, "')"].join('');

  this.proxy(command, function(json) {
    cb(null, json);
  });
};

IOS.prototype.click = function(elementId, cb) {
  var command = ["elements['", elementId, "'].tap()"].join('');

  this.proxy(command, function(json) {
    cb(null, json);
  });
};

IOS.prototype.getText = function(elementId, cb) {
  var command = ["elements['", elementId, "'].getText()"].join('');

  this.proxy(command, function(json) {
    cb(null, json);
  });
};

IOS.prototype.keys = function(elementId, keys, cb) {
  var command = ["sendKeysToActiveElement('", keys ,"')"].join('');

  this.proxy(command, function(json) {
    cb(null, json);
  });
};

IOS.prototype.elementDisplayed = function(elementId, cb) {
  var command = ["elements['", elementId, "'].isDisplayed()"].join('');

  this.proxy(command, function(json) {
    cb(null, json);
  });
};

IOS.prototype.elementEnabled = function(elementId, cb) {
  var command = ["elements['", elementId, "'].isEnabled()"].join('');

  this.proxy(command, function(json) {
    cb(null, json);
  });
};

IOS.prototype.getPageSource = function(cb) {
  this.proxy("wd_frame.getPageSource()", function(json) {
    cb(null, json);
  });
};

IOS.prototype.getAlertText = function(cb) {
  this.proxy("target.frontMostApp().alert().name()", function(json) {
    cb(null, json);
  });
};

IOS.prototype.postAcceptAlert = function(cb) {
  this.proxy("target.frontMostApp().alert().defaultButton().tap()", function(json) {
    cb(null, json);
  });
};

IOS.prototype.postDismissAlert = function(cb) {
  this.proxy("target.frontMostApp().alert().cancelButton().tap()", function(json) {
    cb(null, json);
  });
};
module.exports = function(rest, app, udid, verbose, removeTraceDir) {
  return new IOS(rest, app, udid, verbose, removeTraceDir);
};
<|endoftext|>


<commit_before>import { OriginFactory } from './lib/OriginFactory';
import { ServiceGateway } from './lib/ServiceGateway';

import Prism from './lib/Prism';

class FormPreview {

  constructor({
    container, description, files, render, preview, source, submit, submitter, title,
    initialize = true, service = new ServiceGateway(), origins = new OriginFactory(),
  }) {
    this.container = container;
    this.description = description;
    this.files = files;
    this.render = render;
    this.preview = preview;
    this.source = source;
    this.submit = submit;
    this.submitter = submitter;
    this.title = title;

    this.service = service;
    this.origins = origins;

    if (initialize) {
      this._init();
    }
  }

  _init() {
    this.container.hide();

    this.preview.addClass('button-primary');
    this.preview.on('click', this.onPreview.bind(this));

    this.submit.hide();
    this.submit.on('click', this.onSubmit.bind(this));

    this.source.on('input', this.onSource.bind(this));
    this.source.on('keypress', this.onKeypress.bind(this));
  }

  onKeypress(event) {
    if (event.key === 'Enter' || event.keyCode === 13) {
      this.preview.click();
    }
  }

  onSource(event) {
    this.preview.addClass('button-primary');
    this.container.hide();
    this.submit.hide();
  }

  onPreview(event) {
    const url = this.source.val();
    const origin = this.origins.originFor(url);

    this.container.show();
    this.submit.show();
    this.files.children().remove();
    this.preview.removeClass('button-primary');

    origin.sources
    .then(sources => Promise.resolve(sources.map(this.useSource.bind(this))))
    .then(promises => this.renderInitialSource.call(this, promises))
    ;
  }

  onSubmit(event) {
    return this.service.createReview({
      body: {
        title: this.title.val(),
        description: this.description.val(),
        url: this.source.val(),
        submitter: this.submitter.val(),
      },
    })
    .then(response => this.onReviewCreated(response))
    .catch((xhr, type, error) => this.onReviewFail(xhr, type, error))
    ;
  }

  onReviewCreated(response) {
    window.location.replace(`/review.html?id=${response.id}`);
  }

  onReviewFail(xhr, type, error) {
    // TODO
  }

  useSource(source) {
    return Promise
    .all([ source.filename, source.language ])
    .then(([ filename, language ]) => {
      const link = $(`<li><a href="#/"><tt>${filename}</tt></a></li>`);

      link.on('click', event => {
        this.files.children().removeClass('selected');
        link.addClass('selected');

        this.renderSource(source);
      });

      this.files.append(link);

      return Promise.resolve(link);
    });
  }

  renderInitialSource(sources) {
    if (!sources.length) {
      return;
    }

    sources[0].then(link => {
      link.click();
    });
  }

  renderSource(source) {
    Promise.all([ source.language, source.code ])
    .then(([ language, code ]) => {
      const definition = Prism.languages[language];
      const highlighted = definition ? Prism.highlight(code, definition) : code;

      this.render.html(highlighted);
    })
    .catch(err => {
      console.log(err);
    })
    ;
  }
}

$($ => {
  const preview = new FormPreview({
    container: $('#review'),
    description: $('#description'),
    files: $('#files'),
    render: $('#render'),
    preview: $('#preview'),
    source:$ ('#source'),
    submit:$ ('#submit'),
    submitter:$ ('#submitter'),
    title:$ ('#title'),
  });
});
<commit_msg>Swagger returns result in obj, not the raw object<commit_after>import { OriginFactory } from './lib/OriginFactory';
import { ServiceGateway } from './lib/ServiceGateway';

import Prism from './lib/Prism';

class FormPreview {

  constructor({
    container, description, files, render, preview, source, submit, submitter, title,
    initialize = true, service = new ServiceGateway(), origins = new OriginFactory(),
  }) {
    this.container = container;
    this.description = description;
    this.files = files;
    this.render = render;
    this.preview = preview;
    this.source = source;
    this.submit = submit;
    this.submitter = submitter;
    this.title = title;

    this.service = service;
    this.origins = origins;

    if (initialize) {
      this._init();
    }
  }

  _init() {
    this.container.hide();

    this.preview.addClass('button-primary');
    this.preview.on('click', this.onPreview.bind(this));

    this.submit.hide();
    this.submit.on('click', this.onSubmit.bind(this));

    this.source.on('input', this.onSource.bind(this));
    this.source.on('keypress', this.onKeypress.bind(this));
  }

  onKeypress(event) {
    if (event.key === 'Enter' || event.keyCode === 13) {
      this.preview.click();
    }
  }

  onSource(event) {
    this.preview.addClass('button-primary');
    this.container.hide();
    this.submit.hide();
  }

  onPreview(event) {
    const url = this.source.val();
    const origin = this.origins.originFor(url);

    this.container.show();
    this.submit.show();
    this.files.children().remove();
    this.preview.removeClass('button-primary');

    origin.sources
    .then(sources => Promise.resolve(sources.map(this.useSource.bind(this))))
    .then(promises => this.renderInitialSource.call(this, promises))
    ;
  }

  onSubmit(event) {
    return this.service.createReview({
      body: {
        title: this.title.val(),
        description: this.description.val(),
        url: this.source.val(),
        submitter: this.submitter.val(),
      },
    })
    .then(response => this.onReviewCreated(response.obj))
    .catch((xhr, type, error) => this.onReviewFail(xhr, type, error))
    ;
  }

  onReviewCreated(response) {
    window.location.replace(`/review.html?id=${response.id}`);
  }

  onReviewFail(xhr, type, error) {
    // TODO
  }

  useSource(source) {
    return Promise
    .all([ source.filename, source.language ])
    .then(([ filename, language ]) => {
      const link = $(`<li><a href="#/"><tt>${filename}</tt></a></li>`);

      link.on('click', event => {
        this.files.children().removeClass('selected');
        link.addClass('selected');

        this.renderSource(source);
      });

      this.files.append(link);

      return Promise.resolve(link);
    });
  }

  renderInitialSource(sources) {
    if (!sources.length) {
      return;
    }

    sources[0].then(link => {
      link.click();
    });
  }

  renderSource(source) {
    Promise.all([ source.language, source.code ])
    .then(([ language, code ]) => {
      const definition = Prism.languages[language];
      const highlighted = definition ? Prism.highlight(code, definition) : code;

      this.render.html(highlighted);
    })
    .catch(err => {
      console.log(err);
    })
    ;
  }
}

$($ => {
  const preview = new FormPreview({
    container: $('#review'),
    description: $('#description'),
    files: $('#files'),
    render: $('#render'),
    preview: $('#preview'),
    source:$ ('#source'),
    submit:$ ('#submit'),
    submitter:$ ('#submitter'),
    title:$ ('#title'),
  });
});
<|endoftext|>