<commit_before>import { action } from '@ember/object';
import { inject as service } from '@ember/service';
import Component from '@glimmer/component';

import { task, waitForEvent } from 'ember-concurrency';
import window from 'ember-window-mock';

import ajax from '../utils/ajax';

export default class Header extends Component {
  @service header;
  @service notifications;
  @service router;
  @service session;

  @action
  search(event) {
    event.preventDefault();

    this.router.transitionTo('search', {
      queryParams: {
        q: this.header.searchValue,
        page: 1,
      },
    });
  }

  @action login() {
    this.loginTask.perform();
  }

  /**
   * This task will open a popup window directed at the `github-login` route.
   * After the window has opened it will wait for the window to send a message
   * back and then evaluate whether the OAuth flow was successful.
   *
   * @see `github-authorize` route
   */
  @task(function* () {
    let windowDimensions = [
      'width=1000',
      'height=450',
      'toolbar=0',
      'scrollbars=1',
      'status=1',
      'resizable=1',
      'location=1',
      'menuBar=0',
    ].join(',');

    let win = window.open('/github_login', 'Authorization', windowDimensions);
    if (!win) {
      return;
    }

    let event = yield waitForEvent(window, 'message');
    if (event.origin !== window.location.origin || !event.data) {
      return;
    }

    let { data } = event.data;
    if (data && data.errors) {
      this.notifications.error(`Failed to log in: ${data.errors[0].detail}`);
      return;
    } else if (!event.data.ok) {
      this.notifications.error('Failed to log in');
      return;
    }

    this.session.login();
  })
  loginTask;

  @task(function* () {
    yield ajax(`/api/private/session`, { method: 'DELETE' });
    this.session.logoutUser();
    this.transitionTo('index');
  })
  logoutTask;
}
<commit_msg>Header: Fix `transitionTo()` call<commit_after>import { action } from '@ember/object';
import { inject as service } from '@ember/service';
import Component from '@glimmer/component';

import { task, waitForEvent } from 'ember-concurrency';
import window from 'ember-window-mock';

import ajax from '../utils/ajax';

export default class Header extends Component {
  @service header;
  @service notifications;
  @service router;
  @service session;

  @action
  search(event) {
    event.preventDefault();

    this.router.transitionTo('search', {
      queryParams: {
        q: this.header.searchValue,
        page: 1,
      },
    });
  }

  @action login() {
    this.loginTask.perform();
  }

  /**
   * This task will open a popup window directed at the `github-login` route.
   * After the window has opened it will wait for the window to send a message
   * back and then evaluate whether the OAuth flow was successful.
   *
   * @see `github-authorize` route
   */
  @task(function* () {
    let windowDimensions = [
      'width=1000',
      'height=450',
      'toolbar=0',
      'scrollbars=1',
      'status=1',
      'resizable=1',
      'location=1',
      'menuBar=0',
    ].join(',');

    let win = window.open('/github_login', 'Authorization', windowDimensions);
    if (!win) {
      return;
    }

    let event = yield waitForEvent(window, 'message');
    if (event.origin !== window.location.origin || !event.data) {
      return;
    }

    let { data } = event.data;
    if (data && data.errors) {
      this.notifications.error(`Failed to log in: ${data.errors[0].detail}`);
      return;
    } else if (!event.data.ok) {
      this.notifications.error('Failed to log in');
      return;
    }

    this.session.login();
  })
  loginTask;

  @task(function* () {
    yield ajax(`/api/private/session`, { method: 'DELETE' });
    this.session.logoutUser();
    this.router.transitionTo('index');
  })
  logoutTask;
}
<|endoftext|>


<commit_before>'use strict';

(function (angular) {
  angular
    .module('loyaltyPluginWidget')
    .controller('WidgetAmountCtrl', ['$scope', 'ViewStack', 'RewardCache', 'TAG_NAMES', 'DataStore', '$sce',
      function ($scope, ViewStack, RewardCache, TAG_NAMES, DataStore, $sce) {

        var WidgetAmount = this;

        WidgetAmount.dailyLimitExceeded = false;
        WidgetAmount.totalLimitExceeded = false;
        WidgetAmount.data = [];

        /**
         * Initialize variable with current view returned by ViewStack service. In this case it is "Item_Details" view.
         */
        var currentView = ViewStack.getCurrentView();

        if (RewardCache.getApplication()) {
          WidgetAmount.application = RewardCache.getApplication();
        }

        /*Get application data*/
        WidgetAmount.init = function () {
          WidgetAmount.success = function (result) {
            WidgetAmount.data = result.data;
          };
          WidgetAmount.error = function (err) {
            console.error('Error while getting data', err);
          };
          DataStore.get(TAG_NAMES.LOYALTY_INFO).then(WidgetAmount.success, WidgetAmount.error);
        };

        /*covert html symbols to currency symbol*/
        WidgetAmount.safeHtml = function (html) {
          if (html)
            return $sce.trustAsHtml(html);
        };

        WidgetAmount.onUpdateCallback = function (event) {
          setTimeout(function () {
            if (event && event.tag) {
              switch (event.tag) {
                case TAG_NAMES.LOYALTY_INFO:
                  WidgetAmount.data = event.data;
                  break;
              }
              $scope.$digest();
            }
          }, 0);
        };

        /**
         * DataStore.onUpdate() is bound to listen any changes in datastore
         */
        DataStore.onUpdate().then(null, null, WidgetAmount.onUpdateCallback);
        /**
         * Method to check if user has exceeded the total points limit.
         */
        WidgetAmount.init();
        WidgetAmount.confirmCode = function () {
          console.log("IIIIIIIIIIIIIIIII", WidgetAmount.amount);
          console.log("IIIIIIIIIIIIIIIII", WidgetAmount.application.pointsPerDollar);
          console.log("IIIIIIIIIIIIIIIII", WidgetAmount.application.pointsPerVisit);
          console.log("IIIIIIIIIIIIIIIII", currentView.loyaltyPoints);
          var calculatedPoints = (WidgetAmount.amount * WidgetAmount.application.pointsPerDollar) + WidgetAmount.application.pointsPerVisit + currentView.loyaltyPoints;
          if (WidgetAmount.application.totalPoints <= calculatedPoints) {
            WidgetAmount.totalLimitExceeded = true;
            setTimeout(function () {
              WidgetAmount.totalLimitExceeded = false;
              $scope.$digest();
            }, 3000);
          }
          else {
            ViewStack.push({
              template: 'Code',
              amount: WidgetAmount.amount
            });
          }
        };

      }]);
})(window.angular);
<commit_msg>Console logged type of some variables<commit_after>'use strict';

(function (angular) {
  angular
    .module('loyaltyPluginWidget')
    .controller('WidgetAmountCtrl', ['$scope', 'ViewStack', 'RewardCache', 'TAG_NAMES', 'DataStore', '$sce',
      function ($scope, ViewStack, RewardCache, TAG_NAMES, DataStore, $sce) {

        var WidgetAmount = this;

        WidgetAmount.dailyLimitExceeded = false;
        WidgetAmount.totalLimitExceeded = false;
        WidgetAmount.data = [];

        /**
         * Initialize variable with current view returned by ViewStack service. In this case it is "Item_Details" view.
         */
        var currentView = ViewStack.getCurrentView();

        if (RewardCache.getApplication()) {
          WidgetAmount.application = RewardCache.getApplication();
        }

        /*Get application data*/
        WidgetAmount.init = function () {
          WidgetAmount.success = function (result) {
            WidgetAmount.data = result.data;
          };
          WidgetAmount.error = function (err) {
            console.error('Error while getting data', err);
          };
          DataStore.get(TAG_NAMES.LOYALTY_INFO).then(WidgetAmount.success, WidgetAmount.error);
        };

        /*covert html symbols to currency symbol*/
        WidgetAmount.safeHtml = function (html) {
          if (html)
            return $sce.trustAsHtml(html);
        };

        WidgetAmount.onUpdateCallback = function (event) {
          setTimeout(function () {
            if (event && event.tag) {
              switch (event.tag) {
                case TAG_NAMES.LOYALTY_INFO:
                  WidgetAmount.data = event.data;
                  break;
              }
              $scope.$digest();
            }
          }, 0);
        };

        /**
         * DataStore.onUpdate() is bound to listen any changes in datastore
         */
        DataStore.onUpdate().then(null, null, WidgetAmount.onUpdateCallback);
        /**
         * Method to check if user has exceeded the total points limit.
         */
        WidgetAmount.init();
        WidgetAmount.confirmCode = function () {
          console.log("IIIIIIIIIIIIIIIII", WidgetAmount.amount, typeof WidgetAmount.amount);
          console.log("IIIIIIIIIIIIIIIII", WidgetAmount.application.pointsPerDollar, typeof WidgetAmount.application.pointsPerDollar);
          console.log("IIIIIIIIIIIIIIIII", WidgetAmount.application.pointsPerVisit, typeof WidgetAmount.application.pointsPerVisit);
          console.log("IIIIIIIIIIIIIIIII", currentView.loyaltyPoints, typeof currentView.loyaltyPoints);
          console.log("IIIIIIIIIIIIIIIII", WidgetAmount.application.totalPoints, typeof WidgetAmount.application.totalPoints);
          var calculatedPoints = (WidgetAmount.amount * WidgetAmount.application.pointsPerDollar) + WidgetAmount.application.pointsPerVisit + currentView.loyaltyPoints;
          console.log("IIIIIIIIIIIIIIIII", calculatedPoints, typeof calculatedPoints);
          console.log("IIIIIIIIIIIIIIIII", WidgetAmount.application.totalPoints <= calculatedPoints);
          if (WidgetAmount.application.totalPoints <= calculatedPoints) {
            WidgetAmount.totalLimitExceeded = true;
            setTimeout(function () {
              WidgetAmount.totalLimitExceeded = false;
              $scope.$digest();
            }, 3000);
          }
          else {
            ViewStack.push({
              template: 'Code',
              amount: WidgetAmount.amount
            });
          }
        };

      }]);
})(window.angular);
<|endoftext|>


<commit_before>#!/usr/bin/env node
;(function() {
  'use strict';

  /** The Node filesystem, path, and child process modules */
  var fs = require('fs'),
      path = require('path'),
      spawn = require('child_process').spawn;

  /** The build directory containing the build scripts */
  var buildPath = path.join(__dirname, 'build');

  /** The distribution directory */
  var distPath = path.join(__dirname, 'dist');

  /** Load the pre- and post-processors */
  var preprocess = require(path.join(buildPath, 'pre-compile')),
      postprocess = require(path.join(buildPath, 'post-compile'));

  /** The pre-processed Lo-Dash source */
  var source = preprocess(fs.readFileSync(path.join(__dirname, 'lodash.js'), 'utf8'));

  /** Load the UglifyJS compressor */
  var uglifyJS = require(path.join(__dirname, 'vendor', 'uglifyjs', 'uglify-js'));

  /*--------------------------------------------------------------------------*/

  /**
   * Compresses a `source` string using the Closure Compiler. Yields the
   * minified result, and any exceptions encountered, to a `callback` function.
   *
   * @private
   * @param {String} source The JavaScript source to minify.
   * @param {Function} callback The function called when minifying is complete.
   */
  function compile(source, callback) {
    var stderr = '',
        stdout = '';

    var compiler = spawn('java', [
      // load the Closure Compiler and set the compression options
      '-jar', path.join(__dirname, 'vendor', 'closure-compiler', 'compiler.jar'),
      '--compilation_level=ADVANCED_OPTIMIZATIONS',
      '--language_in=ECMASCRIPT5_STRICT',
      '--warning_level=QUIET'
    ]);

    // explicitly set the encoding of the output and error streams
    compiler.stdout.setEncoding('utf8');
    compiler.stderr.setEncoding('utf8');

    compiler.stdout.on('data', function(data) {
      stdout += data;
    });

    compiler.stderr.on('data', function(data) {
      stderr += data;
    });

    compiler.on('exit', function(status) {
      var exception = null;
      if (status) {
        exception = new Error(stderr);
        exception.status = status;
      }
      callback(exception, stdout);
    });

    // proxy the source string to Closure Compiler
    compiler.stdin.end(source);
  }

  /**
   * Compresses a `source` string using the Unix `gzip` commands. Yields the
   * result, and any exceptions encountered, to a `callback` function.
   *
   * @private
   * @param {String} source The JavaScript source to gzip.
   * @param {Function} callback The function called when gzipping is complete.
   */
  function gzip(source, callback) {
    var compressor = spawn('gzip', ['-9f', '-c']),
        stderr = '',
        stdout = '';

    compressor.stdout.setEncoding('binary');
    compressor.stderr.setEncoding('utf8');

    compressor.stdout.on('data', function(data) {
      stdout += data;
    });

    compressor.stderr.on('data', function(data) {
      stderr += data;
    });

    compressor.on('exit', function(status) {
      var exception = null;
      if (status) {
        exception = new Error(stderr);
        exception.status = status;
      }
      callback(exception, stdout);
    });

    // proxy the source string to the `gzip` executable
    compressor.stdin.end(source);
  }

  /*--------------------------------------------------------------------------*/

  // create the destination directory if it doesn't exist
  if (!path.existsSync(distPath)) {
    fs.mkdirSync(distPath);
  }

  // compress and `gzip` Lo-Dash using the Closure Compiler
  compile(source, function(exception, compiledSource) {
    if (exception) {
      throw exception;
    }

    // post-process the compiled source
    compiledSource = postprocess(compiledSource);

    // save the final compiled version
    fs.writeFileSync(path.join(distPath, 'lodash.compiler.js'), compiledSource);

    // `gzip` the compiled version
    gzip(compiledSource, function gzipCompiled(exception, result) {
      if (exception) {
        throw exception;
      }

      // record the size of the compiled version
      var compiledSize = result.length;

      // explicit `binary` encoding is necessary to ensure that the stream is written correctly
      fs.writeFileSync(path.join(distPath, 'lodash.compiler.js.gz'), result, 'binary');

      // compress Lo-Dash using UglifyJS
      var ugly = uglifyJS.uglify,
          uglifiedSource = ugly.gen_code(
            // enable unsafe transformations
            ugly.ast_squeeze_more(
              ugly.ast_squeeze(
                // munge variable and function names, excluding the special `define`
                // function exposed by AMD loaders
                ugly.ast_mangle(uglifyJS.parser.parse(source), {
                  'except': ['define']
                }
              ))), {
                'ascii_only': true
          });

      // post-process the uglified source and split lines at 500 characters for
      // consistency with Closure Compiler
      uglifiedSource = postprocess(ugly.split_lines(uglifiedSource, 500));

      // save the uglified version
      fs.writeFileSync(path.join(distPath, 'lodash.uglify.js'), uglifiedSource);

      // `gzip` the uglified version
      gzip(uglifiedSource, function gzipUglified(exception, result) {
        if (exception) {
          throw exception;
        }
        var uglifiedSize = result.length;
        fs.writeFileSync(path.join(distPath, 'lodash.uglify.js.gz'), result, 'binary');

        // select the smallest minified distribution and use it as the official
        // minified release
        fs.writeFileSync(path.join(__dirname, "lodash.min.js"), compiledSize < uglifiedSize ? compiledSource : uglifiedSource);
      });
    });
  });
}());
<commit_msg>`build.js`: Print compression status messages to the console.<commit_after>#!/usr/bin/env node
;(function() {
  'use strict';

  /** The Node filesystem, path, and child process modules */
  var fs = require('fs'),
      path = require('path'),
      spawn = require('child_process').spawn;

  /** The build directory containing the build scripts */
  var buildPath = path.join(__dirname, 'build');

  /** The distribution directory */
  var distPath = path.join(__dirname, 'dist');

  /** Load the pre- and post-processors */
  var preprocess = require(path.join(buildPath, 'pre-compile')),
      postprocess = require(path.join(buildPath, 'post-compile'));

  /** The pre-processed Lo-Dash source */
  var source = preprocess(fs.readFileSync(path.join(__dirname, 'lodash.js'), 'utf8'));

  /** Load the UglifyJS compressor */
  var uglifyJS = require(path.join(__dirname, 'vendor', 'uglifyjs', 'uglify-js'));

  /*--------------------------------------------------------------------------*/

  /**
   * Compresses a `source` string using the Closure Compiler. Yields the
   * minified result, and any exceptions encountered, to a `callback` function.
   *
   * @private
   * @param {String} source The JavaScript source to minify.
   * @param {Function} callback The function called when minifying is complete.
   */
  function compile(source, callback) {
    var stderr = '',
        stdout = '';

    var compiler = spawn('java', [
      // load the Closure Compiler and set the compression options
      '-jar', path.join(__dirname, 'vendor', 'closure-compiler', 'compiler.jar'),
      '--compilation_level=ADVANCED_OPTIMIZATIONS',
      '--language_in=ECMASCRIPT5_STRICT',
      '--warning_level=QUIET'
    ]);

    // explicitly set the encoding of the output and error streams
    compiler.stdout.setEncoding('utf8');
    compiler.stderr.setEncoding('utf8');

    compiler.stdout.on('data', function(data) {
      stdout += data;
    });

    compiler.stderr.on('data', function(data) {
      stderr += data;
    });

    compiler.on('exit', function(status) {
      var exception = null;
      if (status) {
        exception = new Error(stderr);
        exception.status = status;
      }
      callback(exception, stdout);
    });

    // proxy the source string to Closure Compiler
    compiler.stdin.end(source);
  }

  /**
   * Compresses a `source` string using the Unix `gzip` commands. Yields the
   * result, and any exceptions encountered, to a `callback` function.
   *
   * @private
   * @param {String} source The JavaScript source to gzip.
   * @param {Function} callback The function called when gzipping is complete.
   */
  function gzip(source, callback) {
    var compressor = spawn('gzip', ['-9f', '-c']),
        stderr = '',
        stdout = '';

    compressor.stdout.setEncoding('binary');
    compressor.stderr.setEncoding('utf8');

    compressor.stdout.on('data', function(data) {
      stdout += data;
    });

    compressor.stderr.on('data', function(data) {
      stderr += data;
    });

    compressor.on('exit', function(status) {
      var exception = null;
      if (status) {
        exception = new Error(stderr);
        exception.status = status;
      }
      callback(exception, stdout);
    });

    // proxy the source string to the `gzip` executable
    compressor.stdin.end(source);
  }

  /*--------------------------------------------------------------------------*/

  // create the destination directory if it doesn't exist
  if (!path.existsSync(distPath)) {
    fs.mkdirSync(distPath);
  }

  // compress and `gzip` Lo-Dash using the Closure Compiler
  compile(source, function(exception, compiledSource) {
    if (exception) {
      throw exception;
    }

    console.log("Compressing Lodash using the Closure Compiler...");

    // post-process the compiled source
    compiledSource = postprocess(compiledSource);

    // save the final compiled version
    fs.writeFileSync(path.join(distPath, 'lodash.compiler.js'), compiledSource);

    // `gzip` the compiled version
    gzip(compiledSource, function gzipCompiled(exception, result) {
      if (exception) {
        throw exception;
      }

      // record the size of the compiled version
      var compiledSize = result.length;

      // explicit `binary` encoding is necessary to ensure that the stream is written correctly
      fs.writeFileSync(path.join(distPath, 'lodash.compiler.js.gz'), result, 'binary');

      console.log("Done. Size: %d KB.", compiledSize);

      // compress Lo-Dash using UglifyJS
      var ugly = uglifyJS.uglify,
          uglifiedSource = ugly.gen_code(
            // enable unsafe transformations
            ugly.ast_squeeze_more(
              ugly.ast_squeeze(
                // munge variable and function names, excluding the special `define`
                // function exposed by AMD loaders
                ugly.ast_mangle(uglifyJS.parser.parse(source), {
                  'except': ['define']
                }
              ))), {
                'ascii_only': true
          });

      console.log("Compressing Lodash using UglifyJS...");

      // post-process the uglified source and split lines at 500 characters for
      // consistency with Closure Compiler
      uglifiedSource = postprocess(ugly.split_lines(uglifiedSource, 500));

      // save the uglified version
      fs.writeFileSync(path.join(distPath, 'lodash.uglify.js'), uglifiedSource);

      // `gzip` the uglified version
      gzip(uglifiedSource, function gzipUglified(exception, result) {
        if (exception) {
          throw exception;
        }
        var uglifiedSize = result.length;
        fs.writeFileSync(path.join(distPath, 'lodash.uglify.js.gz'), result, 'binary');

        console.log("Done. Size: %d KB.", uglifiedSize);

        // select the smallest minified distribution and use it as the official
        // minified release
        fs.writeFileSync(path.join(__dirname, "lodash.min.js"), compiledSize < uglifiedSize ? compiledSource : uglifiedSource);
      });
    });
  });
}());
<|endoftext|>


<commit_before>var Simulation = {
    initialize : function() {
        // Init rotors
        this.rotors = [];
        for (var i = 0; i < 3; i++) {
            this.rotors[i] = new Rotor(i);
        }

        // Create key listener
        document.onkeydown = function(event) {
            Simulation.key_press_handler(String.fromCharCode(event.keyCode));
        };

        // Init display
        Display.initialize();
        Display.update();
    },

    encrypt : function(key) {
        // Perform the encryption
        return "A";
    },

    key_press_handler : function(key) {
        // Remove old highlights
        var prevpt = document.getElementsByClassName("pthighlight");
        if (prevpt[0] != undefined)
            prevpt[0].classList.remove("pthighlight");
        var prevct = document.getElementsByClassName("cthighlight");
        if (prevct[0] != undefined)
            prevct[0].classList.remove("cthighlight");

        // Highlight plaintext
        document.getElementById("key_" + key).classList.add("pthighlight");

        // Highlight ciphertext
        var ct = Simulation.encrypt(key);
        document.getElementById("key_" + ct).classList.add("cthighlight");

        // Add text to text panes
        // TODO: should probably move this
        document.getElementById("tp_pt").innerHTML =
            document.getElementById("tp_pt").innerHTML + " " + key;
        document.getElementById("tp_ct").innerHTML =
            document.getElementById("tp_ct").innerHTML + " " + ct;
    },

    rotor_set_listener : function(event) {
        // Function to call when rotor up or down clicked
        var rtr = event.target.parentNode.id.charAt(6) - 1;
        Simulation.rotors[rtr].change_init_pos((event.target.className == "up") ? -1 : 1);
        Display.update();
    }
};

var Display = {
    initialize : function() {
        this.rotor_disp = [];

        // Create rotor display
        for (var i = 1; i < 4; i++) {

            // Create rotor div
            var parent_d = document.createElement("div");
            parent_d.className = "rotor";
            parent_d.id = "rotor_" + i;
            document.getElementById("rotor_pane").appendChild(parent_d);

            // Create up arrow
            var up_d = document.createElement("div");
            up_d.innerHTML = '↑';
            up_d.className = "up";
            up_d.onclick = Simulation.rotor_set_listener;
            parent_d.appendChild(up_d);

            // Create rotor disp
            var rotor_d = document.createElement("div");
            this.rotor_disp[i - 1] = rotor_d;
            parent_d.appendChild(rotor_d);

            // Create down arrow
            var down_d = document.createElement("div");
            down_d.innerHTML = '↓';
            down_d.className = "down";
            down_d.onclick = Simulation.rotor_set_listener;
            parent_d.appendChild(down_d);

        }
        // Create keys display
        for (var i = 0; i < 26; i++) {
            var key = document.createElement("div");
            var letter = String.fromCharCode(65 + i);
            key.id = "key_" + letter;
            key.innerHTML = letter;
            key.onclick = function(event) {
                Simulation.key_press_handler(event.target.id.charAt(4));
            }
            document.getElementById("key_pane").appendChild(key);
        }
    },

    update : function() {
        // Update rotor letters
        for (var i = 0; i < 3; i++)
            this.rotor_disp[i].innerHTML = Simulation.rotors[i].pos;
    }
};

function Rotor(id) {
    // Rotor position
    this.pos = 'A';

    // Rotor wiring, from rotor_wiring.js
    this.wiring = rotor_wirings[id];

    this.change_init_pos = function(change_by) {
        // Set rotor starting position
        if (change_by == 1 && this.pos == 'Z')
            this.pos = 'A';
        else if (change_by == -1 && this.pos == 'A')
            this.pos = 'Z';
        else
            this.pos = String.fromCharCode(this.pos.charCodeAt() + change_by);
    };

    this.sub_letter = function(letter) {
        // Do the substitution cipher for this rotor
    };
}
<commit_msg>Refactor of key_press_handler<commit_after>var Simulation = {
    initialize : function() {
        // Init rotors
        this.rotors = [];
        for (var i = 0; i < 3; i++) {
            this.rotors[i] = new Rotor(i);
        }

        // Create key listener
        document.onkeydown = function(event) {
            Simulation.key_press_handler(String.fromCharCode(event.keyCode));
        };

        // Init display
        Display.initialize();
        Display.update();
    },

    encrypt : function(key) {
        // Perform the encryption
        return "A";
    },

    key_press_handler : function(key) {
        // Check if key is in acceptable range
        if (key.charCodeAt() < 65 || key.charCodeAt() > 90)
            return;

        // Set current key
        this.ckey = key;
        // Set current ciphertext key
        this.cct = Simulation.encrypt(key);

        // Update display
        Display.update();
    },

    rotor_set_listener : function(event) {
        // Function to call when rotor up or down clicked
        var rtr = event.target.parentNode.id.charAt(6) - 1;
        Simulation.rotors[rtr].change_init_pos((event.target.className == "up") ? -1 : 1);
        Display.update();
    }
};

var Display = {
    initialize : function() {
        this.rotor_disp = [];

        // Create rotor display
        for (var i = 1; i < 4; i++) {

            // Create rotor div
            var parent_d = document.createElement("div");
            parent_d.className = "rotor";
            parent_d.id = "rotor_" + i;
            document.getElementById("rotor_pane").appendChild(parent_d);

            // Create up arrow
            var up_d = document.createElement("div");
            up_d.innerHTML = '↑';
            up_d.className = "up";
            up_d.onclick = Simulation.rotor_set_listener;
            parent_d.appendChild(up_d);

            // Create rotor disp
            var rotor_d = document.createElement("div");
            this.rotor_disp[i - 1] = rotor_d;
            parent_d.appendChild(rotor_d);

            // Create down arrow
            var down_d = document.createElement("div");
            down_d.innerHTML = '↓';
            down_d.className = "down";
            down_d.onclick = Simulation.rotor_set_listener;
            parent_d.appendChild(down_d);

        }
        // Create keys display
        for (var i = 0; i < 26; i++) {
            var key = document.createElement("div");
            var letter = String.fromCharCode(65 + i);
            key.id = "key_" + letter;
            key.innerHTML = letter;
            key.onclick = function(event) {
                Simulation.key_press_handler(event.target.id.charAt(4));
            }
            document.getElementById("key_pane").appendChild(key);
        }
    },

    update : function() {
        // Update rotor letters
        for (var i = 0; i < 3; i++)
            this.rotor_disp[i].innerHTML = Simulation.rotors[i].pos;

        // Remove old highlights
        var prevpt = document.getElementsByClassName("pthighlight");
        if (prevpt[0] != undefined)
            prevpt[0].classList.remove("pthighlight");
        var prevct = document.getElementsByClassName("cthighlight");
        if (prevct[0] != undefined)
            prevct[0].classList.remove("cthighlight");

        // Highlight plaintext
        document.getElementById("key_" + Simulation.ckey).classList.add("pthighlight");

        // Highlight ciphertext
        document.getElementById("key_" + Simulation.cct).classList.add("cthighlight");

        // Add text to text panes
        document.getElementById("tp_pt").innerHTML =
            document.getElementById("tp_pt").innerHTML + " " + Simulation.ckey;
        document.getElementById("tp_ct").innerHTML =
            document.getElementById("tp_ct").innerHTML + " " + Simulation.cct;
    }
};

function Rotor(id) {
    // Rotor position
    this.pos = 'A';

    // Rotor wiring, from rotor_wiring.js
    this.wiring = rotor_wirings[id];

    this.change_init_pos = function(change_by) {
        // Set rotor starting position
        if (change_by == 1 && this.pos == 'Z')
            this.pos = 'A';
        else if (change_by == -1 && this.pos == 'A')
            this.pos = 'Z';
        else
            this.pos = String.fromCharCode(this.pos.charCodeAt() + change_by);
    };

    this.sub_letter = function(letter) {
        // Do the substitution cipher for this rotor
    };
}
<|endoftext|>


<commit_before>/**
 * client.module.js
 * Created by anonymous on 09/12/15 13:12.
 */

(function() {
    'use strict';

    angular
        .module('client', [
            /* Shared */
            'appFoundation',
            'widgets',

            /* components */
            'seneschal',
            'dashboard',
            'posts'
        ]);

})();<commit_msg>Modified client.module<commit_after>/**
 * client.module.js
 * Created by anonymous on 09/12/15 13:12.
 */

(function() {
    'use strict';

    angular
        .module('client', [
            /* Shared */

            /* Components */

        ]);

})();<|endoftext|>


<commit_before>// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Enhance a textarea with auto growing rows to fit the content.
 *
 * @module     core/auto_rows
 * @class      auto_rows
 * @package    core
 * @copyright  2016 Ryan Wyllie <ryan@moodle.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since      3.2
 */
define(['jquery'], function($) {
    var SELECTORS = {
        ELEMENT: '[data-auto-rows]'
    };

    var EVENTS = {
        ROW_CHANGE: 'autorows:rowchange',
    };

    /**
     * Determine how many rows should be set for the given element.
     *
     * @method calculateRows
     * @param {jQuery} element The textarea element
     * @return {int} The number of rows for the element
     * @private
     */
    var calculateRows = function(element) {
        var currentRows = element.attr('rows');
        var maxRows = element.attr('data-max-rows');

        var height = element.height();
        var innerHeight = element.innerHeight();
        var padding = innerHeight - height;

        // Set height to 1ox to force scroll height to calculate correctly.
        element.height('1px');

        var scrollHeight = element[0].scrollHeight;
        var rows = (scrollHeight - padding) / (height / currentRows);

        // Remove the height styling to let the height be calculated automatically
        // based on the row attribute.
        element.css('height', '');

        if (maxRows && rows >= maxRows) {
            return maxRows;
        } else {
            return rows;
        }
    };

    /**
     * Add the event listeners for all text areas within the given element.
     *
     * @method init
     * @param {jQuery|selector} root The container element of all enhanced text areas
     * @public
     */
    var init = function(root) {
        $(root).on('input propertychange', SELECTORS.ELEMENT, function(e) {
            var element = $(e.target);
            var currentRows = element.attr('rows');
            var rows = calculateRows(element);

            if (rows != currentRows) {
                element.attr('rows', rows);
                $(document).trigger(EVENTS.ROW_CHANGE);
            }
        });
    };

    return /** @module core/auto_rows */ {
        init: init,
        events: EVENTS,
    };
});
<commit_msg>MDL-56292 core: auto_rows should fire event on element<commit_after>// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Enhance a textarea with auto growing rows to fit the content.
 *
 * @module     core/auto_rows
 * @class      auto_rows
 * @package    core
 * @copyright  2016 Ryan Wyllie <ryan@moodle.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since      3.2
 */
define(['jquery'], function($) {
    var SELECTORS = {
        ELEMENT: '[data-auto-rows]'
    };

    var EVENTS = {
        ROW_CHANGE: 'autorows:rowchange',
    };

    /**
     * Determine how many rows should be set for the given element.
     *
     * @method calculateRows
     * @param {jQuery} element The textarea element
     * @return {int} The number of rows for the element
     * @private
     */
    var calculateRows = function(element) {
        var currentRows = element.attr('rows');
        var maxRows = element.attr('data-max-rows');

        var height = element.height();
        var innerHeight = element.innerHeight();
        var padding = innerHeight - height;

        // Set height to 1ox to force scroll height to calculate correctly.
        element.height('1px');

        var scrollHeight = element[0].scrollHeight;
        var rows = (scrollHeight - padding) / (height / currentRows);

        // Remove the height styling to let the height be calculated automatically
        // based on the row attribute.
        element.css('height', '');

        if (maxRows && rows >= maxRows) {
            return maxRows;
        } else {
            return rows;
        }
    };

    /**
     * Add the event listeners for all text areas within the given element.
     *
     * @method init
     * @param {jQuery|selector} root The container element of all enhanced text areas
     * @public
     */
    var init = function(root) {
        $(root).on('input propertychange', SELECTORS.ELEMENT, function(e) {
            var element = $(e.target);
            var currentRows = element.attr('rows');
            var rows = calculateRows(element);

            if (rows != currentRows) {
                element.attr('rows', rows);
                $(root).trigger(EVENTS.ROW_CHANGE);
            }
        });
    };

    return /** @module core/auto_rows */ {
        init: init,
        events: EVENTS,
    };
});
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

/**
 * Quiz Schema
 */
var QuizSchema = new Schema({
  created: {
    type: Date,
    default: Date.now
  },
  title: {
    type: String,
    default: '',
    trim: true,
    required: 'Title cannot be blank'
  },
  question: {
    type: String,
    default: '',
    trim: true
  },
  user: { //The professor who created the quiz
    type: Schema.ObjectId,
    ref: 'User'
  },
  courseID: {
    type: String
  } /* May need to modify later */
});

mongoose.model('Quiz', QuizSchema);
<commit_msg>updated quiz schema<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

/**
 * Quiz Schema
 */
var QuizSchema = new Schema({
  created: {
    type: Date,
    default: Date.now
  },
  title: {
    type: String,
    default: '',
    trim: true,
    required: 'Title cannot be blank'
  },
  question: {
    type: String,
    default: '',
    trim: true
  },
  choices: { /* limit possible choices to 5? */
    type: [{
      letter: {
        type: String //Should be auto assigned by system - A, B, C, D....
      },
      description: {
        type: String,
        required: 'Answer description cannot be blank'
      }
    }]
  },
  correctAnswer: {
    type: String //A, B, C, D
  },
  user: { //The professor who created the quiz
    type: Schema.ObjectId,
    ref: 'User'
  },
  courseID: {
    type: String
  } /* May need to modify later */
});

mongoose.model('Quiz', QuizSchema);
<|endoftext|>


<commit_before>import React, { Component } from 'react'

import '../assets/sass/slider.sass'
import reactImg from '../assets/imgs/react.svg'
import codeImg from '../assets/imgs/code.svg'
import cubeImg from '../assets/imgs/cube.svg'

class Slider extends Component {
  state = {
    whichModule: 0,
    content: [
      {
        heading: 'Rapid Prototyping & Ideation',
        img: cubeImg,
        copy: 'All projects have people they are supposed to serve. I quickly translate business requeriments into experince that satisfy users on all their devices; in 2019. Make Options Great Again.'
      },
      {
        heading: 'JavaScript Utilization',
        img: reactImg,
        copy: 'I love JavaScript...a lot! I can use it in lots of ways, but React/React Native are my frameworks of choice.'
      },
      {
        heading: 'Execution & Delivery',
        img: codeImg,
        copy: "I've worked on some pretty interesting projects..."
      }
    ]
  }

  render() {
    return(

          {this.state.content[this.state.whichModule].heading}

          {this.state.content[this.state.whichModule].copy}

    )
  }
}

export default Slider
<commit_msg>add ternary expressions to bind popout show or not show<commit_after>import React, { Component } from 'react'
import FAQ from './FAQ'

import '../assets/sass/slider.sass'
import reactImg from '../assets/imgs/react.svg'
import codeImg from '../assets/imgs/code.svg'
import cubeImg from '../assets/imgs/cube.svg'
import Popout from './Popout'

class Slider extends Component {
  state = {
    content: [
      {
        heading: 'Rapid Prototyping & Ideation',
        img: cubeImg,
        copy: 'All projects have people they are supposed to serve. I quickly translate business requeriments into experince that satisfy users on all their devices; in 2019. Make Options Great Again.'
      },
      {
        heading: 'JavaScript Utilization',
        img: reactImg,
        copy: 'I love JavaScript...a lot! I can use it in lots of ways, but React/React Native are my frameworks of choice.'
      },
      {
        heading: 'Execution & Delivery',
        img: codeImg,
        copy: "I've worked on some pretty interesting projects..."
      }
    ],
    popoutHidden: true,
    popoutData: null
  }

  openPopout = (clickedFAQ) => {
    this.setState({ popoutHidden: false, popoutData: clickedFAQ })
  }

  closePopout = () => {
    this.setState({ popoutHidden: true })
  }

  render() {
    const FAQs = this.state.content.map((item, index) => {
      return <FAQ key={index} img={item.img} heading={item.heading} copy={item.copy} openPopout={(clickedFAQ) => this.openPopout(clickedFAQ)}/>
    })
    return(

          {FAQs}

          <Popout heading={ this.state.popoutData === null ? '' : this.state.popoutData.heading } copy={ this.state.popoutData === null ? '' : this.state.popoutData.copy }/>

    )
  }
}

export default Slider
<|endoftext|>


<commit_before>var pokemons = [
  "Bulbasaur",
  "Ivysaur",
  "Venusaur",
  "Charmander",
  "Charmeleon",
  "Charizard",
  "Squirtle",
  "Wartortle",
  "Blastoise",
  "Caterpie",
  "Metapod",
  "Butterfree",
  "Weedle",
  "Kakuna",
  "Beedrill",
  "Pidgey",
  "Pidgeotto",
  "Pidgeot",
  "Rattata",
  "Raticate",
  "Spearow",
  "Fearow",
  "Ekans",
  "Arbok",
  "Pikachu",
  "Raichu",
  "Sandshrew",
  "Sandslash",
  "Nidoran♀",
  "Nidorina",
  "Nidoqueen",
  "Nidoran♂",
  "Nidorino",
  "Nidoking",
  "Clefairy",
  "Clefable",
  "Vulpix",
  "Ninetales",
  "Jigglypuff",
  "Wigglytuff",
  "Zubat",
  "Golbat",
  "Oddish",
  "Gloom",
  "Vileplume",
  "Paras",
  "Parasect",
  "Venonat",
  "Venomoth",
  "Diglett",
  "Dugtrio",
  "Meowth",
  "Persian",
  "Psyduck",
  "Golduck",
  "Mankey",
  "Primeape",
  "Growlithe",
  "Arcanine",
  "Poliwag",
  "Poliwhirl",
  "Poliwrath",
  "Abra",
  "Kadabra",
  "Alakazam",
  "Machop",
  "Machoke",
  "Machamp",
  "Bellsprout",
  "Weepinbell",
  "Victreebel",
  "Tentacool",
  "Tentacruel",
  "Geodude",
  "Graveler",
  "Golem",
  "Ponyta",
  "Rapidash",
  "Slowpoke",
  "Slowbro",
  "Magnemite",
  "Magneton",
  "Farfetch'd",
  "Duduo",
  "Dodrio",
  "Seel",
  "Dewgong",
  "Grimer",
  "Muk",
  "Shellder",
  "Cloyster",
  "Gastly",
  "Haunter",
  "Gengar",
  "Onix",
  "Drowzee",
  "Hypno",
  "Krabby",
  "Kingler",
  "Voltorb",
  "Electrode",
  "Exeggcute",
  "Exeggutor",
  "Cubone",
  "Marowak",
  "Hitmonlee",
  "Hitmonchan",
  "Lickitung",
  "Koffing",
  "Weezing",
  "Rhyhorn",
  "Rhydon",
  "Chansey",
  "Tangela",
  "Kangaskhan",
  "Horsea",
  "Seadra",
  "Goldeen",
  "Seaking",
  "Staryu",
  "Starmie",
  "MrMime",
  "Scyther",
  "Jynx",
  "Electabuzz",
  "Magmar",
  "Pinsir",
  "Tauros",
  "Magikarp",
  "Gyarados",
  "Lapras",
  "Ditto",
  "Eevee",
  "Vaporeon",
  "Jolteon",
  "Flareon",
  "Porygon",
  "Omanyte",
  "Omastar",
  "Kabuto",
  "Kabutops",
  "Aerodactyl",
  "Snorlax",
  "Articuno",
  "Zapdos",
  "Moltres",
  "Dratini",
  "Dragonair",
  "Dragonite",
  "Mewtwo",
  "Mew"
];

function getPokemonBasicInfo(pokemonName) {
	var xhttp = new XMLHttpRequest();
	xhttp.onreadystatechange = function() {
		if (xhttp.readyState == 4 && xhttp.status == 200) {
			var pokemon = {};
			pokemon.name = pokemonName;

			var el = document.createElement( 'html' );
			el.innerHTML = xhttp.responseText;

			// get evolution data
			var evolutionsList = el.getElementsByClassName('evolution-profile')[0];
			pokemon.evolution = [];
			for(var i = 0; i < evolutionsList.children.length; i++) {
				pokemon.evolution.push(evolutionsList.children[i].getElementsByTagName('a')[0].href.replace('file:///us/pokedex/', ''));

			}
			// get weaknesses
			var weaknessesList = el.getElementsByClassName('dtm-weaknesses')[0].children[1].getElementsByTagName('li');
			pokemon.weaknesses = [];
			for(var i = 0; i < weaknessesList.length; i++) {
				pokemon.weaknesses.push(weaknessesList[i].innerText.trim());

			}
			// get type
			var typeList = el.getElementsByClassName('dtm-type')[0].children[1].getElementsByTagName('li');
			pokemon.type = [];

			for(var i = 0; i < typeList.length; i++) {
				pokemon.type.push(typeList[i].innerText.trim());

			}
			console.log(pokemon);
		}
	};

	xhttp.open("GET", "http://www.pokemon.com/us/pokedex/" + pokemonName, true);
	xhttp.setRequestHeader('Access-Control-Allow-Origin', '*');
	xhttp.setRequestHeader('Access-Control-Allow-Methods', 'GET');
	xhttp.send();
}

for(i = 0; i < 1; i++) {
	console.log(getPokemonBasicInfo(pokemons[i]));
}<commit_msg>Retrive stats for pokemons<commit_after>var pokemons = [
  "Bulbasaur",
  "Ivysaur",
  "Venusaur",
  "Charmander",
  "Charmeleon",
  "Charizard",
  "Squirtle",
  "Wartortle",
  "Blastoise",
  "Caterpie",
  "Metapod",
  "Butterfree",
  "Weedle",
  "Kakuna",
  "Beedrill",
  "Pidgey",
  "Pidgeotto",
  "Pidgeot",
  "Rattata",
  "Raticate",
  "Spearow",
  "Fearow",
  "Ekans",
  "Arbok",
  "Pikachu",
  "Raichu",
  "Sandshrew",
  "Sandslash",
  "Nidoran♀",
  "Nidorina",
  "Nidoqueen",
  "Nidoran♂",
  "Nidorino",
  "Nidoking",
  "Clefairy",
  "Clefable",
  "Vulpix",
  "Ninetales",
  "Jigglypuff",
  "Wigglytuff",
  "Zubat",
  "Golbat",
  "Oddish",
  "Gloom",
  "Vileplume",
  "Paras",
  "Parasect",
  "Venonat",
  "Venomoth",
  "Diglett",
  "Dugtrio",
  "Meowth",
  "Persian",
  "Psyduck",
  "Golduck",
  "Mankey",
  "Primeape",
  "Growlithe",
  "Arcanine",
  "Poliwag",
  "Poliwhirl",
  "Poliwrath",
  "Abra",
  "Kadabra",
  "Alakazam",
  "Machop",
  "Machoke",
  "Machamp",
  "Bellsprout",
  "Weepinbell",
  "Victreebel",
  "Tentacool",
  "Tentacruel",
  "Geodude",
  "Graveler",
  "Golem",
  "Ponyta",
  "Rapidash",
  "Slowpoke",
  "Slowbro",
  "Magnemite",
  "Magneton",
  "Farfetch'd",
  "Duduo",
  "Dodrio",
  "Seel",
  "Dewgong",
  "Grimer",
  "Muk",
  "Shellder",
  "Cloyster",
  "Gastly",
  "Haunter",
  "Gengar",
  "Onix",
  "Drowzee",
  "Hypno",
  "Krabby",
  "Kingler",
  "Voltorb",
  "Electrode",
  "Exeggcute",
  "Exeggutor",
  "Cubone",
  "Marowak",
  "Hitmonlee",
  "Hitmonchan",
  "Lickitung",
  "Koffing",
  "Weezing",
  "Rhyhorn",
  "Rhydon",
  "Chansey",
  "Tangela",
  "Kangaskhan",
  "Horsea",
  "Seadra",
  "Goldeen",
  "Seaking",
  "Staryu",
  "Starmie",
  "MrMime",
  "Scyther",
  "Jynx",
  "Electabuzz",
  "Magmar",
  "Pinsir",
  "Tauros",
  "Magikarp",
  "Gyarados",
  "Lapras",
  "Ditto",
  "Eevee",
  "Vaporeon",
  "Jolteon",
  "Flareon",
  "Porygon",
  "Omanyte",
  "Omastar",
  "Kabuto",
  "Kabutops",
  "Aerodactyl",
  "Snorlax",
  "Articuno",
  "Zapdos",
  "Moltres",
  "Dratini",
  "Dragonair",
  "Dragonite",
  "Mewtwo",
  "Mew"
];

function getPokemonBasicInfo(pokemonName) {
	var xhttp = new XMLHttpRequest();
	xhttp.onreadystatechange = function() {
		if (xhttp.readyState == 4 && xhttp.status == 200) {
			var pokemon = {};
			pokemon.name = pokemonName;

			var el = document.createElement( 'html' );
			el.innerHTML = xhttp.responseText;

			// get evolution data
			var evolutionsList = el.getElementsByClassName('evolution-profile')[0];
			pokemon.evolution = [];
			for(var i = 0; i < evolutionsList.children.length; i++) {
				pokemon.evolution.push(evolutionsList.children[i].getElementsByTagName('a')[0].href.replace('file:///us/pokedex/', ''));

			}
			// get weaknesses
			var weaknessesList = el.getElementsByClassName('dtm-weaknesses')[0].children[1].getElementsByTagName('li');
			pokemon.weaknesses = [];
			for(var i = 0; i < weaknessesList.length; i++) {
				pokemon.weaknesses.push(weaknessesList[i].innerText.trim());

			}
			// get type
			var typeList = el.getElementsByClassName('dtm-type')[0].children[1].getElementsByTagName('li');
			pokemon.type = [];

			for(var i = 0; i < typeList.length; i++) {
				pokemon.type.push(typeList[i].innerText.trim());

			}

			// get stats
			var statsList = el.getElementsByClassName('pokemon-stats-info active')[0].children[1].getElementsByTagName('ul');
			alert(statsList.length);
			console.log(statsList);
			pokemon.stats = [];
			pokemon.stats.HP = statsList[0].getElementsByTagName('li')[0].getAttribute('data-value');
			pokemon.stats.Attack = statsList[1].getElementsByTagName('li')[0].getAttribute('data-value');
			pokemon.stats.Defense = statsList[2].getElementsByTagName('li')[0].getAttribute('data-value');
			pokemon.stats.SpecialAttack = statsList[3].getElementsByTagName('li')[0].getAttribute('data-value');
			pokemon.stats.SpecialDefense = statsList[4].getElementsByTagName('li')[0].getAttribute('data-value');
			pokemon.stats.Speed = statsList[5].getElementsByTagName('li')[0].getAttribute('data-value');

			console.log(pokemon);
		}
	};

	xhttp.open("GET", "http://www.pokemon.com/us/pokedex/" + pokemonName, true);
	xhttp.setRequestHeader('Access-Control-Allow-Origin', '*');
	xhttp.setRequestHeader('Access-Control-Allow-Methods', 'GET');
	xhttp.send();
}

for(i = 0; i < 1; i++) {
	console.log(getPokemonBasicInfo(pokemons[i]));
}<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

require('./dist/app');
<commit_msg>Make sure cspell-tools run<commit_after>#!/usr/bin/env node

'use strict';

const app = require('./dist/app');
const program = require('commander');

app.run(program, process.argv).catch(() => process.exit(1));
<|endoftext|>


<commit_before>$(document).ready(function () {

    get_data = {
        project: READTHEDOCS_DATA['project'],
        version: READTHEDOCS_DATA['version'],
        page: READTHEDOCS_DATA['page'],
        theme: READTHEDOCS_DATA['theme'],
        format: "jsonp",
    };

    // Crappy heuristic, but people change the theme name on us.
    // So we have to do some duck typing.
    var USING_RTD_THEME = (READTHEDOCS_DATA['theme'] == 'sphinx_rtd_theme') || $('div.rst-other-versions').length == 1;

    if ("docroot" in READTHEDOCS_DATA) {
      get_data['docroot'] = READTHEDOCS_DATA['docroot'];
    }

    if ("source_suffix" in READTHEDOCS_DATA) {
      get_data['source_suffix'] = READTHEDOCS_DATA['source_suffix'];
    }

    var API_HOST = READTHEDOCS_DATA['api_host'];
    if (API_HOST === undefined) {
      API_HOST = 'https://readthedocs.org';
    }

    if (window.location.pathname.indexOf('/projects/') === 0) {
      get_data['subproject'] = true;
    }

    // Theme popout code
    $.ajax({
      url: API_HOST + "/api/v2/footer_html/",
      crossDomain: true,
      xhrFields: {
        withCredentials: true,
      },
      dataType: "jsonp",
      data: get_data,
      success: function (data) {
            // If the theme looks like ours, update the existing badge
            // otherwise throw a a full one into the page.
            if (USING_RTD_THEME) {
              $("div.rst-other-versions").html(data['html']);
            } else {
              $("body").append(data['html']);
            }

            if (!data['version_active']) {
                $('.rst-current-version').addClass('rst-out-of-date');
            } else if (!data['version_supported']) {
                //$('.rst-current-version').addClass('rst-active-old-version')
            }

            // using jQuery
            function getCookie(name) {
                var cookieValue = null;
                if (document.cookie && document.cookie !== '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = jQuery.trim(cookies[i]);
                        // Does this cookie string begin with the name we want?
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }

              function csrfSafeMethod(method) {
                  // these HTTP methods do not require CSRF protection
                  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
              }
              var csrftoken = getCookie('csrftoken');
              $.ajaxSetup({
                  beforeSend: function(xhr, settings) {
                      if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                          xhr.setRequestHeader("X-CSRFToken", csrftoken);
                      }
                  }
              });

            // Bookmark Handling
            data = {
                project: READTHEDOCS_DATA['project'],
                version: READTHEDOCS_DATA['version'],
                page: READTHEDOCS_DATA['page'],
                url: document.location.origin + document.location.pathname
            };

            // ask the server if a bookmark exists for this page so we can show the proper icon
            $.ajax({
                    type: 'POST',
                    url: API_HOST + "/bookmarks/exists/",
                    crossDomain: true,
                    xhrFields: {
                      withCredentials: true,
                    },
                    data: JSON.stringify(data),
                    success: function (data) {
                      $(".bookmark-active").show();
                    },
                    error: function(data) {
                      $(".bookmark-inactive").show();
                    },
                    dataType: 'json'
            });

            $(".bookmark-icon").on('click', function (event) {
              var bookmarked = $('.bookmark-active').is(':visible');
              $('div.bookmark-active').toggle();
              $('div.bookmark-inactive').toggle();

              if (bookmarked) {
                  $.ajax({
                    type: "POST",
                    crossDomain: true,
                    xhrFields: {
                      withCredentials: true,
                    },
                    url: API_HOST + "/bookmarks/remove/",
                    data: JSON.stringify(data),
                    });
                  //$(".bookmark-added-msg").hide();
              } else {
                  $.ajax({
                    type: "POST",
                    crossDomain: true,
                    xhrFields: {
                      withCredentials: true,
                    },
                    url: API_HOST + "/bookmarks/add/",
                    data: JSON.stringify(data),
                    });
                    //$(".bookmark-added-msg").html("
Bookmark added
");
                    //$(".bookmark-added-msg").show();
              }
            });
      },
      error: function () {
          console.log('Error loading Read the Docs footer');
      }
    });

    /// Read the Docs theme code

    // Shift nav in mobile when clicking the menu.
    $(document).on('click', "[data-toggle='wy-nav-top']", function() {
      $("[data-toggle='wy-nav-shift']").toggleClass("shift");
      $("[data-toggle='rst-versions']").toggleClass("shift");
    });
    // Close menu when you click a link.
    $(document).on('click', ".wy-menu-vertical .current ul li a", function() {
      $("[data-toggle='wy-nav-shift']").removeClass("shift");
      $("[data-toggle='rst-versions']").toggleClass("shift");
    });
    $(document).on('click', "[data-toggle='rst-current-version']", function() {
      $("[data-toggle='rst-versions']").toggleClass("shift-up");
    });
    // Make tables responsive
    $("table.docutils:not(.field-list)").wrap("

");

    window.SphinxRtdTheme = (function (jquery) {
        var stickyNav = (function () {
            var navBar,
                win,
                stickyNavCssClass = 'stickynav',
                applyStickNav = function () {
                    if (navBar.height() <= win.height()) {
                        navBar.addClass(stickyNavCssClass);
                    } else {
                        navBar.removeClass(stickyNavCssClass);
                    }
                },
                enable = function () {
                    init();
                    applyStickNav();
                    win.on('resize', applyStickNav);
                },
                init = function () {
                    navBar = jquery('nav.wy-nav-side:first');
                    win    = jquery(window);
                };
            jquery(init);
            return {
                enable : enable
            };
        }());
        return {
            StickyNav : stickyNav
        };
    }($));

    /// Add Grok the Docs Client

    /*
    $.ajax({
        url: "https://api.grokthedocs.com/static/javascript/bundle-client.js",
        crossDomain: true,
        dataType: "script",
    });
    */

    /// Out of date message

      var versionURL = [API_HOST + "/api/v1/version/", READTHEDOCS_DATA['project'],
                        "/highest/", READTHEDOCS_DATA['version'], "/?callback=?"].join("");

      $.getJSON(versionURL, onData);

      function onData (data) {
        if (data.is_highest) {
          return;
        }

        var currentURL = window.location.pathname.replace(READTHEDOCS_DATA['version'], data.slug),
            warning = $('

Note

 \
                         You are not using the most up to date version \
                         of the library.  is the newest version.
\

');

        warning
          .find('a')
          .attr('href', currentURL)
          .text(data.version);

        body = $("div.body");
        if (!body.length) {
          body = $("div.document");
        }
        body.prepend(warning);
      }

    // Hijack search on mkdocs
    if ("builder" in READTHEDOCS_DATA && READTHEDOCS_DATA["builder"] == "mkdocs") {
      $('<input>').attr({
          type: 'hidden',
          name: 'project',
          value: READTHEDOCS_DATA["project"]
      }).appendTo('#rtd-search-form');
      $('<input>').attr({
          type: 'hidden',
          name: 'version',
          value: READTHEDOCS_DATA["version"]
      }).appendTo('#rtd-search-form');
      $('<input>').attr({
          type: 'hidden',
          name: 'type',
          value: 'file'
      }).appendTo('#rtd-search-form');

      $("#rtd-search-form").prop("action", API_HOST + "/elasticsearch/");
    }

    /// Search
    /// Here be dragons, this is beta quality code. Beware.

    if (USING_RTD_THEME) {
      searchLanding();
    }

    $(document).on({
      mouseenter: function(ev) {
          var tooltip = $(ev.target).next();
          tooltip.show();
      },
      mouseleave: function(ev) {
          var tooltip = $(ev.target).next();
          tooltip.hide();
      }
    }, '.result-count');

    $(document).on('submit', '#rtd-search-form', function (ev) {
      //ev.preventDefault();
      clearSearch();
      var query = $("#rtd-search-form input[name='q']").val();
      getSearch(query, true);
    });

    $(document).on('click', '.search-result', function (ev) {
      ev.preventDefault();
      //console.log(ev.target)
      html = $(ev.target).next().html();
      displayContent(html);
    });

    function searchLanding() {
      // Highlight based on highlight GET arg
      var params = $.getQueryParameters();
      var query = (params.q) ? params.q[0].split(/\s+/) : [];
      var clear = true;
      /* Don't "search" on highlight phrases
      if (!query.length) {
        // Only clear on q
        clear = false
        var query = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
      }
      */
      if (query.length) {
        query = query.join(" ");
        console.log("Searching based on GET arg for: " + query);
        $("#rtd-search-form input[name='q']").val(query);
        getSearch(query, clear);
      }
    }

    function getSearch(query, clear) {
      var get_data = {
        project: READTHEDOCS_DATA['project'],
        version: READTHEDOCS_DATA['version'],
        format: "jsonp",
        q: query
      };

      // Search results
      $.ajax({
        url: API_HOST + "/api/v2/search/section/",
        crossDomain: true,
        xhrFields: {
          withCredentials: true,
        },
        dataType: "jsonp",
        data: get_data,
        success: function (data) {
          clearSearch(clear);
          hits = data.results.hits.hits;
          if (!hits.length) {
            resetState();
          } else {
            displaySearch(hits, query);
          }
        },
        error: function () {
            console.log('Error searching');
        }
      });
    }

    function displayContent(html) {
        var content = $('.rst-content');
        content.html(html);
    }

    function displaySearch(hits, query) {
      FIRSTRUN = {};
      current = $(".toctree-l1.current > a");
      for (var index in hits) {
        var hit = hits[index];
        var path = hit.fields.path;
        var pageId = hit.fields.page_id;
        var title = hit.fields.title;
        var content = hit.fields.content;
        var highlight = hit.highlight.content;
        var score = hit._score;

        var li = $(".toctree-l1 > a[href^='" + path + "']");

        /*
        // This doesn't work :)
        if (!li.length && $(current.next().children()[0]).text() == title) {
            li = current
            console.log("Current page: " + title)
        } else {
          console.log("Not: " + title)
        }
        */

        var ul = li.next();

        console.log(path);

        // Display content for first result
        if (index === 0) {
          // Don't display content for now, so we show sphinx results
          //displayContent(content)
        }

        // Clear out subheading with result content
        if (!FIRSTRUN[path]) {
          li.show();
          li.attr("href", li.attr('href') + "?highlight=" + query);
          li.parent().addClass("current");
          li.append("");
          ul.empty();
          FIRSTRUN[path] = true;
        }

        // Dedupe
        if (!FIRSTRUN[path+title]) {
          ul.append('
' + '' + title + '' + '' + content + '' + '
');
          if (score > 1) {
            $(".toctree-l2 ");
            inserted = $('.toctree-l2 > [pageId="' + pageId + '"]');
            inserted.append("");
          }
          FIRSTRUN[path+title] = true;
        }
      }
      // Hide non-showing bits
      $.each($(".toctree-l1 > a"), function (index, el) {
          hide = true;
          if ($(el).attr('href') === "") {
              // Current page
              hide = false;
          }
          for (var key in FIRSTRUN) {
              if ($(el).attr('href').indexOf(key) === 0) {
                hide = false;
              }
          }
          if (hide) {
            //console.log("Hiding " + el)
            $(el).hide();
          }

      });

    }

    function resetState() {
      $.each($(".toctree-l1 > a"), function (index, el) {
        var el = $(el);
        el.show();
        el.parent().show();
      });

    }
    function clearSearch(empty) {
      $('.result-icon').remove();
      $.each($(".toctree-l1 > a"), function (index, el) {
        var el = $(el);
        if (empty) {
          //console.log('Clearing ' + el.next())
          el.parent().removeClass('current');
          el.next().empty();
        }
      });
    }

});
<commit_msg>Once more<commit_after>$(document).ready(function () {

    get_data = {
        project: READTHEDOCS_DATA['project'],
        version: READTHEDOCS_DATA['version'],
        page: READTHEDOCS_DATA['page'],
        theme: READTHEDOCS_DATA['theme'],
        format: "jsonp",
    };

    // Crappy heuristic, but people change the theme name on us.
    // So we have to do some duck typing.
    var USING_RTD_THEME = (READTHEDOCS_DATA['theme'] == 'sphinx_rtd_theme') || $('div.rst-other-versions').length == 1;

    if ("docroot" in READTHEDOCS_DATA) {
      get_data['docroot'] = READTHEDOCS_DATA['docroot'];
    }

    if ("source_suffix" in READTHEDOCS_DATA) {
      get_data['source_suffix'] = READTHEDOCS_DATA['source_suffix'];
    }

    var API_HOST = READTHEDOCS_DATA['api_host'];
    if (API_HOST === undefined) {
      API_HOST = 'https://readthedocs.org';
    }

    if (window.location.pathname.indexOf('/projects/') === 0) {
      get_data['subproject'] = true;
    }

    // Theme popout code
    $.ajax({
      url: API_HOST + "/api/v2/footer_html/",
      crossDomain: true,
      xhrFields: {
        withCredentials: true,
      },
      dataType: "jsonp",
      data: get_data,
      success: function (data) {
            // If the theme looks like ours, update the existing badge
            // otherwise throw a a full one into the page.
            if (USING_RTD_THEME) {
              $("div.rst-other-versions").html(data['html']);
            } else {
              $("body").append(data['html']);
            }

            if (!data['version_active']) {
                $('.rst-current-version').addClass('rst-out-of-date');
            } else if (!data['version_supported']) {
                //$('.rst-current-version').addClass('rst-active-old-version')
            }

            // using jQuery
            function getCookie(name) {
                var cookieValue = null;
                if (document.cookie && document.cookie !== '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = jQuery.trim(cookies[i]);
                        // Does this cookie string begin with the name we want?
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }

              function csrfSafeMethod(method) {
                  // these HTTP methods do not require CSRF protection
                  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
              }
              var csrftoken = getCookie('csrftoken');
              $.ajaxSetup({
                  beforeSend: function(xhr, settings) {
                      if (!csrfSafeMethod(settings.type)) {
                          xhr.setRequestHeader("X-CSRFToken", csrftoken);
                      }
                  }
              });

            // Bookmark Handling
            data = {
                project: READTHEDOCS_DATA['project'],
                version: READTHEDOCS_DATA['version'],
                page: READTHEDOCS_DATA['page'],
                url: document.location.origin + document.location.pathname
            };

            // ask the server if a bookmark exists for this page so we can show the proper icon
            $.ajax({
                    type: 'POST',
                    url: API_HOST + "/bookmarks/exists/",
                    crossDomain: true,
                    xhrFields: {
                      withCredentials: true,
                    },
                    data: JSON.stringify(data),
                    success: function (data) {
                      $(".bookmark-active").show();
                    },
                    error: function(data) {
                      $(".bookmark-inactive").show();
                    },
                    dataType: 'json'
            });

            $(".bookmark-icon").on('click', function (event) {
              var bookmarked = $('.bookmark-active').is(':visible');
              $('div.bookmark-active').toggle();
              $('div.bookmark-inactive').toggle();

              if (bookmarked) {
                  $.ajax({
                    type: "POST",
                    crossDomain: true,
                    xhrFields: {
                      withCredentials: true,
                    },
                    url: API_HOST + "/bookmarks/remove/",
                    data: JSON.stringify(data),
                    });
                  //$(".bookmark-added-msg").hide();
              } else {
                  $.ajax({
                    type: "POST",
                    crossDomain: true,
                    xhrFields: {
                      withCredentials: true,
                    },
                    url: API_HOST + "/bookmarks/add/",
                    data: JSON.stringify(data),
                    });
                    //$(".bookmark-added-msg").html("
Bookmark added
");
                    //$(".bookmark-added-msg").show();
              }
            });
      },
      error: function () {
          console.log('Error loading Read the Docs footer');
      }
    });

    /// Read the Docs theme code

    // Shift nav in mobile when clicking the menu.
    $(document).on('click', "[data-toggle='wy-nav-top']", function() {
      $("[data-toggle='wy-nav-shift']").toggleClass("shift");
      $("[data-toggle='rst-versions']").toggleClass("shift");
    });
    // Close menu when you click a link.
    $(document).on('click', ".wy-menu-vertical .current ul li a", function() {
      $("[data-toggle='wy-nav-shift']").removeClass("shift");
      $("[data-toggle='rst-versions']").toggleClass("shift");
    });
    $(document).on('click', "[data-toggle='rst-current-version']", function() {
      $("[data-toggle='rst-versions']").toggleClass("shift-up");
    });
    // Make tables responsive
    $("table.docutils:not(.field-list)").wrap("

");

    window.SphinxRtdTheme = (function (jquery) {
        var stickyNav = (function () {
            var navBar,
                win,
                stickyNavCssClass = 'stickynav',
                applyStickNav = function () {
                    if (navBar.height() <= win.height()) {
                        navBar.addClass(stickyNavCssClass);
                    } else {
                        navBar.removeClass(stickyNavCssClass);
                    }
                },
                enable = function () {
                    init();
                    applyStickNav();
                    win.on('resize', applyStickNav);
                },
                init = function () {
                    navBar = jquery('nav.wy-nav-side:first');
                    win    = jquery(window);
                };
            jquery(init);
            return {
                enable : enable
            };
        }());
        return {
            StickyNav : stickyNav
        };
    }($));

    /// Add Grok the Docs Client

    /*
    $.ajax({
        url: "https://api.grokthedocs.com/static/javascript/bundle-client.js",
        crossDomain: true,
        dataType: "script",
    });
    */

    /// Out of date message

      var versionURL = [API_HOST + "/api/v1/version/", READTHEDOCS_DATA['project'],
                        "/highest/", READTHEDOCS_DATA['version'], "/?callback=?"].join("");

      $.getJSON(versionURL, onData);

      function onData (data) {
        if (data.is_highest) {
          return;
        }

        var currentURL = window.location.pathname.replace(READTHEDOCS_DATA['version'], data.slug),
            warning = $('

Note

 \
                         You are not using the most up to date version \
                         of the library.  is the newest version.
\

');

        warning
          .find('a')
          .attr('href', currentURL)
          .text(data.version);

        body = $("div.body");
        if (!body.length) {
          body = $("div.document");
        }
        body.prepend(warning);
      }

    // Hijack search on mkdocs
    if ("builder" in READTHEDOCS_DATA && READTHEDOCS_DATA["builder"] == "mkdocs") {
      $('<input>').attr({
          type: 'hidden',
          name: 'project',
          value: READTHEDOCS_DATA["project"]
      }).appendTo('#rtd-search-form');
      $('<input>').attr({
          type: 'hidden',
          name: 'version',
          value: READTHEDOCS_DATA["version"]
      }).appendTo('#rtd-search-form');
      $('<input>').attr({
          type: 'hidden',
          name: 'type',
          value: 'file'
      }).appendTo('#rtd-search-form');

      $("#rtd-search-form").prop("action", API_HOST + "/elasticsearch/");
    }

    /// Search
    /// Here be dragons, this is beta quality code. Beware.

    if (USING_RTD_THEME) {
      searchLanding();
    }

    $(document).on({
      mouseenter: function(ev) {
          var tooltip = $(ev.target).next();
          tooltip.show();
      },
      mouseleave: function(ev) {
          var tooltip = $(ev.target).next();
          tooltip.hide();
      }
    }, '.result-count');

    $(document).on('submit', '#rtd-search-form', function (ev) {
      //ev.preventDefault();
      clearSearch();
      var query = $("#rtd-search-form input[name='q']").val();
      getSearch(query, true);
    });

    $(document).on('click', '.search-result', function (ev) {
      ev.preventDefault();
      //console.log(ev.target)
      html = $(ev.target).next().html();
      displayContent(html);
    });

    function searchLanding() {
      // Highlight based on highlight GET arg
      var params = $.getQueryParameters();
      var query = (params.q) ? params.q[0].split(/\s+/) : [];
      var clear = true;
      /* Don't "search" on highlight phrases
      if (!query.length) {
        // Only clear on q
        clear = false
        var query = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
      }
      */
      if (query.length) {
        query = query.join(" ");
        console.log("Searching based on GET arg for: " + query);
        $("#rtd-search-form input[name='q']").val(query);
        getSearch(query, clear);
      }
    }

    function getSearch(query, clear) {
      var get_data = {
        project: READTHEDOCS_DATA['project'],
        version: READTHEDOCS_DATA['version'],
        format: "jsonp",
        q: query
      };

      // Search results
      $.ajax({
        url: API_HOST + "/api/v2/search/section/",
        crossDomain: true,
        xhrFields: {
          withCredentials: true,
        },
        dataType: "jsonp",
        data: get_data,
        success: function (data) {
          clearSearch(clear);
          hits = data.results.hits.hits;
          if (!hits.length) {
            resetState();
          } else {
            displaySearch(hits, query);
          }
        },
        error: function () {
            console.log('Error searching');
        }
      });
    }

    function displayContent(html) {
        var content = $('.rst-content');
        content.html(html);
    }

    function displaySearch(hits, query) {
      FIRSTRUN = {};
      current = $(".toctree-l1.current > a");
      for (var index in hits) {
        var hit = hits[index];
        var path = hit.fields.path;
        var pageId = hit.fields.page_id;
        var title = hit.fields.title;
        var content = hit.fields.content;
        var highlight = hit.highlight.content;
        var score = hit._score;

        var li = $(".toctree-l1 > a[href^='" + path + "']");

        /*
        // This doesn't work :)
        if (!li.length && $(current.next().children()[0]).text() == title) {
            li = current
            console.log("Current page: " + title)
        } else {
          console.log("Not: " + title)
        }
        */

        var ul = li.next();

        console.log(path);

        // Display content for first result
        if (index === 0) {
          // Don't display content for now, so we show sphinx results
          //displayContent(content)
        }

        // Clear out subheading with result content
        if (!FIRSTRUN[path]) {
          li.show();
          li.attr("href", li.attr('href') + "?highlight=" + query);
          li.parent().addClass("current");
          li.append("");
          ul.empty();
          FIRSTRUN[path] = true;
        }

        // Dedupe
        if (!FIRSTRUN[path+title]) {
          ul.append('
' + '' + title + '' + '' + content + '' + '
');
          if (score > 1) {
            $(".toctree-l2 ");
            inserted = $('.toctree-l2 > [pageId="' + pageId + '"]');
            inserted.append("");
          }
          FIRSTRUN[path+title] = true;
        }
      }
      // Hide non-showing bits
      $.each($(".toctree-l1 > a"), function (index, el) {
          hide = true;
          if ($(el).attr('href') === "") {
              // Current page
              hide = false;
          }
          for (var key in FIRSTRUN) {
              if ($(el).attr('href').indexOf(key) === 0) {
                hide = false;
              }
          }
          if (hide) {
            //console.log("Hiding " + el)
            $(el).hide();
          }

      });

    }

    function resetState() {
      $.each($(".toctree-l1 > a"), function (index, el) {
        var el = $(el);
        el.show();
        el.parent().show();
      });

    }
    function clearSearch(empty) {
      $('.result-icon').remove();
      $.each($(".toctree-l1 > a"), function (index, el) {
        var el = $(el);
        if (empty) {
          //console.log('Clearing ' + el.next())
          el.parent().removeClass('current');
          el.next().empty();
        }
      });
    }

});
<|endoftext|>


<commit_before>const moment = require("moment");

exports.run = async client => {
    const sql = require("sqlite");
    sql.open("./bwd/data/score.sqlite");

    await client.user.setPresence({ activity:  { name:` m~help  | Playing around with Butter on ${client.guilds.size} servers`, type: 0 } });
    await console.log(`[${moment().format("YYYY-MM-DD HH:mm")}] This is Margarine speaking! Online and awaiting orders!`);
    await console.log(`[${moment().format("YYYY-MM-DD HH:mm")}] Current status: Serving ${client.guilds.size} guilds and ${client.users.size} people.`);
    await sql.get(`SELECT * FROM scores WHERE userId = "${client.user.id}"`).then(row => { if (!row) { return; } else { return; } }).catch(error => { return; });
};
<commit_msg>Update ready.js<commit_after>const moment = require("moment");

exports.run = async client => {
    await client.user.setPresence({ activity:  { name:` m~help  | Playing around with Butter on ${client.guilds.size} servers`, type: 0 } });
    await console.log(`[${moment().format("YYYY-MM-DD HH:mm")}] This is Margarine speaking! Online and awaiting orders!`);
    await console.log(`[${moment().format("YYYY-MM-DD HH:mm")}] Current status: Serving ${client.guilds.size} guilds and ${client.users.size} people.`);
};
<|endoftext|>


<commit_before>/*
Copyright 2017 New Vector Ltd

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.
*/

/*
* See - https://docs.google.com/document/d/1uPF7XWY_dXTKVKV7jZQ2KmsI19wn9-kFRgQ1tFQP7wQ/edit?usp=sharing for
* spec. details / documentation.
*/

import FromWidgetPostMessageApi from './FromWidgetPostMessageApi';
import ToWidgetPostMessageApi from './ToWidgetPostMessageApi';

if (!global.mxFromWidgetMessaging) {
    global.mxFromWidgetMessaging = new FromWidgetPostMessageApi();
    global.mxFromWidgetMessaging.start();
}
if (!global.mxToWidgetMessaging) {
    global.mxToWidgetMessaging = new ToWidgetPostMessageApi();
    global.mxToWidgetMessaging.start();
}

const OUTBOUND_API_NAME = 'toWidget';

export default class WidgetMessaging {
    constructor(widgetId, widgetUrl, target) {
        this.widgetId = widgetId;
        this.widgetUrl = widgetUrl;
        this.target = target;
        this.fromWidget = global.mxFromWidgetMessaging;
        this.toWidget = global.mxToWidgetMessaging;
        this.start();
    }

    messageToWidget(action) {
        return this.toWidget.exec(action, this.target).then((data) => {
            // Check for errors and reject if found
            if (data.response === undefined) { // null is valid
                throw new Error("Missing 'response' field");
            }
            if (data.response && data.response.error) {
                const err = data.response.error;
                const msg = String(err.message ? err.message : "An error was returned");
                if (err._error) {
                    console.error(err._error);
                }
                // Potential XSS attack if 'msg' is not appropriately sanitized,
                // as it is untrusted input by our parent window (which we assume is Riot).
                // We can't aggressively sanitize [A-z0-9] since it might be a translation.
                throw new Error(msg);
            }
            // Return the response field for the request
            return data.response;
        });
    }

    /**
     * Request a screenshot from a widget
     * @return {Promise} To be resolved with screenshot data when it has been generated
     */
    getScreenshot() {
        console.warn('Requesting screenshot for', this.widgetId);
        return this.messageToWidget({
                api: OUTBOUND_API_NAME,
                action: "screenshot",
            })
            .catch((error) => new Error("Failed to get screenshot: " + error.message))
            .then((response) => response.screenshot);
    }

    /**
     * Request capabilities required by the widget
     * @return {Promise} To be resolved with an array of requested widget capabilities
     */
    getCapabilities() {
        console.warn('Requesting capabilities for', this.widgetId);
        return this.messageToWidget({
                api: OUTBOUND_API_NAME,
                action: "capabilities",
            }).then((response) => {
                console.warn('Got capabilities for', this.widgetId, response.capabilities);
                return response.capabilities;
            });
    }

    sendVisibility(visible) {
        return this.messageToWidget({
            api: OUTBOUND_API_NAME,
            action: "visibility",
            visible,
        })
        .catch((error) => {
            console.error("Failed to send visibility: ", error);
        });
    }

    start() {
        this.fromWidget.addEndpoint(this.widgetId, this.widgetUrl);
    }

    stop() {
        this.fromWidget.removeEndpoint(this.widgetId, this.widgetUrl);
    }
}
<commit_msg>Send the widgetId as part of all toWidget requests<commit_after>/*
Copyright 2017 New Vector Ltd

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.
*/

/*
* See - https://docs.google.com/document/d/1uPF7XWY_dXTKVKV7jZQ2KmsI19wn9-kFRgQ1tFQP7wQ/edit?usp=sharing for
* spec. details / documentation.
*/

import FromWidgetPostMessageApi from './FromWidgetPostMessageApi';
import ToWidgetPostMessageApi from './ToWidgetPostMessageApi';

if (!global.mxFromWidgetMessaging) {
    global.mxFromWidgetMessaging = new FromWidgetPostMessageApi();
    global.mxFromWidgetMessaging.start();
}
if (!global.mxToWidgetMessaging) {
    global.mxToWidgetMessaging = new ToWidgetPostMessageApi();
    global.mxToWidgetMessaging.start();
}

const OUTBOUND_API_NAME = 'toWidget';

export default class WidgetMessaging {
    constructor(widgetId, widgetUrl, target) {
        this.widgetId = widgetId;
        this.widgetUrl = widgetUrl;
        this.target = target;
        this.fromWidget = global.mxFromWidgetMessaging;
        this.toWidget = global.mxToWidgetMessaging;
        this.start();
    }

    messageToWidget(action) {
        action.widgetId = this.widgetId; // Required to be sent for all outbound requests

        return this.toWidget.exec(action, this.target).then((data) => {
            // Check for errors and reject if found
            if (data.response === undefined) { // null is valid
                throw new Error("Missing 'response' field");
            }
            if (data.response && data.response.error) {
                const err = data.response.error;
                const msg = String(err.message ? err.message : "An error was returned");
                if (err._error) {
                    console.error(err._error);
                }
                // Potential XSS attack if 'msg' is not appropriately sanitized,
                // as it is untrusted input by our parent window (which we assume is Riot).
                // We can't aggressively sanitize [A-z0-9] since it might be a translation.
                throw new Error(msg);
            }
            // Return the response field for the request
            return data.response;
        });
    }

    /**
     * Request a screenshot from a widget
     * @return {Promise} To be resolved with screenshot data when it has been generated
     */
    getScreenshot() {
        console.warn('Requesting screenshot for', this.widgetId);
        return this.messageToWidget({
                api: OUTBOUND_API_NAME,
                action: "screenshot",
            })
            .catch((error) => new Error("Failed to get screenshot: " + error.message))
            .then((response) => response.screenshot);
    }

    /**
     * Request capabilities required by the widget
     * @return {Promise} To be resolved with an array of requested widget capabilities
     */
    getCapabilities() {
        console.warn('Requesting capabilities for', this.widgetId);
        return this.messageToWidget({
                api: OUTBOUND_API_NAME,
                action: "capabilities",
            }).then((response) => {
                console.warn('Got capabilities for', this.widgetId, response.capabilities);
                return response.capabilities;
            });
    }

    sendVisibility(visible) {
        return this.messageToWidget({
            api: OUTBOUND_API_NAME,
            action: "visibility",
            visible,
        })
        .catch((error) => {
            console.error("Failed to send visibility: ", error);
        });
    }

    start() {
        this.fromWidget.addEndpoint(this.widgetId, this.widgetUrl);
    }

    stop() {
        this.fromWidget.removeEndpoint(this.widgetId, this.widgetUrl);
    }
}
<|endoftext|>


<commit_before>'use strict';

var hapi   = require('hapi'),
	mol    = require('../'),
	sol    = require('hapi-sol'),
	server = new hapi.Server({ debug: { request: ['error'] } });

server.connection({port: 8000});

server.register([sol, mol], function (err){
	if (err) {
		throw err;
	}
	var App = {
		models: {},
		controllers: {}
	};

	server.auth.strategy('session', 'session', true, {
		redirectTo: '/login',
		isSecure: false
	});

	server.plugins.mol.load('models', App.models, function (path, base, ext, scope){
		scope[base] = require(path);
	}).then(function (){
		server.plugins.mol.load('controllers', App.controllers, function (path, base, ext, scope, parts){
			var prefix,
				controller = require(path);
			scope[base] = controller;
			if (controller.setScope) {
				controller.setScope(App);
			}
			if (parts[0] === 'api') {
				prefix = parts.concat(base).join('/');
				controller.forEach(function (route){
					route.path = '/' + prefix + route.path;
				});
			}
			server.route(controller);
		});
	}).then(server.start.bind(server, function (err) {
		if (err) {
			console.error(err);
		} else {
			console.log('Server running at localhost:8000');
		}
	}));
});<commit_msg>Added missing `return` to example code<commit_after>'use strict';

var hapi   = require('hapi'),
	mol    = require('../'),
	sol    = require('hapi-sol'),
	server = new hapi.Server({ debug: { request: ['error'] } });

server.connection({port: 8000});

server.register([sol, mol], function (err){
	if (err) {
		throw err;
	}
	var App = {
		models: {},
		controllers: {}
	};

	server.auth.strategy('session', 'session', true, {
		redirectTo: '/login',
		isSecure: false
	});

	server.plugins.mol.load('models', App.models, function (path, base, ext, scope){
		scope[base] = require(path);
	}).then(function (){
		return server.plugins.mol.load('controllers', App.controllers, function (path, base, ext, scope, parts){
				var prefix,
					controller = require(path);
				scope[base] = controller;
				if (controller.setScope) {
					controller.setScope(App);
				}
				if (parts[0] === 'api') {
					prefix = parts.concat(base).join('/');
					controller.forEach(function (route){
						route.path = '/' + prefix + route.path;
					});
				}
				server.route(controller);
			});
	}).then(server.start.bind(server, function (err) {
		if (err) {
			console.error(err);
		} else {
			console.log('Server running at localhost:8000');
		}
	}));
});
<|endoftext|>


<commit_before>require('de-builder')({
	"src": "src",
	"build": "build",
	"client": "client",
	"server": "server",
	"less": {
		"file": "app.less",
		"folder": "styles"
	},
	"browserify": {
		"file": "app.js",
		"folder": "js"
	},
	"forever": {
		"enabled": false,
		"file": "app.js"
	},
	"type": 1
});
<commit_msg>added more config field<commit_after>require('de-builder')({
	"src": "src",
	"build": "build",
	"client": "client",
	"server": "server",
	"less": {
		"file": "app.less",
		"folder": "styles"
	},
	"browserify": {
		"file": "app.js",
		"folder": "js"
	},
	"forever": {
		"enabled": false,
		"file": "app.js"
	},
	"browserSync": {
		"enabled": true
	},
	"type": 1
});<|endoftext|>