<commit_before>'use strict';

var oo = require('../util/oo');
var JSONConverter = require('../model/JSONConverter');
var converter = new JSONConverter();
var each = require('lodash/each');
var Err = require('../util/SubstanceError');

/**
  API for creating and retrieving snapshots of documents
*/
function SnapshotEngine(config) {
  this.configurator = config.configurator;
  this.changeStore = config.changeStore;
  this.documentStore = config.documentStore;

  // Optional
  this.snapshotStore = config.snapshotStore;
}

SnapshotEngine.Prototype = function() {

  /*
    Returns a snapshot for a given documentId and version
  */
  this.getSnapshot = function(args, cb) {
    if (!args || !args.documentId) {
      return cb(new Err('InvalidArgumentsError', {
        message: 'args requires a documentId'
      }));
    }
    this._computeSnapshot(args, cb);
  };

  /*
    Called by DocumentEngine.addChange.

    Here the implementer decides whether a snapshot should be created or not.
    It may be a good strategy to only create a snaphot for every 10th version.
    However for now we will just snapshot each change to keep things simple.

    TODO: this could potentially live in DocumentEngine
  */
  this.requestSnapshot = function(documentId, cb) {
    if (this.snapshotStore) {
      this.createSnapshot({
        documentId: documentId
      }, cb);
    } else {
      cb(null); // do nothing
    }
  };

  /*
    Creates a snapshot
  */
  this.createSnapshot = function(args, cb) {
    if (!this.snapshotStore) {
      throw new Err('SnapshotStoreRequiredError', {
        message: 'You must provide a snapshot store to be able to create snapshots'
      });
    }
    this._computeSnapshot(args, function(err, snapshot) {
      if (err) return cb(err);
      this.snapshotStore.saveSnapshot(snapshot, cb);
    }.bind(this));
  };

  /*
    Compute a snapshot based on the documentId and version (optional)

    If no version is provided a snaphot for the latest version is created.
  */
  this._computeSnapshot = function(args, cb) {
    this.documentStore.getDocument(args.documentId, function(err, docRecord) {
      if (err) return cb(err);

      if (!args.version) {
        args.version = docRecord.version; // set version to the latest version
      }

      // We add the docRecord to the args object
      args.docRecord = docRecord;

      if (this.snapshotStore) {
        this._computeSnapshotSmart(args, cb);
      } else {
        this._computeSnapshotDumb(args, cb);
      }
    }.bind(this));
  };

  /*
    Used when a snapshot store is present. This way gives a huge performance
    benefit.

    Example: Let's assume we want to request a snapshot for a new version 20.
    Now getLatestSnapshot will give us version 15. This requires us to fetch
    the changes since version 16 and apply those, plus the very new change.
  */
  this._computeSnapshotSmart = function(args, cb) {
    var documentId = args.documentId;
    var version = args.version;
    var docRecord = args.docRecord;
    var doc;

    // snaphot = null if no snapshot has been found
    this.snapshotStore.getSnapshot({
      documentId: documentId,
      version: version,
      findClosest: true
    }, function(err, snapshot) {
      if (err) return cb(err);

      if (snapshot && version === snapshot.version) {
        // we alread have a snapshot for this version
        return cb(null, snapshot);
      }

      var knownVersion;
      if (snapshot) {
        knownVersion = snapshot.version;
      } else {
        knownVersion = 0; // we need to fetch all changes
      }

      doc = this._createDocumentInstance(docRecord.schemaName);
      if (snapshot.data) {
        doc = converter.importDocument(doc, snapshot.data);
      }

      // Now we get the remaining changes after the known version
      this.changeStore.getChanges({
        documentId: documentId,
        sinceVersion: knownVersion, // 1
        toVersion: version // 2
      }, function(err, result) {
        if (err) cb(err);
        // Apply remaining changes to the doc
        this._applyChanges(doc, result.changes);
        // doc here should be already restored
        var snapshot = {
          documentId: documentId,
          version: version,
          data: converter.exportDocument(doc)
        };
        cb(null, snapshot);
      }.bind(this));
    }.bind(this));
  };

  /*
    Compute a snapshot in a dumb way by applying the full change history
  */
  this._computeSnapshotDumb = function(args, cb) {
    var documentId = args.documentId;
    var version = args.version;
    var docRecord = args.docRecord;
    var doc;

    // Get all changes for a document
    this.changeStore.getChanges({
      documentId: documentId,
      sinceVersion: 0
    }, function(err, result) {
      if (err) cb(err);
      doc = this._createDocumentInstance(docRecord.schemaName);
      // Apply remaining changes to the doc
      this._applyChanges(doc, result.changes);
      // doc here should be already restored
      var snapshot = {
        documentId: documentId,
        version: version,
        data: converter.exportDocument(doc)
      };
      cb(null, snapshot);
    }.bind(this));
  };

  /*
    Based on a given schema create a document instance based
    on given schema configuration
  */
  this._createDocumentInstance = function(schemaName) {
    var schema = this.configurator.getSchema();

    if (schema.name !== schemaName) {
      throw new Err('SnapshotEngine.SchemaNotFoundError', {
        message:'Schema ' + schemaName + ' not found'
      });
    }
    var doc = this.configurator.createArticle();
    return doc;
  };

  /*
    Takes a document and applies the given changes
  */
  this._applyChanges = function(doc, changes) {
    each(changes, function(change) {
      each(change.ops, function(op) {
        doc.data.apply(op);
      });
    });
  };

};

oo.initClass(SnapshotEngine);

module.exports = SnapshotEngine;
<commit_msg>Snapshot creation frequency.<commit_after>'use strict';

var oo = require('../util/oo');
var JSONConverter = require('../model/JSONConverter');
var converter = new JSONConverter();
var each = require('lodash/each');
var Err = require('../util/SubstanceError');

/**
  API for creating and retrieving snapshots of documents
*/
function SnapshotEngine(config) {
  this.configurator = config.configurator;
  this.changeStore = config.changeStore;
  this.documentStore = config.documentStore;

  // Optional
  this.snapshotStore = config.snapshotStore;
  // Snapshot creation frequency,
  // e.g. if it's equals 15 then every
  // 15th version will be saved as snapshot
  this.frequency = config.frequency || 1;
}

SnapshotEngine.Prototype = function() {

  /*
    Returns a snapshot for a given documentId and version
  */
  this.getSnapshot = function(args, cb) {
    if (!args || !args.documentId) {
      return cb(new Err('InvalidArgumentsError', {
        message: 'args requires a documentId'
      }));
    }
    this._computeSnapshot(args, cb);
  };

  /*
    Called by DocumentEngine.addChange.

    Here the implementer decides whether a snapshot should be created or not.
    It may be a good strategy to only create a snaphot for every 10th version.
    However for now we will just snapshot each change to keep things simple.

    TODO: this could potentially live in DocumentEngine
  */
  this.requestSnapshot = function(documentId, version, cb) {
    if (this.snapshotStore && version % this.frequency === 0) {
      this.createSnapshot({
        documentId: documentId
      }, cb);
    } else {
      cb(null); // do nothing
    }
  };

  /*
    Creates a snapshot
  */
  this.createSnapshot = function(args, cb) {
    if (!this.snapshotStore) {
      throw new Err('SnapshotStoreRequiredError', {
        message: 'You must provide a snapshot store to be able to create snapshots'
      });
    }
    this._computeSnapshot(args, function(err, snapshot) {
      if (err) return cb(err);
      this.snapshotStore.saveSnapshot(snapshot, cb);
    }.bind(this));
  };

  /*
    Compute a snapshot based on the documentId and version (optional)

    If no version is provided a snaphot for the latest version is created.
  */
  this._computeSnapshot = function(args, cb) {
    this.documentStore.getDocument(args.documentId, function(err, docRecord) {
      if (err) return cb(err);

      if (args.version === undefined) {
        args.version = docRecord.version; // set version to the latest version
      }

      // We add the docRecord to the args object
      args.docRecord = docRecord;

      if (this.snapshotStore && args.version !== 0) {
        this._computeSnapshotSmart(args, cb);
      } else {
        this._computeSnapshotDumb(args, cb);
      }
    }.bind(this));
  };

  /*
    Used when a snapshot store is present. This way gives a huge performance
    benefit.

    Example: Let's assume we want to request a snapshot for a new version 20.
    Now getLatestSnapshot will give us version 15. This requires us to fetch
    the changes since version 16 and apply those, plus the very new change.
  */
  this._computeSnapshotSmart = function(args, cb) {
    var documentId = args.documentId;
    var version = args.version;
    var docRecord = args.docRecord;
    var doc;

    // snaphot = null if no snapshot has been found
    this.snapshotStore.getSnapshot({
      documentId: documentId,
      version: version,
      findClosest: true
    }, function(err, snapshot) {
      if (err) return cb(err);

      if (snapshot && version === snapshot.version) {
        // we alread have a snapshot for this version
        return cb(null, snapshot);
      }

      var knownVersion;
      if (snapshot) {
        knownVersion = snapshot.version;
      } else {
        knownVersion = 0; // we need to fetch all changes
      }

      doc = this._createDocumentInstance(docRecord.schemaName);
      if (snapshot) {
        doc = converter.importDocument(doc, snapshot.data);
      }

      // Now we get the remaining changes after the known version
      this.changeStore.getChanges({
        documentId: documentId,
        sinceVersion: knownVersion, // 1
        toVersion: version // 2
      }, function(err, result) {
        if (err) cb(err);
        // Apply remaining changes to the doc
        this._applyChanges(doc, result.changes);
        // doc here should be already restored
        var snapshot = {
          documentId: documentId,
          version: version,
          data: converter.exportDocument(doc)
        };
        cb(null, snapshot);
      }.bind(this));
    }.bind(this));
  };

  /*
    Compute a snapshot in a dumb way by applying the full change history
  */
  this._computeSnapshotDumb = function(args, cb) {
    var documentId = args.documentId;
    var version = args.version;
    var docRecord = args.docRecord;
    var doc;

    // Get all changes for a document
    this.changeStore.getChanges({
      documentId: documentId,
      sinceVersion: 0
    }, function(err, result) {
      if (err) cb(err);
      doc = this._createDocumentInstance(docRecord.schemaName);
      // Apply remaining changes to the doc
      this._applyChanges(doc, result.changes);
      // doc here should be already restored
      var snapshot = {
        documentId: documentId,
        version: version,
        data: converter.exportDocument(doc)
      };
      cb(null, snapshot);
    }.bind(this));
  };

  /*
    Based on a given schema create a document instance based
    on given schema configuration
  */
  this._createDocumentInstance = function(schemaName) {
    var schema = this.configurator.getSchema();

    if (schema.name !== schemaName) {
      throw new Err('SnapshotEngine.SchemaNotFoundError', {
        message:'Schema ' + schemaName + ' not found'
      });
    }
    var doc = this.configurator.createArticle();
    return doc;
  };

  /*
    Takes a document and applies the given changes
  */
  this._applyChanges = function(doc, changes) {
    each(changes, function(change) {
      each(change.ops, function(op) {
        doc.data.apply(op);
      });
    });
  };

};

oo.initClass(SnapshotEngine);

module.exports = SnapshotEngine;
<|endoftext|>


<commit_before>/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014-2019 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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.
 */

(function () {
  'use strict';

  angular.module('pnc.builds').component('pncBrewPushButton', {
    bindings: {
      build: '<?',
      groupBuild: '<?'
    },
    templateUrl: 'builds/directives/pnc-brew-push-button/pnc-brew-push-button.html',
    controller: ['$uibModal', 'pncNotify', 'BuildResource', 'GroupBuildResource', 'messageBus', 'EntityRecognizer', Controller]
  });

  function Controller($uibModal, pncNotify, BuildResource, GroupBuildResource, messageBus, EntityRecognizer) {
    var $ctrl = this,
        unsubscribes = [];

    // -- Controller API --

    $ctrl.isButtonVisible = isButtonVisible;
    $ctrl.openTagNameModal = openTagNameModal;

    // --------------------

    function isBuild() {
      return EntityRecognizer.isBuild($ctrl.build);
    }

    function isBuildGroupRecord() {
      return EntityRecognizer.isGroupBuild($ctrl.groupBuild);
    }

    function isButtonVisible() {
      if (isBuild()) {
        return $ctrl.build.$isSuccess();
      } else if (isBuildGroupRecord()) {
        return GroupBuildResource.isSuccess($ctrl.groupBuild);
      }
    }

    function openTagNameModal() {
      var modal = $uibModal.open({
        animation: true,
        backdrop: 'static',
        component: 'pncEnterBrewTagNameModal',
        size: 'md'
      });

      modal.result.then(function (modalValues) {
        return isBuild() ? doPushBuild(modalValues) : doPushGroupBuild(modalValues);
      });
    }

    function subscribe(statuses) {
      statuses.forEach(function (status) {
        unsubscribes.push(messageBus.subscribe({
          topic: 'causeway-push',
          id: status.id
        }));
      });
    }

    function notify(statusObj) {
      switch (statusObj.status) {
        case 'ACCEPTED':
          pncNotify.info('Brew push initiated for build: ' + statusObj.name + '#' + statusObj.id);
          break;
        case 'FAILED':
        case 'SYSTEM_ERROR':
        case 'REJECTED':
          pncNotify.error('Brew push failed for build: ' + statusObj.name + '#' + statusObj.id);
          break;
        case 'CANCELED':
          pncNotify.info('Brew push canceled for build: ' + statusObj.name + '#' + statusObj.id);
          break;
      }
    }

    function filterAccepted(statuses) {
      return statuses.filter(function (status) {
        return status.status === 'ACCEPTED';
      });
    }

    function filterRejected(statuses) {
      return statuses.filter(function (status) {
        return status.status !== 'ACCEPTED';
      });
    }

    function doPushBuild(modalValues) {
      BuildResource.brewPush({
        id: $ctrl.build.id
      }, {
        tagPrefix: modalValues.tagName,
        buildId: $ctrl.build.id
      }).then(function (response) {
        subscribe(response.data);
        notify(response.data[0]);
      });
    }

    function doPushGroupBuild(modalValues) {
      GroupBuildResource.brewPush($ctrl.groupBuild.id, modalValues.tagName).then(function (response) {
        const accepted = filterAccepted(response.data),
              rejected = filterRejected(response.data);

        if (accepted.length > 0) {
          subscribe(accepted);
        }

        if (rejected.length === 0) {
          pncNotify.info('Brew push initiated for Group Build: ' + GroupBuildResource.canonicalName($ctrl.groupBuild));
        } else {
          pncNotify.warn('Some Builds were rejected for brew push of Group Build: ' + GroupBuildResource.canonicalName($ctrl.groupBuild));
          rejected.forEach(function (reject) {
            notify(reject);
          });
        }
      });
    }
  }

})();
<commit_msg>NCL-4201 Remove buildId parameter from brew push POST request<commit_after>/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014-2019 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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.
 */

(function () {
  'use strict';

  angular.module('pnc.builds').component('pncBrewPushButton', {
    bindings: {
      build: '<?',
      groupBuild: '<?'
    },
    templateUrl: 'builds/directives/pnc-brew-push-button/pnc-brew-push-button.html',
    controller: ['$uibModal', 'pncNotify', 'BuildResource', 'GroupBuildResource', 'messageBus', 'EntityRecognizer', Controller]
  });

  function Controller($uibModal, pncNotify, BuildResource, GroupBuildResource, messageBus, EntityRecognizer) {
    var $ctrl = this,
        unsubscribes = [];

    // -- Controller API --

    $ctrl.isButtonVisible = isButtonVisible;
    $ctrl.openTagNameModal = openTagNameModal;

    // --------------------

    function isBuild() {
      return EntityRecognizer.isBuild($ctrl.build);
    }

    function isBuildGroupRecord() {
      return EntityRecognizer.isGroupBuild($ctrl.groupBuild);
    }

    function isButtonVisible() {
      if (isBuild()) {
        return $ctrl.build.$isSuccess();
      } else if (isBuildGroupRecord()) {
        return GroupBuildResource.isSuccess($ctrl.groupBuild);
      }
    }

    function openTagNameModal() {
      var modal = $uibModal.open({
        animation: true,
        backdrop: 'static',
        component: 'pncEnterBrewTagNameModal',
        size: 'md'
      });

      modal.result.then(function (modalValues) {
        return isBuild() ? doPushBuild(modalValues) : doPushGroupBuild(modalValues);
      });
    }

    function subscribe(statuses) {
      statuses.forEach(function (status) {
        unsubscribes.push(messageBus.subscribe({
          topic: 'causeway-push',
          id: status.id
        }));
      });
    }

    function notify(statusObj) {
      switch (statusObj.status) {
        case 'ACCEPTED':
          pncNotify.info('Brew push initiated for build: ' + statusObj.name + '#' + statusObj.id);
          break;
        case 'FAILED':
        case 'SYSTEM_ERROR':
        case 'REJECTED':
          pncNotify.error('Brew push failed for build: ' + statusObj.name + '#' + statusObj.id);
          break;
        case 'CANCELED':
          pncNotify.info('Brew push canceled for build: ' + statusObj.name + '#' + statusObj.id);
          break;
      }
    }

    function filterAccepted(statuses) {
      return statuses.filter(function (status) {
        return status.status === 'ACCEPTED';
      });
    }

    function filterRejected(statuses) {
      return statuses.filter(function (status) {
        return status.status !== 'ACCEPTED';
      });
    }

    function doPushBuild(modalValues) {
      BuildResource.brewPush({
        id: $ctrl.build.id
      }, {
        tagPrefix: modalValues.tagName
      }).then(function (response) {
        subscribe(response.data);
        notify(response.data[0]);
      });
    }

    function doPushGroupBuild(modalValues) {
      GroupBuildResource.brewPush($ctrl.groupBuild.id, modalValues.tagName).then(function (response) {
        const accepted = filterAccepted(response.data),
              rejected = filterRejected(response.data);

        if (accepted.length > 0) {
          subscribe(accepted);
        }

        if (rejected.length === 0) {
          pncNotify.info('Brew push initiated for Group Build: ' + GroupBuildResource.canonicalName($ctrl.groupBuild));
        } else {
          pncNotify.warn('Some Builds were rejected for brew push of Group Build: ' + GroupBuildResource.canonicalName($ctrl.groupBuild));
          rejected.forEach(function (reject) {
            notify(reject);
          });
        }
      });
    }
  }

})();
<|endoftext|>


<commit_before>/*
 * jQuery Foundation Clearing 1.1
 * http://foundation.zurb.com
 * Copyright 2012, ZURB
 * Free to use under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
*/

/*jslint unparam: true, browser: true, indent: 2 */

;(function ($, window, undefined) {
  'use strict';

  var defaults = {
        templates : {
          viewing : '×' +
            '
' +
            '

' +
            '
'
        },

        // comma delimited list of selectors that, on click, will close clearing,
        // add 'div.clearing-blackout, div.visible-img' to close on background click
        close_selectors : 'a.clearing-close',

        // event initializers and locks
        initialized : false,
        swipe_events : false,
        locked : false
      },

      // original clearing methods will be stored here if
      // initialized with custom methods
      superMethods = {},

      cl = {
        init : function (options, extendMethods) {
          return this.find('ul[data-clearing]').each(function () {
            var doc = $(document),
                $el = $(this),
                options = options || {},
                extendMethods = extendMethods || {},
                settings = $el.data('fndtn.clearing.settings');

            if (!settings) {
              options.$parent = $el.parent();

              $el.data('fndtn.clearing.settings', $.extend({}, defaults, options));

              // developer goodness experiment
              cl.extend(cl, extendMethods);

              // if the gallery hasn't been built yet...build it
              cl.assemble($el.find('li'));

              if (!defaults.initialized) {
                cl.events($el);
                cl.swipe_events();
              }

            }
          });
        },

        events : function (el) {
          var settings = el.data('fndtn.clearing.settings');

          $(document)
            .on('click.fndtn.clearing', 'ul[data-clearing] li', function (e, current, target) {
              var current = current || $(this),
                  target = target || current,
                  settings = current.parent().data('fndtn.clearing.settings');

              e.preventDefault();

              if (!settings) {
                current.parent().foundationClearing();
              }

              // set current and target to the clicked li if not otherwise defined.
              cl.open($(e.target), current, target);
              cl.update_paddles(target);
            })

            .on('click.fndtn.clearing', '.clearing-main-right', function (e) {
              var clearing = $('.clearing-blackout').find('ul[data-clearing]');

              e.preventDefault();
              cl.go(clearing, 'next');
            })

            .on('click.fndtn.clearing', '.clearing-main-left', function (e) {
              var clearing = $('.clearing-blackout').find('ul[data-clearing]');

              e.preventDefault();
              cl.go(clearing, 'prev');
            })

            .on('click.fndtn.clearing', '.clearing-main-left', function (e) {
              var clearing = $('.clearing-blackout').find('ul[data-clearing]');

              e.preventDefault();
              cl.go(clearing, 'prev');
            })

            .on('click.fndtn.clearing', settings.close_selectors, function (e) {
              e.preventDefault();

              var root = (function (target) {
                    if (/blackout/.test(target.selector)) {
                      return target;
                    } else {
                      return target.closest('.clearing-blackout');
                    }
                  }($(this))), container, visible_image;

              if (this === e.target && root) {
                container = root.find('div:first'),
                visible_image = container.find('.visible-img');

                defaults.prev_index = 0;

                root.find('ul[data-clearing]').attr('style', '')
                root.removeClass('clearing-blackout');
                container.removeClass('clearing-container');
                visible_image.hide();
              }

              return false;
            })

            .on('keydown.fndtn.clearing', function (e) {
              var clearing = $('.clearing-blackout').find('ul[data-clearing]');

              // right
              if (e.which === 39) {
                cl.go(clearing, 'next');
              }

              // left
              if (e.which === 37) {
                cl.go(clearing, 'prev');
              }

              if (e.which === 27) {
                $('a.clearing-close').trigger('click');
              }
            });

          $(window).on('resize.fndtn.clearing', function () {
            var image = $('.clearing-blackout .visible-img').find('img');

            if (image.length > 0) {
              cl.center(image);
            }
          });

          defaults.initialized = true;
        },

        swipe_events : function () {
          $(document)
            .bind('swipeleft', 'ul[data-clearing]', function (e) {
              var clearing = $('.clearing-blackout').find('ul[data-clearing]');
              cl.go(clearing, 'next');
            })

            .bind('swiperight', 'ul[data-clearing]', function (e) {
              var clearing = $('.clearing-blackout').find('ul[data-clearing]');
              cl.go(clearing, 'prev');
            })

            .bind('movestart', 'ul[data-clearing]', function (e) {
              if ((e.distX > e.distY && e.distX < -e.distY) ||
                  (e.distX < e.distY && e.distX > -e.distY)) {
                e.preventDefault();
              }
            });
        },

        assemble : function ($li) {
          var $el = $li.parent(),
              settings = $el.data('fndtn.clearing.settings'),
              grid = $el.detach(),
              data = {
                grid: '
' + this.outerHTML(grid[0]) + '
',
                viewing: settings.templates.viewing
              },
              wrapper = '

' + data.viewing + data.grid + '

';

          return settings.$parent.append(wrapper);
        },

        open : function ($image, current, target) {
          var root = target.closest('.clearing-assembled'),
              container = root.find('div:first'),
              visible_image = container.find('.visible-img'),
              image = visible_image.find('img').not($image);

          if (!cl.locked()) {

            // set the image to the selected thumbnail
            image.attr('src', this.load($image));

            image.is_good(function () {
              // toggle the gallery if not visible
              root.addClass('clearing-blackout');
              container.addClass('clearing-container');
              this.caption(visible_image.find('.clearing-caption'), $image);
              visible_image.show();
              this.fix_height(target);

              this.center(image);

              // shift the thumbnails if necessary
              this.shift(current, target, function () {
                target.siblings().removeClass('visible');
                target.addClass('visible');
              });
            }.bind(this));
          }
        },

        fix_height : function (target) {
          var lis = target.siblings();

          target.siblings()
            .each(function () {
              var li = $(this),
                  image = li.find('img');

              if (li.height() > image.outerHeight()) {
                li.addClass('fix-height');
              }
            })
            .closest('ul').width(lis.length * 100 + '%');
        },

        update_paddles : function (target) {
          var visible_image = target.closest('.carousel').siblings('.visible-img');

          if (target.next().length > 0) {
            visible_image.find('.clearing-main-right').removeClass('disabled');
          } else {
            visible_image.find('.clearing-main-right').addClass('disabled');
          }

          if (target.prev().length > 0) {
            visible_image.find('.clearing-main-left').removeClass('disabled');
          } else {
            visible_image.find('.clearing-main-left').addClass('disabled');
          }
        },

        load : function ($image) {
          var href = $image.parent().attr('href');

          this.preload($image);

          if (href) {
            return href;
          }

          return $image.attr('src');
        },

        preload : function ($image) {
          var next = $image.closest('li').next(),
              prev = $image.closest('li').prev(),
              next_a, prev_a,
              next_img, prev_img;

          if (next.length > 0) {
            next_img = new Image();
            next_a = next.find('a');
            if (next_a.length > 0) {
              next_img.src = next_a.attr('href');
            } else {
              next_img.src = next.find('img').attr('src');
            }
          }

          if (prev.length > 0) {
            prev_img = new Image();
            prev_a = prev.find('a');
            if (prev_a.length > 0) {
              prev_img.src = prev_a.attr('href');
            } else {
              prev_img.src = prev.find('img').attr('src');
            }
          }
        },

        caption : function (container, $image) {
          var caption = $image.data('caption');

          if (caption) {
            container.text(caption).show();
          } else {
            container.text('').hide();
          }
        },

        go : function ($ul, direction) {
          var current = $ul.find('.visible'),
              target = current[direction]();

          if (target.length > 0) {
            target.find('img').trigger('click', [current, target]);
          }
        },

        shift : function (current, target, callback) {
          var clearing = target.parent(),
              old_index = defaults.prev_index,
              direction = this.direction(clearing, current, target),
              left = parseInt(clearing.css('left'), 10),
              width = target.outerWidth(),
              skip_shift;

          // we use jQuery animate instead of CSS transitions because we
          // need a callback to unlock the next animation

          if (target.index() !== old_index && !/skip/.test(direction)){
            if (/left/.test(direction)) {
              this.lock();
              clearing.animate({left : left + width}, 300, this.unlock);
            } else if (/right/.test(direction)) {
              this.lock();
              clearing.animate({left : left - width}, 300, this.unlock);
            }
          } else if (/skip/.test(direction)) {

            // the target image is not adjacent to the current image, so
            // do we scroll right or not
            skip_shift = target.index() - defaults.up_count;
            this.lock();

            if (skip_shift > 0) {
              clearing.animate({left : -(skip_shift * width)}, 300, this.unlock);
            } else {
              clearing.animate({left : 0}, 300, this.unlock);
            }
          }

          callback();
        },

        lock : function () {
          defaults.locked = true;
        },

        unlock : function () {
          defaults.locked = false;
        },

        locked : function () {
          return defaults.locked;
        },

        direction : function ($el, current, target) {
          var lis = $el.find('li'),
              li_width = lis.outerWidth() + (lis.outerWidth() / 4),
              up_count = Math.floor($('.clearing-container').outerWidth() / li_width) - 1,
              target_index = lis.index(target),
              response;

          defaults.up_count = up_count;

          if (this.adjacent(defaults.prev_index, target_index)) {
            if ((target_index > up_count) && target_index > defaults.prev_index) {
              response = 'right';
            } else if ((target_index > up_count - 1) && target_index <= defaults.prev_index) {
              response = 'left';
            } else {
              response = false;
            }
          } else {
            response = 'skip';
          }

          defaults.prev_index = target_index;

          return response;
        },

        adjacent : function (current_index, target_index) {
          if (target_index - 1 === current_index) {
            return true;
          } else if (target_index + 1 === current_index) {
            return true;
          } else if (target_index === current_index) {
            return true;
          }

          return false;
        },

        center : function (target) {
          target.css({
            marginLeft : -(target.outerWidth() / 2),
            marginTop : -(target.outerHeight() / 2)
          });
        },

        outerHTML : function (el) {
          // support FireFox < 11
          return el.outerHTML || new XMLSerializer().serializeToString(el);
        },

        // experimental functionality for overwriting or extending
        // clearing methods during initialization.
        //
        // ex $doc.foundationClearing({}, {
        //      shift : function (current, target, callback) {
        //        // modify arguments, etc.
        //        this._super('shift', [current, target, callback]);
        //        // do something else here.
        //      }
        //    });

        extend : function (supers, extendMethods) {
          $.each(supers, function (name, method) {
            if (extendMethods.hasOwnProperty(name)) {
              superMethods[name] = method;
            }
          });

          $.extend(cl, extendMethods);
        },

        // you can call this._super('methodName', [args]) to call
        // the original method and wrap it in your own code

        _super : function (method, args) {
          return superMethods[method].apply(this, args);
        }
      };

  $.fn.foundationClearing = function (method) {
    if (cl[method]) {
      return cl[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
      return cl.init.apply(this, arguments);
    } else {
      $.error('Method ' +  method + ' does not exist on jQuery.foundationClearing');
    }
  };

  // jquery.imageready.js
  // @weblinc, @jsantell, (c) 2012

  (function( $ ) {
    $.fn.is_good = function ( callback, userSettings ) {
      var
        options = $.extend( {}, $.fn.is_good.defaults, userSettings ),
        $images = this.find( 'img' ).add( this.filter( 'img' ) ),
        unloadedImages = $images.length;

      function loaded () {
        unloadedImages -= 1;
        !unloadedImages && callback();
      }

      function bindLoad () {
        this.one( 'load', loaded );
        if ( $.browser.msie ) {
          var
            src   = this.attr( 'src' ),
            param = src.match( /\?/ ) ? '&' : '?';
          param  += options.cachePrefix + '=' + ( new Date() ).getTime();
          this.attr( 'src', src + param );
        }
      }

      return $images.each(function () {
        var $this = $( this );
        if ( !$this.attr( 'src' ) ) {
          loaded();
          return;
        }
        this.complete || this.readyState === 4 ?
          loaded() :
          bindLoad.call( $this );
      });
    };

    $.fn.is_good.defaults = {
      cachePrefix: 'random'
    };

  }(jQuery));

}(jQuery, this));
<commit_msg>Use Modernizr to check for touch events before binding swipe events.<commit_after>/*
 * jQuery Foundation Clearing 1.2
 * http://foundation.zurb.com
 * Copyright 2012, ZURB
 * Free to use under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
*/

/*jslint unparam: true, browser: true, indent: 2 */

;(function ($, window, document, undefined) {
  'use strict';

  var defaults = {
        templates : {
          viewing : '×' +
            '
' +
            '

' +
            '
'
        },

        // comma delimited list of selectors that, on click, will close clearing,
        // add 'div.clearing-blackout, div.visible-img' to close on background click
        close_selectors : 'a.clearing-close',

        // event initializers and locks
        initialized : false,
        locked : false
      },

      // original clearing methods will be stored here if
      // initialized with custom methods
      superMethods = {},

      cl = {
        init : function (options, extendMethods) {
          return this.find('ul[data-clearing]').each(function () {
            var doc = $(document),
                $el = $(this),
                options = options || {},
                extendMethods = extendMethods || {},
                settings = $el.data('fndtn.clearing.settings');

            if (!settings) {
              options.$parent = $el.parent();

              $el.data('fndtn.clearing.settings', $.extend({}, defaults, options));

              // developer goodness experiment
              cl.extend(cl, extendMethods);

              cl.assemble($el.find('li'));

              if (!defaults.initialized) {
                cl.events($el);
                if (Modernizr.touch) cl.swipe_events();
              }

            }
          });
        },

        events : function (el) {
          var settings = el.data('fndtn.clearing.settings');

          $(document)
            .on('click.fndtn.clearing', 'ul[data-clearing] li', function (e, current, target) {
              var current = current || $(this),
                  target = target || current,
                  settings = current.parent().data('fndtn.clearing.settings');

              e.preventDefault();

              if (!settings) {
                current.parent().foundationClearing();
              }

              // set current and target to the clicked li if not otherwise defined.
              cl.open($(e.target), current, target);
              cl.update_paddles(target);
            })

            .on('click.fndtn.clearing', '.clearing-main-right', function (e) { cl.nav(e, 'next') })
            .on('click.fndtn.clearing', '.clearing-main-left', function (e) { cl.nav(e, 'prev') })
            .on('click.fndtn.clearing', settings.close_selectors, this.close)
            .on('keydown.fndtn.clearing', this.keydown);

          $(window).on('resize.fndtn.clearing', this.resize);

          defaults.initialized = true;
        },

        swipe_events : function () {
          $(document)
            .bind('swipeleft', 'ul[data-clearing]', function (e) { cl.nav(e, 'next') })
            .bind('swiperight', 'ul[data-clearing]', function (e) { cl.nav(e, 'prev') })
            .bind('movestart', 'ul[data-clearing]', function (e) {
              if ((e.distX > e.distY && e.distX < -e.distY) ||
                  (e.distX < e.distY && e.distX > -e.distY)) {
                e.preventDefault();
              }
            });
        },

        assemble : function ($li) {
          var $el = $li.parent(),
              settings = $el.data('fndtn.clearing.settings'),
              grid = $el.detach(),
              data = {
                grid: '
' + this.outerHTML(grid[0]) + '
',
                viewing: settings.templates.viewing
              },
              wrapper = '

' + data.viewing + data.grid + '

';

          return settings.$parent.append(wrapper);
        },

        open : function ($image, current, target) {
          var root = target.closest('.clearing-assembled'),
              container = root.find('div:first'),
              visible_image = container.find('.visible-img'),
              image = visible_image.find('img').not($image);

          if (!cl.locked()) {

            // set the image to the selected thumbnail
            image.attr('src', this.load($image));

            image.loaded(function () {
              // toggle the gallery if not visible
              root.addClass('clearing-blackout');
              container.addClass('clearing-container');
              this.caption(visible_image.find('.clearing-caption'), $image);
              visible_image.show();
              this.fix_height(target);
              this.center(image);

              // shift the thumbnails if necessary
              this.shift(current, target, function () {
                target.siblings().removeClass('visible');
                target.addClass('visible');
              });
            }.bind(this));
          }
        },

        close : function (e) {
          e.preventDefault();

          var root = (function (target) {
                if (/blackout/.test(target.selector)) {
                  return target;
                } else {
                  return target.closest('.clearing-blackout');
                }
              }($(this))), container, visible_image;

          if (this === e.target && root) {
            container = root.find('div:first'),
            visible_image = container.find('.visible-img');

            defaults.prev_index = 0;

            root.find('ul[data-clearing]').attr('style', '')
            root.removeClass('clearing-blackout');
            container.removeClass('clearing-container');
            visible_image.hide();
          }

          return false;
        },

        keydown : function (e) {
          var clearing = $('.clearing-blackout').find('ul[data-clearing]');

          if (e.which === 39) cl.go(clearing, 'next');
          if (e.which === 37) cl.go(clearing, 'prev');
          if (e.which === 27) $('a.clearing-close').trigger('click');
        },

        nav : function (e, direction) {
          var clearing = $('.clearing-blackout').find('ul[data-clearing]');

          e.preventDefault();
          this.go(clearing, direction);
        },

        resize : function () {
          var image = $('.clearing-blackout .visible-img').find('img');

          if (image.length > 0) {
            cl.center(image);
          }
        },

        fix_height : function (target) {
          var lis = target.siblings();

          lis.each(function () {
              var li = $(this),
                  image = li.find('img');

              if (li.height() > image.outerHeight()) {
                li.addClass('fix-height');
              }
            })
            .closest('ul').width(lis.length * 100 + '%');
        },

        update_paddles : function (target) {
          var visible_image = target.closest('.carousel').siblings('.visible-img');

          if (target.next().length > 0) {
            visible_image.find('.clearing-main-right').removeClass('disabled');
          } else {
            visible_image.find('.clearing-main-right').addClass('disabled');
          }

          if (target.prev().length > 0) {
            visible_image.find('.clearing-main-left').removeClass('disabled');
          } else {
            visible_image.find('.clearing-main-left').addClass('disabled');
          }
        },

        load : function ($image) {
          var href = $image.parent().attr('href');

          this.preload($image);

          if (href) return href;
          return $image.attr('src');
        },

        preload : function ($image) {
          this.img($image.closest('li').next());
          this.img($image.closest('li').prev());
        },

        img : function (img) {
          if (img.length > 0) {
            var new_img = new Image(),
                new_a = img.find('a');

            if (new_a.length > 0) {
              new_img.src = new_a.attr('href');
            } else {
              new_img.src = img.find('img').attr('src');
            }
          }
        },

        caption : function (container, $image) {
          var caption = $image.data('caption');

          if (caption) {
            container.text(caption).show();
          } else {
            container.text('').hide();
          }
        },

        go : function ($ul, direction) {
          var current = $ul.find('.visible'),
              target = current[direction]();

          if (target.length > 0) {
            target.find('img').trigger('click', [current, target]);
          }
        },

        shift : function (current, target, callback) {
          var clearing = target.parent(),
              old_index = defaults.prev_index,
              direction = this.direction(clearing, current, target),
              left = parseInt(clearing.css('left'), 10),
              width = target.outerWidth(),
              skip_shift;

          // we use jQuery animate instead of CSS transitions because we
          // need a callback to unlock the next animation
          if (target.index() !== old_index && !/skip/.test(direction)){
            if (/left/.test(direction)) {
              this.lock();
              clearing.animate({left : left + width}, 300, this.unlock);
            } else if (/right/.test(direction)) {
              this.lock();
              clearing.animate({left : left - width}, 300, this.unlock);
            }
          } else if (/skip/.test(direction)) {

            // the target image is not adjacent to the current image, so
            // do we scroll right or not
            skip_shift = target.index() - defaults.up_count;
            this.lock();

            if (skip_shift > 0) {
              clearing.animate({left : -(skip_shift * width)}, 300, this.unlock);
            } else {
              clearing.animate({left : 0}, 300, this.unlock);
            }
          }

          callback();
        },

        lock : function () {
          defaults.locked = true;
        },

        unlock : function () {
          defaults.locked = false;
        },

        locked : function () {
          return defaults.locked;
        },

        direction : function ($el, current, target) {
          var lis = $el.find('li'),
              li_width = lis.outerWidth() + (lis.outerWidth() / 4),
              up_count = Math.floor($('.clearing-container').outerWidth() / li_width) - 1,
              target_index = lis.index(target),
              response;

          defaults.up_count = up_count;

          if (this.adjacent(defaults.prev_index, target_index)) {
            if ((target_index > up_count) && target_index > defaults.prev_index) {
              response = 'right';
            } else if ((target_index > up_count - 1) && target_index <= defaults.prev_index) {
              response = 'left';
            } else {
              response = false;
            }
          } else {
            response = 'skip';
          }

          defaults.prev_index = target_index;

          return response;
        },

        adjacent : function (current_index, target_index) {
          for (var i = target_index + 1; i >= target_index - 1; i--) {
            if (i === current_index) return true;
          }
          return false;
        },

        center : function (target) {
          target.css({
            marginLeft : -(target.outerWidth() / 2),
            marginTop : -(target.outerHeight() / 2)
          });
        },

        outerHTML : function (el) {
          // support FireFox < 11
          return el.outerHTML || new XMLSerializer().serializeToString(el);
        },

        // experimental functionality for overwriting or extending
        // clearing methods during initialization.
        //
        // ex $doc.foundationClearing({}, {
        //      shift : function (current, target, callback) {
        //        // modify arguments, etc.
        //        this._super('shift', [current, target, callback]);
        //        // do something else here.
        //      }
        //    });

        extend : function (supers, extendMethods) {
          $.each(supers, function (name, method) {
            if (extendMethods.hasOwnProperty(name)) {
              superMethods[name] = method;
            }
          });

          $.extend(cl, extendMethods);
        },

        // you can call this._super('methodName', [args]) to call
        // the original method and wrap it in your own code

        _super : function (method, args) {
          return superMethods[method].apply(this, args);
        }
      };

  $.fn.foundationClearing = function (method) {
    if (cl[method]) {
      return cl[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
      return cl.init.apply(this, arguments);
    } else {
      $.error('Method ' +  method + ' does not exist on jQuery.foundationClearing');
    }
  };

  // jquery.imageready.js
  // @weblinc, @jsantell, (c) 2012

  (function( $ ) {
    $.fn.loaded = function ( callback, userSettings ) {
      var
        options = $.extend( {}, $.fn.loaded.defaults, userSettings ),
        $images = this.find( 'img' ).add( this.filter( 'img' ) ),
        unloadedImages = $images.length;

      function loaded () {
        unloadedImages -= 1;
        !unloadedImages && callback();
      }

      function bindLoad () {
        this.one( 'load', loaded );
        if ( $.browser.msie ) {
          var
            src   = this.attr( 'src' ),
            param = src.match( /\?/ ) ? '&' : '?';
          param  += options.cachePrefix + '=' + ( new Date() ).getTime();
          this.attr( 'src', src + param );
        }
      }

      return $images.each(function () {
        var $this = $( this );
        if ( !$this.attr( 'src' ) ) {
          loaded();
          return;
        }
        this.complete || this.readyState === 4 ?
          loaded() :
          bindLoad.call( $this );
      });
    };

    $.fn.loaded.defaults = {
      cachePrefix: 'random'
    };

  }(jQuery));

}(jQuery, this, this.document));<|endoftext|>


<commit_before>exports.run = async (client, message, [action, kind, amount]) => {
    const sql = require("sqlite");
    let user = message.author;
    sql.open("./bwd/data/score.sqlite");

    if (!action) {
        sql.get(`SELECT * FROM scores WHERE userId = "${user.id}"`).then(row => {
            if (!row) { return message.reply("You haven't signed up and received your credits yet! D: Use `m~daily` (Using default prefix) to earn your first amount of credits."); }
            if (row.credits < 5) { return message.reply("You don't have that many credits, baka!"); }
            else { sql.run(`UPDATE scores SET credits = ${row.credits - 10} WHERE userId = ${user.id}`); }
        }).catch(error => {
            console.log(error);
            return message.reply("Error in command: Scores table. Please try again later.");
        });

        die = Math.random();

        if (0 < die && die < .5) {
            kind = "trash";
            text = "some trash and threw it out";
            image = ":wastebasket:";
            result = "You have lost 10 credits";
        } if (.5 < die && die < .75) {
            kind = "common";
            text = "a nice fish. A bit small but still good";
            image = ":fish:";
            result = "You have placed the fish in your inventory";
        } if (.75 < die && die < .85) {
            kind = "uncommon";
            text = "a decent catch. This will catch some decent credits";
            image = ":crab:";
            result = "You have placed the fish in your inventory";
        } if (.85 < die && die < .98) {
            kind = "rare";
            text = "a fantastic catch! This will fund your gambling habits for awhile";
            image = ":squid:";
            result = "You have placed the fish in your inventory";
        } if (.98 < die && die < 1) {
            kind = "ultraRare";
            text = "an extremely rare fish! O: That's bound to buy you a house *(No guarantees)*";
            image = ":shark:";
            result = "You have placed the fish in your inventory";
        }

        sql.get(`SELECT * FROM fish_inv WHERE userId = "${user.id}"`).then(row => {
            if (!row) {
                return message.reply("Error in finding your information");
            } else if (kind === "common") {
                sql.run(`UPDATE fish_inv SET common = ${row.common + 1} WHERE userId = ${user.id}`);
            } else if (kind === "uncommon") {
                sql.run(`UPDATE fish_inv SET uncommon = ${row.uncommon + 1} WHERE userId = ${user.id}`);
            } else if (kind === "rare") {
                sql.run(`UPDATE fish_inv SET rare = ${row.rare + 1} WHERE userId = ${user.id}`);
            } else if (kind === "ultraRare") {
                sql.run(`UPDATE fish_inv SET ultraRare = ${row.ultraRare + 1} WHERE userId = ${user.id}`);
            }
        }).catch(error => {
            console.log(error);
            return message.reply("Error in command: Fish_inv table. Please try again later.");
        });

        sql.get(`SELECT * FROM fish_stats WHERE userId = "${user.id}"`).then(row => {
            if (!row) {
                return;
            } else if (kind === "common") {
                sql.run(`UPDATE fish_stats SET common = ${row.common + 1} WHERE userId = ${user.id}`);
            } else if (kind === "uncommon") {
                sql.run(`UPDATE fish_stats SET uncommon = ${row.uncommon + 1} WHERE userId = ${user.id}`);
            } else if (kind === "rare") {
                sql.run(`UPDATE fish_stats SET rare = ${row.rare + 1} WHERE userId = ${user.id}`);
            } else if (kind === "ultraRare") {
                sql.run(`UPDATE fish_stats SET ultraRare = ${row.ultraRare + 1} WHERE userId = ${user.id}`);
            } else if (kind === "trash") {
                sql.run(`UPDATE fish_stats SET trash = ${row.trash + 1} WHERE userId = ${user.id}`);
            }

            message.channel.send(`${user.username}, you have caught ${text}. ${image} ${result}.`);
        }).catch(error => {
            console.log(error);
            return message.reply("Error in command: Fish_stats table. Please try again later.");
        });
    } if (action === "inv" || action === "inventory") {
        sql.get(`SELECT * FROM fish_inv WHERE userId = "${user.id}"`).then(row => {
            if (!row) { return message.reply("You haven't caught any fish yet!"); }
            else {
                const embed = new client.methods.Embed()
                    .setTimestamp()
                    .setAuthor(message.guild.name, message.guild.iconURL())
                    .setColor("#4d5fd")
                    .setThumbnail(user.avatarURL())
                    .setTitle(`${user.username}'s Fishing Inventory:`)
                    .setDescription("*:eyes: Let's see what you've caught.*");
                    if (row.common > 0) { embed.addField("Common fish:", row.common, true); }
                    if (row.uncommon > 0) { embed.addField("Uncommon fish:", row.uncommon, true); }
                    if (row.rare > 0) { embed.addField("Rare fish:", row.rare, true); }
                    if (row.ultraRare > 0) { embed.addField("Ultra rare fish:", row.ultraRare, true); }
                    if ((row.common == 0) && (row.uncommon == 0) && (row.rare == 0) && (row.ultraRare == 0)) { embed.addField("There's a slight problem here...", "You don't actually have any fish in your inventory."); }
                return message.channel.send({embed});
            }
        }).catch(error => {
            console.log(error);
            return message.reply("Error in command: Inventory section. Please try again later.");
        });
    } if (action === "sell") {
        sql.get(`SELECT * FROM fish_inv WHERE userId = "${user.id}"`).then(row => {
            if (!row) { return message.reply("You haven't caught any fish yet!"); }
            if (kind === "common" && row.common == 0) {
                return message.reply("You don't have any common fish to sell!");
            } if (kind === "uncommon" && row.uncommon == 0) {
                return message.reply("You don't have any uncommon fish to sell!");
            } if (kind === "rare" && row.rare == 0) {
                return message.reply("You don't have any rare fish to sell!");
            } if (kind === "ultraRare" && row.ultraRare == 0) {
                return message.reply("You don't have any ultra rare fish to sell!");
            }
            else {
                if (kind === "common") {
                    if (!amount) { amount = row.common; }
                    income = (amount * 10).toFixed(0);
                    sql.run(`UPDATE fish_inv SET common = ${row.common - amount} WHERE userId = ${user.id}`);
                    message.channel.send(`You have sold ${amount} common fish and earned ${income} credits!`);
                } if (kind === "uncommon") {
                    if (!amount) { amount = row.uncommon; }
                    income = (amount * 15).toFixed(0);
                    sql.run(`UPDATE fish_inv SET uncommon = ${row.uncommon - amount} WHERE userId = ${user.id}`);
                    message.channel.send(`You have sold ${amount} uncommon fish and earned ${income} credits!`);
                } if (kind === "rare") {
                    if (!amount) { amount = row.rare; }
                    income = (amount * 25).toFixed(0);
                    sql.run(`UPDATE fish_inv SET rare = ${row.rare - amount} WHERE userId = ${user.id}`);
                    message.channel.send(`You have sold ${amount} rare fish and earned ${income} credits!`);
                } if (kind === "ultraRare") {
                    if (!amount) { amount = row.ultraRare; }
                    income = (amount * 50).toFixed(0);
                    sql.run(`UPDATE fish_inv SET ultraRare = ${row.ultraRare - amount} WHERE userId = ${user.id}`);
                    message.channel.send(`You have sold ${amount} ultra rare fish and earned ${income} credits!`);
                }

                sql.get(`SELECT * FROM scores WHERE userId = "${user.id}"`).then(row => {
                    sql.run(`UPDATE scores SET credits = ${parseInt(row.credits) + parseInt(income)} WHERE userId = ${user.id}`);
                });
            }
        }).catch(error => {
            console.log(error);
            return message.reply("Error in command: Sell section. Please try again later.");
        });
    } if (action === "stats") {
        var User = client.funcs.userSearch(client, message, kind);
        if (User.username === null || User.username === undefined) { return; }
        if (User.bot === true) { return message.reply("Bots can't fish!"); }

        sql.get(`SELECT * FROM fish_stats WHERE userId = "${User.id}"`).then(row => {
            if (!row) {
                if (User.id == message.author.id) { return message.reply("You haven't caught any fish yet!"); }
                else { return message.channel.send("That user has not caught any fish yet!"); }
            } else {
                sum = row.common + row.uncommon + row.rare + row.ultraRare + row.trash;
                const embed = new client.methods.Embed()
                    .setTimestamp()
                    .setAuthor(message.guild.name, message.guild.iconURL())
                    .setColor("#4d5fd")
                    .setThumbnail(User.avatarURL())
                    .setTitle(`${User.username}'s Fishing Statistics:`)
                    .setDescription(`*Total catch amount: ${sum}*`)
                    .addField("Trash:", row.trash, true)
                    .addField("Common fish:", row.common, true)
                    .addField("Uncommon fish:", row.uncommon, true)
                    .addField("Rare fish:", row.rare, true)
                    .addField("Ultra rare fish:", row.ultraRare, true);
                return message.channel.send({embed});
            }
        }).catch(error => {
            console.log(error);
            return message.reply("Error in command: Stats section. Please try again later.");
        });
    } if (action != undefined && action != "stats" && action != "inv" && action != "inventory" && action != "sell") {
        return message.reply("You didn't provide a valid action. I can either provide you with selling `m~fish sell [type]`, showing your inventory `m~fish inv`, showing your stats `m~fish stats`, or fishing `m~fish`");
    }
};

exports.conf = {
    enabled: true,
    runIn: ["text"],
    aliases: [],
    permLevel: 0,
    botPerms: [],
    requiredFuncs: [],
};

exports.help = {
    name: "fish",
    description: "Fish and try to turn your credits into a fortune!",
    usage: "[action:str] [kind:str] [amount:int]",
    usageDelim: " ",
    extendedHelp: "Spend 10 credits to fish and catch yourself a fortune! Check someone's stats with `m~fish stats [user]`. Or check your inventory with `m~fish inv`.",
};
<commit_msg>Update fish.js<commit_after>exports.run = async (client, message, [action, kind, amount]) => {
    const sql = require("sqlite");
    let user = message.author;
    sql.open("./bwd/data/score.sqlite");

    if (!action) {
        sql.get(`SELECT * FROM scores WHERE userId = "${user.id}"`).then(row => {
            if (!row) { return message.reply("You haven't signed up and received your credits yet! D: Use `m~daily` (Using default prefix) to earn your first amount of credits."); }
            if (row.credits < 5) { return message.reply("You don't have that many credits, baka!"); }
            else {
                sql.run(`UPDATE scores SET credits = ${row.credits - 5} WHERE userId = ${user.id}`);

                die = Math.random();

                if (0 < die && die < .5) {
                    kind = "trash";
                    text = "some trash and threw it out";
                    image = ":wastebasket:";
                    result = "You have lost 5 credits";
                } if (.5 < die && die < .75) {
                    kind = "common";
                    text = "a nice fish. A bit small but still good";
                    image = ":fish:";
                    result = "You have placed the fish in your inventory";
                } if (.75 < die && die < .88) {
                    kind = "uncommon";
                    text = "a decent catch. This will catch some decent credits";
                    image = ":crab:";
                    result = "You have placed the fish in your inventory";
                } if (.88 < die && die < .98) {
                    kind = "rare";
                    text = "a fantastic catch! This will fund your gambling habits for awhile";
                    image = ":squid:";
                    result = "You have placed the fish in your inventory";
                } if (.98 < die && die < 1) {
                    kind = "epic";
                    text = "an extremely rare fish! O: That's bound to buy you a house *(No guarantees)*";
                    image = ":shark:";
                    result = "You have placed the fish in your inventory";
                }

                sql.get(`SELECT * FROM fish_inv WHERE userId = "${user.id}"`).then(row => {
                    if (!row) {
                        return message.reply("Error in finding your information. Fish_inv table is lacking your id!");
                    } else if (kind === "common") {
                        sql.run(`UPDATE fish_inv SET common = ${row.common + 1} WHERE userId = ${user.id}`);
                    } else if (kind === "uncommon") {
                        sql.run(`UPDATE fish_inv SET uncommon = ${row.uncommon + 1} WHERE userId = ${user.id}`);
                    } else if (kind === "rare") {
                        sql.run(`UPDATE fish_inv SET rare = ${row.rare + 1} WHERE userId = ${user.id}`);
                    } else if (kind === "epic") {
                        sql.run(`UPDATE fish_inv SET epic = ${row.epic + 1} WHERE userId = ${user.id}`);
                    }
                });

                sql.get(`SELECT * FROM fish_stats WHERE userId = "${user.id}"`).then(row => {
                    if (!row) {
                        return;
                    } else if (kind === "common") {
                        sql.run(`UPDATE fish_stats SET common = ${row.common + 1} WHERE userId = ${user.id}`);
                    } else if (kind === "uncommon") {
                        sql.run(`UPDATE fish_stats SET uncommon = ${row.uncommon + 1} WHERE userId = ${user.id}`);
                    } else if (kind === "rare") {
                        sql.run(`UPDATE fish_stats SET rare = ${row.rare + 1} WHERE userId = ${user.id}`);
                    } else if (kind === "epic") {
                        sql.run(`UPDATE fish_stats SET epic = ${row.epic + 1} WHERE userId = ${user.id}`);
                    } else if (kind === "trash") {
                        sql.run(`UPDATE fish_stats SET trash = ${row.trash + 1} WHERE userId = ${user.id}`);
                    }

                    message.channel.send(`${user.username}, you have caught ${text}. ${image} ${result}.`);
                });
            }
        }).catch(error => {
            console.log(error);
            return message.reply("Error in command: Scores table. Please try again later.");
        });
    } if (action === "inv" || action === "inventory") {
        sql.get(`SELECT * FROM fish_inv WHERE userId = "${user.id}"`).then(row => {
            if (!row) { return message.reply("You haven't caught any fish yet!"); }
            else {
                const embed = new client.methods.Embed()
                    .setTimestamp()
                    .setAuthor(message.guild.name, message.guild.iconURL())
                    .setColor("#4d5fd")
                    .setThumbnail(user.avatarURL())
                    .setTitle(`${user.username}'s Fishing Inventory:`)
                    .setDescription("*:eyes: Let's see what you've caught.*");
                    if (row.common > 0) { embed.addField("Common fish:", row.common, true); }
                    if (row.uncommon > 0) { embed.addField("Uncommon fish:", row.uncommon, true); }
                    if (row.rare > 0) { embed.addField("Rare fish:", row.rare, true); }
                    if (row.epic > 0) { embed.addField("Epic fish:", row.epic, true); }
                    if ((row.common == 0) && (row.uncommon == 0) && (row.rare == 0) && (row.epic == 0)) { embed.addField("There's a slight problem here...", "You don't actually have any fish in your inventory."); }
                return message.channel.send({embed});
            }
        }).catch(error => {
            console.log(error);
            return message.reply("Error in command: Inventory section. Please try again later.");
        });
    } if (action === "sell") {
        sql.get(`SELECT * FROM fish_inv WHERE userId = "${user.id}"`).then(row => {
            if (!row) { return message.reply("You haven't caught any fish yet!"); }
            else {
                if (kind === "common") {
                    if (!amount) { amount = row.common; }
                    else if (row.common == 0) { return message.reply("You don't have any common fish to sell! D:"); }
                    else if (row.common < amount) { return message.reply("You don't have that much fish to sell."); }
                    income = (amount * 5).toFixed(0);
                    sql.run(`UPDATE fish_inv SET common = ${row.common - amount} WHERE userId = ${user.id}`);
                    message.channel.send(`You have sold ${amount} common fish and earned ${income} credits!`);
                } if (kind === "uncommon") {
                    if (!amount) { amount = row.uncommon; }
                    else if (row.uncommon == 0) { return message.reply("You don't have any uncommon fish to sell! D:"); }
                    else if (row.uncommon < amount) { return message.reply("You don't have that much fish to sell."); }
                    income = (amount * 10).toFixed(0);
                    sql.run(`UPDATE fish_inv SET uncommon = ${row.uncommon - amount} WHERE userId = ${user.id}`);
                    message.channel.send(`You have sold ${amount} uncommon fish and earned ${income} credits!`);
                } if (kind === "rare") {
                    if (!amount) { amount = row.rare; }
                    else if (row.rare == 0) { return message.reply("You don't have any rare fish to sell! D:"); }
                    else if (row.rare < amount) { return message.reply("You don't have that much fish to sell."); }
                    income = (amount * 25).toFixed(0);
                    sql.run(`UPDATE fish_inv SET rare = ${row.rare - amount} WHERE userId = ${user.id}`);
                    message.channel.send(`You have sold ${amount} rare fish and earned ${income} credits!`);
                } if (kind === "epic") {
                    if (!amount) { amount = row.epic; }
                    else if (row.epic == 0) { return message.reply("You don't have any epic fish to sell! D:"); }
                    else if (row.epic < amount) { return message.reply("You don't have that much fish to sell."); }
                    income = (amount * 50).toFixed(0);
                    sql.run(`UPDATE fish_inv SET epic = ${row.epic - amount} WHERE userId = ${user.id}`);
                    message.channel.send(`You have sold ${amount} Epic fish and earned ${income} credits!`);
                }

                sql.get(`SELECT * FROM scores WHERE userId = "${user.id}"`).then(row => {
                    sql.run(`UPDATE scores SET credits = ${parseInt(row.credits) + parseInt(income)} WHERE userId = ${user.id}`);
                });
            }
        }).catch(error => {
            console.log(error);
            return message.reply("Error in command: Sell section. Please try again later.");
        });
    } if (action === "stats") {
        var User = client.funcs.userSearch(client, message, kind);
        if (User.username === null || User.username === undefined) { return; }
        if (User.bot === true) { return message.reply("Bots can't fish!"); }

        sql.get(`SELECT * FROM fish_stats WHERE userId = "${User.id}"`).then(row => {
            if (!row) {
                if (User.id == message.author.id) { return message.reply("You haven't caught any fish yet!"); }
                else { return message.channel.send("That user has not caught any fish yet!"); }
            } else {
                sum = row.common + row.uncommon + row.rare + row.epic + row.trash;
                const embed = new client.methods.Embed()
                    .setTimestamp()
                    .setAuthor(message.guild.name, message.guild.iconURL())
                    .setColor("#4d5fd")
                    .setThumbnail(User.avatarURL())
                    .setTitle(`${User.username}'s Fishing Statistics:`)
                    .setDescription(`*Total catch amount: ${sum}*`)
                    .addField("Trash:", row.trash, true)
                    .addField("Common fish:", row.common, true)
                    .addField("Uncommon fish:", row.uncommon, true)
                    .addField("Rare fish:", row.rare, true)
                    .addField("Epic fish:", row.epic, true);
                return message.channel.send({embed});
            }
        }).catch(error => {
            console.log(error);
            return message.reply("Error in command: Stats section. Please try again later.");
        });
    } if (action != undefined && action != "stats" && action != "inv" && action != "inventory" && action != "sell") {
        return message.reply("You didn't provide a valid action. I can either provide you with selling `m~fish sell [type]`, showing your inventory `m~fish inv`, showing your stats `m~fish stats`, or fishing `m~fish`");
    }
};

exports.conf = {
    enabled: true,
    runIn: ["text"],
    aliases: [],
    permLevel: 0,
    botPerms: [],
    requiredFuncs: [],
    cooldown: 15,
};

exports.help = {
    name: "fish",
    description: "Fish and try to turn your credits into a fortune!",
    usage: "[action:str] [kind:str] [amount:int]",
    usageDelim: " ",
    extendedHelp: "Spend 10 credits to fish and catch yourself a fortune! Check someone's stats with `m~fish stats [user]`. Or check your inventory with `m~fish inv`.",
};
<|endoftext|>


<commit_before>//id canal musica = 375842517566095360
module.exports = (client, message, args) => {
    let channel = client.channels.get('375842517566095360');
    //if (message.member.voiceChannel) {
    if (channel)
    {
      channel.join()
      .then(connection =>
      {
        message.reply('Eu conectei no canal com sucesso! Aproveite o som da rádio **Metal & Hardcore**! :musical_note:').then(msg => {
          msg.delete(60000)
        });
        connection.playArbitraryInput('http://www.hrhradio.com/site/popup.php');
        //connection.playFile('./radio/anime01.pls');
      })
    .catch(console.log);
    }
    /*else { message.reply('Você precisa estar em um canal de voz para digitar o comando!');  }  */
    message.delete(60000);
};<commit_msg><commit_after>//id canal musica = 375842517566095360
module.exports = (client, message, args) => {
    let channel = client.channels.get('375842517566095360');
    //if (message.member.voiceChannel) {
    if (channel)
    {
      channel.join()
      .then(connection =>
      {
        message.reply('Eu conectei no canal com sucesso! Aproveite o som da rádio **Metal & Hardcore**! :musical_note:').then(msg => {
          msg.delete(60000)
        });
        connection.playArbitraryInput('http://www.hrhradio.com/site/popup.php/;?.mp3');
        //connection.playFile('./radio/anime01.pls');
      })
    .catch(console.log);
    }
    /*else { message.reply('Você precisa estar em um canal de voz para digitar o comando!');  }  */
    message.delete(60000);
};<|endoftext|>


<commit_before>import resources from 'resources';

test('resources has the required properties', () => {

  expect(resources).toHaveProperty('webmap');
  expect(resources).toHaveProperty('title');
  expect(resources).toHaveProperty('language');

  expect(resources).not.toHaveProperty('Lucas');

  if (resources.useAlternativeLanguage) {
    expect(resources).toHaveProperty('alternativeLanguage');
    expect(resources.alternativeLanguage).toBeDefined();
    expect(resources.alternativeLanguage).toBeTruthy();
  }

  if (resources.initialExtent) {
    const { initialExtent } = resources;
    expect(typeof resources.initialExtent).toBe('object');
    expect(resources.initialExtent).toHaveProperty('x');
    expect(resources.initialExtent).toHaveProperty('y');
    expect(resources.initialExtent).toHaveProperty('z');

    if (initialExtent.x && initialExtent.y && initialExtent.z) {
      expect(typeof resources.initialExtent.x).toBe('number');
      expect(typeof resources.initialExtent.y).toBe('number');
      expect(typeof resources.initialExtent.z).toBe('number');

      expect(resources.initialExtent.x).toBeGreaterThanOrEqual(-180);
      expect(resources.initialExtent.x).toBeLessThan(180);

      expect(resources.initialExtent.y).toBeGreaterThanOrEqual(-90);
      expect(resources.initialExtent.y).toBeLessThan(90);

      expect(resources.initialExtent.z).toBeGreaterThanOrEqual(1);
      expect(resources.initialExtent.z).toBeLessThan(21);
    }

  }

  if (resources.includeCartoTemplateLayers) {
    expect(resources).toHaveProperty('cartoTemplateId');
    expect(resources).toHaveProperty('cartoApiKey');
    expect(resources).toHaveProperty('cartoGroupLabel');
    expect(resources.cartoGroupLabel).toHaveProperty(resources.language);
  }

  expect(resources).toHaveProperty('layerPanel');
  expect(resources).toHaveProperty('layerPanel.GROUP_WEBMAP');
  expect(resources).toHaveProperty('layerPanel.GROUP_WEBMAP.label');
  expect(resources).toHaveProperty('layerPanel.GROUP_WEBMAP.layers');
  expect(resources.layerPanel.GROUP_WEBMAP.layers).toBeInstanceOf(Array);
  expect(resources.layerPanel.GROUP_WEBMAP.layers).toHaveLength(0);

  // expect(resources).toHaveProperty('layerPanel.GROUP_LCD'); //we Are checking for these layers in LossControls & LayerLegend
  // expect(resources).toHaveProperty('layerPanel.GROUP_LCD.layers');
  // expect(resources.layerPanel.GROUP_LCD.layers).toBeInstanceOf(Array);

  // expect(resources).toHaveProperty('layerPanel.GROUP_LC'); //same thing
  // expect(resources).toHaveProperty('layerPanel.GROUP_LC.layers');
  // expect(resources.layerPanel.GROUP_LC.layers).toBeInstanceOf(Array);

  expect(resources).toHaveProperty('layerPanel.GROUP_BASEMAP'); //same thing
  expect(resources).toHaveProperty('layerPanel.GROUP_BASEMAP.layers');
  expect(resources.layerPanel.GROUP_BASEMAP.layers).toBeInstanceOf(Array);

  expect(resources).toHaveProperty('layerPanel.extraLayers');
  expect(resources.layerPanel.extraLayers).toBeInstanceOf(Array); //gets concat'ed somewhere!

});

describe('resources layer spec', () => {

  const layerPanelKeys = Object.keys(resources.layerPanel).filter(g => g !== 'GROUP_BASEMAP' && g !== 'GROUP_WEBMAP' && g !== 'extraLayers');
  const allLayers = layerPanelKeys.map(k => resources.layerPanel[k].layers).reduce((acc, current) => [...acc, ...current], []);

  allLayers.forEach((layer) => {
    if (layer.type === 'wms') {
      it('has a layerName property if it is a WMSLayer', () => {
        expect(layer).toHaveProperty('layerName');
        expect(typeof layer.layerName).toBe('string');
      });
    }
    if (layer.type !== 'remoteDataLayer') {
      it(`layer ${layer.id} has the required properties`, () => {
        if (layer.type !== 'imagery') {
          expect(layer).toHaveProperty('url');
        }
        expect(layer).toHaveProperty('id');
        expect(layer).toHaveProperty('type');
        expect(layer).toHaveProperty('label');
        expect(layer.label).toHaveProperty(resources.language);
        if (layer.filterField) {
          expect(layer.type).toEqual('feature' || 'dynamic');
          expect(layer).toHaveProperty('url');
          expect(typeof layer.filterField).toBe('object');
          expect(layer).toHaveProperty('filterLabel');
          expect(typeof layer.filterLabel).toBe('object');
        }
      });
    } else {
      expect(layer).toHaveProperty('order');
      expect(layer).toHaveProperty('type');
      expect(layer).toHaveProperty('uuid');
    }
  });

  // resources.layerPanel.GROUP_LCD.layers.forEach((layer) => {
  //   it(`the ${layer.id} layer has the properties we need`, () => {
  //     expect(layer).toHaveProperty('id');
  //     expect(layer).toHaveProperty('type');
  //     expect(layer).toHaveProperty('url');
  //     expect(layer).toHaveProperty('label');
  //     expect(layer.label).toHaveProperty(resources.language);
  //   });
  // });

  // resources.layerPanel.GROUP_LC.layers.forEach((layer) => {
  //   it(`the ${layer.id} layer has the properties we need`, () => {
  //     expect(layer).toHaveProperty('id');
  //     expect(layer).toHaveProperty('type');
  //     expect(layer).toHaveProperty('url');
  //     expect(layer).toHaveProperty('label');
  //     expect(layer.label).toHaveProperty(resources.language);
  //   });
  // });

  resources.layerPanel.GROUP_BASEMAP.layers.forEach((layer) => {
    it(`the ${layer.id} basemap layer has the properties we need`, () => {
      expect(layer).toHaveProperty('id');
      expect(layer).toHaveProperty('thumbnailUrl');
    });
  });
});
<commit_msg>Fix test for filter field layer type<commit_after>import resources from 'resources';

test('resources has the required properties', () => {

  expect(resources).toHaveProperty('webmap');
  expect(resources).toHaveProperty('title');
  expect(resources).toHaveProperty('language');

  expect(resources).not.toHaveProperty('Lucas');

  if (resources.useAlternativeLanguage) {
    expect(resources).toHaveProperty('alternativeLanguage');
    expect(resources.alternativeLanguage).toBeDefined();
    expect(resources.alternativeLanguage).toBeTruthy();
  }

  if (resources.initialExtent) {
    const { initialExtent } = resources;
    expect(typeof resources.initialExtent).toBe('object');
    expect(resources.initialExtent).toHaveProperty('x');
    expect(resources.initialExtent).toHaveProperty('y');
    expect(resources.initialExtent).toHaveProperty('z');

    if (initialExtent.x && initialExtent.y && initialExtent.z) {
      expect(typeof resources.initialExtent.x).toBe('number');
      expect(typeof resources.initialExtent.y).toBe('number');
      expect(typeof resources.initialExtent.z).toBe('number');

      expect(resources.initialExtent.x).toBeGreaterThanOrEqual(-180);
      expect(resources.initialExtent.x).toBeLessThan(180);

      expect(resources.initialExtent.y).toBeGreaterThanOrEqual(-90);
      expect(resources.initialExtent.y).toBeLessThan(90);

      expect(resources.initialExtent.z).toBeGreaterThanOrEqual(1);
      expect(resources.initialExtent.z).toBeLessThan(21);
    }

  }

  if (resources.includeCartoTemplateLayers) {
    expect(resources).toHaveProperty('cartoTemplateId');
    expect(resources).toHaveProperty('cartoApiKey');
    expect(resources).toHaveProperty('cartoGroupLabel');
    expect(resources.cartoGroupLabel).toHaveProperty(resources.language);
  }

  expect(resources).toHaveProperty('layerPanel');
  expect(resources).toHaveProperty('layerPanel.GROUP_WEBMAP');
  expect(resources).toHaveProperty('layerPanel.GROUP_WEBMAP.label');
  expect(resources).toHaveProperty('layerPanel.GROUP_WEBMAP.layers');
  expect(resources.layerPanel.GROUP_WEBMAP.layers).toBeInstanceOf(Array);
  expect(resources.layerPanel.GROUP_WEBMAP.layers).toHaveLength(0);

  // expect(resources).toHaveProperty('layerPanel.GROUP_LCD'); //we Are checking for these layers in LossControls & LayerLegend
  // expect(resources).toHaveProperty('layerPanel.GROUP_LCD.layers');
  // expect(resources.layerPanel.GROUP_LCD.layers).toBeInstanceOf(Array);

  // expect(resources).toHaveProperty('layerPanel.GROUP_LC'); //same thing
  // expect(resources).toHaveProperty('layerPanel.GROUP_LC.layers');
  // expect(resources.layerPanel.GROUP_LC.layers).toBeInstanceOf(Array);

  expect(resources).toHaveProperty('layerPanel.GROUP_BASEMAP'); //same thing
  expect(resources).toHaveProperty('layerPanel.GROUP_BASEMAP.layers');
  expect(resources.layerPanel.GROUP_BASEMAP.layers).toBeInstanceOf(Array);

  expect(resources).toHaveProperty('layerPanel.extraLayers');
  expect(resources.layerPanel.extraLayers).toBeInstanceOf(Array); //gets concat'ed somewhere!

});

describe('resources layer spec', () => {

  const layerPanelKeys = Object.keys(resources.layerPanel).filter(g => g !== 'GROUP_BASEMAP' && g !== 'GROUP_WEBMAP' && g !== 'extraLayers');
  const allLayers = layerPanelKeys.map(k => resources.layerPanel[k].layers).reduce((acc, current) => [...acc, ...current], []);

  allLayers.forEach((layer) => {
    if (layer.type === 'wms') {
      it('has a layerName property if it is a WMSLayer', () => {
        expect(layer).toHaveProperty('layerName');
        expect(typeof layer.layerName).toBe('string');
      });
    }
    if (layer.type !== 'remoteDataLayer') {
      it(`layer ${layer.id} has the required properties`, () => {
        if (layer.type !== 'imagery') {
          expect(layer).toHaveProperty('url');
        }
        expect(layer).toHaveProperty('id');
        expect(layer).toHaveProperty('type');
        expect(layer).toHaveProperty('label');
        expect(layer.label).toHaveProperty(resources.language);
        if (layer.filterField) {
          expect(layer.type === 'feature' || layer.type === 'dynamic').toBeTruthy();
          expect(layer).toHaveProperty('url');
          expect(typeof layer.filterField).toBe('object');
          expect(layer).toHaveProperty('filterLabel');
          expect(typeof layer.filterLabel).toBe('object');
        }
      });
    } else {
      expect(layer).toHaveProperty('order');
      expect(layer).toHaveProperty('type');
      expect(layer).toHaveProperty('uuid');
    }
  });

  // resources.layerPanel.GROUP_LCD.layers.forEach((layer) => {
  //   it(`the ${layer.id} layer has the properties we need`, () => {
  //     expect(layer).toHaveProperty('id');
  //     expect(layer).toHaveProperty('type');
  //     expect(layer).toHaveProperty('url');
  //     expect(layer).toHaveProperty('label');
  //     expect(layer.label).toHaveProperty(resources.language);
  //   });
  // });

  // resources.layerPanel.GROUP_LC.layers.forEach((layer) => {
  //   it(`the ${layer.id} layer has the properties we need`, () => {
  //     expect(layer).toHaveProperty('id');
  //     expect(layer).toHaveProperty('type');
  //     expect(layer).toHaveProperty('url');
  //     expect(layer).toHaveProperty('label');
  //     expect(layer.label).toHaveProperty(resources.language);
  //   });
  // });

  resources.layerPanel.GROUP_BASEMAP.layers.forEach((layer) => {
    it(`the ${layer.id} basemap layer has the properties we need`, () => {
      expect(layer).toHaveProperty('id');
      expect(layer).toHaveProperty('thumbnailUrl');
    });
  });
});
<|endoftext|>


<commit_before>/*global console*/
var path = require('path');
var express = require('express');
var helmet = require('helmet');
var Moonboots = require('moonboots');
var config = require('getconfig');
var semiStatic = require('semi-static');
var stylizer = require('stylizer');
var templatizer = require('templatizer');
var app = express();

// a little helper for fixing paths for various enviroments
var fixPath = function (pathString) {
    return path.resolve(path.normalize(pathString));
};

// -----------------
// Configure express
// -----------------
app.use(express.compress());
app.use(express.static(fixPath('public')));
// we only want to expose tests in dev
if (config.isDev) {
    app.use(express.static(fixPath('test/assets')));
    app.use(express.static(fixPath('test/spacemonkey')));
}
app.use(express.bodyParser());
app.use(express.cookieParser());
// in order to test this with spacemonkey we need frames
if (!config.isDev) {
    app.use(helmet.xframe());
}
app.use(helmet.iexss());
app.use(helmet.contentTypeOptions());
app.set('view engine', 'jade');

// ---------------------------------------------------
// Configure Moonboots to serve our client application
// ---------------------------------------------------
var clientApp = new Moonboots({
    jsFileName: '{{{machineName}}}',
    cssFileName: '{{{machineName}}}',
    main: fixPath('client/app.js'),
    developmentMode: config.isDev,
    libraries: [
        fixPath('client/libraries/zepto.js')
    ],
    stylesheets: [
        fixPath('public/css/bootstrap.css'),
        fixPath('public/css/app.css')
    ],
    browserify: {
        debug: false
    },
    server: app,
    beforeBuildJS: function () {
        // This re-builds our template files from jade each time the app's main
        // js file is requested. Which means you can seamlessly change jade and
        // refresh in your browser to get new templates.
        if (config.isDev) {
            templatizer(fixPath('templates'), fixPath('client/templates.js'));
        }
    },
    beforeBuildCSS: function (done) {
        // This re-builds css from stylus each time the app's main
        // css file is requested. Which means you can seamlessly change stylus files
        // and see new styles on refresh.
        if (config.isDev) {
            stylizer({
                infile: fixPath('public/css/app.styl'),
                outfile: fixPath('public/css/app.css'),
                development: true
            }, done);
        }
    }
});

// Set up our little demo API
var api = require('./fakeApi');
app.get('/api/people', api.list);
app.get('/api/people/:id', api.get);
app.delete('/api/people/:id', api.delete);
app.put('/api/people/:id', api.update);
app.post('/api/people', api.add);

// Enable the functional test site in development
if (config.isDev) {
    app.get('/test*', semiStatic({
        folderPath: fixPath('test'),
        root: '/test'
    }));
}

// use a cookie to send config items to client
var clientSettingsMiddleware = function (req, res, next) {
    res.cookie('config', JSON.stringify(config.client));
    next();
};

// configure our main route that will serve our moonboots app
app.get('*', clientSettingsMiddleware, clientApp.html());

// listen for incoming http requests on the port as specified in our config
app.listen(config.http.port);
console.log("{{{title}}} is running at: http://localhost:" + config.http.port + " Yep. That\'s pretty awesome.");
<commit_msg>Corrected a typo in the express server.<commit_after>/*global console*/
var path = require('path');
var express = require('express');
var helmet = require('helmet');
var Moonboots = require('moonboots');
var config = require('getconfig');
var semiStatic = require('semi-static');
var stylizer = require('stylizer');
var templatizer = require('templatizer');
var app = express();

// a little helper for fixing paths for various environments
var fixPath = function (pathString) {
    return path.resolve(path.normalize(pathString));
};

// -----------------
// Configure express
// -----------------
app.use(express.compress());
app.use(express.static(fixPath('public')));
// we only want to expose tests in dev
if (config.isDev) {
    app.use(express.static(fixPath('test/assets')));
    app.use(express.static(fixPath('test/spacemonkey')));
}
app.use(express.bodyParser());
app.use(express.cookieParser());
// in order to test this with spacemonkey we need frames
if (!config.isDev) {
    app.use(helmet.xframe());
}
app.use(helmet.iexss());
app.use(helmet.contentTypeOptions());
app.set('view engine', 'jade');

// ---------------------------------------------------
// Configure Moonboots to serve our client application
// ---------------------------------------------------
var clientApp = new Moonboots({
    jsFileName: '{{{machineName}}}',
    cssFileName: '{{{machineName}}}',
    main: fixPath('client/app.js'),
    developmentMode: config.isDev,
    libraries: [
        fixPath('client/libraries/zepto.js')
    ],
    stylesheets: [
        fixPath('public/css/bootstrap.css'),
        fixPath('public/css/app.css')
    ],
    browserify: {
        debug: false
    },
    server: app,
    beforeBuildJS: function () {
        // This re-builds our template files from jade each time the app's main
        // js file is requested. Which means you can seamlessly change jade and
        // refresh in your browser to get new templates.
        if (config.isDev) {
            templatizer(fixPath('templates'), fixPath('client/templates.js'));
        }
    },
    beforeBuildCSS: function (done) {
        // This re-builds css from stylus each time the app's main
        // css file is requested. Which means you can seamlessly change stylus files
        // and see new styles on refresh.
        if (config.isDev) {
            stylizer({
                infile: fixPath('public/css/app.styl'),
                outfile: fixPath('public/css/app.css'),
                development: true
            }, done);
        }
    }
});

// Set up our little demo API
var api = require('./fakeApi');
app.get('/api/people', api.list);
app.get('/api/people/:id', api.get);
app.delete('/api/people/:id', api.delete);
app.put('/api/people/:id', api.update);
app.post('/api/people', api.add);

// Enable the functional test site in development
if (config.isDev) {
    app.get('/test*', semiStatic({
        folderPath: fixPath('test'),
        root: '/test'
    }));
}

// use a cookie to send config items to client
var clientSettingsMiddleware = function (req, res, next) {
    res.cookie('config', JSON.stringify(config.client));
    next();
};

// configure our main route that will serve our moonboots app
app.get('*', clientSettingsMiddleware, clientApp.html());

// listen for incoming http requests on the port as specified in our config
app.listen(config.http.port);
console.log("{{{title}}} is running at: http://localhost:" + config.http.port + " Yep. That\'s pretty awesome.");
<|endoftext|>


<commit_before>/**
 * Controller
 * @return
 */

export default class extends THINK.Controller {
    //构造方法
    init(http){
        //调用父类构造方法
        super.init(http);
    }
    //所有该控制器(含子类)方法前置方法
    __before(){
        console.log('__before');
    }
    //URI定位到该控制器,如果该控制器不存在某个方法时自动调用
    __empty(){
        return this.json('can\'t find action');
    }
    //indexAction前置方法
    _before_index(){
        console.log('_before_index');
    }
    //控制器默认方法
    indexAction () {
        // test
        return this.display()
        // return this.redirect(this.http.runType.toLowerCase() + "://" + this.http.hostname + ":8080");
    }

}<commit_msg>for jenkins test 8<commit_after>/**
 * Controller
 * @return
 */

export default class extends THINK.Controller {
    //构造方法
    init(http){
        //调用父类构造方法
        super.init(http);
    }
    //所有该控制器(含子类)方法前置方法
    __before(){
        console.log('__before');
    }
    //URI定位到该控制器,如果该控制器不存在某个方法时自动调用
    __empty(){
        return this.json('can\'t find action');
    }
    //indexAction前置方法
    _before_index(){
        console.log('_before_index');
    }
    //控制器默认方法
    indexAction () {
        // test 7
        return this.display();
        // return this.redirect(this.http.runType.toLowerCase() + "://" + this.http.hostname + ":8080");
    }

}<|endoftext|>


<commit_before>import delve from 'dlv';
import { defined } from './util';
import template from './template';

/** Attempts to look up a translated value from a given dictionary.
 *  Also supports json templating using the format: {{variable}}
 *	Falls back to default text.
 *
 *	@private
 *	@param {String} id				Intl field name/id (subject to scope)
 *	@param {String} [scope='']		Scope, which prefixes `id` with `${scope}.`
 *	@param {Object} dictionary		A nested object containing translations
 *	@param {Object} [fields={}]		Template fields for use by translated strings
 *	@param {Number} [plural]		Indicates a quantity, used to trigger pluralization
 *	@param {String|Array} [fallback]	Text to return if no translation is found
 *	@returns {String} translated
 */
export default function translate(id, scope, dictionary, fields, plural, fallback) {
	if (scope) id = scope + '.' + id;

	let value = dictionary && delve(dictionary, id);

	// plural forms:
	// key: ['plural', 'singular']
	// key: { none, one, many }
	// key: { zero, one, other }
	// key: { singular, plural }
	if ((plural || plural===0) && value && typeof value==='object') {
		if (value.splice) {
			value = value[plural] || value[0];
		}
		else if (plural===0 && defined(value.none)) {
			value = value.none || value.zero;
		}
		else if (plural===1 && defined(value.one || value.singular)) {
			value = value.one || value.singular;
		}
		else {
			value = value.some || value.many || value.plural || value.other || value;
		}
	}

	return value && template(value, fields, scope, dictionary) || fallback || null;
}
<commit_msg>Check if "zero" pluralisation form is defined<commit_after>import delve from 'dlv';
import { defined } from './util';
import template from './template';

/** Attempts to look up a translated value from a given dictionary.
 *  Also supports json templating using the format: {{variable}}
 *	Falls back to default text.
 *
 *	@private
 *	@param {String} id				Intl field name/id (subject to scope)
 *	@param {String} [scope='']		Scope, which prefixes `id` with `${scope}.`
 *	@param {Object} dictionary		A nested object containing translations
 *	@param {Object} [fields={}]		Template fields for use by translated strings
 *	@param {Number} [plural]		Indicates a quantity, used to trigger pluralization
 *	@param {String|Array} [fallback]	Text to return if no translation is found
 *	@returns {String} translated
 */
export default function translate(id, scope, dictionary, fields, plural, fallback) {
	if (scope) id = scope + '.' + id;

	let value = dictionary && delve(dictionary, id);

	// plural forms:
	// key: ['plural', 'singular']
	// key: { none, one, many }
	// key: { zero, one, other }
	// key: { singular, plural }
	if ((plural || plural===0) && value && typeof value==='object') {
		if (value.splice) {
			value = value[plural] || value[0];
		}
		else if (plural===0 && defined(value.none || value.zero)) {
			value = value.none || value.zero;
		}
		else if (plural===1 && defined(value.one || value.singular)) {
			value = value.one || value.singular;
		}
		else {
			value = value.some || value.many || value.plural || value.other || value;
		}
	}

	return value && template(value, fields, scope, dictionary) || fallback || null;
}
<|endoftext|>