<commit_before>const app = require('../../index.js');
const server = require('http').createServer(app);
const socketio = require('socket.io');
const db = require('../db/db');
const radius = 3000;

const dynamicResponder = require('../db/models/dynamicResponders');
const beacon = require('../db/models/beacons');

const websocket = socketio(server);
const activeBeaconSession = {
  beacon: '',
  responder: '',
  chatRoom: '',
  messages: [],
};

websocket.on('connection', (socket) => {
  console.log('+++A client just joined on socket.id:', socket.id);

  beacon.create({
    socket: socket.id
  });

  socket.on('updateUser', (options) => {
    console.log('+++options.query: ', options.query);
    dynamicResponder.find({ where: options.query })
      .then((responder) => {
        if (responder) {
          responder.update({ socket: socket.id })
            .then(updatedResponder => socket.emit('updateUser', updatedResponder));
        } else {
          socket.emit('updateUser', { socket: socket.id });
        }
      });
  });

  socket.on('disconnect', () => {
    // check if socket is in a beacon session
      // if yes and isResponder -> ask beacon if they still need help
        // if yes then rerun getHelp functionality
        // if no then remove session
      // if yes and isBeacon ->
        // remove session
          // update responder

    // remove from beacon store
    beacon.destroy({ where: { socket: socket.id } })
    .then(rows => console.log(`deleted ${rows} rows`));
  });

  socket.on('getHelp', (activeBeacon) => {
    console.log('+++server rcvd help request, activeBeacon: ', activeBeacon);
    //need current location
    const currentLocation = [activeBeacon.loc[0], activeBeacon.loc[1]];
    activeBeaconSession.beacon = activeBeacon.id;
    db
    .query(`select "socket", st_distance_sphere(geometry, ST_MakePoint(40.750486, -73.976401)) from "dynamicResponders" WHERE ST_DWithin(geometry, ST_MakePoint(${currentLocation[0]}, ${currentLocation[1]})::geography, ${radius}) AND available = TRUE ORDER BY geometry <-> 'Point(${currentLocation[0]} ${currentLocation[1]})'::geometry`)
    .then((responders) => {
      console.log("responders are ", responders);
        if (Array.isArray(responders)) {
          responders.forEach((responder) => {
            console.log('+++responder.socket: ', responder.socket);
            if (responder.socket !== socket.id) { // OR responder.socket !== activeBeacon.id ???
              socket.to(responder.socket).emit('newBeacon', activeBeacon);
            }
          });
        } else if (responders) {
          console.log(responders.id);
          if (responders.socket !== socket.id) { // OR responder.socket !== activeBeacon.id ???
            socket.to(responders.socket).emit('newBeacon', activeBeacon);
          }
        } else {
          console.log('no responder for gethelp');
        }
      });
    // const chatRoom = activeBeacon.id;
    // socket.join(chatRoom);
  });

  socket.on('acceptBeacon', (chatRoom) => {
    console.log('+++in socket.js - acceptBeacon - chatRoomID: ', chatRoom);
    activeBeaconSession.responder = socket.id;
    activeBeaconSession.chatRoom = chatRoom;
    console.log('+++in socket.js - activeBeacon object: ', activeBeaconSession);
    socket.join(chatRoom);

    socket.to(chatRoom).emit('render all messages', activeBeaconSession.messages);
  })

  socket.on('new message', (eachMessage) => {
    console.log('+++in socket.js - new message - message: ', eachMessage.message);
    activeBeaconSession.messages.unshift(eachMessage);
    console.log('+++in socket.js - PUSH - messages: ', activeBeaconSession.messages);
    websocket.to(activeBeaconSession.beacon).emit('render all messages', activeBeaconSession.messages);
    websocket.to(activeBeaconSession.responder).emit('render all messages', activeBeaconSession.messages);

    // socket.emit('render all messages', activeBeaconSession.messages);
    // websocket.to(eachMessage.chatRoom).emit('render all messages', activeBeaconSession.messages);
    // socket.broadcast.emit('render all messages', activeBeaconSession.messages); // ???
    // socket.to(eachMessage.chatRoom).emit('render all messages', activeBeaconSession.messages);
  })

  socket.on('get all messages', () => {
    console.log('+++in socket.js - get all messages - messages: ', activeBeaconSession.messages);
    socket.emit('render all messages', activeBeaconSession.messages);
  })

});

module.exports = {
  websocket,
  socketio,
  server,
};
<commit_msg>bug fix to dbquery line 58:<commit_after>const app = require('../../index.js');
const server = require('http').createServer(app);
const socketio = require('socket.io');
const db = require('../db/db');
const radius = 3000;

const dynamicResponder = require('../db/models/dynamicResponders');
const beacon = require('../db/models/beacons');

const websocket = socketio(server);
const activeBeaconSession = {
  beacon: '',
  responder: '',
  chatRoom: '',
  messages: [],
};

websocket.on('connection', (socket) => {
  console.log('+++A client just joined on socket.id:', socket.id);

  beacon.create({
    socket: socket.id
  });

  socket.on('updateUser', (options) => {
    console.log('+++options.query: ', options.query);
    dynamicResponder.find({ where: options.query })
      .then((responder) => {
        if (responder) {
          responder.update({ socket: socket.id })
            .then(updatedResponder => socket.emit('updateUser', updatedResponder));
        } else {
          socket.emit('updateUser', { socket: socket.id });
        }
      });
  });

  socket.on('disconnect', () => {
    // check if socket is in a beacon session
      // if yes and isResponder -> ask beacon if they still need help
        // if yes then rerun getHelp functionality
        // if no then remove session
      // if yes and isBeacon ->
        // remove session
          // update responder

    // remove from beacon store
    beacon.destroy({ where: { socket: socket.id } })
    .then(rows => console.log(`deleted ${rows} rows`));
  });

  socket.on('getHelp', (activeBeacon) => {
    console.log('+++server rcvd help request, activeBeacon: ', activeBeacon);
    //need current location
    const currentLocation = [activeBeacon.loc[0], activeBeacon.loc[1]];
    activeBeaconSession.beacon = activeBeacon.id;
    db
    .query(`select "socket", st_distance_sphere(geometry, ST_MakePoint(${activeBeacon.loc[0]}, ${activeBeacon.loc[1]}) from "dynamicResponders" WHERE ST_DWithin(geometry, ST_MakePoint(${activeBeacon.loc[0]}, ${activeBeacon.loc[1]})::geography, ${radius}) AND available = TRUE ORDER BY geometry <-> 'Point(${activeBeacon.loc[0]} ${activeBeacon.loc[1]})'::geometry`)
    .then((responders) => {
      console.log("responders are ", responders);
        if (Array.isArray(responders)) {
          responders.forEach((responder) => {
            console.log('+++responder.socket: ', responder.socket);
            if (responder.socket !== socket.id) { // OR responder.socket !== activeBeacon.id ???
              socket.to(responder.socket).emit('newBeacon', activeBeacon);
            }
          });
        } else if (responders) {
          console.log(responders.id);
          if (responders.socket !== socket.id) { // OR responder.socket !== activeBeacon.id ???
            socket.to(responders.socket).emit('newBeacon', activeBeacon);
          }
        } else {
          console.log('no responder for gethelp');
        }
      });
    // const chatRoom = activeBeacon.id;
    // socket.join(chatRoom);
  });

  socket.on('acceptBeacon', (chatRoom) => {
    console.log('+++in socket.js - acceptBeacon - chatRoomID: ', chatRoom);
    activeBeaconSession.responder = socket.id;
    activeBeaconSession.chatRoom = chatRoom;
    console.log('+++in socket.js - activeBeacon object: ', activeBeaconSession);
    socket.join(chatRoom);

    socket.to(chatRoom).emit('render all messages', activeBeaconSession.messages);
  })

  socket.on('new message', (eachMessage) => {
    console.log('+++in socket.js - new message - message: ', eachMessage.message);
    activeBeaconSession.messages.unshift(eachMessage);
    console.log('+++in socket.js - PUSH - messages: ', activeBeaconSession.messages);
    websocket.to(activeBeaconSession.beacon).emit('render all messages', activeBeaconSession.messages);
    websocket.to(activeBeaconSession.responder).emit('render all messages', activeBeaconSession.messages);

    // socket.emit('render all messages', activeBeaconSession.messages);
    // websocket.to(eachMessage.chatRoom).emit('render all messages', activeBeaconSession.messages);
    // socket.broadcast.emit('render all messages', activeBeaconSession.messages); // ???
    // socket.to(eachMessage.chatRoom).emit('render all messages', activeBeaconSession.messages);
  })

  socket.on('get all messages', () => {
    console.log('+++in socket.js - get all messages - messages: ', activeBeaconSession.messages);
    socket.emit('render all messages', activeBeaconSession.messages);
  })

});

module.exports = {
  websocket,
  socketio,
  server,
};
<|endoftext|>


<commit_before>/**
 * @author Longbo Ma
 */
var request = require('request');
var zlib = require('zlib');
var $ = require('jQuery');

var movie = function (options, cb) {
  this.q = options.q;
};

movie.searchSources = function () {
  request({
    url: "http://www.soku.com/v?keyword="+this.q,
    encoding: null
  },function (err, res, body) {
      if (!err && res.statusCode==200) {
          var res_encoding  = res.headers['content-encoding'];
          if (res_encoding && res_encoding.indexOf("gzip")  >= 0) {
              zlib.unzip(body, function(err, buffer) {
                  body =  buffer.toString();
              });
          } else {
          }
      }
  });
};

module.exports = function (options, cb) {

};<commit_msg>完成视频播放来源搜索功能<commit_after>/**
 * @author Longbo Ma
 */
var request = require('./request');
var $ = require('jQuery');

var movie = function (options, cb) {
  this.q = options.q;
  this.callback = cb || function () {};
};

/**
 *  解析html数据
 **/
movie.prototype.parseBody = function (body) {
  var doc = $(body),
      arr = [],
      sources;
  // var sources_html = doc.find("div.source.source_one").html();
  sources = doc.find("div.source.source_one span a");
  if (sources) {
  // 	console.log(sources.length);
  	for(var i = 0, total = sources.length; i < total; i++) {
  		var link = $(sources[i]);
  		arr.push({
  		  iconImage: link.html(),//图标image标签
  		  title: link.attr("title"),//a标签标题
  		  href: link.attr("href")//a标签href
  		});
  	}

  }

	console.log(arr);
	this.callback(arr);
};

/**
 * 发送查询请求
 **/
movie.prototype.searchSources = function () {
  var self = this;
  request({
    url: "http://www.soku.com/v?keyword="+this.q
  },function (err, res, body) {
    if (!err) {
      self.parseBody(body);
    }
  });
};

module.exports = function (options, cb) {
  new movie(options, cb).searchSources();
};<|endoftext|>


<commit_before>"use strict";

var module = angular.module("sabhiram.slick-slider", []);
module.directive("sabSlickSlider", function() {
    return {
        restrict: "E",
        scope: {
            val: "=value",
            min: "@",
            max: "@",
            default: "@"
        },
        replace: true,
        transclude: true,
        template: [
            "
",
            "
",
            "

",
            "
",
            "            {{val}}",
            "
default
",
            "
",
            "
",
            "
{{min}}
",
            "
{{max}}
",
            "
",
            "        <input class='sab-slider-input' ng-model='val' value='{{val}}' type='range' min='{{min}}' max='{{max}}'></input>",
            "
",
            "
",
        ].join("\n"),
        link: function(scope, element, attributes) {
            scope.min     = parseInt(scope.min, 10) || 0;
            scope.max     = parseInt(scope.max, 10) || 100;
            scope.default = parseInt(scope.default, 10) || 50;

            if (typeof(scope.val) == "undefined") {
                scope.val = scope.default;
            }
        }
    };
});
<commit_msg>small test to see if val will update input position<commit_after>"use strict";

var module = angular.module("sabhiram.slick-slider", []);
module.directive("sabSlickSlider", function() {
    return {
        restrict: "E",
        scope: {
            val: "=value",
            min: "@",
            max: "@",
            default: "@"
        },
        replace: true,
        transclude: true,
        template: [
            "
",
            "
",
            "

",
            "
",
            "            {{val}}",
            "
default
",
            "
",
            "
",
            "
{{min}}
",
            "
{{max}}
",
            "
",
            "        <input class='sab-slider-input' ng-model='val' value='{{val}}' type='range' min='{{min}}' max='{{max}}'></input>",
            "
",
            "
",
        ].join("\n"),
        link: function(scope, element, attributes) {
            scope.min     = parseInt(scope.min, 10) || 0;
            scope.max     = parseInt(scope.max, 10) || 100;
            scope.default = parseInt(scope.default, 10) || 50;

            if (typeof(scope.val) == "undefined") {
                scope.val = scope.default;
            }

            scope.val = scope.val + 1;
        }
    };
});
<|endoftext|>


<commit_before>// Copyright 2014 The Oppia 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.

/**
 * @fileoverview Data and controllers for the Oppia contributors' gallery page.
 *
 * @author sll@google.com (Sean Lip)
 */

// Overwrite the default ui-bootstrap carousel template to remove the
// on-mouseover behaviour, as well as the left and right arrows.
angular.module('template/carousel/carousel.html', []).run([
    '$templateCache', function($templateCache) {
  $templateCache.put('template/carousel/carousel.html',
    '
\n' +
    '
 1\">\n' +
    '

\n' +
    '
\n' +
    '

\n' +
    '
\n');
}]);

oppia.constant('GALLERY_DATA_URL', '/galleryhandler/data');

oppia.factory('searchService', [
    '$http', '$rootScope', 'GALLERY_DATA_URL',
    function($http, $rootScope, GALLERY_DATA_URL) {
  var _lastQuery = null;
  var _lastSelectedCategories = {};
  var _lastSelectedLanguageCodes = {};
  var _searchCursor = null;

  // Appends a suffix to the query describing allowed category and language
  // codes to filter on.
  var _getSuffixForQuery = function(selectedCategories, selectedLanguageCodes) {
    var querySuffix = '';

    var _categories = '';
    for (var key in selectedCategories) {
      if (selectedCategories[key]) {
        if (_categories) {
          _categories += '" OR "';
        }
        _categories += key;
      }
    }
    if (_categories) {
      querySuffix += ' category=("' + _categories + '")';
    }

    var _languageCodes = '';
    for (var key in selectedLanguageCodes) {
      if (selectedLanguageCodes[key]) {
        if (_languageCodes) {
          _languageCodes += '" OR "';
        }
        _languageCodes += key;
      }
    }
    if (_languageCodes) {
      querySuffix += ' language_code=("' + _languageCodes + '")';
    }

    return querySuffix;
  };

  var hasPageFinishedLoading = function() {
    return _searchCursor === null;
  };

  var _isCurrentlyFetchingResults = false;

  return {
    // Note that an empty query results in all explorations being shown.
    executeSearchQuery: function(
        searchQuery, selectedCategories, selectedLanguageCodes,
        successCallback) {
      var queryUrl = GALLERY_DATA_URL + '?q=' + encodeURI(
        searchQuery +
        _getSuffixForQuery(selectedCategories, selectedLanguageCodes));

      _isCurrentlyFetchingResults = true;
      $http.get(queryUrl).success(function(data) {
        _lastQuery = searchQuery;
        _lastSelectedCategories = angular.copy(selectedCategories);
        _lastSelectedLanguageCodes = angular.copy(selectedLanguageCodes);
        _searchCursor = data.search_cursor;
        if ($('.oppia-splash-search-input').val() === searchQuery){
          $rootScope.$broadcast( 'refreshGalleryData', data, hasPageFinishedLoading());
          _isCurrentlyFetchingResults = false;
        } else {
          console.log('Mismatch');
          console.log('SearchQuery: ' + searchQuery);
          console.log('Input: ' + $('.oppia-splash-search-input').val());
          }
      });

      if (successCallback) {
        successCallback();
      }
    },
    loadMoreData: function(successCallback) {
      // If a new query is still being sent, do not fetch more results.
      if (_isCurrentlyFetchingResults) {
        return;
      }

      var queryUrl = GALLERY_DATA_URL + '?q=' + encodeURI(
        _lastQuery + _getSuffixForQuery(
          _lastSelectedCategories, _lastSelectedLanguageCodes));

      if (_searchCursor) {
        queryUrl += '&cursor=' + _searchCursor;
      }

      _isCurrentlyFetchingResults = true;
      $http.get(queryUrl).success(function(data) {
        _searchCursor = data.search_cursor;
        _isCurrentlyFetchingResults = false;
        if (successCallback) {
          successCallback(data, hasPageFinishedLoading());
        }
      });
    }
  };
}]);

oppia.controller('Gallery', [
  '$scope', '$http', '$rootScope', '$modal', '$window', '$timeout',
  'ExplorationCreationButtonService', 'oppiaDatetimeFormatter',
  'oppiaDebouncer', 'urlService', 'GALLERY_DATA_URL', 'CATEGORY_LIST',
  'searchService',
  function(
      $scope, $http, $rootScope, $modal, $window, $timeout,
      ExplorationCreationButtonService, oppiaDatetimeFormatter,
      oppiaDebouncer, urlService, GALLERY_DATA_URL, CATEGORY_LIST,
      searchService) {
    $window.addEventListener('scroll', function() {
      var oppiaBanner = $('.oppia-gallery-banner-container');
      var oppiaTagline = $('.oppia-gallery-banner-tagline');
      var bannerVanishRate = oppiaBanner.height();
      var taglineVanishRate = oppiaBanner.height() * 0.3;

      oppiaBanner.css({
        opacity: (bannerVanishRate - $(window).scrollTop()) / bannerVanishRate
      });
      oppiaTagline.css({
        opacity: (taglineVanishRate - $(window).scrollTop()) / taglineVanishRate
      });
    });

    $scope.CAROUSEL_INTERVAL = 3500;
    $scope.CAROUSEL_SLIDES = GLOBALS.CAROUSEL_SLIDES_CONFIG || [];

    // Preload images, otherwise they will only start showing up some time after
    // the carousel slide comes into view. See:
    //
    //     http://stackoverflow.com/q/1373142
    for (var i = 0; i < $scope.CAROUSEL_SLIDES.length; i++) {
      var pic = new Image();
      pic.src = '/images/splash/' + $scope.CAROUSEL_SLIDES[i].image_filename;
    }

    $scope.getLocaleAbbreviatedDatetimeString = function(millisSinceEpoch) {
      return oppiaDatetimeFormatter.getLocaleAbbreviatedDatetimeString(
        millisSinceEpoch);
    };

    $rootScope.loadingMessage = 'Loading';

    $scope.showCreateExplorationModal = function() {
      ExplorationCreationButtonService.showCreateExplorationModal(
        CATEGORY_LIST);
    };

    $scope.currentUserIsModerator = false;

    $scope.inSplashMode = ($scope.CAROUSEL_SLIDES.length > 0);
    $scope.$on('hasChangedSearchQuery', function() {
      if ($scope.inSplashMode) {
        $('.oppia-gallery-container').fadeOut(function() {
          $scope.inSplashMode = false;
          $timeout(function() {
            $('.oppia-gallery-container').fadeIn();
          }, 50);
        });
      }
    });

    // SEARCH FUNCTIONALITY

    $scope.allExplorationsInOrder = [];

    // Called when the page loads, and after every search query.
    var _refreshGalleryData = function(data, hasPageFinishedLoading) {
      $scope.searchIsLoading = false;
      $scope.allExplorationsInOrder = data.explorations_list;
      $scope.finishedLoadingPage = hasPageFinishedLoading;
      $rootScope.loadingMessage = '';
    };

    $scope.pageLoaderIsBusy = false;
    $scope.showMoreExplorations = function() {
      if (!$rootScope.loadingMessage) {
        $scope.pageLoaderIsBusy = true;

        searchService.loadMoreData(function(data, hasPageFinishedLoading) {
          $scope.allExplorationsInOrder = $scope.allExplorationsInOrder.concat(
            data.explorations_list);
          $scope.finishedLoadingPage = hasPageFinishedLoading;
          $scope.pageLoaderIsBusy = false;
        });
      }
    };

    $scope.$on(
      'refreshGalleryData',
      function(evt, data, hasPageFinishedLoading) {
        _refreshGalleryData(data, hasPageFinishedLoading);
      }
    );

    // Retrieves gallery data from the server.
    $http.get(GALLERY_DATA_URL).success(function(data) {
      $scope.currentUserIsModerator = Boolean(data.is_moderator);

      // Note that this will cause an initial search query to be sent.
      $rootScope.$broadcast(
        'preferredLanguageCodesLoaded', data.preferred_language_codes);

      if (data.username) {
        if (urlService.getUrlParams().mode === 'create') {
          $scope.showCreateExplorationModal(CATEGORY_LIST);
        }
      }
    });
  }
]);

oppia.controller('SearchBar', [
  '$scope', '$rootScope', 'searchService', 'oppiaDebouncer',
  'ExplorationCreationButtonService', 'urlService', 'CATEGORY_LIST',
  function(
      $scope, $rootScope, searchService, oppiaDebouncer,
      ExplorationCreationButtonService, urlService, CATEGORY_LIST) {
    $scope.searchIsLoading = false;
    $scope.ALL_CATEGORIES = CATEGORY_LIST.map(function(categoryName) {
      return {
        id: categoryName,
        text: categoryName
      };
    });
    $scope.ALL_LANGUAGE_CODES = GLOBALS.LANGUAGE_CODES_AND_NAMES.map(
      function(languageItem) {
        return {
          id: languageItem.code,
          text: languageItem.name
        };
      });

    $scope.searchQuery = '';
    $scope.selectionDetails = {
      categories: {
        description: '',
        itemsName: 'categories',
        masterList: $scope.ALL_CATEGORIES,
        numSelections: 0,
        selections: {},
        summary: ''
      },
      languageCodes: {
        description: '',
        itemsName: 'languages',
        masterList: $scope.ALL_LANGUAGE_CODES,
        numSelections: 0,
        selections: {},
        summary: ''
      }
    };

    // Update the description, numSelections and summary fields of the relevant
    // entry of $scope.selectionDetails.
    var _updateSelectionDetails = function(itemsType) {
      var itemsName = $scope.selectionDetails[itemsType].itemsName;
      var masterList = $scope.selectionDetails[itemsType].masterList;

      var selectedItems = [];
      for (var i = 0; i < masterList.length; i++) {
        if ($scope.selectionDetails[itemsType].selections[masterList[i].id]) {
          selectedItems.push(masterList[i].text);
        }
      }

      var totalCount = selectedItems.length;
      $scope.selectionDetails[itemsType].numSelections = totalCount;

      $scope.selectionDetails[itemsType].summary = (
        totalCount === 0 ? (
          'All ' + itemsName.charAt(0).toUpperCase() + itemsName.substr(1)) :
        totalCount === 1 ? selectedItems[0] :
        totalCount + ' ' + itemsName);

      $scope.selectionDetails[itemsType].description = (
        selectedItems.length > 0 ? selectedItems.join(', ') :
        'All ' + itemsName + ' selected');
    };

    $scope.toggleSelection = function(itemsType, optionName) {
      var selections = $scope.selectionDetails[itemsType].selections;
      if (!selections.hasOwnProperty(optionName)) {
        selections[optionName] = true;
      } else {
        selections[optionName] = !selections[optionName];
      }

      _updateSelectionDetails(itemsType);
      _onSearchQueryChangeExec();
    };

    var _searchBarFullyLoaded = false;

    var _hasChangedSearchQuery = Boolean(urlService.getUrlParams().q);
    var _onSearchQueryChangeExec = function() {
      $scope.searchIsLoading = true;
      searchService.executeSearchQuery(
          $scope.searchQuery, $scope.selectionDetails.categories.selections,
          $scope.selectionDetails.languageCodes.selections, function() {
        $scope.searchIsLoading = false;

        if (!_hasChangedSearchQuery && _searchBarFullyLoaded) {
          _hasChangedSearchQuery = true;
          $rootScope.$broadcast('hasChangedSearchQuery');
        }
      });
    };

    // Initialize the selection descriptions and summaries.
    for (var itemsType in $scope.selectionDetails) {
      _updateSelectionDetails(itemsType);
    }

    $scope.onSearchQueryChange = function(evt) {
      // Query immediately when the enter or space key is pressed.
      if (evt.keyCode == 13 || evt.keyCode == 32) {
        _onSearchQueryChangeExec();
      } else {
        oppiaDebouncer.debounce(_onSearchQueryChangeExec, 400)();
      }
    };

    $scope.$on(
      'preferredLanguageCodesLoaded',
      function(evt, preferredLanguageCodesList) {
        for (var i = 0; i < preferredLanguageCodesList.length; i++) {
          var selections = $scope.selectionDetails.languageCodes.selections;
          var languageCode = preferredLanguageCodesList[i];
          if (!selections.hasOwnProperty(languageCode)) {
            selections[languageCode] = true;
          } else {
            selections[languageCode] = !selections[languageCode];
          }
        }

        _updateSelectionDetails('languageCodes');
        _onSearchQueryChangeExec();

        _searchBarFullyLoaded = true;
      }
    );

    $scope.showCreateExplorationModal = function() {
      ExplorationCreationButtonService.showCreateExplorationModal(
        CATEGORY_LIST);
    };
    $scope.showUploadExplorationModal = function() {
      ExplorationCreationButtonService.showUploadExplorationModal(
        CATEGORY_LIST);
    };
  }
]);
<commit_msg>Still trying to pass linter<commit_after>// Copyright 2014 The Oppia 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.

/**
 * @fileoverview Data and controllers for the Oppia contributors' gallery page.
 *
 * @author sll@google.com (Sean Lip)
 */

// Overwrite the default ui-bootstrap carousel template to remove the
// on-mouseover behaviour, as well as the left and right arrows.
angular.module('template/carousel/carousel.html', []).run([
    '$templateCache', function($templateCache) {
  $templateCache.put('template/carousel/carousel.html',
    '
\n' +
    '
 1\">\n' +
    '

\n' +
    '
\n' +
    '

\n' +
    '
\n');
}]);

oppia.constant('GALLERY_DATA_URL', '/galleryhandler/data');

oppia.factory('searchService', [
    '$http', '$rootScope', 'GALLERY_DATA_URL',
    function($http, $rootScope, GALLERY_DATA_URL) {
  var _lastQuery = null;
  var _lastSelectedCategories = {};
  var _lastSelectedLanguageCodes = {};
  var _searchCursor = null;

  // Appends a suffix to the query describing allowed category and language
  // codes to filter on.
  var _getSuffixForQuery = function(selectedCategories, selectedLanguageCodes) {
    var querySuffix = '';

    var _categories = '';
    for (var key in selectedCategories) {
      if (selectedCategories[key]) {
        if (_categories) {
          _categories += '" OR "';
        }
        _categories += key;
      }
    }
    if (_categories) {
      querySuffix += ' category=("' + _categories + '")';
    }

    var _languageCodes = '';
    for (var key in selectedLanguageCodes) {
      if (selectedLanguageCodes[key]) {
        if (_languageCodes) {
          _languageCodes += '" OR "';
        }
        _languageCodes += key;
      }
    }
    if (_languageCodes) {
      querySuffix += ' language_code=("' + _languageCodes + '")';
    }

    return querySuffix;
  };

  var hasPageFinishedLoading = function() {
    return _searchCursor === null;
  };

  var _isCurrentlyFetchingResults = false;

  return {
    // Note that an empty query results in all explorations being shown.
    executeSearchQuery: function(
        searchQuery, selectedCategories, selectedLanguageCodes,
        successCallback) {
      var queryUrl = GALLERY_DATA_URL + '?q=' + encodeURI(
        searchQuery +
        _getSuffixForQuery(selectedCategories, selectedLanguageCodes));

      _isCurrentlyFetchingResults = true;
      $http.get(queryUrl).success(function(data) {
        _lastQuery = searchQuery;
        _lastSelectedCategories = angular.copy(selectedCategories);
        _lastSelectedLanguageCodes = angular.copy(selectedLanguageCodes);
        _searchCursor = data.search_cursor;

        if ($('.oppia-splash-search-input').val()===searchQuery){
          $rootScope.$broadcast('refreshGalleryData', data, hasPageFinishedLoading());
          _isCurrentlyFetchingResults = false;
        } else {
          console.log('Mismatch');
          console.log('SearchQuery: ' + searchQuery);
          console.log('Input: ' + $('.oppia-splash-search-input').val());
          }
      });

      if (successCallback) {
        successCallback();
      }
    },
    loadMoreData: function(successCallback) {
      // If a new query is still being sent, do not fetch more results.
      if (_isCurrentlyFetchingResults) {
        return;
      }

      var queryUrl = GALLERY_DATA_URL + '?q=' + encodeURI(
        _lastQuery + _getSuffixForQuery(
          _lastSelectedCategories, _lastSelectedLanguageCodes));

      if (_searchCursor) {
        queryUrl += '&cursor=' + _searchCursor;
      }

      _isCurrentlyFetchingResults = true;
      $http.get(queryUrl).success(function(data) {
        _searchCursor = data.search_cursor;
        _isCurrentlyFetchingResults = false;

        if (successCallback) {
          successCallback(data, hasPageFinishedLoading());
        }
      });
    }
  };
}]);

oppia.controller('Gallery', [
  '$scope', '$http', '$rootScope', '$modal', '$window', '$timeout',
  'ExplorationCreationButtonService', 'oppiaDatetimeFormatter',
  'oppiaDebouncer', 'urlService', 'GALLERY_DATA_URL', 'CATEGORY_LIST',
  'searchService',
  function(
      $scope, $http, $rootScope, $modal, $window, $timeout,
      ExplorationCreationButtonService, oppiaDatetimeFormatter,
      oppiaDebouncer, urlService, GALLERY_DATA_URL, CATEGORY_LIST,
      searchService) {
    $window.addEventListener('scroll', function() {
      var oppiaBanner = $('.oppia-gallery-banner-container');
      var oppiaTagline = $('.oppia-gallery-banner-tagline');
      var bannerVanishRate = oppiaBanner.height();
      var taglineVanishRate = oppiaBanner.height() * 0.3;

      oppiaBanner.css({
        opacity: (bannerVanishRate - $(window).scrollTop()) / bannerVanishRate
      });
      oppiaTagline.css({
        opacity: (taglineVanishRate - $(window).scrollTop()) / taglineVanishRate
      });
    });

    $scope.CAROUSEL_INTERVAL = 3500;
    $scope.CAROUSEL_SLIDES = GLOBALS.CAROUSEL_SLIDES_CONFIG || [];

    // Preload images, otherwise they will only start showing up some time after
    // the carousel slide comes into view. See:
    //
    //     http://stackoverflow.com/q/1373142
    for (var i = 0; i < $scope.CAROUSEL_SLIDES.length; i++) {
      var pic = new Image();
      pic.src = '/images/splash/' + $scope.CAROUSEL_SLIDES[i].image_filename;
    }

    $scope.getLocaleAbbreviatedDatetimeString = function(millisSinceEpoch) {
      return oppiaDatetimeFormatter.getLocaleAbbreviatedDatetimeString(
        millisSinceEpoch);
    };

    $rootScope.loadingMessage = 'Loading';

    $scope.showCreateExplorationModal = function() {
      ExplorationCreationButtonService.showCreateExplorationModal(
        CATEGORY_LIST);
    };

    $scope.currentUserIsModerator = false;

    $scope.inSplashMode = ($scope.CAROUSEL_SLIDES.length > 0);
    $scope.$on('hasChangedSearchQuery', function() {
      if ($scope.inSplashMode) {
        $('.oppia-gallery-container').fadeOut(function() {
          $scope.inSplashMode = false;
          $timeout(function() {
            $('.oppia-gallery-container').fadeIn();
          }, 50);
        });
      }
    });

    // SEARCH FUNCTIONALITY

    $scope.allExplorationsInOrder = [];

    // Called when the page loads, and after every search query.
    var _refreshGalleryData = function(data, hasPageFinishedLoading) {
      $scope.searchIsLoading = false;
      $scope.allExplorationsInOrder = data.explorations_list;
      $scope.finishedLoadingPage = hasPageFinishedLoading;
      $rootScope.loadingMessage = '';
    };

    $scope.pageLoaderIsBusy = false;
    $scope.showMoreExplorations = function() {
      if (!$rootScope.loadingMessage) {
        $scope.pageLoaderIsBusy = true;

        searchService.loadMoreData(function(data, hasPageFinishedLoading) {
          $scope.allExplorationsInOrder = $scope.allExplorationsInOrder.concat(
            data.explorations_list);
          $scope.finishedLoadingPage = hasPageFinishedLoading;
          $scope.pageLoaderIsBusy = false;
        });
      }
    };

    $scope.$on(
      'refreshGalleryData',
      function(evt, data, hasPageFinishedLoading) {
        _refreshGalleryData(data, hasPageFinishedLoading);
      }
    );

    // Retrieves gallery data from the server.
    $http.get(GALLERY_DATA_URL).success(function(data) {
      $scope.currentUserIsModerator = Boolean(data.is_moderator);

      // Note that this will cause an initial search query to be sent.
      $rootScope.$broadcast(
        'preferredLanguageCodesLoaded', data.preferred_language_codes);

      if (data.username) {
        if (urlService.getUrlParams().mode === 'create') {
          $scope.showCreateExplorationModal(CATEGORY_LIST);
        }
      }
    });
  }
]);

oppia.controller('SearchBar', [
  '$scope', '$rootScope', 'searchService', 'oppiaDebouncer',
  'ExplorationCreationButtonService', 'urlService', 'CATEGORY_LIST',
  function(
      $scope, $rootScope, searchService, oppiaDebouncer,
      ExplorationCreationButtonService, urlService, CATEGORY_LIST) {
    $scope.searchIsLoading = false;
    $scope.ALL_CATEGORIES = CATEGORY_LIST.map(function(categoryName) {
      return {
        id: categoryName,
        text: categoryName
      };
    });
    $scope.ALL_LANGUAGE_CODES = GLOBALS.LANGUAGE_CODES_AND_NAMES.map(
      function(languageItem) {
        return {
          id: languageItem.code,
          text: languageItem.name
        };
      });

    $scope.searchQuery = '';
    $scope.selectionDetails = {
      categories: {
        description: '',
        itemsName: 'categories',
        masterList: $scope.ALL_CATEGORIES,
        numSelections: 0,
        selections: {},
        summary: ''
      },
      languageCodes: {
        description: '',
        itemsName: 'languages',
        masterList: $scope.ALL_LANGUAGE_CODES,
        numSelections: 0,
        selections: {},
        summary: ''
      }
    };

    // Update the description, numSelections and summary fields of the relevant
    // entry of $scope.selectionDetails.
    var _updateSelectionDetails = function(itemsType) {
      var itemsName = $scope.selectionDetails[itemsType].itemsName;
      var masterList = $scope.selectionDetails[itemsType].masterList;

      var selectedItems = [];
      for (var i = 0; i < masterList.length; i++) {
        if ($scope.selectionDetails[itemsType].selections[masterList[i].id]) {
          selectedItems.push(masterList[i].text);
        }
      }

      var totalCount = selectedItems.length;
      $scope.selectionDetails[itemsType].numSelections = totalCount;

      $scope.selectionDetails[itemsType].summary = (
        totalCount === 0 ? (
          'All ' + itemsName.charAt(0).toUpperCase() + itemsName.substr(1)) :
        totalCount === 1 ? selectedItems[0] :
        totalCount + ' ' + itemsName);

      $scope.selectionDetails[itemsType].description = (
        selectedItems.length > 0 ? selectedItems.join(', ') :
        'All ' + itemsName + ' selected');
    };

    $scope.toggleSelection = function(itemsType, optionName) {
      var selections = $scope.selectionDetails[itemsType].selections;
      if (!selections.hasOwnProperty(optionName)) {
        selections[optionName] = true;
      } else {
        selections[optionName] = !selections[optionName];
      }

      _updateSelectionDetails(itemsType);
      _onSearchQueryChangeExec();
    };

    var _searchBarFullyLoaded = false;

    var _hasChangedSearchQuery = Boolean(urlService.getUrlParams().q);
    var _onSearchQueryChangeExec = function() {
      $scope.searchIsLoading = true;
      searchService.executeSearchQuery(
          $scope.searchQuery, $scope.selectionDetails.categories.selections,
          $scope.selectionDetails.languageCodes.selections, function(){
        $scope.searchIsLoading = false;
        if (!_hasChangedSearchQuery && _searchBarFullyLoaded){
          _hasChangedSearchQuery = true;
          $rootScope.$broadcast('hasChangedSearchQuery');
        }
      });
    };

    // Initialize the selection descriptions and summaries.
    for (var itemsType in $scope.selectionDetails) {
      _updateSelectionDetails(itemsType);
    }

    $scope.onSearchQueryChange = function(evt) {
      // Query immediately when the enter or space key is pressed.
      if (evt.keyCode == 13 || evt.keyCode == 32) {
        _onSearchQueryChangeExec();
      } else {
        oppiaDebouncer.debounce(_onSearchQueryChangeExec, 400)();
      }
    };

    $scope.$on(
      'preferredLanguageCodesLoaded',
      function(evt, preferredLanguageCodesList) {
        for (var i = 0; i < preferredLanguageCodesList.length; i++) {
          var selections = $scope.selectionDetails.languageCodes.selections;
          var languageCode = preferredLanguageCodesList[i];
          if (!selections.hasOwnProperty(languageCode)) {
            selections[languageCode] = true;
          } else {
            selections[languageCode] = !selections[languageCode];
          }
        }

        _updateSelectionDetails('languageCodes');
        _onSearchQueryChangeExec();

        _searchBarFullyLoaded = true;
      }
    );

    $scope.showCreateExplorationModal = function() {
      ExplorationCreationButtonService.showCreateExplorationModal(
        CATEGORY_LIST);
    };
    $scope.showUploadExplorationModal = function() {
      ExplorationCreationButtonService.showUploadExplorationModal(
        CATEGORY_LIST);
    };
  }
]);
<|endoftext|>


<commit_before>var _ = require('underscore')._;

var api = function(dbot) {
    var escapeRegexen = function(str) {
        return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    };

    var api = {
        'resolveUser': function(server, nick, useLowerCase) {
            var knownUsers = this.getServerUsers(server);
            var user = nick;

            if(!useLowerCase) {
                if(!_.include(knownUsers.users, nick) && _.has(knownUsers.aliases, nick)) {
                    user = knownUsers.aliases[nick];
                }
            } else {
                // this is retarded
                user = user.toLowerCase();
                var toMatch = new RegExp("^" + escapeRegexen(user) + "$", "i");

                var resolvedUser = _.find(knownUsers.users, function(nick) {
                    return nick.match(toMatch) !== null;
                }, this);

                if(!resolvedUser) {
                    resolvedUser = _.find(knownUsers.aliases, function(nick, alias) {
                        if(alias.match(toMatch) !== null) return nick;
                    }, this);
                    if(!_.isUndefined(resolvedUser)) user = resolvedUser;
                }
                else{
                    user = resolvedUser;
                }
            }
            return user;
        },

        'getServerUsers': function(server) {
            return dbot.db.knownUsers[server].users;
        },

        'getAllUsers': function() {
            return _.reduce(dbot.db.knownUsers, function(memo, server, name) {
                memo[name] = server.users;
                return memo;
            }, {}, this);
        },

        'isKnownUser': function(server, nick) {
            var knownUsers = this.getServerUsers(server);
            return (_.include(knownUsers.users, nick) || _.has(knownUsers.aliases, nick));
        },

        'isPrimaryUser': function(server, nick) {
            var knownUsers = this.getServerUsers(server);
            return _.include(knownUsers.users, nick);
        },

        'getAliases': function(server, nick) {
            var knownUsers = this.getServerUsers(server);
            return _.chain(knownUsers.aliases)
                .keys()
                .filter(function(user) {
                    return knownUsers.aliases[user] == nick;
                }, this)
                .value();
        },

        'isOnline': function(server, user, channel, useLowerCase) {
            var user = this.api.resolveUser(server, user, useLowerCase);
            var possiNicks = [user].concat(this.api.getAliases(server, user));

            if(!_.has(dbot.instance.connections[server].channels[channel], "nicks")) return false;
            var onlineNicks = dbot.instance.connections[server].channels[channel].nicks;

            return _.any(onlineNicks, function(nick) {
                nick = nick.name;
                return _.include(possiNicks, nick);
            }, this);
        },

        'isChannelUser': function(server, user, channel, useLowerCase) {
            var knownUsers = this.getServerUsers(server);
            var user = this.api.resolveUser(server, user, useLowerCase);

            if(!_.has(knownUsers.channelUsers, channel)) {
                return false;
            }
            return _.include(knownUsers.channelUsers[channel], user);
        }
    };

    return api;
};

exports.fetch = function(dbot) {
    return api(dbot);
};
<commit_msg>Check for channel not nick [#201]<commit_after>var _ = require('underscore')._;

var api = function(dbot) {
    var escapeRegexen = function(str) {
        return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    };

    var api = {
        'resolveUser': function(server, nick, useLowerCase) {
            var knownUsers = this.getServerUsers(server);
            var user = nick;

            if(!useLowerCase) {
                if(!_.include(knownUsers.users, nick) && _.has(knownUsers.aliases, nick)) {
                    user = knownUsers.aliases[nick];
                }
            } else {
                // this is retarded
                user = user.toLowerCase();
                var toMatch = new RegExp("^" + escapeRegexen(user) + "$", "i");

                var resolvedUser = _.find(knownUsers.users, function(nick) {
                    return nick.match(toMatch) !== null;
                }, this);

                if(!resolvedUser) {
                    resolvedUser = _.find(knownUsers.aliases, function(nick, alias) {
                        if(alias.match(toMatch) !== null) return nick;
                    }, this);
                    if(!_.isUndefined(resolvedUser)) user = resolvedUser;
                }
                else{
                    user = resolvedUser;
                }
            }
            return user;
        },

        'getServerUsers': function(server) {
            return dbot.db.knownUsers[server].users;
        },

        'getAllUsers': function() {
            return _.reduce(dbot.db.knownUsers, function(memo, server, name) {
                memo[name] = server.users;
                return memo;
            }, {}, this);
        },

        'isKnownUser': function(server, nick) {
            var knownUsers = this.getServerUsers(server);
            return (_.include(knownUsers.users, nick) || _.has(knownUsers.aliases, nick));
        },

        'isPrimaryUser': function(server, nick) {
            var knownUsers = this.getServerUsers(server);
            return _.include(knownUsers.users, nick);
        },

        'getAliases': function(server, nick) {
            var knownUsers = this.getServerUsers(server);
            return _.chain(knownUsers.aliases)
                .keys()
                .filter(function(user) {
                    return knownUsers.aliases[user] == nick;
                }, this)
                .value();
        },

        'isOnline': function(server, user, channel, useLowerCase) {
            var user = this.api.resolveUser(server, user, useLowerCase);
            var possiNicks = [user].concat(this.api.getAliases(server, user));

            if(!_.has(dbot.instance.connections[server].channels, channel)) return false;
            var onlineNicks = dbot.instance.connections[server].channels[channel].nicks;

            return _.any(onlineNicks, function(nick) {
                nick = nick.name;
                return _.include(possiNicks, nick);
            }, this);
        },

        'isChannelUser': function(server, user, channel, useLowerCase) {
            var knownUsers = this.getServerUsers(server);
            var user = this.api.resolveUser(server, user, useLowerCase);

            if(!_.has(knownUsers.channelUsers, channel)) {
                return false;
            }
            return _.include(knownUsers.channelUsers[channel], user);
        }
    };

    return api;
};

exports.fetch = function(dbot) {
    return api(dbot);
};
<|endoftext|>


<commit_before>// ==UserScript==
// @id             iitc-plugin-basemap-mapquest-open-aerial@jonatkins
// @name           IITC plugin: MapQuest Open Satellite view (US Only)
// @category       Map Tiles
// @version        0.1.1.@@DATETIMEVERSION@@
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL      @@UPDATEURL@@
// @downloadURL    @@DOWNLOADURL@@
// @description    [@@BUILDNAME@@-@@BUILDDATE@@] Add the MapQuest Open Aerial satellite view tiles as a map layer. High detail in the US (lower 48) only.
// @include        https://*.ingress.com/intel*
// @include        http://*.ingress.com/intel*
// @match          https://*.ingress.com/intel*
// @match          http://*.ingress.com/intel*
// @include        https://*.ingress.com/mission/*
// @include        http://*.ingress.com/mission/*
// @match          https://*.ingress.com/mission/*
// @match          http://*.ingress.com/mission/*
// @grant          none
// ==/UserScript==

@@PLUGINSTART@@

// PLUGIN START ////////////////////////////////////////////////////////

// use own namespace for plugin
window.plugin.mapTileMapQuestSat = function() {};

window.plugin.mapTileMapQuestSat.addLayer = function() {

  var mqSubdomains = [ 'otile1','otile2', 'otile3', 'otile4' ];
  var mqTileUrlPrefix = window.location.protocol !== 'https:' ? 'http://{s}.mqcdn.com' : 'https://{s}-s.mqcdn.com';
  //MapQuest satellite coverage outside of the US is rather limited - so not really worth having as we have google as an op!
  var mqSatOpt = {attribution: 'Portions Courtesy NASA/JPL-Caltech and U.S. Depart. of Agriculture, Farm Service Agency', maxNativeZoom: 18, maxZoom: 21, subdomains: mqSubdomains};
  var mqSat = new L.TileLayer('http://{s}.mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg',mqSatOpt);

  layerChooser.addBaseLayer(mqSat, "MapQuest Open Satellite");
};

var setup =  window.plugin.mapTileMapQuestSat.addLayer;

// PLUGIN END //////////////////////////////////////////////////////////

@@PLUGINEND@@
<commit_msg>delete mapquest-open-aerial as they doesn't support maptiles anymore<commit_after>// ==UserScript==
// @id             iitc-plugin-basemap-mapquest-open-aerial@jonatkins
// @name           IITC plugin: MapQuest Open Satellite view (US Only)
// @category       Deleted
// @version        0.0.0
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL      @@UPDATEURL@@
// @downloadURL    @@DOWNLOADURL@@
// @description    MapQuest doesn't support this anymore: https://lists.openstreetmap.org/pipermail/tile-serving/2016-June/003928.html
// @include        https://*.ingress.com/intel*
// @include        http://*.ingress.com/intel*
// @match          https://*.ingress.com/intel*
// @match          http://*.ingress.com/intel*
// @include        https://*.ingress.com/mission/*
// @include        http://*.ingress.com/mission/*
// @match          https://*.ingress.com/mission/*
// @match          http://*.ingress.com/mission/*
// @grant          none
// ==/UserScript==
<|endoftext|>


<commit_before>const regions = require('./regions');
const accounts = require('./accounts');

const SLACK_DEBUG_CHANNEL = '#ops-debug';
const SLACK_INFO_CHANNEL = '#ops-info';
const SLACK_ICON = ':ops-cloudformation:';
const SLACK_USERNAME = 'AWS CloudFormation';

// These colors match events in the CloudFormation console
function colorForResourceStatus(status) {
  const green = [
    'CREATE_COMPLETE',
    'ROLLBACK_COMPLETE',
    'UPDATE_COMPLETE',
    'UPDATE_ROLLBACK_COMPLETE',
  ];

  const yellow = [
    'CREATE_IN_PROGRESS',
    'DELETE_IN_PROGRESS',
    'REVIEW_IN_PROGRESS',
    'ROLLBACK_IN_PROGRESS',
    'UPDATE_IN_PROGRESS',
    'UPDATE_COMPLETE_CLEANUP_IN_PROGRESS',
  ];

  const red = [
    'CREATE_FAILED',
    'DELETE_FAILED',
    'UPDATE_FAILED',
    'ROLLBACK_FAILED',
    'UPDATE_ROLLBACK_FAILED',
    'UPDATE_ROLLBACK_IN_PROGRESS',
    'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS',
  ];

  const grey = ['DELETE_COMPLETE'];

  if (green.includes(status)) {
    return '#2eb886';
  }

  if (yellow.includes(status)) {
    return '#f4f323';
  }

  if (red.includes(status)) {
    return '#a30200';
  }

  if (grey.includes(status)) {
    return '#AAAAAA';
  }

  return '#000000';
}

const concerning = [
  'ROLLBACK_COMPLETE',
  'UPDATE_ROLLBACK_COMPLETE',
  'DELETE_IN_PROGRESS',
  'ROLLBACK_IN_PROGRESS',
  'CREATE_FAILED',
  'DELETE_FAILED',
  'UPDATE_FAILED',
  'ROLLBACK_FAILED',
  'UPDATE_ROLLBACK_FAILED',
  'UPDATE_ROLLBACK_IN_PROGRESS',
  'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS',
];

exports.message = function (event) {
  // Each event includes information about the stack where the change is
  // happening. These will be present on both stack status and resource status
  // events.
  const stackId = event.detail['stack-id'];
  const timestamp = event.time;

  // Extract the stack name from the stack ID
  const stackName = stackId.split(':stack/')[1].split('/')[0];

  // Both stack status and resource status events will have a status and reason
  const status = event.detail['status-details'].status;
  const statusReason = event.detail['status-details']['status-reason'];

  // For resource status events, there will also be information about the
  // resource that is changing
  // And information about the resource that is actually changing
  const resourceType = event.detail['resource-type'];
  const logicalResourceId = event.detail['logical-resource-id'];
  const physicalResourceId = event.detail['physical-resource-id'];

  const region = event.region;
  const stackUrl = `https://${region}.console.aws.amazon.com/cloudformation/home#/stack/detail?stackId=${stackId}`;

  const regionNickname = regions(region);
  const accountNickname = accounts(event.account);
  const header = [
    `*<${stackUrl}|${accountNickname} - ${regionNickname} » ${stackName}>*`,
    resourceType
      ? `Resource Status Change: *${status}* for \`${resourceType}\``
      : `Stack Status Change: *${status}*`,
  ].join('\n');

  const fallback = resourceType
    ? `${accountNickname} - ${regionNickname} » ${resourceType} ${logicalResourceId} in ${stackName} is now ${status}`
    : `${accountNickname} - ${regionNickname} » Stack ${stackName} is now ${status}`;

  const msg = {
    username: SLACK_USERNAME,
    icon_emoji: SLACK_ICON,
    channel: '#sandbox2',
    attachments: [
      {
        color: colorForResourceStatus(status),
        fallback,
        blocks: [
          {
            type: 'section',
            text: {
              type: 'mrkdwn',
              text: header,
            },
          },
        ],
      },
    ],
  };

  // DELETE_SKIPPED events are funnelled to a specific Slack channel so they
  // can be cleaned up if necessary
  if (status === 'DELETE_SKIPPED') {
    // msg.channel = '#ops-delete-skipped';
    msg.attachments[0].blocks.push({
      type: 'section',
      text: {
        type: 'mrkdwn',
        text: physicalResourceId
          ? `Physical ID: \`${physicalResourceId}\``
          : 'No physical ID',
      },
    });

    return msg;
  }

  // For root stacks, send all start, finish, and concerning status
  // notifications to INFO
  // For stack status events, send all start, finish, and concerning
  // notifications to the INFO channel
  if (
    !resourceType &&
    // (stackName.endsWith('root-staging') ||
    //   stackName.endsWith('root-production')) &&
    (concerning.includes(status) ||
      ['UPDATE_IN_PROGRESS', 'UPDATE_COMPLETE'].includes(status))
  ) {
    // msg.channel = SLACK_INFO_CHANNEL;
    return msg;
  }

  // For everything that isn't a root stack, send any notifications that
  // include a reason to DEBUG. Reasons are most often provided when there is
  // an issue ("resources failed to create", "handler returned message", etc).
  // But some nominal updates do include reasons.
  // Certain irrelevant reasons are filtered out.
  if (
    statusReason &&
    ![
      'User Initiated',
      'Transformation succeeded',
      'Resource creation Initiated',
      'Requested update required the provider to create a new physical resource',
      'Requested update requires the creation of a new physical resource; hence creating one.',
    ].includes(statusReason)
  ) {
    // msg.channel = SLACK_DEBUG_CHANNEL;
    return msg;
  }

  return;
};
<commit_msg>Update message routing<commit_after>const regions = require('./regions');
const accounts = require('./accounts');

const SLACK_DEBUG_CHANNEL = '#ops-debug';
const SLACK_INFO_CHANNEL = '#ops-info';
const SLACK_ICON = ':ops-cloudformation:';
const SLACK_USERNAME = 'AWS CloudFormation';

// These colors match events in the CloudFormation console
function colorForResourceStatus(status) {
  const green = [
    'CREATE_COMPLETE',
    'ROLLBACK_COMPLETE',
    'UPDATE_COMPLETE',
    'UPDATE_ROLLBACK_COMPLETE',
  ];

  const yellow = [
    'CREATE_IN_PROGRESS',
    'DELETE_IN_PROGRESS',
    'REVIEW_IN_PROGRESS',
    'ROLLBACK_IN_PROGRESS',
    'UPDATE_IN_PROGRESS',
    'UPDATE_COMPLETE_CLEANUP_IN_PROGRESS',
  ];

  const red = [
    'CREATE_FAILED',
    'DELETE_FAILED',
    'UPDATE_FAILED',
    'ROLLBACK_FAILED',
    'UPDATE_ROLLBACK_FAILED',
    'UPDATE_ROLLBACK_IN_PROGRESS',
    'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS',
  ];

  const grey = ['DELETE_COMPLETE'];

  if (green.includes(status)) {
    return '#2eb886';
  }

  if (yellow.includes(status)) {
    return '#f4f323';
  }

  if (red.includes(status)) {
    return '#a30200';
  }

  if (grey.includes(status)) {
    return '#AAAAAA';
  }

  return '#000000';
}

const concerning = [
  'ROLLBACK_COMPLETE',
  'UPDATE_ROLLBACK_COMPLETE',
  'DELETE_IN_PROGRESS',
  'ROLLBACK_IN_PROGRESS',
  'CREATE_FAILED',
  'DELETE_FAILED',
  'UPDATE_FAILED',
  'ROLLBACK_FAILED',
  'UPDATE_ROLLBACK_FAILED',
  'UPDATE_ROLLBACK_IN_PROGRESS',
  'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS',
];

exports.message = function (event) {
  // Each event includes information about the stack where the change is
  // happening. These will be present on both stack status and resource status
  // events.
  const stackId = event.detail['stack-id'];

  // Extract the stack name from the stack ID
  const stackName = stackId.split(':stack/')[1].split('/')[0];

  // Both stack status and resource status events will have a status and reason
  const status = event.detail['status-details'].status;
  const statusReason = event.detail['status-details']['status-reason'];

  // For resource status events, there will also be information about the
  // resource that is changing
  // And information about the resource that is actually changing
  const resourceType = event.detail['resource-type'];
  const logicalResourceId = event.detail['logical-resource-id'];
  const physicalResourceId = event.detail['physical-resource-id'];

  const region = event.region;
  const stackUrl = `https://${region}.console.aws.amazon.com/cloudformation/home#/stack/detail?stackId=${stackId}`;

  const regionNickname = regions(region);
  const accountNickname = accounts(event.account);
  const header = [
    `*<${stackUrl}|${accountNickname} - ${regionNickname} » ${stackName}>*`,
    resourceType
      ? `Resource Status Change: *${status}* for \`${resourceType}\``
      : `Stack Status Change: *${status}*`,
  ].join('\n');

  const fallback = resourceType
    ? `${accountNickname} - ${regionNickname} » ${resourceType} ${logicalResourceId} in ${stackName} is now ${status}`
    : `${accountNickname} - ${regionNickname} » Stack ${stackName} is now ${status}`;

  const msg = {
    username: SLACK_USERNAME,
    icon_emoji: SLACK_ICON,
    channel: '#sandbox2',
    attachments: [
      {
        color: colorForResourceStatus(status),
        fallback,
        blocks: [
          {
            type: 'section',
            text: {
              type: 'mrkdwn',
              text: header,
            },
          },
        ],
      },
    ],
  };

  // DELETE_SKIPPED events are funnelled to a specific Slack channel so they
  // can be cleaned up if necessary
  if (status === 'DELETE_SKIPPED') {
    msg.channel = '#ops-delete-skipped';
    msg.attachments[0].blocks.push({
      type: 'section',
      text: {
        type: 'mrkdwn',
        text: physicalResourceId
          ? `Physical ID: \`${physicalResourceId}\``
          : 'No physical ID',
      },
    });

    return msg;
  }

  // For Spire root stacks, send all start, finish, and concerning status
  // notifications to INFO
  // For stack status events, send all start, finish, and concerning
  // notifications to the INFO channel
  if (
    !resourceType &&
    (stackName.endsWith('root-staging') ||
      stackName.endsWith('root-production')) &&
    (concerning.includes(status) ||
      ['UPDATE_IN_PROGRESS', 'UPDATE_COMPLETE'].includes(status))
  ) {
    msg.channel = SLACK_INFO_CHANNEL;
    return msg;
  }

  // For other stacks, send finish and concerning notifications to DEBUG
  if (
    !resourceType &&
    (concerning.includes(status) || ['UPDATE_COMPLETE'].includes(status))
  ) {
    msg.channel = SLACK_DEBUG_CHANNEL;
    return msg;
  }

  // For everything that isn't a root stack, send any notifications that
  // include a reason to DEBUG. Reasons are most often provided when there is
  // an issue ("resources failed to create", "handler returned message", etc).
  // But some nominal updates do include reasons.
  // Certain irrelevant reasons are filtered out.
  if (
    statusReason &&
    ![
      'User Initiated',
      'Transformation succeeded',
      'Resource creation Initiated',
      'Requested update required the provider to create a new physical resource',
      'Requested update requires the creation of a new physical resource; hence creating one.',
    ].includes(statusReason)
  ) {
    msg.channel = SLACK_DEBUG_CHANNEL;
    return msg;
  }

  return;
};
<|endoftext|>


<commit_before>'use strict';

angular.module('a2App')
  .service('KWCarbonTrailService', function () {
  this.state_data =
  {
    AK: { name: 'Alaska'   , average: 15.65227014, ranking: 35 },
    AL: { name: 'Alabama'  , average: 34.63312419, ranking: 19 },
    AR: { name: 'Arkansas' , average: 20.96569983, ranking: 30 },
    AZ: { name: 'Arizona'  , average: 34.40358322, ranking: 20 },
    CA: { name: 'California'   , average: 224.9807134, ranking: 1  },
    CO: { name: 'Colorado' , average: 28.22752076, ranking: 27 },
    CT: { name: 'Connecticut'  , average: 17.43797401, ranking: 33 },
    DC: { name: 'District of Columbia' , average: 1.607517584, ranking: 51 },
    DE: { name: 'Delaware' , average: 5.086506951, ranking: 48 },
    FL: { name: 'Florida'  , average: 105.5471576, ranking: 3  },
    GA: { name: 'Georgia'  , average: 65.63167608, ranking: 9  },
    HI: { name: 'Hawaii'   , average: 10.5958076 , ranking: 40 },
    IA: { name: 'Iowa' , average: 20.72783811, ranking: 31 },
    ID: { name: 'Idaho', average: 9.035525822, ranking: 41 },
    IL: { name: 'Illinois' , average: 68.53668966, ranking: 7  },
    IN: { name: 'Indiana'  , average: 46.12729378, ranking: 14 },
    KS: { name: 'Kansas'   , average: 19.51034596, ranking: 32 },
    KY: { name: 'Kentucky' , average: 33.06597993, ranking: 21 },
    LA: { name: 'Louisiana', average: 54.6350019 , ranking: 11 },
    MA: { name: 'Massachusetts', average: 32.97345567, ranking: 22 },
    MD: { name: 'Maryland' , average: 30.41207254, ranking: 25 },
    ME: { name: 'Maine', average: 8.768777109, ranking: 42 },
    MI: { name: 'Michigan' , average: 57.43456236, ranking: 10 },
    MN: { name: 'Minnesota', average: 35.08564391, ranking: 18 },
    MO: { name: 'Missouri' , average: 42.80473351, ranking: 17 },
    MS: { name: 'Mississippi'  , average: 26.10664302, ranking: 28 },
    MT: { name: 'Montana'  , average: 7.872191111, ranking: 44 },
    NC: { name: 'North Carolina'   , average: 51.93398922, ranking: 12 },
    ND: { name: 'North Dakota' , average: 6.143962895, ranking: 47 },
    NE: { name: 'Nebraska' , average: 12.87536346, ranking: 38 },
    NH: { name: 'New Hampshire', average: 7.414865772, ranking: 45 },
    NJ: { name: 'New Jersey'   , average: 66.34039064, ranking: 8  },
    NM: { name: 'New Mexico'   , average: 15.48398015, ranking: 36 },
    NV: { name: 'Nevada'   , average: 15.34314648, ranking: 37 },
    NY: { name: 'New York' , average: 73.20149315, ranking: 4  },
    OH: { name: 'Ohio' , average: 70.18691675, ranking: 6  },
    OK: { name: 'Oklahoma' , average: 30.78184755, ranking: 24 },
    OR: { name: 'Oregon'   , average: 23.51745881, ranking: 29 },
    PA: { name: 'Pennsylvania' , average: 71.29168029, ranking: 5  },
    RI: { name: 'Rhode Island' , average: 4.62921442 , ranking: 49 },
    SC: { name: 'South Carolina'   , average: 29.50374605, ranking: 26 },
    SD: { name: 'South Dakota' , average: 6.159112742, ranking: 46 },
    TN: { name: 'Tennessee', average: 43.78492339, ranking: 16 },
    TX: { name: 'Texas', average: 192.9793922, ranking: 2  },
    UT: { name: 'Utah' , average: 16.37846847, ranking: 34 },
    VA: { name: 'Virginia' , average: 51.72370847, ranking: 13 },
    VT: { name: 'Vermont'  , average: 3.884205832, ranking: 50 },
    WA: { name: 'Washington'   , average: 45.23309938, ranking: 15 },
    WI: { name: 'Wisconsin', average: 31.10640391, ranking: 23 },
    WV: { name: 'West Virginia', average: 12.59547573, ranking: 39 },
    WY: { name: 'Wyoming'  , average: 8.144043387, ranking: 43 }
};

    this.highlightedState = null;
    this.stateID = null;
    this.sidePanelLineData = [];
    this.sidePanelShadowData = [];
    this.generateMapDataByAverage = function() {
        var i;
        var renderData = {};
        angular.forEach(this.state_data, function(value, key) {
            renderData[key] = value.average;
        })
        return renderData;
    };
    this.filterDataByYear = function(data, year) {
        var i;
        var renderData = {};
        for (i=1; i<data.length; i++) {
            if (data[i][1] == year) {
                renderData[data[i][0]] = data[i][2];
            }
        }
        return renderData;
    };
    this.filterDataByState = function(data, state) {
        var i;
        var renderData = {};
        for (i=1; i<data.length; i++) {
            if (data[i][0] == state) {
                renderData[data[i][1]] = data[i][2];
            }
        }
        return renderData;
    };
    this.onMapDataLoaded = function(data) {
        // get header
        var headerRow = ['year'];
        var firstState = data[1][0];
        var i;
        for (i=1; i<data.length; i++) {
          if (data[i][0] !== firstState)
            break;
          headerRow.push(data[i][1]);
        };

        var prevRowState = "";
        var contentRow = null;
        var output = [headerRow];
        for (i=1; i<data.length; i++) {
          if (prevRowState !== data[i][0]) {
            if (contentRow)
              output.push(contentRow);
            contentRow = new Array(0);
            contentRow.push(data[i][0]);
          }
          contentRow.push(data[i][2]);
          prevRowState = data[i][0];
        }
        var self = this;
        self.sidePanelShadowData.length = 0;
        angular.forEach(output, function(val){
          self.sidePanelShadowData.push(val);
        });
        notifyObservers('sidePanelShadowData');
    }
    this.onStateChanged = function(data, state) {
        var obj = this.filterDataByState(data, state);
        this.stateID = state;
        this.sidePanelLineData.length = 0;
        var i;
        var headerRow = [];
        headerRow.push('year');
        angular.forEach(obj, function(value, key){
          headerRow.push(key);
        });
        this.sidePanelLineData.push(headerRow);
        var contentRow = [];
        contentRow.push(state);
        angular.forEach(obj, function(value, key){
          contentRow.push(value);
        });
        this.sidePanelLineData.push(contentRow);

        notifyObservers('sidePanelLineData');
    }

    var ObserverCallbacks = {};

    this.registerObserverCallback = function(name, callback){
      if (!ObserverCallbacks[name])
        ObserverCallbacks[name] = [];
      ObserverCallbacks[name].push(callback);
    };

    var notifyObservers = function(name){
      angular.forEach(ObserverCallbacks[name], function(callback){
        callback();
      });
    };

    this.getPowerPlantNumber = function() {
        console.log(this.stateID);
        console.log(parseInt((this.state_data[this.stateID].average)/22.011155));
        return new Array(parseInt((this.state_data[this.stateID].average)/22.011155));
    }
  });
<commit_msg>Add the reference of power-plant number.<commit_after>'use strict';

angular.module('a2App')
  .service('KWCarbonTrailService', function () {
  this.state_data =
  {
    AK: { name: 'Alaska'   , average: 15.65227014, ranking: 35 },
    AL: { name: 'Alabama'  , average: 34.63312419, ranking: 19 },
    AR: { name: 'Arkansas' , average: 20.96569983, ranking: 30 },
    AZ: { name: 'Arizona'  , average: 34.40358322, ranking: 20 },
    CA: { name: 'California'   , average: 224.9807134, ranking: 1  },
    CO: { name: 'Colorado' , average: 28.22752076, ranking: 27 },
    CT: { name: 'Connecticut'  , average: 17.43797401, ranking: 33 },
    DC: { name: 'District of Columbia' , average: 1.607517584, ranking: 51 },
    DE: { name: 'Delaware' , average: 5.086506951, ranking: 48 },
    FL: { name: 'Florida'  , average: 105.5471576, ranking: 3  },
    GA: { name: 'Georgia'  , average: 65.63167608, ranking: 9  },
    HI: { name: 'Hawaii'   , average: 10.5958076 , ranking: 40 },
    IA: { name: 'Iowa' , average: 20.72783811, ranking: 31 },
    ID: { name: 'Idaho', average: 9.035525822, ranking: 41 },
    IL: { name: 'Illinois' , average: 68.53668966, ranking: 7  },
    IN: { name: 'Indiana'  , average: 46.12729378, ranking: 14 },
    KS: { name: 'Kansas'   , average: 19.51034596, ranking: 32 },
    KY: { name: 'Kentucky' , average: 33.06597993, ranking: 21 },
    LA: { name: 'Louisiana', average: 54.6350019 , ranking: 11 },
    MA: { name: 'Massachusetts', average: 32.97345567, ranking: 22 },
    MD: { name: 'Maryland' , average: 30.41207254, ranking: 25 },
    ME: { name: 'Maine', average: 8.768777109, ranking: 42 },
    MI: { name: 'Michigan' , average: 57.43456236, ranking: 10 },
    MN: { name: 'Minnesota', average: 35.08564391, ranking: 18 },
    MO: { name: 'Missouri' , average: 42.80473351, ranking: 17 },
    MS: { name: 'Mississippi'  , average: 26.10664302, ranking: 28 },
    MT: { name: 'Montana'  , average: 7.872191111, ranking: 44 },
    NC: { name: 'North Carolina'   , average: 51.93398922, ranking: 12 },
    ND: { name: 'North Dakota' , average: 6.143962895, ranking: 47 },
    NE: { name: 'Nebraska' , average: 12.87536346, ranking: 38 },
    NH: { name: 'New Hampshire', average: 7.414865772, ranking: 45 },
    NJ: { name: 'New Jersey'   , average: 66.34039064, ranking: 8  },
    NM: { name: 'New Mexico'   , average: 15.48398015, ranking: 36 },
    NV: { name: 'Nevada'   , average: 15.34314648, ranking: 37 },
    NY: { name: 'New York' , average: 73.20149315, ranking: 4  },
    OH: { name: 'Ohio' , average: 70.18691675, ranking: 6  },
    OK: { name: 'Oklahoma' , average: 30.78184755, ranking: 24 },
    OR: { name: 'Oregon'   , average: 23.51745881, ranking: 29 },
    PA: { name: 'Pennsylvania' , average: 71.29168029, ranking: 5  },
    RI: { name: 'Rhode Island' , average: 4.62921442 , ranking: 49 },
    SC: { name: 'South Carolina'   , average: 29.50374605, ranking: 26 },
    SD: { name: 'South Dakota' , average: 6.159112742, ranking: 46 },
    TN: { name: 'Tennessee', average: 43.78492339, ranking: 16 },
    TX: { name: 'Texas', average: 192.9793922, ranking: 2  },
    UT: { name: 'Utah' , average: 16.37846847, ranking: 34 },
    VA: { name: 'Virginia' , average: 51.72370847, ranking: 13 },
    VT: { name: 'Vermont'  , average: 3.884205832, ranking: 50 },
    WA: { name: 'Washington'   , average: 45.23309938, ranking: 15 },
    WI: { name: 'Wisconsin', average: 31.10640391, ranking: 23 },
    WV: { name: 'West Virginia', average: 12.59547573, ranking: 39 },
    WY: { name: 'Wyoming'  , average: 8.144043387, ranking: 43 }
};

    this.highlightedState = null;
    this.stateID = null;
    this.sidePanelLineData = [];
    this.sidePanelShadowData = [];
    this.generateMapDataByAverage = function() {
        var i;
        var renderData = {};
        angular.forEach(this.state_data, function(value, key) {
            renderData[key] = value.average;
        })
        return renderData;
    };
    this.filterDataByYear = function(data, year) {
        var i;
        var renderData = {};
        for (i=1; i<data.length; i++) {
            if (data[i][1] == year) {
                renderData[data[i][0]] = data[i][2];
            }
        }
        return renderData;
    };
    this.filterDataByState = function(data, state) {
        var i;
        var renderData = {};
        for (i=1; i<data.length; i++) {
            if (data[i][0] == state) {
                renderData[data[i][1]] = data[i][2];
            }
        }
        return renderData;
    };
    this.onMapDataLoaded = function(data) {
        // get header
        var headerRow = ['year'];
        var firstState = data[1][0];
        var i;
        for (i=1; i<data.length; i++) {
          if (data[i][0] !== firstState)
            break;
          headerRow.push(data[i][1]);
        };

        var prevRowState = "";
        var contentRow = null;
        var output = [headerRow];
        for (i=1; i<data.length; i++) {
          if (prevRowState !== data[i][0]) {
            if (contentRow)
              output.push(contentRow);
            contentRow = new Array(0);
            contentRow.push(data[i][0]);
          }
          contentRow.push(data[i][2]);
          prevRowState = data[i][0];
        }
        var self = this;
        self.sidePanelShadowData.length = 0;
        angular.forEach(output, function(val){
          self.sidePanelShadowData.push(val);
        });
        notifyObservers('sidePanelShadowData');
    }
    this.onStateChanged = function(data, state) {
        var obj = this.filterDataByState(data, state);
        this.stateID = state;
        this.sidePanelLineData.length = 0;
        var i;
        var headerRow = [];
        headerRow.push('year');
        angular.forEach(obj, function(value, key){
          headerRow.push(key);
        });
        this.sidePanelLineData.push(headerRow);
        var contentRow = [];
        contentRow.push(state);
        angular.forEach(obj, function(value, key){
          contentRow.push(value);
        });
        this.sidePanelLineData.push(contentRow);

        notifyObservers('sidePanelLineData');
    }

    var ObserverCallbacks = {};

    this.registerObserverCallback = function(name, callback){
      if (!ObserverCallbacks[name])
        ObserverCallbacks[name] = [];
      ObserverCallbacks[name].push(callback);
    };

    var notifyObservers = function(name){
      angular.forEach(ObserverCallbacks[name], function(callback){
        callback();
      });
    };

    this.getPowerPlantNumber = function() {
        // Based on Bowen power plant, GA. Annual CO2 emissions: 22,011,155 MTCD
        // Source: Wu, Brandon. Lethal Legacy: A comprehensive look at america's dirtiest power plants. US PIRG Education Fund, 2003. pp.20.
        // Available at: http://www.csu.edu/cerc/documents/LethalLegacy_001.pdf
        return new Array(parseInt((this.state_data[this.stateID].average)/22.011155));
    }
  });
<|endoftext|>


<commit_before>const {resolveJsonResponse} = require('./dataAccess/azureJson');
const {getCollection, addRow} = require('./dataAccess/dbMethods');
const TYPES = require('tedious').TYPES;

module.exports = {
    getLicences: function(nomisIds) {
        return new Promise((resolve, reject) => {
            const sql = `SELECT NOMIS_ID as nomisId, ID as id, STATUS as status, JSON_QUERY(LICENCE) AS licence
                         FROM LICENCES WHERE NOMIS_ID IN (${nomisIds.map(id => `'${id}'`).join(',')}) FOR JSON PATH`;

            getCollection(sql, null, resolveJsonResponse(resolve), reject);
        });
    },

    getLicence: function(nomisId) {
        return new Promise((resolve, reject) => {
            const sql = `SELECT NOMIS_ID as nomisId, ID as id, JSON_QUERY(LICENCE) AS licence
                         FROM LICENCES WHERE NOMIS_ID = '${nomisId}' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER`;

            getCollection(sql, null, resolveJsonResponse(resolve), reject);
        });
    },

    createLicence: function(nomisId, licence = {}, status = 'STARTED') {
        return new Promise((resolve, reject) => {
            const sql = 'INSERT INTO LICENCES (NOMIS_ID, LICENCE, STATUS) ' +
                        'VALUES (@nomisId, @licence, @status)';

            const parameters = [
                {column: 'nomisId', type: TYPES.VarChar, value: nomisId},
                {column: 'licence', type: TYPES.VarChar, value: JSON.stringify(licence)},
                {column: 'status', type: TYPES.VarChar, value: status}
            ];

            addRow(sql, parameters, resolve, reject);
        });
    },

    updateSection: function(section, nomisId, object) {
        return new Promise((resolve, reject) => {
            const sql = `UPDATE LICENCES
                         SET LICENCE = JSON_MODIFY(LICENCE, @section, JSON_QUERY(@object))
                         WHERE NOMIS_ID=@nomisId`;

            const parameters = [
                {column: 'section', type: TYPES.VarChar, value: '$.'+section},
                {column: 'object', type: TYPES.VarChar, value: JSON.stringify(object)},
                {column: 'nomisId', type: TYPES.VarChar, value: nomisId}
            ];

            addRow(sql, parameters, resolve, reject);
        });
    },

    getStandardConditions: function() {
        return new Promise((resolve, reject) => {
            const sql = 'select * from CONDITIONS Where TYPE = \'STANDARD\'';

            getCollection(sql, null, resolve, reject);
        });
    },

    getAdditionalConditions: function() {
        return new Promise((resolve, reject) => {
            const sql = 'select * from CONDITIONS Where TYPE = \'ADDITIONAL\'';

            getCollection(sql, null, resolve, reject);
        });
    },

    updateStatus: function(nomisId, status) {
        return new Promise((resolve, reject) => {
            const sql = `UPDATE LICENCES SET STATUS = @status
                         WHERE NOMIS_ID = @nomisId`;

            const parameters = [
                {column: 'status', type: TYPES.VarChar, value: status},
                {column: 'nomisId', type: TYPES.VarChar, value: nomisId}
            ];

            addRow(sql, parameters, resolve, reject);
        });
    }
};
<commit_msg>Fix string formatting<commit_after>const {resolveJsonResponse} = require('./dataAccess/azureJson');
const {getCollection, addRow} = require('./dataAccess/dbMethods');
const TYPES = require('tedious').TYPES;

module.exports = {
    getLicences: function(nomisIds) {
        return new Promise((resolve, reject) => {
            const sql = `SELECT NOMIS_ID as nomisId, ID as id, STATUS as status, JSON_QUERY(LICENCE) AS licence
                         FROM LICENCES WHERE NOMIS_ID IN (${nomisIds.map(id => `'${id}'`).join(',')}) FOR JSON PATH`;

            getCollection(sql, null, resolveJsonResponse(resolve), reject);
        });
    },

    getLicence: function(nomisId) {
        return new Promise((resolve, reject) => {
            const sql = `SELECT NOMIS_ID as nomisId, ID as id, JSON_QUERY(LICENCE) AS licence
                         FROM LICENCES WHERE NOMIS_ID = '${nomisId}' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER`;

            getCollection(sql, null, resolveJsonResponse(resolve), reject);
        });
    },

    createLicence: function(nomisId, licence = {}, status = 'STARTED') {
        return new Promise((resolve, reject) => {
            const sql = 'INSERT INTO LICENCES (NOMIS_ID, LICENCE, STATUS) ' +
                'VALUES (@nomisId, @licence, @status)';

            const parameters = [
                {column: 'nomisId', type: TYPES.VarChar, value: nomisId},
                {column: 'licence', type: TYPES.VarChar, value: JSON.stringify(licence)},
                {column: 'status', type: TYPES.VarChar, value: status}
            ];

            addRow(sql, parameters, resolve, reject);
        });
    },

    updateSection: function(section, nomisId, object) {
        return new Promise((resolve, reject) => {
            const sql = `UPDATE LICENCES
                         SET LICENCE = JSON_MODIFY(LICENCE, @section, JSON_QUERY(@object))
                         WHERE NOMIS_ID=@nomisId`;

            const parameters = [
                {column: 'section', type: TYPES.VarChar, value: '$.' + section},
                {column: 'object', type: TYPES.VarChar, value: JSON.stringify(object)},
                {column: 'nomisId', type: TYPES.VarChar, value: nomisId}
            ];

            addRow(sql, parameters, resolve, reject);
        });
    },

    getStandardConditions: function() {
        return new Promise((resolve, reject) => {
            const sql = 'select * from CONDITIONS Where TYPE = \'STANDARD\'';

            getCollection(sql, null, resolve, reject);
        });
    },

    getAdditionalConditions: function() {
        return new Promise((resolve, reject) => {
            const sql = 'select * from CONDITIONS Where TYPE = \'ADDITIONAL\'';

            getCollection(sql, null, resolve, reject);
        });
    },

    updateStatus: function(nomisId, status) {
        return new Promise((resolve, reject) => {
            const sql = 'UPDATE LICENCES SET STATUS = @status WHERE NOMIS_ID = @nomisId';

            const parameters = [
                {column: 'status', type: TYPES.VarChar, value: status},
                {column: 'nomisId', type: TYPES.VarChar, value: nomisId}
            ];

            addRow(sql, parameters, resolve, reject);
        });
    }
};
<|endoftext|>


<commit_before>var parse = function(uptime){
	var minutes = Math.round(uptime / 60) % 60;
	var hours = Math.round(uptime / 60 / 60) % 24;
	var days = Math.round(uptime / 60 / 60 / 24);
	var seconds = Math.round(uptime) % 60;

	uptime = [];
	if (days >= 1) {
		uptime.push('' + days + ' day' + (days > 1 ? 's' : ''));
	}
	if (hours >= 1) {
		uptime.push('' + hours +' hour' + (hours > 1 ? 's' : ''));
	}
	if (minutes >= 1) {
		uptime.push('' + minutes + ' minute' + (minutes > 1 ? 's' : ''));
	}
	if (seconds >= 1) {
		uptime.push('' + seconds + ' second' + (seconds > 1 ? 's' : ''));
	}
	uptime = uptime.join(', ');
	return uptime;
}
var uptime = function(bot, channel){
	var parsed = (new Date().getTime() - bot.startTime) / 1000;
	IRC.message(channel, 'Bot has been online for: ' + parse(parsed));
}
exports.init = function(plugins, bot){
	bot.addCommand('uptime', '', 'Shows uptime of bot', USER_LEVEL_GLOBAL, true);
	plugins.listen(this, 'command', function(args){
		if(args.command && args.command == 'uptime'){
			uptime(bot, args.channel);
		}
	});
}<commit_msg>variable name fail<commit_after>var parse = function(uptime){
	var minutes = Math.round(uptime / 60) % 60;
	var hours = Math.round(uptime / 60 / 60) % 24;
	var days = Math.round(uptime / 60 / 60 / 24);
	var seconds = Math.round(uptime) % 60;

	uptime = [];
	if (days >= 1) {
		uptime.push('' + days + ' day' + (days > 1 ? 's' : ''));
	}
	if (hours >= 1) {
		uptime.push('' + hours +' hour' + (hours > 1 ? 's' : ''));
	}
	if (minutes >= 1) {
		uptime.push('' + minutes + ' minute' + (minutes > 1 ? 's' : ''));
	}
	if (seconds >= 1) {
		uptime.push('' + seconds + ' second' + (seconds > 1 ? 's' : ''));
	}
	uptime = uptime.join(', ');
	return uptime;
}
var uptime = function(bot, channel){
	var time = (new Date().getTime() - bot.startTime) / 1000;
	IRC.message(channel, 'Bot has been online for: ' + parse(time));
}
exports.init = function(plugins, bot){
	bot.addCommand('uptime', '', 'Shows uptime of bot', USER_LEVEL_GLOBAL, true);
	plugins.listen(this, 'command', function(args){
		if(args.command && args.command == 'uptime'){
			uptime(bot, args.channel);
		}
	});
}<|endoftext|>


<commit_before>const CompressionPlugin = require("compression-webpack-plugin")
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require('webpack');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const path = process.cwd();
const _p = require('path');
const production = process.env.NODE_ENV == 'production';

const imageFormats = 'png|svg|jpg|gif';

module.exports = function(opts) {
  /***********
   * OPTIONS *
   ***********/

  opts = opts || {};
  const entryPoint = opts.entryPoint || './src/main.js';
  const outputPath = opts.outputPath || './assets';
  const serverBase = opts.serverBase || './';
  const publicPath = opts.publicPath || '/assets/';
  const host = opts.host || '0.0.0.0';
  const port = opts.port || 8080;
  const public = opts.public || `${host}:${port}`;
  const lookupPaths = opts.lookupPaths || [];
  const gzip = (opts.gzip === false) ? false : true;
  const singlePageApp = opts.singlePageApp || false;
  const showStats = process.argv.includes('--stats');
  const statsOptions = opts.statsOptions;
  const productionSourcemaps = opts.productionSourcemaps || false;

  /******************
   * WEBPACK CONFIG *
   ******************/

  const config = {
    mode: production ? 'production' : 'development',
    entry: _p.resolve(path, entryPoint),
    output: {
      path: _p.resolve(path, outputPath),
      publicPath: publicPath,
      filename: 'javascripts/ui.js',
      chunkFilename: 'javascripts/[name].bundle.js'
    },
    resolve: {
      modules: lookupPaths.concat([
        _p.resolve(path, './src'),
        'node_modules'
      ]),
      extensions: ['.wasm', '.mjs', '.js', '.json', '.ts', '.tsx']
    }
  };

  // Enable sourcemaps, different kinds depending on environment
  if (production && productionSourcemaps) config.devtool = 'source-map'
  if (!production) config.devtool = 'eval-source-maps';

  /***********
   * LOADERS *
   ***********/

  // Babel Loader
  const babelLoader = {
    test: /\.(ts|js|tsx|jsx)$/,
    exclude: /node_modules/,
    use: {
      loader: 'babel-loader',
      options: {
        presets: [
          [
            '@babel/preset-env',
            {
              useBuiltIns: 'usage',
              targets: {
                browsers: 'IE 11'
              },
              corejs: 3
            }
          ],
          "@babel/preset-react",
          "@babel/preset-typescript"
        ],
        plugins: [
          '@babel/plugin-proposal-class-properties',
          '@babel/plugin-proposal-object-rest-spread',
          '@babel/plugin-syntax-dynamic-import'
        ]
      }
    }
  };

  // CSS Loader
  const cssLoader = {
    test: /\.(scss|css)$/,
    use: [{
      loader: production ? MiniCssExtractPlugin.loader : 'style-loader'
    }, {
      loader: 'css-loader'
    }, {
      loader: 'sass-loader',
      options: {
        includePaths: [
          _p.resolve(path, './src/style-config'),
          _p.resolve(path, './node_modules/carbon-react/lib/style-config')
        ]
      }
    }],
  };

  // Image Loader
  const imageLoader = {
    test: new RegExp(`\.(${imageFormats})$`, 'i'),
    use: [{
      loader: 'file-loader',
      options: {
        name: '[name].[ext]',
        outputPath: 'images/'
      }
    }]
  };

  // Font Loader
  const fontLoader = {
    test: /\.(woff|woff2|eot|ttf|otf)$/,
    use: [{
      loader: 'file-loader',
      options: {
        name: '[name].[ext]',
        outputPath: 'fonts/'
      }
    }]
  };

  config.module = {
    rules: [
      babelLoader,
      cssLoader,
      imageLoader,
      fontLoader
    ]
  };

  /**************
   * DEV SERVER *
   **************/

  config.devServer = production ? {} : {
    contentBase: _p.resolve(path, serverBase),
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Credentials': true
    },
    host: host,
    hot: true,
    port: port,
    public: public,
    publicPath: publicPath,
    historyApiFallback: singlePageApp,
    before(app) {
      app.get(/stylesheets\/ui.css/, (req, res) => {
        res.sendFile(_p.resolve(path, './node_modules/carbon-factory/fake.css'));
      });
    }
  };

  /***********
   * PLUGINS *
   ***********/

  // Clean Webpack Plugin
  const clean = new CleanWebpackPlugin([_p.resolve(path, outputPath)], {
    root: _p.resolve(path)
  });

  if (production) {
    // Production Plugins
    config.plugins = [
      clean,
      new OptimizeCSSAssetsPlugin({
        cssProcessorOptions: {
          safe: true
        }
      }),
      new MiniCssExtractPlugin({
        filename: 'stylesheets/ui.css'
      })
    ]

    if (gzip) {
      config.plugins.push(
        new CompressionPlugin({
          asset: '[path][query]',
          exclude: new RegExp(`\.(${imageFormats})$`, 'i'),
          minRatio: Infinity
        })
      );
    }
  } else {
    // Development Plugins
    config.plugins = [
      clean,
      new webpack.NamedModulesPlugin(),
      new webpack.HotModuleReplacementPlugin()
    ];
  }

  // Bundle stats
  if (showStats) config.plugins.push(new BundleAnalyzerPlugin(statsOptions));

  return config;
};
<commit_msg>fix: replaces asset object with filename object<commit_after>const CompressionPlugin = require("compression-webpack-plugin")
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require('webpack');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const path = process.cwd();
const _p = require('path');
const production = process.env.NODE_ENV == 'production';

const imageFormats = 'png|svg|jpg|gif';

module.exports = function(opts) {
  /***********
   * OPTIONS *
   ***********/

  opts = opts || {};
  const entryPoint = opts.entryPoint || './src/main.js';
  const outputPath = opts.outputPath || './assets';
  const serverBase = opts.serverBase || './';
  const publicPath = opts.publicPath || '/assets/';
  const host = opts.host || '0.0.0.0';
  const port = opts.port || 8080;
  const public = opts.public || `${host}:${port}`;
  const lookupPaths = opts.lookupPaths || [];
  const gzip = (opts.gzip === false) ? false : true;
  const singlePageApp = opts.singlePageApp || false;
  const showStats = process.argv.includes('--stats');
  const statsOptions = opts.statsOptions;
  const productionSourcemaps = opts.productionSourcemaps || false;

  /******************
   * WEBPACK CONFIG *
   ******************/

  const config = {
    mode: production ? 'production' : 'development',
    entry: _p.resolve(path, entryPoint),
    output: {
      path: _p.resolve(path, outputPath),
      publicPath: publicPath,
      filename: 'javascripts/ui.js',
      chunkFilename: 'javascripts/[name].bundle.js'
    },
    resolve: {
      modules: lookupPaths.concat([
        _p.resolve(path, './src'),
        'node_modules'
      ]),
      extensions: ['.wasm', '.mjs', '.js', '.json', '.ts', '.tsx']
    }
  };

  // Enable sourcemaps, different kinds depending on environment
  if (production && productionSourcemaps) config.devtool = 'source-map'
  if (!production) config.devtool = 'eval-source-maps';

  /***********
   * LOADERS *
   ***********/

  // Babel Loader
  const babelLoader = {
    test: /\.(ts|js|tsx|jsx)$/,
    exclude: /node_modules/,
    use: {
      loader: 'babel-loader',
      options: {
        presets: [
          [
            '@babel/preset-env',
            {
              useBuiltIns: 'usage',
              targets: {
                browsers: 'IE 11'
              },
              corejs: 3
            }
          ],
          "@babel/preset-react",
          "@babel/preset-typescript"
        ],
        plugins: [
          '@babel/plugin-proposal-class-properties',
          '@babel/plugin-proposal-object-rest-spread',
          '@babel/plugin-syntax-dynamic-import'
        ]
      }
    }
  };

  // CSS Loader
  const cssLoader = {
    test: /\.(scss|css)$/,
    use: [{
      loader: production ? MiniCssExtractPlugin.loader : 'style-loader'
    }, {
      loader: 'css-loader'
    }, {
      loader: 'sass-loader',
      options: {
        includePaths: [
          _p.resolve(path, './src/style-config'),
          _p.resolve(path, './node_modules/carbon-react/lib/style-config')
        ]
      }
    }],
  };

  // Image Loader
  const imageLoader = {
    test: new RegExp(`\.(${imageFormats})$`, 'i'),
    use: [{
      loader: 'file-loader',
      options: {
        name: '[name].[ext]',
        outputPath: 'images/'
      }
    }]
  };

  // Font Loader
  const fontLoader = {
    test: /\.(woff|woff2|eot|ttf|otf)$/,
    use: [{
      loader: 'file-loader',
      options: {
        name: '[name].[ext]',
        outputPath: 'fonts/'
      }
    }]
  };

  config.module = {
    rules: [
      babelLoader,
      cssLoader,
      imageLoader,
      fontLoader
    ]
  };

  /**************
   * DEV SERVER *
   **************/

  config.devServer = production ? {} : {
    contentBase: _p.resolve(path, serverBase),
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Credentials': true
    },
    host: host,
    hot: true,
    port: port,
    public: public,
    publicPath: publicPath,
    historyApiFallback: singlePageApp,
    before(app) {
      app.get(/stylesheets\/ui.css/, (req, res) => {
        res.sendFile(_p.resolve(path, './node_modules/carbon-factory/fake.css'));
      });
    }
  };

  /***********
   * PLUGINS *
   ***********/

  // Clean Webpack Plugin
  const clean = new CleanWebpackPlugin([_p.resolve(path, outputPath)], {
    root: _p.resolve(path)
  });

  if (production) {
    // Production Plugins
    config.plugins = [
      clean,
      new OptimizeCSSAssetsPlugin({
        cssProcessorOptions: {
          safe: true
        }
      }),
      new MiniCssExtractPlugin({
        filename: 'stylesheets/ui.css'
      })
    ]

    if (gzip) {
      config.plugins.push(
        new CompressionPlugin({
          filename: '[path][query]',
          exclude: new RegExp(`\.(${imageFormats})$`, 'i'),
          minRatio: Infinity
        })
      );
    }
  } else {
    // Development Plugins
    config.plugins = [
      clean,
      new webpack.NamedModulesPlugin(),
      new webpack.HotModuleReplacementPlugin()
    ];
  }

  // Bundle stats
  if (showStats) config.plugins.push(new BundleAnalyzerPlugin(statsOptions));

  return config;
};
<|endoftext|>