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

foam.CLASS({
  package: 'foam.java',
  name: 'PropertyInfo',
  extends: 'foam.java.Class',

  properties: [
    ['anonymous', true],
    'propName',
    {
      class: 'Boolean',
      name: 'transient',
      value: false
    },
    {
      class: 'Boolean',
      name: 'networkTransient',
      expression: function (transient) {
        return transient;
      }
    },
    {
      class: 'Boolean',
      name: 'storageTransient',
      expression: function (transient) {
        return transient;
      }
    },
    {
      name: 'getterName',
      expression: function(propName) {
        return 'get' + foam.String.capitalize(propName);
      }
    },
    {
      name: 'setterName',
      expression: function(propName) {
        return 'set' + foam.String.capitalize(propName);
      }
    },
    'sourceCls',
    'propType',
    'propRequired',
    'jsonParser',
    {
      name: 'methods',
      factory: function() {
        return [
          {
            name: 'getName',
            visibility: 'public',
            type: 'String',
            body: 'return "' + this.propName + '";'
          },
          {
            name: 'get',
            visibility: 'public',
            type: 'Object',
            args: [ { name: 'o', type: 'Object' } ],
            body: 'return get_(o);'
          },
          {
            name: 'get_',
            type: this.propType,
            visibility: 'public',
            args: [ { name: 'o', type: 'Object' } ],
            body: 'return ((' + this.sourceCls.name + ') o).' + this.getterName + '();'
          },
          {
            name: 'set',
            type: 'void',
            visibility: 'public',
            args: [ { name: 'o', type: 'Object' }, { name: 'value', type: 'Object' } ],
            body: '((' + this.sourceCls.name + ') o).' + this.setterName + '(cast(value));'
          },
          {
            name: 'cast',
            type: this.propType,
            visibility: 'public',
            args: [ { name: 'o', type: 'Object' } ],
            body: 'return (' + this.propType + ') o;'
          },
          {
            name: 'compare',
            type: 'int',
            visibility: 'public',
            args: [ { name: 'o1', type: 'Object' }, { name: 'o2', type: 'Object' } ],
            body: 'return compareValues(get_(o1), get_(o2));'
          },
          {
            name: 'comparePropertyToObject',
            type: 'int',
            visibility: 'public',
            args: [ { name: 'key', type: 'Object' }, { name: 'o', type: 'foam.core.FObject' } ],
            body: 'return compareValues(key, f(o));'
          },
          {
            name: 'jsonParser',
            type: 'foam.lib.parse.Parser',
            visibility: 'public',
            body: 'return new ' + this.jsonParser + '();'
          },
          {
            name: 'getTransient',
            type: 'boolean',
            visibility: 'public',
            body: 'return ' + this.transient + ';'
          },
          {
            name: 'getNetworkTransient',
            type: 'boolean',
            visibility: 'public',
            body: 'return ' + this.networkTransient + ';'
          },
          {
            name: 'getStorageTransient',
            type: 'boolean',
            visibility: 'public',
            body: 'return ' + this.networkTransient + ';'
          },
          {
            name: 'getRequired',
            visibility: 'public',
            type: 'boolean',
            body: 'return ' + Boolean(this.propRequired) + ';'
          },
          {
            name: 'getValueClass',
            visibility: 'public',
            type: 'Class',
            body: `return ${this.propType}.class;`
          }
        ]
      }
    }
  ]
});
<commit_msg>Changed incorrect variable<commit_after>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.java',
  name: 'PropertyInfo',
  extends: 'foam.java.Class',

  properties: [
    ['anonymous', true],
    'propName',
    {
      class: 'Boolean',
      name: 'transient',
      value: false
    },
    {
      class: 'Boolean',
      name: 'networkTransient',
      expression: function (transient) {
        return transient;
      }
    },
    {
      class: 'Boolean',
      name: 'storageTransient',
      expression: function (transient) {
        return transient;
      }
    },
    {
      name: 'getterName',
      expression: function(propName) {
        return 'get' + foam.String.capitalize(propName);
      }
    },
    {
      name: 'setterName',
      expression: function(propName) {
        return 'set' + foam.String.capitalize(propName);
      }
    },
    'sourceCls',
    'propType',
    'propRequired',
    'jsonParser',
    {
      name: 'methods',
      factory: function() {
        return [
          {
            name: 'getName',
            visibility: 'public',
            type: 'String',
            body: 'return "' + this.propName + '";'
          },
          {
            name: 'get',
            visibility: 'public',
            type: 'Object',
            args: [ { name: 'o', type: 'Object' } ],
            body: 'return get_(o);'
          },
          {
            name: 'get_',
            type: this.propType,
            visibility: 'public',
            args: [ { name: 'o', type: 'Object' } ],
            body: 'return ((' + this.sourceCls.name + ') o).' + this.getterName + '();'
          },
          {
            name: 'set',
            type: 'void',
            visibility: 'public',
            args: [ { name: 'o', type: 'Object' }, { name: 'value', type: 'Object' } ],
            body: '((' + this.sourceCls.name + ') o).' + this.setterName + '(cast(value));'
          },
          {
            name: 'cast',
            type: this.propType,
            visibility: 'public',
            args: [ { name: 'o', type: 'Object' } ],
            body: 'return (' + this.propType + ') o;'
          },
          {
            name: 'compare',
            type: 'int',
            visibility: 'public',
            args: [ { name: 'o1', type: 'Object' }, { name: 'o2', type: 'Object' } ],
            body: 'return compareValues(get_(o1), get_(o2));'
          },
          {
            name: 'comparePropertyToObject',
            type: 'int',
            visibility: 'public',
            args: [ { name: 'key', type: 'Object' }, { name: 'o', type: 'foam.core.FObject' } ],
            body: 'return compareValues(key, f(o));'
          },
          {
            name: 'jsonParser',
            type: 'foam.lib.parse.Parser',
            visibility: 'public',
            body: 'return new ' + this.jsonParser + '();'
          },
          {
            name: 'getTransient',
            type: 'boolean',
            visibility: 'public',
            body: 'return ' + this.transient + ';'
          },
          {
            name: 'getNetworkTransient',
            type: 'boolean',
            visibility: 'public',
            body: 'return ' + this.networkTransient + ';'
          },
          {
            name: 'getStorageTransient',
            type: 'boolean',
            visibility: 'public',
            body: 'return ' + this.storageTransient + ';'
          },
          {
            name: 'getRequired',
            visibility: 'public',
            type: 'boolean',
            body: 'return ' + Boolean(this.propRequired) + ';'
          },
          {
            name: 'getValueClass',
            visibility: 'public',
            type: 'Class',
            body: `return ${this.propType}.class;`
          }
        ]
      }
    }
  ]
});
<|endoftext|>


<commit_before>'use strict';

// Setting up route
angular.module('admin').config(['$stateProvider',
	function($stateProvider) {
		// Requests state routing
		$stateProvider.
		state('adminRequests', {
			url: '/admin/requests',
			templateUrl: 'modules/admin/views/list-requests.client.view.html'
		}).
		state('adminCreateRequest', {
			url: '/requests/create',
			templateUrl: 'modules/admin/views/create-request.client.view.html'
		}).
		state('adminViewRequest', {
			url: '/requests/:requestId',
			templateUrl: 'modules/admin/views/view-request.client.view.html'
		}).
		state('adminEditRequest', {
			url: '/requests/:requestId/edit',
			templateUrl: 'modules/admin/views/edit-request.client.view.html'
		});
	}
]);<commit_msg>Added new routes for admin.<commit_after>'use strict';

// Setting up route
angular.module('admin').config(['$stateProvider',
	function($stateProvider) {
		// Requests admin routes
		$stateProvider.
		state('adminRequests', {
			url: '/admin/requests',
			templateUrl: 'modules/admin/views/admin-requests/list-requests.client.view.html'
		}).
		state('adminCreateRequest', {
			url: '/admin/requests/create',
			templateUrl: 'modules/admin/views/admin-requests/create-request.client.view.html'
		}).
		state('adminViewRequest', {
			url: '/admin/requests/:requestId',
			templateUrl: 'modules/admin/views/admin-requests/view-request.client.view.html'
		}).
		state('adminEditRequest', {
			url: '/admin/requests/:requestId/edit',
			templateUrl: 'modules/admin/views/admin-requests/edit-request.client.view.html'
		}).
		// Users admin routes
		state('adminUsers', {
			url: '/admin/users',
			templateUrl: 'modules/admin/views/admin-users/list-users.client.view.html'
		}).
		state('adminCreateUser', {
			url: '/admin/users/create',
			templateUrl: 'modules/admin/views/admin-users/create-user.client.view.html'
		});
	}
]);<|endoftext|>


<commit_before>var app = angular.module("CBEcalc", ["xeditable"]);

app.factory('classList', [function(){
  var o = {
    classList: []
  };
  return o;
}]);

app.factory('classPrefixes', [function(){
  var c = {
    classPrefixes: []
  };
  return c;
}]);

app.controller('MainCtrl', [
  '$scope',
  'classList',
  'classPrefixes',
  function($scope, classList, classPrefixes){
    $scope.classList = classList.classList;
    $scope.previousGPA = [];
    $scope.classPrefixes = classPrefixes.classPrefixes;
    $scope.gpa = (0.0).toFixed(2);
    $scope.totalCredits = 0;

    $scope.addClass = function(){
      if(!$scope.name || $scope.name === ''){
        return;
      }
      if(!$scope.grade || $scope.grade === ''){
        return;
      }
      if(!$scope.credits || $scope.credits === '' || $scope.credits != parseInt($scope.credits, 10)){
        return;
      }

      var gpa = 0;
      var tempGrade = $scope.grade;
      var letter = tempGrade.substring(0,1);
      var mod = '';
      if(tempGrade.length >= 2){
        mod = tempGrade.substring(1,2);
        if(!(mod === '+' || mod ==='-')){
          mod = '';
        }
      }
      if(letter === "a" || letter === 'A'){
        gpa = 4;
      }else if(letter === "b" || letter === 'B'){
        gpa = 3;
      }else if(letter === "c" || letter === 'C'){
        gpa = 2;
      }else if(letter === "d" || letter === 'D'){
        gpa = 1;
      }else if(letter === "f" || letter === 'F'){
        gpa = 0;
      }else{
        return;
      }

      if(mod === '+' && gpa < 4){
        gpa += 0.3;
      }else if(mod === '-'){
        gpa -= 0.3;
      }

      $scope.classList.push({
        name: $scope.name.substring(0,15),
        grade: letter.toUpperCase() + mod,
        gpa: gpa.toFixed(2),
        credits: $scope.credits
      });

      $scope.name = '';
      $scope.grade = '';
      $scope.credits = '';

      $scope.setGpa();

      return;
    };

    $scope.updatePrevious = function() {
      console.log("made it into function");
      console.log($scope.prevGPA);
      console.log($scope.prevCredits);
      if(!$scope.prevGPA || $scope.prevGPA === ''){
        return;
      }
      if(parseInt($scope.prevGPA) > 4){
        return;
      }
      if(!$scope.prevCredits || $scope.prevCredits === ''){
        return;
      }
      if($scope.prevCredits != parseInt($scope.prevCredits, 10)){
        return;
      }
      if($scope.previousGPA.length > 0){
        $scope.previousGPA.splice(0, $scope.previousGPA.length);
      }

      $scope.previousGPA.push({
        gpa: parseFloat($scope.prevGPA).toFixed(2),
        prevCredits: parseInt($scope.prevCredits)
      });

      $scope.prevGPA = '';
      $scope.prevCredits = '';

      $scope.setGpa();

      return;
    };

    $scope.setGpa = function() {
      var gpa = 0.00;
      var credits = 0.00;

      if($scope.previousGPA.length > 0){
        gpa = $scope.previousGPA[0].gpa * $scope.previousGPA[0].prevCredits;
        credits = $scope.previousGPA[0].prevCredits;
      }

      for(var i = 0 ; i < $scope.classList.length ; i++){
        gpa += (+$scope.classList[i].gpa * +$scope.classList[i].credits);
        credits += +$scope.classList[i].credits;
      }
      if(gpa != 0){
        gpa = gpa / credits;
      }
      $scope.totalCredits = credits;
      $scope.gpa = gpa.toFixed(2);
    };

    $scope.removeClass = function(item) {
      var index = $scope.classList.indexOf(item);
      $scope.classList.splice(index, 1);
      $scope.setGpa();
    };
    /* Proof of concept to fetch page content
    $scope.updateDOMInfo = function(info){
      document.getElementById('total').textContent = info.total;
      document.getElementById('inputs').textContent = info.inputs;
      document.getElementById('buttons').textContent = info.buttons;
      document.getElementById('data').textContent = info.data; //Actual text
    };
    */
    /* Function to scrape text off page and parse out class information */
    $scope.addPrevClasses = function(info){
      var localData = String(info.data);
      var lines = localData.split('\n');
      var headers = [
        'ECON',
        'ACCT',
        'DSCI',
        'MIS',
        'FIN',
        'MRKT',
        'OPS',
        'MGMT',
        'IBUS',
        'HRM',
        'PSY'
      ];
      var grades = [
        'A',
        'A+',
        'A-',
        'B',
        'B+',
        'B-',
        'C',
        'C+',
        'C-',
        'D',
        'D+',
        'D-',
        'F',
        'F+',
        'F-'
      ];
      for(var i = 0 ; i < lines.length ; i++){
        //split on space or group of spaces and store in lineArray
        var lineArray = lines[i].trim().split(/\s+/);

        if(headers.indexOf(lineArray[0]) >= 0){
          var tempName = (lineArray[0] + ' ' + lineArray[1]).substring(0, 8)
          var tempGrade;
          var tempCredits;
          /*
          for(var j = 0 ; j < grades.length ; j++){
            if((lineArray.indexOf(grades[j]) >= 0) || (lineArray.indexOf('K' + grades[j]) >= 0)){
              tempGrade = lineArray[j];
              break;
            }
          }*/

          for(var ind = 5; ind < lineArray.length; ind++){
            if(grades.indexOf(lineArray[ind])>=0){
              tempGrade = lineArray[ind];
              //credits are located one before the grade.
              tempCredits = lineArray[ind-1];
              break;
            }
          }

          $scope.classList.push({
            name: tempName,
            grade: tempGrade,
            gpa: getGPAValue(tempGrade).toFixed(1),
            credits: tempCredits
          });
        }
      }
      $scope.setGpa();
      return;
    };
  }
]);
//function to calculate GPA point based on letter grades
function getGPAValue(string){
  var gpa;
  var letter = string.substring(0,1);
  if(string.length >= 2){
        var mod = string.substring(1,2);
        if(!(mod === '+' || mod ==='-')){
          var mod = '';
        }
      }
      if(letter === "a" || letter === 'A'){
        gpa = 4;
      }else if(letter === "b" || letter === 'B'){
        gpa = 3;
      }else if(letter === "c" || letter === 'C'){
        gpa = 2;
      }else if(letter === "d" || letter === 'D'){
        gpa = 1;
      }else if(letter === "f" || letter === 'F'){
        gpa = 0;
      }else{
        return;
      }

      if(mod === '+' && gpa < 4){
        gpa += 0.3;
      }else if(mod === '-'){
        gpa -= 0.3;
      }
  return gpa;
}

// Update the relevant fields with the new data
function setDOMInfo(info) {
  var scope = angular.element(document.getElementById("main")).scope();
  scope.$apply(function(){
    scope.classList.length = 0;
    scope.addPrevClasses(info);

  });
}

// Once the DOM is ready...
window.addEventListener('DOMContentLoaded', function () {
  // ...query for the active tab...
  chrome.tabs.query({
    active: true,
    currentWindow: true
  }, function (tabs) {
    // ...and send a request for the DOM info...
    chrome.tabs.sendMessage(
        tabs[0].id,
        {from: 'popup', subject: 'DOMInfo'},
        // ...also specifying a callback to be called
        //    from the receiving end (content script)
        setDOMInfo);
  });
});
<commit_msg>Removed 'PSY' from class list<commit_after>var app = angular.module("CBEcalc", ["xeditable"]);

app.factory('classList', [function(){
  var o = {
    classList: []
  };
  return o;
}]);

app.factory('classPrefixes', [function(){
  var c = {
    classPrefixes: []
  };
  return c;
}]);

app.controller('MainCtrl', [
  '$scope',
  'classList',
  'classPrefixes',
  function($scope, classList, classPrefixes){
    $scope.classList = classList.classList;
    $scope.previousGPA = [];
    $scope.classPrefixes = classPrefixes.classPrefixes;
    $scope.gpa = (0.0).toFixed(2);
    $scope.totalCredits = 0;

    $scope.addClass = function(){
      if(!$scope.name || $scope.name === ''){
        return;
      }
      if(!$scope.grade || $scope.grade === ''){
        return;
      }
      if(!$scope.credits || $scope.credits === '' || $scope.credits != parseInt($scope.credits, 10)){
        return;
      }

      var gpa = 0;
      var tempGrade = $scope.grade;
      var letter = tempGrade.substring(0,1);
      var mod = '';
      if(tempGrade.length >= 2){
        mod = tempGrade.substring(1,2);
        if(!(mod === '+' || mod ==='-')){
          mod = '';
        }
      }
      if(letter === "a" || letter === 'A'){
        gpa = 4;
      }else if(letter === "b" || letter === 'B'){
        gpa = 3;
      }else if(letter === "c" || letter === 'C'){
        gpa = 2;
      }else if(letter === "d" || letter === 'D'){
        gpa = 1;
      }else if(letter === "f" || letter === 'F'){
        gpa = 0;
      }else{
        return;
      }

      if(mod === '+' && gpa < 4){
        gpa += 0.3;
      }else if(mod === '-'){
        gpa -= 0.3;
      }

      $scope.classList.push({
        name: $scope.name.substring(0,15),
        grade: letter.toUpperCase() + mod,
        gpa: gpa.toFixed(2),
        credits: $scope.credits
      });

      $scope.name = '';
      $scope.grade = '';
      $scope.credits = '';

      $scope.setGpa();

      return;
    };

    $scope.updatePrevious = function() {
      console.log("made it into function");
      console.log($scope.prevGPA);
      console.log($scope.prevCredits);
      if(!$scope.prevGPA || $scope.prevGPA === ''){
        return;
      }
      if(parseInt($scope.prevGPA) > 4){
        return;
      }
      if(!$scope.prevCredits || $scope.prevCredits === ''){
        return;
      }
      if($scope.prevCredits != parseInt($scope.prevCredits, 10)){
        return;
      }
      if($scope.previousGPA.length > 0){
        $scope.previousGPA.splice(0, $scope.previousGPA.length);
      }

      $scope.previousGPA.push({
        gpa: parseFloat($scope.prevGPA).toFixed(2),
        prevCredits: parseInt($scope.prevCredits)
      });

      $scope.prevGPA = '';
      $scope.prevCredits = '';

      $scope.setGpa();

      return;
    };

    $scope.setGpa = function() {
      var gpa = 0.00;
      var credits = 0.00;

      if($scope.previousGPA.length > 0){
        gpa = $scope.previousGPA[0].gpa * $scope.previousGPA[0].prevCredits;
        credits = $scope.previousGPA[0].prevCredits;
      }

      for(var i = 0 ; i < $scope.classList.length ; i++){
        gpa += (+$scope.classList[i].gpa * +$scope.classList[i].credits);
        credits += +$scope.classList[i].credits;
      }
      if(gpa != 0){
        gpa = gpa / credits;
      }
      $scope.totalCredits = credits;
      $scope.gpa = gpa.toFixed(2);
    };

    $scope.removeClass = function(item) {
      var index = $scope.classList.indexOf(item);
      $scope.classList.splice(index, 1);
      $scope.setGpa();
    };
    /* Proof of concept to fetch page content
    $scope.updateDOMInfo = function(info){
      document.getElementById('total').textContent = info.total;
      document.getElementById('inputs').textContent = info.inputs;
      document.getElementById('buttons').textContent = info.buttons;
      document.getElementById('data').textContent = info.data; //Actual text
    };
    */
    /* Function to scrape text off page and parse out class information */
    $scope.addPrevClasses = function(info){
      var localData = String(info.data);
      var lines = localData.split('\n');
      var headers = [
        'ECON',
        'ACCT',
        'DSCI',
        'MIS',
        'FIN',
        'MRKT',
        'OPS',
        'MGMT',
        'IBUS',
        'HRM',
      ];
      var grades = [
        'A',
        'A+',
        'A-',
        'B',
        'B+',
        'B-',
        'C',
        'C+',
        'C-',
        'D',
        'D+',
        'D-',
        'F',
        'F+',
        'F-'
      ];
      for(var i = 0 ; i < lines.length ; i++){
        //split on space or group of spaces and store in lineArray
        var lineArray = lines[i].trim().split(/\s+/);

        if(headers.indexOf(lineArray[0]) >= 0){
          var tempName = (lineArray[0] + ' ' + lineArray[1]).substring(0, 8)
          var tempGrade;
          var tempCredits;
          /*
          for(var j = 0 ; j < grades.length ; j++){
            if((lineArray.indexOf(grades[j]) >= 0) || (lineArray.indexOf('K' + grades[j]) >= 0)){
              tempGrade = lineArray[j];
              break;
            }
          }*/

          for(var ind = 5; ind < lineArray.length; ind++){
            if(grades.indexOf(lineArray[ind])>=0){
              tempGrade = lineArray[ind];
              //credits are located one before the grade.
              tempCredits = lineArray[ind-1];
              break;
            }
          }

          $scope.classList.push({
            name: tempName,
            grade: tempGrade,
            gpa: getGPAValue(tempGrade).toFixed(1),
            credits: tempCredits
          });
        }
      }
      $scope.setGpa();
      return;
    };
  }
]);
//function to calculate GPA point based on letter grades
function getGPAValue(string){
  var gpa;
  var letter = string.substring(0,1);
  if(string.length >= 2){
        var mod = string.substring(1,2);
        if(!(mod === '+' || mod ==='-')){
          var mod = '';
        }
      }
      if(letter === "a" || letter === 'A'){
        gpa = 4;
      }else if(letter === "b" || letter === 'B'){
        gpa = 3;
      }else if(letter === "c" || letter === 'C'){
        gpa = 2;
      }else if(letter === "d" || letter === 'D'){
        gpa = 1;
      }else if(letter === "f" || letter === 'F'){
        gpa = 0;
      }else{
        return;
      }

      if(mod === '+' && gpa < 4){
        gpa += 0.3;
      }else if(mod === '-'){
        gpa -= 0.3;
      }
  return gpa;
}

// Update the relevant fields with the new data
function setDOMInfo(info) {
  var scope = angular.element(document.getElementById("main")).scope();
  scope.$apply(function(){
    scope.classList.length = 0;
    scope.addPrevClasses(info);

  });
}

// Once the DOM is ready...
window.addEventListener('DOMContentLoaded', function () {
  // ...query for the active tab...
  chrome.tabs.query({
    active: true,
    currentWindow: true
  }, function (tabs) {
    // ...and send a request for the DOM info...
    chrome.tabs.sendMessage(
        tabs[0].id,
        {from: 'popup', subject: 'DOMInfo'},
        // ...also specifying a callback to be called
        //    from the receiving end (content script)
        setDOMInfo);
  });
});
<|endoftext|>


<commit_before>const config = require('../userconfig/config.json');
var Commands = require('../command_handler.js');
var disabledCommands = require('../userconfig/disabled_commands.json');

exports.main = function(selfbot, msg, msgArray, chalk) {
    var command = "help";
    msg.delete();
    var commandsExpl = [];
    var cmdList = Object.keys(Commands.commands);
    var arg = msgArray[1];
    // possible arg to get help on a command
    if(arg && cmdList.indexOf(arg) !== -1) return msg.edit(`**__Syntax for '${arg}' is:__** \`\`\`${config.commandPrefix + arg + " " + Commands.commands[arg].syntax}\`\`\``).then(msg => msg.delete(20000));
    for(var i = 0; i < cmdList.length; i++) commandsExpl.push(`\`\`'${cmdList[i]}' -- ${Commands.commands[cmdList[i]].desc}\`\``);
    msg.channel.sendMessage(`**__Available commands are:__**\n\n${commandsExpl.join("\n")}\n\n\`\`Use '${config.commandPrefix + command} <commandname>' to get syntax help on a command!\`\`\n\n**${disabledCommands.join(", ").length>0 ? "Disabled commands: " + disabledCommands.join(", ") : "No commands have been disabled."}**`, {split: {char: "\n"}});
};

exports.desc = "Display this mesage";
exports.syntax = "<command to get help on, optional>";<commit_msg>Fix help arguments<commit_after>const config = require('../userconfig/config.json');
var Commands = require('../command_handler.js');
var disabledCommands = require('../userconfig/disabled_commands.json');

exports.main = function(selfbot, msg, msgArray, chalk) {
    var command = "help";
    msg.delete();
    var commandsExpl = [];
    var cmdList = Object.keys(Commands.commands);
    var arg = msgArray[1];
    // possible arg to get help on a command
    if(arg && cmdList.indexOf(arg) !== -1) return msg.channel.sendMessage(`**__Syntax for '${arg}' is:__** \`\`\`${config.commandPrefix + arg + " " + Commands.commands[arg].syntax}\`\`\``).then(msg => msg.delete(20000));
    for(var i = 0; i < cmdList.length; i++) commandsExpl.push(`\`\`'${cmdList[i]}' -- ${Commands.commands[cmdList[i]].desc}\`\``);
    msg.channel.sendMessage(`**__Available commands are:__**\n\n${commandsExpl.join("\n")}\n\n\`\`Use '${config.commandPrefix + command} <commandname>' to get syntax help on a command!\`\`\n\n**${disabledCommands.join(", ").length>0 ? "Disabled commands: " + disabledCommands.join(", ") : "No commands have been disabled."}**`, {split: {char: "\n"}});
};

exports.desc = "Display this mesage";
exports.syntax = "<command to get help on, optional>";<|endoftext|>


<commit_before>var express = require('express');
var client = require('../connection.js');
var fs = require('fs');
var router = express.Router();

/* POST upload page. */
var handleUpload = function(req, res) {
    var body = req.body;
    console.log(body);
    var blueTeams = req.body.blueTeam.split(",");
    var redTeams = req.body.redTeam.split(",");
    var gameid = req.body.gameid;
    var matchType = req.body.matchType;
    var comments = req.body.comments;
    client.index({
        index: 'games',
        id: gameid,
        type: matchType,
        body: {
            "blueTeams": blueTeams,
            "redTeams": redTeams,
            "comments": comments,
            "gameId": gameid
        }
    }, function(err, resp, status) {
        console.log(resp);
        if (err) {
            console.log(err);
            res.sendStatus(500); // Internal server error
        } else {
            /// .   .   .   Insert into ES and get gameid
            console.log(req);
            res.render('upload', {success: 1, firstTime: 0});
        }
    });

};

/* GET upload page. */
router.get('/', function(req, res, next) {
    client.search({
        index: 'games',
        type: 'game',
        body: {
            aggs : {
                max_gameid : {
                    max : {
                        field : "gameId"
                    }
                }
            }
        }
    },function (error, response,status) {
        if (error){
            console.log("search error: " + error);
            res.sendStatus(500);
        }
        else {
            res.render('upload', {success: 0, firstTime: 1, gameId: response.aggregations.max_gameid.value});
        }
    });
});

module.exports = {router: router, handleUpload: handleUpload};
<commit_msg>Fix: now automatic filling of gameid fills the next gameid in line instead of the current gameid<commit_after>var express = require('express');
var client = require('../connection.js');
var fs = require('fs');
var router = express.Router();

/* POST upload page. */
var handleUpload = function(req, res) {
    var body = req.body;
    console.log(body);
    var blueTeams = req.body.blueTeam.split(",");
    var redTeams = req.body.redTeam.split(",");
    var gameid = req.body.gameid;
    var matchType = req.body.matchType;
    var comments = req.body.comments;
    client.index({
        index: 'games',
        id: gameid,
        type: matchType,
        body: {
            "blueTeams": blueTeams,
            "redTeams": redTeams,
            "comments": comments,
            "gameId": gameid
        }
    }, function(err, resp, status) {
        console.log(resp);
        if (err) {
            console.log(err);
            res.sendStatus(500); // Internal server error
        } else {
            /// .   .   .   Insert into ES and get gameid
            console.log(req);
            res.render('upload', {success: 1, firstTime: 0});
        }
    });

};

/* GET upload page. */
router.get('/', function(req, res, next) {
    client.search({
        index: 'games',
        type: 'game',
        body: {
            aggs : {
                max_gameid : {
                    max : {
                        field : "gameId"
                    }
                }
            }
        }
    },function (error, response,status) {
        if (error){
            console.log("search error: " + error);
            res.sendStatus(500);
        }
        else {
            res.render('upload', {success: 0, firstTime: 1, gameId: response.aggregations.max_gameid.value + 1});
        }
    });
});

module.exports = {router: router, handleUpload: handleUpload};
<|endoftext|>


<commit_before>var DataExplorer = (function () {
    var deferred = new $.Deferred(),
        options = {
            'User': {},
            'Site': {}
        };

    function init(settings) {
        if (typeof settings === 'object') {
            for (var setting in settings) {
                if (settings.hasOwnProperty(setting)) {
                    if (settings[setting] && typeof settings[setting] === 'object') {
                        if (typeof options[setting] === 'object') {
                            $.extend(options[setting], settings[setting]);
                        }
                    } else {
                        if (setting.indexOf('.') !== -1) {
                            var option = setting.split('.');

                            if (typeof options[option[0]] === 'object') {
                                options[option[0]][option[1]] = settings[setting];
                            }
                        } else {
                            options[setting] = settings[setting];
                        }
                    }
                }
            }
        }

        $(document).ready(function () {
            deferred.resolve();
        });
    }

    function ready(callback) {
        deferred.done(callback);
    }

    function template(target, attribute, replacements) {
        if (typeof target === 'string') {
            target = $(target);
        }

        if (!target.length) {
            return;
        }

        target.each(function () {
            var key = 'tmpl-' + attribute,
                self = $(this),
                template = self.data(key);

            if (!template) {
                if (attribute === 'text') {
                    template = this.firstChild.nodeValue;
                } else {
                    template = this[attribute];
                }

                if (!template) {
                    return;
                }

                self.data(key, template);
            }

            if (attribute === 'text') {
                this.firstChild.nodeValue = template.format(replacements);
            } else {
                this[attribute] = template.format(replacements);
            }
        });
    }

    return {
        'init': init,
        'ready': ready,
        'options': options,
        'template': template
    };
})(), _textContent = 'textContent' in document.createElement('span') ? 'textContent' : 'innerText';

DataExplorer.DeferredRequest = function DeferredRequest(settings) {
    if (!(this instanceof DeferredRequest)) {
        return new DeferredRequest(settings);
    }

    var options = $.extend({
            'delay': 950,
            'type': 'post',
            force: true
        }, settings),
        pending = null,
        dispatched = false,
        canceled = false,
        deferred = null;

    if (options.force) {
        $(document).bind('unload', function () {
            request(true);
        });
    }

    this.request = function rerequest(data) {
        if (pending) {
            clearTimeout(pending);
        }

        canceled = false;

        if (!dispatched) {
            options.data = data;
            pending = setTimeout(request, options.delay);
        } else {
            deferred = function () {
                rerequest(data);
            };
        }
    }

    this.cancel = function cancel() {
        clearTimeout(pending);
        canceled = true;
    }

    function request(synchronous) {
        dispatched = true;
        synchronous = !!synchronous;

        var data = typeof options.data === 'function' ? options.data() : options.data;

        if (!canceled) {
            $.ajax({
                'async': synchronous,
                'data': data,
                'type': options.type,
                'url': options.url,
                'success': response
            });
        } else {
            dispatched = false;
        }
    }

    function response(response) {
        if (options.callback) {
            options.callback(response);
        }

        dispatched = false;

        if (deferred) {
            deferred();
        }
    }
}

DataExplorer.Voting = (function () {
    var id, error, counter, star,
        voted = false, pending = false;

    function init(target, revision, vote, readOnly) {
        target = $(target);

        if (readOnly) {
            return;
        }

        id = revision;
        voted = vote;

        star = target.find('span').click(click);
        counter = target.find('.favoritecount');
        error = target.find('.error-notification');
    }

    function click(event) {
        if (!DataExplorer.options.User.isAuthenticated) {
            error.show();

            return;
        }

        if (pending) {
            return;
        }

        pending = true;

        $.post('/vote/' + id, { 'voteType': 'favorite' }, function (response) {
            if (typeof response === 'object' && response.success) {
                var count = parseInt(counter.text());

                voted = !voted;

                if (!voted) {
                    counter.removeClass('favoritecount-selected');
                    counter.text(count - 1);
                    star.removeClass('star-on');
                    star.addClass('star-off');
                } else {
                    counter.addClass('favoritecount-selected');
                    counter.text(count + 1);
                    star.removeClass('star-off');
                    star.addClass('star-on');
                }
            }

            pending = false;
        });
    }

    return {
        'init': init
    }
})();

DataExplorer.ready(function () {
    $(document).delegate('.error-notification', 'click', function () {
        $(this).hide();
    });
});

$.fn.tabs = function () {
    return this.delegate("a:not(.youarehere)", "click", function () {
        $(this.hash).show();
        $(this).addClass("youarehere")
            .trigger('show')
            .siblings()
            .removeClass("youarehere")
            .each(function () {
                $(this.hash).hide();
            });
    }).delegate("a", "click", function () {
        return false;
    });
};

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

String.prototype.format = function (replacements) {
    if (!replacements) {
        return this;
    }

    var result = this, replacement;

    for (replacement in replacements) {
        if (replacements.hasOwnProperty(replacement)) {
            var regex = new RegExp(":" + replacement + ';?', 'g');

            result = result.replace(regex, function (match, optional) {
                var sub = replacements[replacement];

                if (!sub && sub !== 0) {
                    sub = "";
                }

                return sub;
            });
        }
    }

    return result;
}

String.prototype.from = function (ch, inclusive) {
    ch = this.indexOf(ch);

    if (typeof inclusive === 'undefined') {
        inclusive = true;
    }

    if (ch < 1) {
        return this;
    }

    return this.substring(ch + (inclusive ? 0 : 1));
}

String.prototype.asVariable = function () {
    var chunks = this.split(/\s+/),
        result = chunks[0].toLowerCase();

    if (chunks.length == 0) {
        return result;
    }

    for (var i = 1; i < chunks.length; ++i) {
        result = result
            + chunks[i].substring(0, 1).toUpperCase()
            + chunks[i].substring(1).toLowerCase();
    }

    return result;
}

if (!Date.now) {
    Date.now = function () {
        return +new Date();
    }
}

window.location.param = (function () {
    var cache = null;

    return function (name) {
        if (cache === null) {
            cache = {};

            if (window.location.search.length < 4) {
                cache = false;

                return;
            }

            var search = window.location.search.substring(1),
                groups = search.split('&'), i;

            for (i = 0; i < groups.length; ++i) {
                search = groups[i].split('=');

                if (search.length === 2 && search[0].length) {
                    cache[search[0].toLowerCase()] = search[1];
                }
            }
        }

        if (cache === false) {
            return;
        }

        return cache[name.toLowerCase()];
    }
})();

Date.parseTimestamp = (function () {
    var implementation = function (timestamp) {
        return new Date(timestamp);
    };

    try {
        implementation('2011-01-01 12:00:00Z');
    } catch (ex) {
        implementation = function (timestamp) {
            var bits = timestamp.split(/[-: Z]/);

            // We only care about local and UTC, so assume non-local is always UTC
            if (typeof bits[7] === 'undefined') {
                return new Date(
                    parseInt(bits[0], 10),
                    parseInt(bits[1], 10),
                    parseInt(bits[2], 10),
                    parseInt(bits[3], 10),
                    parseInt(bits[4], 10),
                    parseInt(bits[5], 10)
                );
            } else {
                return new Date(Date.UTC(
                    parseInt(bits[0], 10),
                    parseInt(bits[1], 10),
                    parseInt(bits[2], 10),
                    parseInt(bits[3], 10),
                    parseInt(bits[4], 10),
                    parseInt(bits[5], 10)
                ));
            }
        }
    }

    return implementation;
})();

Date.prototype.toUTC = (function () {
    function zero(val) {
        return val < 9 ? '0' + val : val;
    }

    return function () {
        return this.getUTCFullYear() +
            '-' + zero(this.getUTCMonth() + 1) +
            '-' + zero(this.getUTCDate()) +
            ' ' + zero(this.getUTCHours()) +
            ':' + zero(this.getUTCMinutes()) +
            ':' + zero(this.getUTCSeconds());
    }
})();

Date.prototype.toRelativeTimeMini = (function () {
    months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];

    return function () {
        var delta = (Date.now() - this) / 1000,
            rendered = "",
            minute = 60, hour = 60 * minute, day = 24 * hour,
            minutes = this.getUTCMinutes();

        if (delta < 5) {
            rendered = 'just now';
        } else if (delta < minute) {
            rendered = Math.round(delta) + 's ago';
        } else if (delta < hour) {
            rendered = Math.round(delta / minute) + 'm ago';
        } else if (delta < day) {
            rendered = Math.round(delta / hour) + 'h ago';
        } else {
            delta = Math.round(delta / day);

            if (delta <= 2) {
                rendered = delta + 'd ago';
            } else if (delta <= 330) {
                rendered = months[this.getUTCMonth()] + ' ' + this.getUTCDate() + ' at ' + this.getUTCHours() + ':' + (minutes < 10 ? '0' : '') + minutes;
            }
        }

        return rendered;
    };
})();<commit_msg>Decode arguments passed in from parameters<commit_after>var DataExplorer = (function () {
    var deferred = new $.Deferred(),
        options = {
            'User': {},
            'Site': {}
        };

    function init(settings) {
        if (typeof settings === 'object') {
            for (var setting in settings) {
                if (settings.hasOwnProperty(setting)) {
                    if (settings[setting] && typeof settings[setting] === 'object') {
                        if (typeof options[setting] === 'object') {
                            $.extend(options[setting], settings[setting]);
                        }
                    } else {
                        if (setting.indexOf('.') !== -1) {
                            var option = setting.split('.');

                            if (typeof options[option[0]] === 'object') {
                                options[option[0]][option[1]] = settings[setting];
                            }
                        } else {
                            options[setting] = settings[setting];
                        }
                    }
                }
            }
        }

        $(document).ready(function () {
            deferred.resolve();
        });
    }

    function ready(callback) {
        deferred.done(callback);
    }

    function template(target, attribute, replacements) {
        if (typeof target === 'string') {
            target = $(target);
        }

        if (!target.length) {
            return;
        }

        target.each(function () {
            var key = 'tmpl-' + attribute,
                self = $(this),
                template = self.data(key);

            if (!template) {
                if (attribute === 'text') {
                    template = this.firstChild.nodeValue;
                } else {
                    template = this[attribute];
                }

                if (!template) {
                    return;
                }

                self.data(key, template);
            }

            if (attribute === 'text') {
                this.firstChild.nodeValue = template.format(replacements);
            } else {
                this[attribute] = template.format(replacements);
            }
        });
    }

    return {
        'init': init,
        'ready': ready,
        'options': options,
        'template': template
    };
})(), _textContent = 'textContent' in document.createElement('span') ? 'textContent' : 'innerText';

DataExplorer.DeferredRequest = function DeferredRequest(settings) {
    if (!(this instanceof DeferredRequest)) {
        return new DeferredRequest(settings);
    }

    var options = $.extend({
            'delay': 950,
            'type': 'post',
            force: true
        }, settings),
        pending = null,
        dispatched = false,
        canceled = false,
        deferred = null;

    if (options.force) {
        $(document).bind('unload', function () {
            request(true);
        });
    }

    this.request = function rerequest(data) {
        if (pending) {
            clearTimeout(pending);
        }

        canceled = false;

        if (!dispatched) {
            options.data = data;
            pending = setTimeout(request, options.delay);
        } else {
            deferred = function () {
                rerequest(data);
            };
        }
    }

    this.cancel = function cancel() {
        clearTimeout(pending);
        canceled = true;
    }

    function request(synchronous) {
        dispatched = true;
        synchronous = !!synchronous;

        var data = typeof options.data === 'function' ? options.data() : options.data;

        if (!canceled) {
            $.ajax({
                'async': synchronous,
                'data': data,
                'type': options.type,
                'url': options.url,
                'success': response
            });
        } else {
            dispatched = false;
        }
    }

    function response(response) {
        if (options.callback) {
            options.callback(response);
        }

        dispatched = false;

        if (deferred) {
            deferred();
        }
    }
}

DataExplorer.Voting = (function () {
    var id, error, counter, star,
        voted = false, pending = false;

    function init(target, revision, vote, readOnly) {
        target = $(target);

        if (readOnly) {
            return;
        }

        id = revision;
        voted = vote;

        star = target.find('span').click(click);
        counter = target.find('.favoritecount');
        error = target.find('.error-notification');
    }

    function click(event) {
        if (!DataExplorer.options.User.isAuthenticated) {
            error.show();

            return;
        }

        if (pending) {
            return;
        }

        pending = true;

        $.post('/vote/' + id, { 'voteType': 'favorite' }, function (response) {
            if (typeof response === 'object' && response.success) {
                var count = parseInt(counter.text());

                voted = !voted;

                if (!voted) {
                    counter.removeClass('favoritecount-selected');
                    counter.text(count - 1);
                    star.removeClass('star-on');
                    star.addClass('star-off');
                } else {
                    counter.addClass('favoritecount-selected');
                    counter.text(count + 1);
                    star.removeClass('star-off');
                    star.addClass('star-on');
                }
            }

            pending = false;
        });
    }

    return {
        'init': init
    }
})();

DataExplorer.ready(function () {
    $(document).delegate('.error-notification', 'click', function () {
        $(this).hide();
    });
});

$.fn.tabs = function () {
    return this.delegate("a:not(.youarehere)", "click", function () {
        $(this.hash).show();
        $(this).addClass("youarehere")
            .trigger('show')
            .siblings()
            .removeClass("youarehere")
            .each(function () {
                $(this.hash).hide();
            });
    }).delegate("a", "click", function () {
        return false;
    });
};

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

String.prototype.format = function (replacements) {
    if (!replacements) {
        return this;
    }

    var result = this, replacement;

    for (replacement in replacements) {
        if (replacements.hasOwnProperty(replacement)) {
            var regex = new RegExp(":" + replacement + ';?', 'g');

            result = result.replace(regex, function (match, optional) {
                var sub = replacements[replacement];

                if (!sub && sub !== 0) {
                    sub = "";
                }

                return sub;
            });
        }
    }

    return result;
}

String.prototype.from = function (ch, inclusive) {
    ch = this.indexOf(ch);

    if (typeof inclusive === 'undefined') {
        inclusive = true;
    }

    if (ch < 1) {
        return this;
    }

    return this.substring(ch + (inclusive ? 0 : 1));
}

String.prototype.asVariable = function () {
    var chunks = this.split(/\s+/),
        result = chunks[0].toLowerCase();

    if (chunks.length == 0) {
        return result;
    }

    for (var i = 1; i < chunks.length; ++i) {
        result = result
            + chunks[i].substring(0, 1).toUpperCase()
            + chunks[i].substring(1).toLowerCase();
    }

    return result;
}

if (!Date.now) {
    Date.now = function () {
        return +new Date();
    }
}

window.location.param = (function () {
    var cache = null;

    return function (name) {
        if (cache === null) {
            cache = {};

            if (window.location.search.length < 4) {
                cache = false;

                return;
            }

            var search = window.location.search.substring(1),
                groups = search.split('&'), i;

            for (i = 0; i < groups.length; ++i) {
                search = groups[i].split('=');

                if (search.length === 2 && search[0].length) {
                    cache[search[0].toLowerCase()] = window.decodeURIComponent(search[1].replace(/\+/g, ' '));
                }
            }
        }

        if (cache === false) {
            return;
        }

        return cache[name.toLowerCase()];
    }
})();

Date.parseTimestamp = (function () {
    var implementation = function (timestamp) {
        return new Date(timestamp);
    };

    try {
        implementation('2011-01-01 12:00:00Z');
    } catch (ex) {
        implementation = function (timestamp) {
            var bits = timestamp.split(/[-: Z]/);

            // We only care about local and UTC, so assume non-local is always UTC
            if (typeof bits[7] === 'undefined') {
                return new Date(
                    parseInt(bits[0], 10),
                    parseInt(bits[1], 10),
                    parseInt(bits[2], 10),
                    parseInt(bits[3], 10),
                    parseInt(bits[4], 10),
                    parseInt(bits[5], 10)
                );
            } else {
                return new Date(Date.UTC(
                    parseInt(bits[0], 10),
                    parseInt(bits[1], 10),
                    parseInt(bits[2], 10),
                    parseInt(bits[3], 10),
                    parseInt(bits[4], 10),
                    parseInt(bits[5], 10)
                ));
            }
        }
    }

    return implementation;
})();

Date.prototype.toUTC = (function () {
    function zero(val) {
        return val < 9 ? '0' + val : val;
    }

    return function () {
        return this.getUTCFullYear() +
            '-' + zero(this.getUTCMonth() + 1) +
            '-' + zero(this.getUTCDate()) +
            ' ' + zero(this.getUTCHours()) +
            ':' + zero(this.getUTCMinutes()) +
            ':' + zero(this.getUTCSeconds());
    }
})();

Date.prototype.toRelativeTimeMini = (function () {
    months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];

    return function () {
        var delta = (Date.now() - this) / 1000,
            rendered = "",
            minute = 60, hour = 60 * minute, day = 24 * hour,
            minutes = this.getUTCMinutes();

        if (delta < 5) {
            rendered = 'just now';
        } else if (delta < minute) {
            rendered = Math.round(delta) + 's ago';
        } else if (delta < hour) {
            rendered = Math.round(delta / minute) + 'm ago';
        } else if (delta < day) {
            rendered = Math.round(delta / hour) + 'h ago';
        } else {
            delta = Math.round(delta / day);

            if (delta <= 2) {
                rendered = delta + 'd ago';
            } else if (delta <= 330) {
                rendered = months[this.getUTCMonth()] + ' ' + this.getUTCDate() + ' at ' + this.getUTCHours() + ':' + (minutes < 10 ? '0' : '') + minutes;
            }
        }

        return rendered;
    };
})();<|endoftext|>


<commit_before>angular
    .module('ngSharepoint.Lists')
    .factory('$spList', ['SPList', 'SelectQuery', 'UpdateQuery', 'InsertIntoQuery', 'DeleteQuery', function (SPList, SelectQuery, UpdateQuery, InsertIntoQuery, DeleteQuery) {
        return ({
            getList: function(title) {
              return new SPList(title);
            },
            select: function(fields) {
                return new SelectQuery(fields);
            },
            update: function(list) {
                return new UpdateQuery(list);
            },
            insertInto: function(list) {
                return new InsertIntoQuery(list);
            },
            delete: function() {
                return new DeleteQuery();
            }
        });
    }])
    .factory('SPList', ['$q', '$http', '$sp', '$spLog', function($q, $http, $sp, $spLog) {
      /**
       * @ngdoc object
       * @name  SPList
       * @param {string} title The List Title
       *
       * @module  ngSharepoint.Lists
       *
       * @description
       * SPList represents a Sharepoint List
       */
      var SPList = function(title) {
        this.title = title;
        if ($sp.getConnectionMode() == "JSOM") {
          this.__list = new JsomSPList(title);
        }else {
          this.__list = new RestSPList(title);
        }
      };
      /**
       * @ngdoc function
       * @name  SPList#insert
       * @param  {object} data The Data you wanna insert
       * @return {Promise}      A Promise which resolves when the insertion was sucessful
       */
      SPList.prototype.insert = function(data) {
        return this.__list.insert(data).catch($spLog.error);
      };
      /**
       * @ngdoc function
       * @name  SPList#select
       * @param {SP.CamlQuery} query A CamlQuery to filter for
       * @return {Promise} A Promise which resolves to the selected data
       */
      SPList.prototype.select = function(query) {
        return this.__list.select(query).catch($spLog.error);
      };
      /**
       * @ngdoc function
       * @param  {SP.CamlQuery} query A CamlQuery to filter for
       * @return {Promise}       [description]
       */
      SPList.prototype.delete = function(query) {
        return this.__list.delete(query).catch($spLog.error);
      };
      /**
       * @ngdoc function
       * @param  {SP.CamlQuery} query  A CamlQuery which selects the rows to update
       * @param  {object} data The Data you wanna update
       * @return {Promise}        A Promise which resolves when the update was sucessfull
       */
      SPList.prototype.update = function(query, data) {
        return this.__list.update(query, data).catch($spLog.error);
      };
      //RestSPList
      var RestSPList = function(title) {
        this.title = title;
      };
      RestSPList.prototype.select = function(query) {
        var endpoint = "_api/web/Lists/GetByTitle('" + this.title + "')/GetItems";
        var body = {
          query: {
            __metadata: {
              type: "SP.CamlQuery"
            },
            ViewXml: query.build()
          }
        };
        var headers = {
          "X-RequestDigest": $("#__REQUESTDIGEST").val(),
          "Accept": "application/json; odata=verbose",
          "Content-Type": "application/json; odata=verbose"
        };
        return $q(function(resolve, reject) {
          $http({
            method: 'POST',
            url: $sp.getSiteUrl() + endpoint,
            data: body,
            headers: headers
          }).then(function(data) {
            //TODO: Parse Result
          }, reject);
        });
      };
      RestSPList.prototype.insert = function(data) {
        var endpoint = "_api/web/Lists/GetByTitle('" + this.title + "')/items";
        var body = {
          __metadata: {
            type: 'SP.Data.TestListItem'
          }
        };
        var headers = {
          "X-RequestDigest": $("#__REQUESTDIGEST").val(),
          "Accept": "application/json; odata=verbose",
          "Content-Type": "application/json; odata=verbose"
        };
        Object.getOwnPropertyNames(data).forEach(function(key) {
          var value = data[key];
          if (value !== null && value !== undefined && typeof value == 'string') {
            value = value.trim();
          }
          body[key] = value;
        });
        return $q(function(resolve, reject) {
          $http({
            method: 'POST',
            url: $sp.getSiteUrl() + endpoint,
            data: body,
            headers: headers
          }).then(function(data) {
            //TODO: Parse Result
          }, reject);
        });
      };
      RestSPList.prototype.delete = function(query) {
        //TODO: Implement
      };
      RestSPList.prototype.update = function(query, data) {
        //TODO: Implement
      };
      //JsomSPList
      var JsomSPList = function(title) {
        this.title = title;
      };
      JsomSPList.prototype.select = function(query) {
        return $q(function(resolve, reject) {
          var context = $sp.getContext();
          var list = context.get_web().get_lists().getByTitle(this.title);
          var camlQuery = new SP.CamlQuery();
          camlQuery.set_viewXml(query);
          var items = list.getItems(camlQuery);
          context.load(items);
          context.executeQueryAsync(function() {
            var result = [];
            var itemIterator = items.getEnumerator();
            while (itemIterator.moveNext()) {
              var item = itemIterator.get_current();
              result.push(query.unpackItem(item));
            }
            resolve(result);
          }, function(sender, args) {
            reject(args);
          });
        });
      };
      JsomSPList.prototype.insert = function(data) {
        var list = this;
        return $q(function(resolve, reject) {
          var clientContext = $sp.getContext();
          var list = clientContext.get_web().get_lists().getByTitle(list.title);
          var itemInfo = new SP.ListItemCreationInformation();
          var item = list.addItem(itemInfo);
          list.__pack(item, data);
          item.update();
          clientContext.load(item);
          clientContext.executeQueryAsync(function(sender, args) {
              resolve(query.unpackItem(item));
          }, function(sender, args) {
              reject(args);
          });
        });
      };
      JsomSPList.prototype.delete = function(query) {
        var list = this;
        return $q(function(resolve, reject) {
          var clientContext = $sp.getContext();
          var list = clientContext.get_web().get_lists().getByTitle(list.title);
          var camlQuery = new SP.CamlQuery();
          camlQuery.set_viewXml(query);
          var items = list.getItems(camlQuery);
          clientContext.load(items);
          clientContext.executeQueryAsync(
              function(sender, args) {
                  var itemIterator = items.getEnumerator();
                  var a = [];
                  while (itemIterator.moveNext()) {
                     var item = itemIterator.get_current();
                     a.push(item);
                  }
                  a.forEach(function(item) {
                      item.deleteObject();
                  });
                  clientContext.executeQueryAsync(function(sender, args) {
                      resolve(args);
                  }, function(sender, args) {
                      reject(args);
                  });
              },
              function(sender, args) {
                  reject(args);
              }
          );
        });
      };
      JsomSPList.prototype.update = function(query, data) {
        var list = this;
        return $q(function(resolve, reject) {
          var clientContext = $sp.getContext();
          var list = clientContext.get_web().get_lists().getByTitle(query.__list);
          var camlQuery = new SP.CamlQuery();
          camlQuery.set_viewXml(query);
          var items = list.getItems(camlQuery);
          clientContext.load(items);
          clientContext.executeQueryAsync(function(sender, args) {
            var itemIterator = items.getEnumerator();
            while (itemIterator.moveNext()) {
              var item = itemIterator.get_current();
              list.__pack(item, data);
              item.update();
            }
            clientContext.executeQueryAsync(function(sender, args) {
                resolve(args);
            }, function(sender, args) {
                reject(args);
            });
          }, function(sender, args) {
              reject(args);
          });
        });
      };
      JsomSPList.prototype.__pack = function(item, data) {
        Object.getOwnPropertyNames(data).forEach(function(key) {
          var value = data[key];
          if (value !== null && value !== undefined && typeof value == 'string') {
            value = value.trim();
          }
          item.set_item(key, value);
        });
      };
      JsomSPList.prototype.__unpack = function(item, fields) {
        var query = this;
        var obj = {};
        var cols = fields;
        if (!Array.isArray(fields)) {
          cols = Object.getOwnPropertyNames(fields);
        }
        cols.forEach(function(key) {
            var value = item.get_item(key);
            if (value !== null && value !== undefined && typeof value == 'string') {
              value = value.trim();
            }
            obj[key] = value;
        });
        return obj;
      };
      return (SPList);
    }]);
<commit_msg>No need to unpack the data, just return it<commit_after>angular
    .module('ngSharepoint.Lists')
    .factory('$spList', ['SPList', 'SelectQuery', 'UpdateQuery', 'InsertIntoQuery', 'DeleteQuery', function (SPList, SelectQuery, UpdateQuery, InsertIntoQuery, DeleteQuery) {
        return ({
            getList: function(title) {
              return new SPList(title);
            },
            select: function(fields) {
                return new SelectQuery(fields);
            },
            update: function(list) {
                return new UpdateQuery(list);
            },
            insertInto: function(list) {
                return new InsertIntoQuery(list);
            },
            delete: function() {
                return new DeleteQuery();
            }
        });
    }])
    .factory('SPList', ['$q', '$http', '$sp', '$spLog', function($q, $http, $sp, $spLog) {
      /**
       * @ngdoc object
       * @name  SPList
       * @param {string} title The List Title
       *
       * @module  ngSharepoint.Lists
       *
       * @description
       * SPList represents a Sharepoint List
       */
      var SPList = function(title) {
        this.title = title;
        if ($sp.getConnectionMode() == "JSOM") {
          this.__list = new JsomSPList(title);
        }else {
          this.__list = new RestSPList(title);
        }
      };
      /**
       * @ngdoc function
       * @name  SPList#insert
       * @param  {object} data The Data you wanna insert
       * @return {Promise}      A Promise which resolves when the insertion was sucessful
       */
      SPList.prototype.insert = function(data) {
        return this.__list.insert(data).catch($spLog.error);
      };
      /**
       * @ngdoc function
       * @name  SPList#select
       * @param {SP.CamlQuery} query A CamlQuery to filter for
       * @return {Promise} A Promise which resolves to the selected data
       */
      SPList.prototype.select = function(query) {
        return this.__list.select(query).catch($spLog.error);
      };
      /**
       * @ngdoc function
       * @param  {SP.CamlQuery} query A CamlQuery to filter for
       * @return {Promise}       [description]
       */
      SPList.prototype.delete = function(query) {
        return this.__list.delete(query).catch($spLog.error);
      };
      /**
       * @ngdoc function
       * @param  {SP.CamlQuery} query  A CamlQuery which selects the rows to update
       * @param  {object} data The Data you wanna update
       * @return {Promise}        A Promise which resolves when the update was sucessfull
       */
      SPList.prototype.update = function(query, data) {
        return this.__list.update(query, data).catch($spLog.error);
      };
      //RestSPList
      var RestSPList = function(title) {
        this.title = title;
      };
      RestSPList.prototype.select = function(query) {
        var endpoint = "_api/web/Lists/GetByTitle('" + this.title + "')/GetItems";
        var body = {
          query: {
            __metadata: {
              type: "SP.CamlQuery"
            },
            ViewXml: query.build()
          }
        };
        var headers = {
          "X-RequestDigest": $("#__REQUESTDIGEST").val(),
          "Accept": "application/json; odata=verbose",
          "Content-Type": "application/json; odata=verbose"
        };
        return $q(function(resolve, reject) {
          $http({
            method: 'POST',
            url: $sp.getSiteUrl() + endpoint,
            data: body,
            headers: headers
          }).then(function(data) {
            //TODO: Parse Result
          }, reject);
        });
      };
      RestSPList.prototype.insert = function(data) {
        var endpoint = "_api/web/Lists/GetByTitle('" + this.title + "')/items";
        var body = {
          __metadata: {
            type: 'SP.Data.TestListItem'
          }
        };
        var headers = {
          "X-RequestDigest": $("#__REQUESTDIGEST").val(),
          "Accept": "application/json; odata=verbose",
          "Content-Type": "application/json; odata=verbose"
        };
        Object.getOwnPropertyNames(data).forEach(function(key) {
          var value = data[key];
          if (value !== null && value !== undefined && typeof value == 'string') {
            value = value.trim();
          }
          body[key] = value;
        });
        return $q(function(resolve, reject) {
          $http({
            method: 'POST',
            url: $sp.getSiteUrl() + endpoint,
            data: body,
            headers: headers
          }).then(function(data) {
            //TODO: Parse Result
          }, reject);
        });
      };
      RestSPList.prototype.delete = function(query) {
        //TODO: Implement
      };
      RestSPList.prototype.update = function(query, data) {
        //TODO: Implement
      };
      //JsomSPList
      var JsomSPList = function(title) {
        this.title = title;
      };
      JsomSPList.prototype.select = function(query) {
        return $q(function(resolve, reject) {
          var context = $sp.getContext();
          var list = context.get_web().get_lists().getByTitle(this.title);
          var camlQuery = new SP.CamlQuery();
          camlQuery.set_viewXml(query);
          var items = list.getItems(camlQuery);
          context.load(items);
          context.executeQueryAsync(function() {
            var result = [];
            var itemIterator = items.getEnumerator();
            while (itemIterator.moveNext()) {
              var item = itemIterator.get_current();
              result.push(query.unpackItem(item));
            }
            resolve(result);
          }, function(sender, args) {
            reject(args);
          });
        });
      };
      JsomSPList.prototype.insert = function(data) {
        var list = this;
        return $q(function(resolve, reject) {
          var clientContext = $sp.getContext();
          var list = clientContext.get_web().get_lists().getByTitle(list.title);
          var itemInfo = new SP.ListItemCreationInformation();
          var item = list.addItem(itemInfo);
          list.__pack(item, data);
          item.update();
          clientContext.load(item);
          clientContext.executeQueryAsync(function(sender, args) {
              resolve(data);
          }, function(sender, args) {
              reject(args);
          });
        });
      };
      JsomSPList.prototype.delete = function(query) {
        var list = this;
        return $q(function(resolve, reject) {
          var clientContext = $sp.getContext();
          var list = clientContext.get_web().get_lists().getByTitle(list.title);
          var camlQuery = new SP.CamlQuery();
          camlQuery.set_viewXml(query);
          var items = list.getItems(camlQuery);
          clientContext.load(items);
          clientContext.executeQueryAsync(
              function(sender, args) {
                  var itemIterator = items.getEnumerator();
                  var a = [];
                  while (itemIterator.moveNext()) {
                     var item = itemIterator.get_current();
                     a.push(item);
                  }
                  a.forEach(function(item) {
                      item.deleteObject();
                  });
                  clientContext.executeQueryAsync(function(sender, args) {
                      resolve(args);
                  }, function(sender, args) {
                      reject(args);
                  });
              },
              function(sender, args) {
                  reject(args);
              }
          );
        });
      };
      JsomSPList.prototype.update = function(query, data) {
        var list = this;
        return $q(function(resolve, reject) {
          var clientContext = $sp.getContext();
          var list = clientContext.get_web().get_lists().getByTitle(query.__list);
          var camlQuery = new SP.CamlQuery();
          camlQuery.set_viewXml(query);
          var items = list.getItems(camlQuery);
          clientContext.load(items);
          clientContext.executeQueryAsync(function(sender, args) {
            var itemIterator = items.getEnumerator();
            while (itemIterator.moveNext()) {
              var item = itemIterator.get_current();
              list.__pack(item, data);
              item.update();
            }
            clientContext.executeQueryAsync(function(sender, args) {
                resolve(args);
            }, function(sender, args) {
                reject(args);
            });
          }, function(sender, args) {
              reject(args);
          });
        });
      };
      JsomSPList.prototype.__pack = function(item, data) {
        Object.getOwnPropertyNames(data).forEach(function(key) {
          var value = data[key];
          if (value !== null && value !== undefined && typeof value == 'string') {
            value = value.trim();
          }
          item.set_item(key, value);
        });
      };
      JsomSPList.prototype.__unpack = function(item, fields) {
        var query = this;
        var obj = {};
        var cols = fields;
        if (!Array.isArray(fields)) {
          cols = Object.getOwnPropertyNames(fields);
        }
        cols.forEach(function(key) {
            var value = item.get_item(key);
            if (value !== null && value !== undefined && typeof value == 'string') {
              value = value.trim();
            }
            obj[key] = value;
        });
        return obj;
      };
      return (SPList);
    }]);
<|endoftext|>