<commit_before>/*
 javascript functions for the geojson_rest app
*/
gnt.app_version.geojson_rest = '5.0.0';
gnt.geo = {};

/*
 This function queries features from the database that fit the
 given values.

 user -- the user the features belong to, also allowed: '@me', '@all'
 group -- the group the features belong to, also allowed: '@all', '@self'
 limit_params -- string starting with '?'
    parameters in the get limiting parameters:
    time -- the time the features was valid, also allowed '@now', '@all'

*/
gnt.geo.get_features =
function(user, group, limit_params, ajax_params) {
    if(limit_params == undefined) {
        limit_params = "";
    }
    if(ajax_params === undefined) {
        ajax_param = {};
    }
    if(user === undefined) {
        user = '@me';
    }
    if(group === undefined) {
        group = '@self';
    }

    var kwargs = $.extend(
        ajax_params,
        {
            url: "{% url feat %}/" + user + "/" + group + limit_params,
            type: "GET",
            contentType: "application/json",
            dataType: "json",
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
            }
        }
    );
    $.ajax(kwargs);
};

/*
 This function retreives only one feature from the database
 that fit the given user, group and feature_id.

 user -- the user the features belong to, also allowed: '@me', '@all'
 group -- the group the features belong to, also allowed: '@all', '@self'
 feature_id -- the id of the feature

*/
gnt.geo.get_feature =
function(user, group, feature_id, ajax_params) {
    if(limit_params == undefined) {
        limit_params = "";
    }
    if(ajax_params === undefined) {
        ajax_param = {};
    }
    if(user === undefined) {
        user = '@me';
    }
    if(group === undefined) {
        group = '@self';
    }

    var kwargs = $.extend(
        ajax_params,
        {
            url: "{% url feat %}/" + user + "/" + group + "/" + feature_id,
            type: "GET",
            contentType: "application/json",
            dataType: "json",
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
            }
        }
    );
    $.ajax(kwargs);
};

/*
 create_feature function saves a new feature, this function
 only saves one feature at the time. The function takes the
 following arguments:
 user -- the user that is saving the feature, '@me', '@all' reserved
 group -- the group the feature belongs to '@self', '@all' reserved
 feature -- geojson feature with additional parameters
 ajax_params -- possibility to extend the ajax call with this json

 The feature can have the following parameters:

 "type" -- always 'Feature' required
 "geometry" -- geojson geometry required
 "properties" -- json object required
 "id" -- will be overridden as this will create a new feature
 "private" -- tells if the feature is private or not, optional, default: true
 "time" -- time object (read only)
 "user" -- the owner of the feature (read only)
 "group" -- the group the feature belong to (read only)

*/
gnt.geo.create_feature =
function(user, group, feature, ajax_params) {

    var geojson_string = feature;
    if( typeof(" ") !== typeof(geojson_string)) {
        geojson_string = JSON.stringify(geojson_string);
    }
    if(ajax_params === undefined) {
        ajax_param = {};
    }
    if(user === undefined) {
        user = '@me';
    }
    if(group === undefined) {
        group = '@self';
    }

    var kwargs = $.extend(
        ajax_params,
        {
            url: "{% url feat %}/" + user + "/" + group,
            type: "POST",
            data: geojson_string,
            contentType: "application/json",
            dataType: "json",
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
            }
        }
    );
    $.ajax(kwargs);
};

/*
 update_feature, updates a feature with an id.
 All features in the collection should already have been saved
 once and should contain an id.

 user -- the user that the feature belong to
 group -- the group the feature belongs to
 feature -- the features to be updated (check create for params)
 ajax_params -- extra ajax params for ajax call
*/
gnt.geo.update_feature =
function(user, group, feature, ajax_params) {
    var geojson_string = feature;
    var feature_id = '';
    if( typeof(" ") !== typeof(geojson_string)) {
        feature_id = feature.id;
        geojson_string = JSON.stringify(geojson_string);
    } else {
        // need to get the id of the feature
        feature_id = JSON.parse(geojson_string).id;
    }
    if(ajax_params === undefined) {
        ajax_params = {};
    }
    if(user === undefined) {
        user = '@me';
    }
    if(group === undefined) {
        group = '@self';
    }

    var kwargs = $.extend(
        ajax_params,
        {
            url: "{% url feat %}/" + user + "/" + group + "/" + feature_id,
            type: "PUT",
            data: geojson_string,
            contentType: "application/json",
            dataType: "json",
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
            }
        }
    );

    $.ajax(kwargs);
};

/*
 delete_feature, deletes one feature
 the feature has to have an id set to be deleted.
*/
gnt.geo.delete_feature =
function(user, group, feature, ajax_params) {
    var geojson_string = feature;
    var feature_id = '';
    if( typeof(" ") !== typeof(geojson_string)) {
        feature_id = feature.id;
        geojson_string = JSON.stringify(geojson_string);
    } else {
        // need to get the id of the feature
        feature_id = JSON.parse(geojson_string).id;
    }
    if(ajax_params === undefined) {
        ajax_params = {};
    }
    if(user === undefined) {
        user = '@me';
    }
    if(group === undefined) {
        group = '@self';
    }

    var kwargs = $.extend(
        ajax_params,
        {
            url: "{% url feat %}/" + user + "/" + group + "/" + feature_id,
            type: "DELETE",
            contentType: "application/json",
            dataType: "json",
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
            }
        }
    );

    $.ajax(kwargs);
};

/*
 This function will create a property.

 user -- the user the property belongs to, defaults to @me
 group -- the group the property should be saved to defaults to @self
 feature_id -- id of the feature the created property should belong to
               if set as @null the property will not be connected to a feature
 property -- A JSON of the key value pairs to save
 ajax_params -- additional parameters to handle callbacks etc.

*/
gnt.geo.create_property =
function(user, group, feature_id, property, ajax_params) {

    var json_string = property;

    if( typeof(" ") !== typeof(geojson_string)) {
        json_string = JSON.stringify(json_string);
    }

    if(ajax_params === undefined) {
        ajax_params = {};
    }
    if(user === undefined) {
        user = '@me';
    }
    if(group === undefined) {
        group = '@self';
    }
    if(feature_id === undefined) {
        feature_id = '@null';
    }

    var kwargs = $.extend(
        ajax_params,
        {
            url: "{% url prop %}/" + user + "/" + group + "/" + feature_id,
            type: "POST",
            contentType: "application/json",
            dataType: "json",
            data: json_string,
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
            }
        }
    );

    $.ajax(kwargs);
};

/*
 This function will update a property.

 user -- the user the property belongs to, defaults to @me
 group -- the group the property should be saved to defaults to @self
 feature_id -- id of the feature the updated property should belong to
               if set as @null the property will not be connected to a feature
 property -- A JSON of the key value pairs to update, requires an id field
 ajax_params -- additional parameters to handle callbacks etc.

*/
gnt.geo.update_property =
function(user, group, feature_id, property, ajax_params) {

    if( typeof(" ") !== typeof(geojson_string)) {
        property_id = property.id;
        json_string = JSON.stringify(property);
    } else {
        // need to get the id of the feature
        property_id = JSON.parse(property).id;
        json_string = property;
    }

    if(ajax_params === undefined) {
        ajax_params = {};
    }
    if(user === undefined) {
        user = '@me';
    }
    if(group === undefined) {
        group = '@self';
    }
    if(feature_id === undefined) {
        feature_id = '@null';
    }

    var kwargs = $.extend(
        ajax_params,
        {
            url: "{% url prop %}/" + user + "/" + group + "/" + feature_id + "/" + property_id,
            type: "PUT",
            contentType: "application/json",
            dataType: "json",
            data: json_string,
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
            }
        }
    );

    $.ajax(kwargs);
};

/*
get properties

*/
gnt.geo.get_properties = function(user,
                                  group,
                                  feature_id,
                                  property_id,
                                  ajax_params) {

    if(ajax_params === undefined) {
        ajax_param = {};
    }

    if(user === undefined) {
        user = '@all';
    }
    if(group === undefined) {
        group = '@all';
    }
    if(feature_id === undefined) {
        feature_id = '@all';
    }
    if(property_id === undefined) {
        property_id = '@all';
    }

    var kwargs = $.extend(
        ajax_params,
        {
            url: "{% url prop %}/" + user + "/" + group + "/" + feature_id + "/" + property_id,
            type: "GET",
            contentType: "application/json",
            dataType: "json",
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
            }
        }
    );
    $.ajax(kwargs);
};<commit_msg>Features can now be saved as public or private<commit_after>/*
 javascript functions for the geojson_rest app
*/
gnt.app_version.geojson_rest = '5.0.0';
gnt.geo = {};

/*
 This function queries features from the database that fit the
 given values.

 user -- the user the features belong to, also allowed: '@me', '@all'
 group -- the group the features belong to, also allowed: '@all', '@self'
 limit_params -- string starting with '?'
    parameters in the get limiting parameters:
    time -- the time the features was valid, also allowed '@now', '@all'

*/
gnt.geo.get_features =
function(user, group, limit_params, ajax_params) {
    if(limit_params == undefined) {
        limit_params = "";
    }
    if(ajax_params === undefined) {
        ajax_param = {};
    }
    if(user === undefined) {
        user = '@me';
    }
    if(group === undefined) {
        group = '@self';
    }

    var kwargs = $.extend(
        ajax_params,
        {
            url: "{% url feat %}/" + user + "/" + group + limit_params,
            type: "GET",
            contentType: "application/json",
            dataType: "json",
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
            }
        }
    );
    $.ajax(kwargs);
};

/*
 This function retreives only one feature from the database
 that fit the given user, group and feature_id.

 user -- the user the features belong to, also allowed: '@me', '@all'
 group -- the group the features belong to, also allowed: '@all', '@self'
 feature_id -- the id of the feature

*/
gnt.geo.get_feature =
function(user, group, feature_id, ajax_params) {
    if(limit_params == undefined) {
        limit_params = "";
    }
    if(ajax_params === undefined) {
        ajax_param = {};
    }
    if(user === undefined) {
        user = '@me';
    }
    if(group === undefined) {
        group = '@self';
    }

    var kwargs = $.extend(
        ajax_params,
        {
            url: "{% url feat %}/" + user + "/" + group + "/" + feature_id,
            type: "GET",
            contentType: "application/json",
            dataType: "json",
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
            }
        }
    );
    $.ajax(kwargs);
};

/*
 create_feature function saves a new feature, this function
 only saves one feature at the time. The function takes the
 following arguments:
 user -- the user that is saving the feature, '@me', '@all' reserved
 group -- the group the feature belongs to '@self', '@all' reserved
 feature -- geojson feature with additional parameters
 ajax_params -- possibility to extend the ajax call with this json

 The feature can have the following parameters:

 "type" -- always 'Feature' required
 "geometry" -- geojson geometry required
 "properties" -- json object required
 "id" -- will be overridden as this will create a new feature
 "private" -- tells if the feature is private or not, optional, default: true
 "time" -- time object (read only)
 "user" -- the owner of the feature (read only)
 "group" -- the group the feature belong to (read only)

*/
gnt.geo.create_feature =
function(user, group, feature, ajax_params) {

    var geojson_string = feature;
    if( typeof(" ") !== typeof(geojson_string)) {
        geojson_string = JSON.stringify(geojson_string);
    }
    if(ajax_params === undefined) {
        ajax_param = {};
    }
    if(user === undefined) {
        user = '@me';
    }
    if(group === undefined) {
        group = '@self';
    }

    var kwargs = $.extend(
        ajax_params,
        {
            url: "{% url feat %}/" + user + "/" + group,
            type: "POST",
            data: geojson_string,
            contentType: "application/json",
            dataType: "json",
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
            }
        }
    );
    $.ajax(kwargs);
};

/*
 update_feature, updates a feature with an id.
 All features in the collection should already have been saved
 once and should contain an id.

 user -- the user that the feature belong to
 group -- the group the feature belongs to
 feature -- the features to be updated (check create for params)
 ajax_params -- extra ajax params for ajax call
*/
gnt.geo.update_feature =
function(user, group, feature, ajax_params) {
    var geojson_string = feature;
    var feature_id = '';
    if( typeof(" ") !== typeof(geojson_string)) {
        feature_id = feature.id;
        geojson_string = JSON.stringify(geojson_string);
    } else {
        // need to get the id of the feature
        feature_id = JSON.parse(geojson_string).id;
    }
    if(ajax_params === undefined) {
        ajax_params = {};
    }
    if(user === undefined) {
        user = '@me';
    }
    if(group === undefined) {
        group = '@self';
    }

    var kwargs = $.extend(
        ajax_params,
        {
            url: "{% url feat %}/" + user + "/" + group + "/" + feature_id,
            type: "PUT",
            data: geojson_string,
            contentType: "application/json",
            dataType: "json",
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
            }
        }
    );

    $.ajax(kwargs);
};

/*
 delete_feature, deletes one feature
 the feature has to have an id set to be deleted.
*/
gnt.geo.delete_feature =
function(user, group, feature, ajax_params) {
    var geojson_string = feature;
    var feature_id = '';
    if( typeof(" ") !== typeof(geojson_string)) {
        feature_id = feature.id;
        geojson_string = JSON.stringify(geojson_string);
    } else {
        // need to get the id of the feature
        feature_id = JSON.parse(geojson_string).id;
    }
    if(ajax_params === undefined) {
        ajax_params = {};
    }
    if(user === undefined) {
        user = '@me';
    }
    if(group === undefined) {
        group = '@self';
    }

    var kwargs = $.extend(
        ajax_params,
        {
            url: "{% url feat %}/" + user + "/" + group + "/" + feature_id,
            type: "DELETE",
            contentType: "application/json",
            dataType: "json",
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
            }
        }
    );

    $.ajax(kwargs);
};

/*
 This function will create a property.

 user -- the user the property belongs to, defaults to @me
 group -- the group the property should be saved to defaults to @self
 feature_id -- id of the feature the created property should belong to
               if set as @null the property will not be connected to a feature
 property -- A JSON of the key value pairs to save
 ajax_params -- additional parameters to handle callbacks etc.

*/
gnt.geo.create_property =
function(user, group, feature_id, property, ajax_params) {

    var json_string = property;

    if( typeof(" ") !== typeof(geojson_string)) {
        json_string = JSON.stringify(json_string);
    }

    if(ajax_params === undefined) {
        ajax_params = {};
    }
    if(user === undefined) {
        user = '@me';
    }
    if(group === undefined) {
        group = '@self';
    }
    if(feature_id === undefined) {
        feature_id = '@null';
    }

    var kwargs = $.extend(
        ajax_params,
        {
            url: "{% url prop %}/" + user + "/" + group + "/" + feature_id,
            type: "POST",
            contentType: "application/json",
            dataType: "json",
            data: json_string,
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
            }
        }
    );

    $.ajax(kwargs);
};

/*
 This function will update a property.

 user -- the user the property belongs to, defaults to @me
 group -- the group the property should be saved to defaults to @self
 feature_id -- id of the feature the updated property should belong to
               if set as @null the property will not be connected to a feature
 property -- A JSON of the key value pairs to update, requires an id field
 ajax_params -- additional parameters to handle callbacks etc.

*/
gnt.geo.update_property =
function(user, group, feature_id, property, ajax_params) {

    if( typeof(" ") !== typeof(geojson_string)) {
        property_id = property.id;
        json_string = JSON.stringify(property);
    } else {
        // need to get the id of the feature
        property_id = JSON.parse(property).id;
        json_string = property;
    }

    if(ajax_params === undefined) {
        ajax_params = {};
    }
    if(user === undefined) {
        user = '@me';
    }
    if(group === undefined) {
        group = '@self';
    }
    if(feature_id === undefined) {
        feature_id = '@null';
    }

    var kwargs = $.extend(
        ajax_params,
        {
            url: "{% url prop %}/" + user + "/" + group + "/" + feature_id + "/" + property_id,
            type: "PUT",
            contentType: "application/json",
            dataType: "json",
            data: json_string,
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
            }
        }
    );

    $.ajax(kwargs);
};

/*
get properties

*/
gnt.geo.get_properties = function(user,
                                  group,
                                  feature_id,
                                  property_id,
                                  ajax_params) {

    if(ajax_params === undefined) {
        ajax_param = {};
    }

    if(user === undefined) {
        user = '@all';
    }
    if(group === undefined) {
        group = '@all';
    }
    if(feature_id === undefined) {
        feature_id = '@all';
    }
    if(property_id === undefined) {
        property_id = '@all';
    }

    var kwargs = $.extend(
        ajax_params,
        {
            url: "{% url prop %}/" + user + "/" + group + "/" + feature_id + "/" + property_id,
            type: "GET",
            contentType: "application/json",
            dataType: "json",
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
            }
        }
    );
    $.ajax(kwargs);
};
<|endoftext|>


<commit_before>var React = require('react');
var classnames = require('classnames');
var setSelectionLayer = require('./actions/setSelectionLayer');
var getXStartAndWidthOfRowAnnotation = require('./getXStartAndWidthOfRowAnnotation');
var getXCenterOfRowAnnotation = require('./getXCenterOfRowAnnotation');
var Feature = require('./Feature');
var PureRenderMixin = require('react/addons').addons.PureRenderMixin;

var AnnotationContainer = React.createClass({
  mixins: [PureRenderMixin],

  render: function () {
    var annotationRanges = this.props.annotationRanges;
    var bpsPerRow = this.props.bpsPerRow;
    var charWidth = this.props.charWidth;
    var annotationHeight = this.props.annotationHeight;
    var spaceBetweenAnnotations = this.props.spaceBetweenAnnotations;

    if (annotationRanges.length === 0) {
      return null;
    }
    var maxAnnotationYOffset = 0;
    var annotationsSVG = [];
    annotationRanges.forEach(function(annotationRange) {
      if (annotationRange.yOffset > maxAnnotationYOffset) {
        maxAnnotationYOffset = annotationRange.yOffset;
      }
      var annotation = annotationRange.annotation;
// <path
//             onClick={function (event) {
//               // appActions.setCaretPosition(-1);
//               setSelectionLayer(this);
//               event.stopPropagation();
//             }.bind(annotation)}
//             key={annotation.id + 'start:' + annotationRange.start}
//             className={classnames(annotation.id, annotation.type)}
//             d={createAnnotationRawPath(annotationRange, bpsPerRow, charWidth, annotationHeight)}
//             stroke={annotation.color}
//             fillOpacity={0.4}
//             fill={annotation.color}>
//           </path>
      var result = getXStartAndWidthOfRowAnnotation(annotationRange, bpsPerRow, charWidth);
      annotationsSVG.push(
        <svg
          height={annotationHeight}
          width={result.width}
          key={'feature' + annotation.id + 'start:' + annotationRange.start}
          style = {
            {
              display: 'block',
              float: 'left',
              left: result.xStart,
              position: 'absolute',
              marginBottom: spaceBetweenAnnotations,
            }
          }
          >
          <Feature
            onClick={function (event) {
              setSelectionLayer(this);
              event.stopPropagation();
            }.bind(annotation)}
            className={classnames(annotation.id, annotation.type)}
            widthInBps={annotationRange.end - annotationRange.start + 1}
            charWidth={charWidth}
            forward={annotation.forward}
            height={annotationHeight}
            color={annotation.color}
            fill={annotation.color}>
          </Feature>
        </svg>
      );
    });
    var height = (maxAnnotationYOffset + 1) * (annotationHeight + spaceBetweenAnnotations);
    return (

        {annotationsSVG}

    );

    function createAnnotationRawPath(annotationRange, bpsPerRow, charWidth, annotationHeight) {
      var annotation = annotationRange.annotation;
      var result = getXStartAndWidthOfRowAnnotation(annotationRange, bpsPerRow, charWidth);
      var yStart = annotationRange.yOffset * (annotationHeight + spaceBetweenAnnotations);
      var height = annotationHeight;
      var enclosingRangeType = annotationRange.enclosingRangeType;
      var forward = annotation.forward;
      var xEnd = result.xStart + result.width;
      var yEnd = yStart + height;

      if (forward) {

      } else {

      }
      //either "beginning", "end" or "beginningAndEnd"
      if (enclosingRangeType === 'beginningAndEnd') {

      } else {

      }
      var path = "M" + result.xStart + "," + yStart + " L" + xEnd + "," + yStart + " L" + xEnd + "," + yEnd + " L" + result.xStart + "," + yEnd + " Z";
      return path;
    }

  }
});
module.exports = AnnotationContainer;<commit_msg>little change<commit_after>var React = require('react');
var classnames = require('classnames');
var setSelectionLayer = require('./actions/setSelectionLayer');
var getXStartAndWidthOfRowAnnotation = require('./getXStartAndWidthOfRowAnnotation');
var getXCenterOfRowAnnotation = require('./getXCenterOfRowAnnotation');
var Feature = require('./Feature');
var PureRenderMixin = require('react/addons').addons.PureRenderMixin;

var AnnotationContainer = React.createClass({
  mixins: [PureRenderMixin],

  render: function () {
    var annotationRanges = this.props.annotationRanges;
    var bpsPerRow = this.props.bpsPerRow;
    var charWidth = this.props.charWidth;
    var annotationHeight = this.props.annotationHeight;
    var spaceBetweenAnnotations = this.props.spaceBetweenAnnotations;

    if (annotationRanges.length === 0) {
      return null;
    }
    var maxAnnotationYOffset = 0;
    var annotationsSVG = [];
    annotationRanges.forEach(function(annotationRange) {
      if (annotationRange.yOffset > maxAnnotationYOffset) {
        maxAnnotationYOffset = annotationRange.yOffset;
      }
      var annotation = annotationRange.annotation;
// <path
//             onClick={function (event) {
//               // appActions.setCaretPosition(-1);
//               setSelectionLayer(this);
//               event.stopPropagation();
//             }.bind(annotation)}
//             key={annotation.id + 'start:' + annotationRange.start}
//             className={classnames(annotation.id, annotation.type)}
//             d={createAnnotationRawPath(annotationRange, bpsPerRow, charWidth, annotationHeight)}
//             stroke={annotation.color}
//             fillOpacity={0.4}
//             fill={annotation.color}>
//           </path>
      var result = getXStartAndWidthOfRowAnnotation(annotationRange, bpsPerRow, charWidth);
      annotationsSVG.push(
        <svg
          height={annotationHeight}
          width={result.width}
          key={'feature' + annotation.id + 'start:' + annotationRange.start}
          style = {
            {
              display: 'inline-block',
              float: 'top',
              left: result.xStart,
              position: 'relative',
              marginBottom: spaceBetweenAnnotations,
            }
          }
          >
          <Feature
            onClick={function (event) {
              setSelectionLayer(this);
              event.stopPropagation();
            }.bind(annotation)}
            className={classnames(annotation.id, annotation.type)}
            widthInBps={annotationRange.end - annotationRange.start + 1}
            charWidth={charWidth}
            forward={annotation.forward}
            height={annotationHeight}
            color={annotation.color}
            fill={annotation.color}>
          </Feature>
        </svg>
      );
    });
    var height = (maxAnnotationYOffset + 1) * (annotationHeight + spaceBetweenAnnotations);
    return (

        {annotationsSVG}

    );

    function createAnnotationRawPath(annotationRange, bpsPerRow, charWidth, annotationHeight) {
      var annotation = annotationRange.annotation;
      var result = getXStartAndWidthOfRowAnnotation(annotationRange, bpsPerRow, charWidth);
      var yStart = annotationRange.yOffset * (annotationHeight + spaceBetweenAnnotations);
      var height = annotationHeight;
      var enclosingRangeType = annotationRange.enclosingRangeType;
      var forward = annotation.forward;
      var xEnd = result.xStart + result.width;
      var yEnd = yStart + height;

      if (forward) {

      } else {

      }
      //either "beginning", "end" or "beginningAndEnd"
      if (enclosingRangeType === 'beginningAndEnd') {

      } else {

      }
      var path = "M" + result.xStart + "," + yStart + " L" + xEnd + "," + yStart + " L" + xEnd + "," + yEnd + " L" + result.xStart + "," + yEnd + " Z";
      return path;
    }

  }
});
module.exports = AnnotationContainer;<|endoftext|>


<commit_before>/* global describe, it */

var expect = require('chai').expect;
var sinon = require('sinon');
var factory = require('../../../../app/http/handlers/authorize/processtransaction');
var EventEmitter = require('events').EventEmitter;

describe('http/handlers/authorize/processtransaction', function() {

  it('should export factory function', function() {
    expect(factory).to.be.a('function');
  });

  it('should be annotated', function() {
    expect(factory['@implements']).to.equal('http://schemas.authnomicon.org/js/oauth2/http/authorize/processTransactionFunc');
    expect(factory['@singleton']).to.be.undefined;
  });

  describe('processTransaction', function() {
    var resources = {
      infer: function(){}
    }
    var aaa = {
      request: function(){}
    }
    var ds = {
      get: function(){}
    }

    describe('that requires login', function() {
      var allow, info;

      before(function() {
        var dreq = new EventEmitter();
        var dec = new EventEmitter();
        dreq.send = function() {
          process.nextTick(function() {
            dec.emit('prompt', 'login');
            dec.emit('end');
          });
        };

        sinon.stub(resources, 'infer').yields(null, '112210f47de98100');
        sinon.stub(aaa, 'request').returns(dreq).yields(dec);
        sinon.stub(ds, 'get').yields(null, { id: '112210f47de98100', identifier: 'https://api.example.com/', name: 'Example API' });
      });

      after(function() {
        ds.get.restore();
        aaa.request.restore();
        resources.infer.restore();
      });

      before(function(done) {
        var client = {
          id: 's6BhdRkqt3',
          name: 'Example Client',
          redirectURIs: [
            'https://client.example.com/cb'
          ]
        };
        var areq = {
          type: 'code',
          clientID: 's6BhdRkqt3'
        };

        var processTransaction = factory(resources, aaa, ds);
        processTransaction(client, undefined, areq.scope, areq.type, areq, undefined, function(err, a, i) {
          if (err) { return done(err); }
          allow = a;
          info = i;
          done();
        });
      });

      it('should infer resource', function() {
        expect(resources.infer.callCount).to.equal(1);
        expect(resources.infer.args[0][0]).to.equal(undefined);
        expect(resources.infer.args[0][1]).to.deep.equal({
          id: 's6BhdRkqt3',
          name: 'Example Client',
          redirectURIs: [
            'https://client.example.com/cb'
          ]
        });
      });

      it('should request authorization', function() {
        expect(aaa.request.callCount).to.equal(1);
        expect(aaa.request.args[0][0]).to.deep.equal({
          client: {
            id: 's6BhdRkqt3',
            name: 'Example Client',
            redirectURIs: [
              'https://client.example.com/cb'
            ]
          },
          user: undefined,
          resource: {
            id: '112210f47de98100',
            identifier: 'https://api.example.com/',
            name: 'Example API'
          }
        });
      });

      it('should not allow', function() {
        expect(allow).to.equal(false);
      });

      it('should prompt', function() {
        expect(info).to.deep.equal({ prompt: 'login' });
      });
    }); // that requires login

    describe('that permits access', function() {
      var allow, info;

      before(function() {
        var dreq = new EventEmitter();
        var dec = new EventEmitter();
        dreq.send = function() {
          process.nextTick(function() {
            dec.emit('decision', true, [ 'read:foo', 'write:foo' ]);
            dec.emit('end');
          });
        };

        sinon.stub(resources, 'infer').yields(null, 'https://api.example.com/');
        sinon.stub(aaa, 'request').returns(dreq).yields(dec);
        sinon.stub(ds, 'get').yields(null, { id: '112210f47de98100', identifier: 'https://api.example.com/', name: 'Example API' });
      });

      after(function() {
        ds.get.restore();
        aaa.request.restore();
        resources.infer.restore();
      });

      before(function(done) {
        var client = {
          id: 's6BhdRkqt3',
          name: 'Example Client',
          redirectURIs: [
            'https://client.example.com/cb'
          ]
        };
        var areq = {
          type: 'code',
          clientID: 's6BhdRkqt3',
          scope: [ 'read:foo', 'write:foo', 'write:bar' ]
        };

        var processTransaction = factory(resources, aaa, ds);
        processTransaction(client, undefined, areq.scope, areq.type, areq, undefined, function(err, a, i) {
          if (err) { return done(err); }
          allow = a;
          info = i;
          done();
        });
      });

      it('should infer resource', function() {
        expect(resources.infer.callCount).to.equal(1);
        expect(resources.infer.args[0][0]).to.deep.equal([ 'read:foo', 'write:foo', 'write:bar' ]);
        expect(resources.infer.args[0][1]).to.deep.equal({
          id: 's6BhdRkqt3',
          name: 'Example Client',
          redirectURIs: [
            'https://client.example.com/cb'
          ]
        });
      });

      it('should request authorization', function() {
        expect(aaa.request.callCount).to.equal(1);
        expect(aaa.request.args[0][0]).to.deep.equal({
          client: {
            id: 's6BhdRkqt3',
            name: 'Example Client',
            redirectURIs: [
              'https://client.example.com/cb'
            ]
          },
          user: undefined,
          resource: {
            id: '112210f47de98100',
            identifier: 'https://api.example.com/',
            name: 'Example API'
          }
        });
      });

      it('should allow', function() {
        expect(allow).to.equal(true);
      });

      it('should supply result', function() {
        expect(info).to.deep.equal({
          permissions: [ {
            resource: {
            id: '112210f47de98100',
            identifier: 'https://api.example.com/',
            name: 'Example API'
          },
            "scope": [
              "foo"
            ]
          } ]
        });
      });
    }); // that permits access

  }); // processTransaction

});
<commit_msg>Pass user to test.<commit_after>/* global describe, it */

var expect = require('chai').expect;
var sinon = require('sinon');
var factory = require('../../../../app/http/handlers/authorize/processtransaction');
var EventEmitter = require('events').EventEmitter;

describe('http/handlers/authorize/processtransaction', function() {

  it('should export factory function', function() {
    expect(factory).to.be.a('function');
  });

  it('should be annotated', function() {
    expect(factory['@implements']).to.equal('http://schemas.authnomicon.org/js/oauth2/http/authorize/processTransactionFunc');
    expect(factory['@singleton']).to.be.undefined;
  });

  describe('processTransaction', function() {
    var resources = {
      infer: function(){}
    }
    var aaa = {
      request: function(){}
    }
    var ds = {
      get: function(){}
    }

    describe('that requires login', function() {
      var allow, info;

      before(function() {
        var dreq = new EventEmitter();
        var dec = new EventEmitter();
        dreq.send = function() {
          process.nextTick(function() {
            dec.emit('prompt', 'login');
            dec.emit('end');
          });
        };

        sinon.stub(resources, 'infer').yields(null, '112210f47de98100');
        sinon.stub(aaa, 'request').returns(dreq).yields(dec);
        sinon.stub(ds, 'get').yields(null, { id: '112210f47de98100', identifier: 'https://api.example.com/', name: 'Example API' });
      });

      after(function() {
        ds.get.restore();
        aaa.request.restore();
        resources.infer.restore();
      });

      before(function(done) {
        var client = {
          id: 's6BhdRkqt3',
          name: 'Example Client',
          redirectURIs: [
            'https://client.example.com/cb'
          ]
        };
        var areq = {
          type: 'code',
          clientID: 's6BhdRkqt3'
        };

        var processTransaction = factory(resources, aaa, ds);
        processTransaction(client, undefined, areq.scope, areq.type, areq, undefined, function(err, a, i) {
          if (err) { return done(err); }
          allow = a;
          info = i;
          done();
        });
      });

      it('should infer resource', function() {
        expect(resources.infer.callCount).to.equal(1);
        expect(resources.infer.args[0][0]).to.equal(undefined);
        expect(resources.infer.args[0][1]).to.deep.equal({
          id: 's6BhdRkqt3',
          name: 'Example Client',
          redirectURIs: [
            'https://client.example.com/cb'
          ]
        });
      });

      it('should request authorization', function() {
        expect(aaa.request.callCount).to.equal(1);
        expect(aaa.request.args[0][0]).to.deep.equal({
          client: {
            id: 's6BhdRkqt3',
            name: 'Example Client',
            redirectURIs: [
              'https://client.example.com/cb'
            ]
          },
          user: undefined,
          resource: {
            id: '112210f47de98100',
            identifier: 'https://api.example.com/',
            name: 'Example API'
          }
        });
      });

      it('should not allow', function() {
        expect(allow).to.equal(false);
      });

      it('should prompt', function() {
        expect(info).to.deep.equal({ prompt: 'login' });
      });
    }); // that requires login

    describe('that permits access', function() {
      var allow, info;

      before(function() {
        var dreq = new EventEmitter();
        var dec = new EventEmitter();
        dreq.send = function() {
          process.nextTick(function() {
            dec.emit('decision', true, [ 'read:foo', 'write:foo' ]);
            dec.emit('end');
          });
        };

        sinon.stub(resources, 'infer').yields(null, 'https://api.example.com/');
        sinon.stub(aaa, 'request').returns(dreq).yields(dec);
        sinon.stub(ds, 'get').yields(null, { id: '112210f47de98100', identifier: 'https://api.example.com/', name: 'Example API' });
      });

      after(function() {
        ds.get.restore();
        aaa.request.restore();
        resources.infer.restore();
      });

      before(function(done) {
        var client = {
          id: 's6BhdRkqt3',
          name: 'Example Client',
          redirectURIs: [
            'https://client.example.com/cb'
          ]
        };
        var user = {
          id: '1',
          displayName: 'John Doe'
        };
        var areq = {
          type: 'code',
          clientID: 's6BhdRkqt3',
          scope: [ 'read:foo', 'write:foo', 'write:bar' ]
        };

        var processTransaction = factory(resources, aaa, ds);
        processTransaction(client, user, areq.scope, areq.type, areq, undefined, function(err, a, i) {
          if (err) { return done(err); }
          allow = a;
          info = i;
          done();
        });
      });

      it('should infer resource', function() {
        expect(resources.infer.callCount).to.equal(1);
        expect(resources.infer.args[0][0]).to.deep.equal([ 'read:foo', 'write:foo', 'write:bar' ]);
        expect(resources.infer.args[0][1]).to.deep.equal({
          id: 's6BhdRkqt3',
          name: 'Example Client',
          redirectURIs: [
            'https://client.example.com/cb'
          ]
        });
      });

      it('should request authorization', function() {
        expect(aaa.request.callCount).to.equal(1);
        expect(aaa.request.args[0][0]).to.deep.equal({
          client: {
            id: 's6BhdRkqt3',
            name: 'Example Client',
            redirectURIs: [
              'https://client.example.com/cb'
            ]
          },
          user: {
            id: '1',
            displayName: 'John Doe'
          },
          resource: {
            id: '112210f47de98100',
            identifier: 'https://api.example.com/',
            name: 'Example API'
          }
        });
      });

      it('should allow', function() {
        expect(allow).to.equal(true);
      });

      it('should supply result', function() {
        expect(info).to.deep.equal({
          permissions: [ {
            resource: {
            id: '112210f47de98100',
            identifier: 'https://api.example.com/',
            name: 'Example API'
          },
            "scope": [
              "foo"
            ]
          } ]
        });
      });
    }); // that permits access

  }); // processTransaction

});
<|endoftext|>


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

CLASS({
  package: 'foam.dao.auth',
  name: 'Account',
  properties: [
    'id',
    {
      model_: 'EMailProperty',
      name: 'email',
      mode: 'read-only'
    },
    {
      model_: 'foam.core.types.StringEnumProperty',
      name: 'level',
      defaultValue: 'user',
      choices: [
        'user',
        'admin'
      ]
    }
  ]
});
<commit_msg>Add authorizationCodeo to Account.js<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  package: 'foam.dao.auth',
  name: 'Account',
  properties: [
    'id',
    {
      model_: 'EMailProperty',
      name: 'email',
      mode: 'read-only'
    },
    {
      model_: 'foam.core.types.StringEnumProperty',
      name: 'level',
      defaultValue: 'user',
      choices: [
        'user',
        'admin'
      ]
    },
    {
      name: 'authorizationCode',
      type: 'String'
    }
  ]
});
<|endoftext|>


<commit_before>import uuid from 'uuid';
import Events from 'ampersand-events';

function setupWidgets() {
  if (!window.ciscospark.widget || typeof window.ciscospark.widget !== `function`) {
    window.ciscospark.widget = function widget(el) {

      /**
       * Base Widget
       * @param {object} widgetEl HTML element where widget mounts
       * @returns {object} this
       */
      function W(widgetEl) {
        this.el = widgetEl;

        /**
         * Handle React Events
         *
         * @param {string} name of event
         * @param {object} data
         * @returns {CustomEvent} event
         */
        this.handleEvent = (name, data) => {
          const [resource, eventName] = name.split(`:`);
          const detail = {
            resource,
            event: eventName,
            data
          };

          if (data.actorId) {
            detail.actorId = data.actorId;
          }

          if (data.action) {
            detail.action = data.action;
          }

          // Dispatch DOM event
          const event = new CustomEvent(name, {
            detail
          });
          this.el.dispatchEvent(event);

          // Trigger ampersand events
          this.trigger(name, detail);

          // Trigger onEvent callback
          if (this.options.onEvent) {
            return this.options.onEvent(name, detail);
          }

          return this;
        };

        return this;
      }

      // Attach widget functions to prototype
      W.prototype = window.ciscospark.widgetFn;

      // Hook in ampersand-events
      Object.assign(W.prototype, Events);

      /**
       * Creates a new widget object and stores it
       * @param  {object} widgetEl HTML element where a widget is mounted
       * @returns {object} widgetObject
       */
      function createNewWidget(widgetEl) {
        const widgetObj = new W(widgetEl);
        const id = uuid.v4();
        // Store ID as attribute on dom element
        widgetEl.setAttribute(`data-uuid`, id);
        window.ciscospark.widgetStore[id] = widgetObj;
        return widgetObj;
      }

      /**
       * Retrieves a Widget from global widget store
       * @param  {object} widgetEl HTML element where a widget is mounted
       * @returns {object} widgetObject
       */
      function getWidget(widgetEl) {
        // Check if element exists and is HTML Element
        if (widgetEl && widgetEl.nodeType === 1) {
          // Get ID as attribute on dom element
          const id = widgetEl.getAttribute(`data-uuid`);
          // Add class
          widgetEl.classList.add(`ciscospark-widget`);
          // Get widget from store if it exists
          const widgetObj = window.ciscospark.widgetStore[id];
          if (widgetObj) {
            return widgetObj;
          }
          // Otherwise create new widget store
          return createNewWidget(widgetEl);
        }
        console.warn(`WARNING: ciscospark.widget: No HTML element provided.`); // eslint-disable-line no-console
        return false;
      }

      return getWidget(el);
    };
  }
}

/**
 * Register widget to browser globals
 * @param  {String}  name  Name of widget type
 * @param  {Function}  widgetInit  Method to instantiate widget into DOM
 * @param  {Function}  widgetRemove  Clean up and tear down
 * @param  {Boolean}  [force=false]  Force registry even if widget with same name already registered
 * @returns {undefined}
 */

export default function registerWidget(name, widgetInit, widgetRemove, force = false) {
  // Inject widget into browser globals
  if (!window.ciscospark) {
    window.ciscospark = {};
  }
  if (!window.ciscospark.widgetStore) {
    window.ciscospark.widgetStore = {};
  }
  if (!window.ciscospark.widgetFn) {
    window.ciscospark.widgetFn = {};
  }

  // Creates widget bindings
  if (typeof window.ciscospark.widgetFn[`${name}Widget`] === `function` && !force) {
    console.warn(`${name} Widget is already registered.`); // eslint-disable-line no-console
  }
  else {
    window.ciscospark.widgetFn[`${name}Widget`] = function(options) { // eslint-disable-line func-names
      this.options = options;
      const widgetOptions = Object.assign({}, options, {
        onEvent: this.handleEvent
      });
      this.widgetOptions = widgetOptions;
      widgetInit(this.el, widgetOptions);

      // Attach remove method
      this.remove = (callback) => new Promise((resolve) => {
        const id = this.el.getAttribute(`data-uuid`);
        // Remove ampersand events
        this.off();
        const removed = widgetRemove(this.el);
        Reflect.deleteProperty(window.ciscospark.widgetStore, id);
        if (typeof callback === `function`) {
          return callback(removed);
        }
        return resolve(removed);
      });

      return this;
    };
  }
  setupWidgets();
}
<commit_msg>feat(widget-base): Add version to constructor and instance<commit_after>import uuid from 'uuid';
import Events from 'ampersand-events';

function setupWidgets() {
  if (!window.ciscospark.widget || typeof window.ciscospark.widget !== `function`) {
    window.ciscospark.widget = function widget(el) {

      /**
       * Base Widget
       * @param {object} widgetEl HTML element where widget mounts
       * @returns {object} this
       */
      function W(widgetEl) {
        this.el = widgetEl;

        /**
         * Handle React Events
         *
         * @param {string} name of event
         * @param {object} data
         * @returns {CustomEvent} event
         */
        this.handleEvent = (name, data) => {
          const [resource, eventName] = name.split(`:`);
          const detail = {
            resource,
            event: eventName,
            data
          };

          if (data.actorId) {
            detail.actorId = data.actorId;
          }

          if (data.action) {
            detail.action = data.action;
          }

          // Dispatch DOM event
          const event = new CustomEvent(name, {
            detail
          });
          this.el.dispatchEvent(event);

          // Trigger ampersand events
          this.trigger(name, detail);

          // Trigger onEvent callback
          if (this.options.onEvent) {
            return this.options.onEvent(name, detail);
          }

          return this;
        };

        return this;
      }

      // Attach widget functions to prototype
      W.prototype = window.ciscospark.widgetFn;

      // Hook in ampersand-events
      Object.assign(W.prototype, Events);

      /**
       * Creates a new widget object and stores it
       * @param  {object} widgetEl HTML element where a widget is mounted
       * @returns {object} widgetObject
       */
      function createNewWidget(widgetEl) {
        const widgetObj = new W(widgetEl);
        const id = uuid.v4();
        // Store ID as attribute on dom element
        widgetEl.setAttribute(`data-uuid`, id);
        window.ciscospark.widgetStore[id] = widgetObj;
        return widgetObj;
      }

      /**
       * Retrieves a Widget from global widget store
       * @param  {object} widgetEl HTML element where a widget is mounted
       * @returns {object} widgetObject
       */
      function getWidget(widgetEl) {
        // Check if element exists and is HTML Element
        if (widgetEl && widgetEl.nodeType === 1) {
          // Get ID as attribute on dom element
          const id = widgetEl.getAttribute(`data-uuid`);
          // Add class
          widgetEl.classList.add(`ciscospark-widget`);
          // Get widget from store if it exists
          const widgetObj = window.ciscospark.widgetStore[id];
          if (widgetObj) {
            return widgetObj;
          }
          // Otherwise create new widget store
          return createNewWidget(widgetEl);
        }
        console.warn(`WARNING: ciscospark.widget: No HTML element provided.`); // eslint-disable-line no-console
        return false;
      }

      return getWidget(el);
    };
  }
}

/**
 * Register widget to browser globals
 * @param  {String}  name  Name of widget type
 * @param  {Function}  widgetInit  Method to instantiate widget into DOM
 * @param  {Function}  widgetRemove  Clean up and tear down
 * @param  {Boolean}  [force=false]  Force registry even if widget with same name already registered
 * @returns {undefined}
 */

export default function registerWidget(name, widgetInit, widgetRemove, force = false) {
  // Inject widget into browser globals
  if (!window.ciscospark) {
    window.ciscospark = {};
  }
  if (!window.ciscospark.widgetStore) {
    window.ciscospark.widgetStore = {};
  }
  if (!window.ciscospark.widgetFn) {
    window.ciscospark.widgetFn = {};
  }

  // Creates widget bindings
  if (typeof window.ciscospark.widgetFn[`${name}Widget`] === `function` && !force) {
    console.warn(`${name} Widget is already registered.`); // eslint-disable-line no-console
  }
  else {
    window.ciscospark.widgetFn[`${name}Widget`] = function(options) { // eslint-disable-line func-names
      this.options = options;
      const widgetOptions = Object.assign({}, options, {
        onEvent: this.handleEvent
      });
      this.widgetOptions = widgetOptions;
      widgetInit(this.el, widgetOptions);

      // Add version number to widget
      this.version = process.env.REACT_CISCOSPARK_VERSION;

      // Attach remove method
      this.remove = (callback) => new Promise((resolve) => {
        const id = this.el.getAttribute(`data-uuid`);
        // Remove ampersand events
        this.off();
        const removed = widgetRemove(this.el);
        Reflect.deleteProperty(window.ciscospark.widgetStore, id);
        if (typeof callback === `function`) {
          return callback(removed);
        }
        return resolve(removed);
      });

      return this;
    };
    window.ciscospark.widgetFn[`${name}Widget`].version = process.env.REACT_CISCOSPARK_VERSION;
  }
  setupWidgets();
}
<|endoftext|>


<commit_before>const path = require('path')
const Discord = require('discord.js-commando')
const request = require('request-promise')
const config = require('./data/client.json')
const DiscordServer = require('./DiscordServer')
const {Cache} = require('./GlobalCache')
const requestDebug = require('request-debug')
const SettingProvider = require('./commands/SettingProvider')
const Util = require('./Util')

if (config.loud) requestDebug(request, (type, data) => console.log(`${type} ${data.debugId} : ${data.uri || data.statusCode}`))

/**
 * The main Discord bot class, only one per shard.
 * @class DiscordBot
 */
class DiscordBot {
  constructor () {
    this.initialize()
    this.servers = {}
  }

  /**
   * Initialize the bot, hook up events, and log in.
   * @memberof DiscordBot
   */
  initialize () {
    this.bot = new Discord.Client({
      shardId: parseInt(process.env.SHARD_ID, 10),
      shardCount: parseInt(process.env.SHARD_COUNT, 10),
      apiRequestMethod: config.apiRequestMethod || 'sequential',
      disabledEvents: ['TYPING_START', 'VOICE_STATE_UPDATE', 'PRESENCE_UPDATE', 'MESSAGE_DELETE', 'MESSAGE_UPDATE'],
      owner: config.owner || '0',
      commandPrefix: config.commandPrefix || '!',
      unknownCommandResponse: false
    })

    this.bot.setProvider(new SettingProvider())

    // Instantiate the shard's Cache singleton to interface with the main process.
    // A global variable is used here because the cache is dependent on the client
    // being initialized, but I don't like the idea of having to pass down the cache
    // from this object into every instance (DiscordMember, DiscordServer). This seemed
    // like the best solution.
    global.Cache = new Cache(this.bot)
    this.shardClientUtil = global.Cache.shardClientUtil

    // Set a reference to this instance inside of the client
    // for use in Commando modules. Is this bad? Probably.
    this.bot.discordBot = this

    // Events

    // We use .bind(this) so that the context remains within
    // the class and not the event.
    this.bot.on('ready', this.ready.bind(this))
    this.bot.on('guildMemberAdd', this.guildMemberAdd.bind(this))
    if (config.loud) this.bot.on('error', (message) => console.log(message))

    // Only hook up if lockNicknames mode is enabled.
    if (config.lockNicknames) {
      this.bot.on('message', this.message.bind(this))
    }

    // Register commands
    this.bot.registry
      .registerGroup('rover', 'RoVer')
      .registerDefaultTypes()
      .registerDefaultGroups()
      .registerDefaultCommands({
        ping: false,
        commandState: false,
        prefix: true,
        help: true
      })
      .registerCommandsIn(path.join(__dirname, 'commands'))

    // Login.
    this.bot.login(process.env.CLIENT_TOKEN)
  }

  /**
   * Called when the bot is ready and has logged in.
   * @listens Discord.Client#ready
   * @memberof DiscordBot
   */
  ready () {
    console.log(`Shard ${process.env.SHARD_ID} is ready, serving ${this.bot.guilds.array().length} guilds.`)

    let currentActivity = 0
    let totalUsers = null

    request('https://verify.eryn.io/api/count')
      .then(count => {
        totalUsers = (parseInt(count, 10) / 1000).toFixed(1) + 'K'
      })

    setInterval(async () => {
      currentActivity++
      if (currentActivity === 2 && totalUsers == null) currentActivity++

      if (currentActivity > 3) {
        currentActivity = 0
      }

      switch (currentActivity) {
        case 0:
          this.bot.user.setActivity('http://eryn.io/RoVer')
          break
        case 1:
          let totalGuilds = (await this.shardClientUtil.fetchClientValues('guilds.size')).reduce((prev, val) => prev + val, 0)
          this.bot.user.setActivity(`${totalGuilds} servers`, { type: 'WATCHING' })
          break
        case 2:
          this.bot.user.setActivity(`${totalUsers} users`, { type: 'LISTENING' })
          break
        case 3:
          this.bot.user.setActivity('!rover', { type: 'LISTENING' })
          break
      }
    }, 15000)

    this.bot.user.setActivity('http://eryn.io/RoVer')
  }

  /**
   * This method is called when a user sends a message, but it's used
   * for setting their nickname back to what it should be if they've
   * changed it. Only active if lockNicknames is true in config.
   * @listens Discord.Client#message
   * @param {Message} message The new message.
   * @memberof DiscordBot
   */
  async message (message) {
    // Don't want to do anything if this is a DM or message was sent by the bot itself.
    // Additionally, if the message is !verify, we don't want to run it twice (since it
    // will get picked up by the command anyway)
    if (!message.guild || message.author.id === this.bot.user.id || message.cleanContent.toLowerCase() === message.guild.commandPrefix + 'verify' || message.author.bot) {
      return
    }

    // We call discordMember.verify but we want to retain the cache
    // and we don't want it to post any announcements.
    let server = await this.getServer(message.guild.id)
    let member = await server.getMember(message.author.id)
    if (!member) return

    if (server.getSetting('verifyChannel') === message.channel.id && message.cleanContent.toLowerCase() !== message.guild.commandPrefix + 'verify') {
      message.delete()
      return member.verify({ message })
    }

    await member.verify({
      announce: false,
      clearBindingsCache: false
    })
  }

  /**
   * This is called when a user joins any Discord server.
   * @listens Discord.Client#guildMemberAdd
   * @param {GuildMember} member The new guild member
   * @memberof DiscordBot
   */
  async guildMemberAdd (member) {
    if (member.user.bot) return

    let server = await this.getServer(member.guild.id)

    if (server.getSetting('joinDM') === false) {
      return
    }

    let discordMember = await server.getMember(member.id)
    if (!member) return
    let action = await discordMember.verify()

    try {
      if (action.status) {
        member.send(server.getWelcomeMessage(action, member))
      } else if (!action.status && action.nonFatal) {
        member.send(`Welcome to ${member.guild.name}! You are already verified, but something went wrong when updating your roles. Try running \`${member.guild.commandPrefix}verify\` in the server for more information.`)
      } else {
        member.send(`Welcome to ${member.guild.name}! This Discord server uses a Roblox account verification system to keep our community safe. Verifying your account is quick and safe and doesn't require any information other than your username. All you have to do is either join a game or put a code in your profile, and you're in!\n\nVisit the following link to verify your Roblox account: ${Util.getVerifyLink(member.guild)}`)
      }
    } catch (e) {}
  }

  /**
   * This is used to get the DiscordServer instance associated
   * with the specific guild id.
   * @param {Snowflake} id Guild id
   * @returns {Promise<DiscordServer>} DiscordServer
   * @memberof DiscordBot
   */
  async getServer (id) {
    if (!this.servers[id]) {
      this.servers[id] = new DiscordServer(this, id)
      await this.servers[id].loadSettings()
    } else if (!this.servers[id].areSettingsLoaded) {
      await this.servers[id].loadSettings()
    }
    return this.servers[id]
  }

  /**
   * This is called by the update server when a user verifies
   * online. It updates the member in every DiscordServer they
   * are in.
   * @param {object} args An object with keys `id` (string) and `guilds` (array)
   * @memberof DiscordBot
   */
  async globallyUpdateMember (args) {
    let {id, guilds} = args

    // Start off by clearing their global cache.
    DiscordServer.clearMemberCache(id)

    let firstRun = true

    // Iterate through all of the guilds the bot is in.
    for (let guildId of guilds) {
      try {
        if (!this.bot.guilds.has(guildId)) continue

        let guild = this.bot.guilds.get(guildId)
        let server = await this.getServer(guild.id)

        let member = await server.getMember(id)
        if (!member) continue
        let action = await member.verify({
          // We want to clear the group rank bindings cache because
          // this is the first iteration.
          clearBindingsCache: firstRun
        })

        if (!action.status && !action.nonFatal) {
          // If there's a fatal error, don't continue with the rest.
          break
        } else if (action.status && server.hasCustomWelcomeMessage()) {
          // It worked, checking if there's a custom welcome message.
          await this.bot.users.fetch(id)

          let guildMember = await this.bot.guilds.get(guild.id).members.fetch(id)
          guildMember.send(server.getWelcomeMessage(action, guildMember))
        }

        firstRun = false
      } catch (e) {
        continue
      }
    }
  }
}

module.exports = DiscordBot
<commit_msg>Remove !prefix data store<commit_after>const path = require('path')
const Discord = require('discord.js-commando')
const request = require('request-promise')
const config = require('./data/client.json')
const DiscordServer = require('./DiscordServer')
const {Cache} = require('./GlobalCache')
const requestDebug = require('request-debug')
const SettingProvider = require('./commands/SettingProvider')
const Util = require('./Util')

if (config.loud) requestDebug(request, (type, data) => console.log(`${type} ${data.debugId} : ${data.uri || data.statusCode}`))

/**
 * The main Discord bot class, only one per shard.
 * @class DiscordBot
 */
class DiscordBot {
  constructor () {
    this.initialize()
    this.servers = {}
  }

  /**
   * Initialize the bot, hook up events, and log in.
   * @memberof DiscordBot
   */
  initialize () {
    this.bot = new Discord.Client({
      shardId: parseInt(process.env.SHARD_ID, 10),
      shardCount: parseInt(process.env.SHARD_COUNT, 10),
      apiRequestMethod: config.apiRequestMethod || 'sequential',
      disabledEvents: ['TYPING_START', 'VOICE_STATE_UPDATE', 'PRESENCE_UPDATE', 'MESSAGE_DELETE', 'MESSAGE_UPDATE'],
      owner: config.owner || '0',
      commandPrefix: config.commandPrefix || '!',
      unknownCommandResponse: false
    })

    // this.bot.setProvider(new SettingProvider())

    // Instantiate the shard's Cache singleton to interface with the main process.
    // A global variable is used here because the cache is dependent on the client
    // being initialized, but I don't like the idea of having to pass down the cache
    // from this object into every instance (DiscordMember, DiscordServer). This seemed
    // like the best solution.
    global.Cache = new Cache(this.bot)
    this.shardClientUtil = global.Cache.shardClientUtil

    // Set a reference to this instance inside of the client
    // for use in Commando modules. Is this bad? Probably.
    this.bot.discordBot = this

    // Events

    // We use .bind(this) so that the context remains within
    // the class and not the event.
    this.bot.on('ready', this.ready.bind(this))
    this.bot.on('guildMemberAdd', this.guildMemberAdd.bind(this))
    if (config.loud) this.bot.on('error', (message) => console.log(message))

    // Only hook up if lockNicknames mode is enabled.
    if (config.lockNicknames) {
      this.bot.on('message', this.message.bind(this))
    }

    // Register commands
    this.bot.registry
      .registerGroup('rover', 'RoVer')
      .registerDefaultTypes()
      .registerDefaultGroups()
      .registerDefaultCommands({
        ping: false,
        commandState: false,
        prefix: true,
        help: true
      })
      .registerCommandsIn(path.join(__dirname, 'commands'))

    // Login.
    this.bot.login(process.env.CLIENT_TOKEN)
  }

  /**
   * Called when the bot is ready and has logged in.
   * @listens Discord.Client#ready
   * @memberof DiscordBot
   */
  ready () {
    console.log(`Shard ${process.env.SHARD_ID} is ready, serving ${this.bot.guilds.array().length} guilds.`)

    let currentActivity = 0
    let totalUsers = null

    request('https://verify.eryn.io/api/count')
      .then(count => {
        totalUsers = (parseInt(count, 10) / 1000).toFixed(1) + 'K'
      })

    setInterval(async () => {
      currentActivity++
      if (currentActivity === 2 && totalUsers == null) currentActivity++

      if (currentActivity > 3) {
        currentActivity = 0
      }

      switch (currentActivity) {
        case 0:
          this.bot.user.setActivity('http://eryn.io/RoVer')
          break
        case 1:
          let totalGuilds = (await this.shardClientUtil.fetchClientValues('guilds.size')).reduce((prev, val) => prev + val, 0)
          this.bot.user.setActivity(`${totalGuilds} servers`, { type: 'WATCHING' })
          break
        case 2:
          this.bot.user.setActivity(`${totalUsers} users`, { type: 'LISTENING' })
          break
        case 3:
          this.bot.user.setActivity('!rover', { type: 'LISTENING' })
          break
      }
    }, 15000)

    this.bot.user.setActivity('http://eryn.io/RoVer')
  }

  /**
   * This method is called when a user sends a message, but it's used
   * for setting their nickname back to what it should be if they've
   * changed it. Only active if lockNicknames is true in config.
   * @listens Discord.Client#message
   * @param {Message} message The new message.
   * @memberof DiscordBot
   */
  async message (message) {
    // Don't want to do anything if this is a DM or message was sent by the bot itself.
    // Additionally, if the message is !verify, we don't want to run it twice (since it
    // will get picked up by the command anyway)
    if (!message.guild || message.author.id === this.bot.user.id || message.cleanContent.toLowerCase() === message.guild.commandPrefix + 'verify' || message.author.bot) {
      return
    }

    // We call discordMember.verify but we want to retain the cache
    // and we don't want it to post any announcements.
    let server = await this.getServer(message.guild.id)
    let member = await server.getMember(message.author.id)
    if (!member) return

    if (server.getSetting('verifyChannel') === message.channel.id && message.cleanContent.toLowerCase() !== message.guild.commandPrefix + 'verify') {
      message.delete()
      return member.verify({ message })
    }

    await member.verify({
      announce: false,
      clearBindingsCache: false
    })
  }

  /**
   * This is called when a user joins any Discord server.
   * @listens Discord.Client#guildMemberAdd
   * @param {GuildMember} member The new guild member
   * @memberof DiscordBot
   */
  async guildMemberAdd (member) {
    if (member.user.bot) return

    let server = await this.getServer(member.guild.id)

    if (server.getSetting('joinDM') === false) {
      return
    }

    let discordMember = await server.getMember(member.id)
    if (!member) return
    let action = await discordMember.verify()

    try {
      if (action.status) {
        member.send(server.getWelcomeMessage(action, member))
      } else if (!action.status && action.nonFatal) {
        member.send(`Welcome to ${member.guild.name}! You are already verified, but something went wrong when updating your roles. Try running \`${member.guild.commandPrefix}verify\` in the server for more information.`)
      } else {
        member.send(`Welcome to ${member.guild.name}! This Discord server uses a Roblox account verification system to keep our community safe. Verifying your account is quick and safe and doesn't require any information other than your username. All you have to do is either join a game or put a code in your profile, and you're in!\n\nVisit the following link to verify your Roblox account: ${Util.getVerifyLink(member.guild)}`)
      }
    } catch (e) {}
  }

  /**
   * This is used to get the DiscordServer instance associated
   * with the specific guild id.
   * @param {Snowflake} id Guild id
   * @returns {Promise<DiscordServer>} DiscordServer
   * @memberof DiscordBot
   */
  async getServer (id) {
    if (!this.servers[id]) {
      this.servers[id] = new DiscordServer(this, id)
      await this.servers[id].loadSettings()
    } else if (!this.servers[id].areSettingsLoaded) {
      await this.servers[id].loadSettings()
    }
    return this.servers[id]
  }

  /**
   * This is called by the update server when a user verifies
   * online. It updates the member in every DiscordServer they
   * are in.
   * @param {object} args An object with keys `id` (string) and `guilds` (array)
   * @memberof DiscordBot
   */
  async globallyUpdateMember (args) {
    let {id, guilds} = args

    // Start off by clearing their global cache.
    DiscordServer.clearMemberCache(id)

    let firstRun = true

    // Iterate through all of the guilds the bot is in.
    for (let guildId of guilds) {
      try {
        if (!this.bot.guilds.has(guildId)) continue

        let guild = this.bot.guilds.get(guildId)
        let server = await this.getServer(guild.id)

        let member = await server.getMember(id)
        if (!member) continue
        let action = await member.verify({
          // We want to clear the group rank bindings cache because
          // this is the first iteration.
          clearBindingsCache: firstRun
        })

        if (!action.status && !action.nonFatal) {
          // If there's a fatal error, don't continue with the rest.
          break
        } else if (action.status && server.hasCustomWelcomeMessage()) {
          // It worked, checking if there's a custom welcome message.
          await this.bot.users.fetch(id)

          let guildMember = await this.bot.guilds.get(guild.id).members.fetch(id)
          guildMember.send(server.getWelcomeMessage(action, guildMember))
        }

        firstRun = false
      } catch (e) {
        continue
      }
    }
  }
}

module.exports = DiscordBot
<|endoftext|>


<commit_before>function PPApplication(canvasName) {
  this.canvasName = canvasName;
}

PPApplication.prototype.setEditController = function (controller) {
  this.editController = controller;
  this.editController.setTournament(this.tournament);
}

PPApplication.prototype.setTournament = function ( tObj ) {
  this.tournament = tObj;
  this.canvasView = new PPCanvasView(this.tournament);
  var canvas = $(this.canvasName);
  var self = this;

  this.canvasView.setCanvas(canvas);

  canvas.onclick = function handleClick (e) {
    self.canvasView.handleClick(e);
  }

  this.setEditController(new PPEditController());
}

PPApplication.prototype.titleChanged = function (id, evt) {
    this.tournament.titleChanged(id,evt);
}

PPApplication.prototype.redraw = function () {
  this.canvasView.redraw();
}
<commit_msg>Add optional editor parameter to constructor.  Add setCanvasView method.<commit_after>function PPApplication(canvasName, editor) {
  this.canvasName = canvasName;

  if (editor != null ) {
    this.setEditController(editor);
  }
}

PPApplication.prototype.setEditController = function (controller) {
  this.editController = controller;

  if(this.tournament != null ) {
    this.editController.setTournament(this.tournament);
  }
}

PPApplication.prototype.setCanvasView = function (view) {
  this.canvasView = view;

  var canvas = $(this.canvasName);
  var self = this;

  this.canvasView.setCanvas(canvas);

  canvas.onclick = function handleClick (e) {
    self.canvasView.handleClick(e);
  }

}

PPApplication.prototype.setTournament = function ( tObj ) {
  this.tournament = tObj;

  this.setCanvasView( new PPCanvasView(this.tournament) );

  if (this.editController != null ) {
    this.editController.setTournament(this.tournament);
  }

}

PPApplication.prototype.titleChanged = function (id, evt) {
    this.tournament.titleChanged(id,evt);
}

PPApplication.prototype.redraw = function () {
  this.canvasView.redraw();
}
<|endoftext|>


<commit_before>var characterBuilder = function(game){};

characterBuilder.prototype = {
	create: function(){
		hitPointsVal = 1;
		moveVal = 0;
		rangeVal = 1;
		attackVal = 0;
		defenseVal = 0;

		xOffset = 250;
		yOffset = 120;

		this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
		this.scale.pageAlignHorizontally = true;
		this.scale.pageAlignVertically = true;
		this.scale.setScreenSize(true);
		game.stage.backgroundColor = "#7d7d7d";

		character = game.add.sprite(document.body.offsetWidth/2,
									document.body.offsetHeight/2, "character");
		character.anchor.setTo(0.5, 0.5);
		character.scale.setTo(0.5, 0.5);

		stats = game.add.group();

		hitPointsTile = game.add.sprite(xOffset, 0, "hitpoints");
		hitPointsTile.scale.setTo(0.85, 0.85);
		hitPointsTile.anchor.setTo(0.5, 0.5);
		moveTile = game.add.sprite(xOffset, yOffset, "move");
		moveTile.scale.setTo(0.85, 0.85);
		moveTile.anchor.setTo(0.5, 0.5);
		rangeTile = game.add.sprite(xOffset, yOffset*2, "range");
		rangeTile.scale.setTo(0.85, 0.85);
		rangeTile.anchor.setTo(0.5, 0.5);
		attackTile = game.add.sprite(xOffset, yOffset*3, "attack");
		attackTile.scale.setTo(0.85, 0.85);
		attackTile.anchor.setTo(0.5, 0.5);
		defenseTile = game.add.sprite(xOffset, yOffset*4, "defense");
		defenseTile.scale.setTo(0.85, 0.85);
		defenseTile.anchor.setTo(0.5, 0.5);

		stats.add(hitPointsTile);
		stats.add(moveTile);
		stats.add(rangeTile);
		stats.add(attackTile);
		stats.add(defenseTile);

		var style = {font: "32px Arial", fill: "#000000", align: "center"};

		hitPointsText = game.add.text(hitPointsTile.x, hitPointsTile.y,
									 hitPointsVal.toString(), style);
		hitPointsText.anchor.set(0.5);

		moveText = game.add.text(moveTile.x, moveTile.y + 25,
								 moveVal.toString(), style);
		moveText.anchor.set(0.5);

		rangeText = game.add.text(rangeTile.x, rangeTile.y + 25,
								  rangeVal.toString(), style);
		rangeText.anchor.set(0.5);

		attackText = game.add.text(attackTile.x, attackTile.y + 25,
								   attackVal.toString(), style);
		attackText.anchor.set(0.5);

		defenseText = game.add.text(defenseTile.x, defenseTile.y + 25,
								 	defenseVal.toString(), style);
		defenseText.anchor.set(0.5);

		stats.add(hitPointsText);
		stats.add(moveText);
		stats.add(rangeText);
		stats.add(attackText);
		stats.add(defenseText);

		// creates plus and minus buttons
		for(var i = 0; i < 5; i++){
			var minusButton = game.add.button(xOffset-75, yOffset*i, "minus",
										this.decreaseStat, this);
			minusButton.scale.setTo(0.4, 0.4);
			minusButton.anchor.setTo(0.5, 0.5);
			minusButton.input.useHandCursor = true;

			var plusButton = game.add.button(xOffset+75, yOffset*i, "plus",
										this.increaseStat, this);
			plusButton.scale.setTo(0.4, 0.4);
			plusButton.anchor.setTo(0.5, 0.5);
			plusButton.input.useHandCursor = true;

			stats.add(minusButton);
			stats.add(plusButton);
		}

		// centers stats on y axis EXCEPT NOT REALLY
		stats.y = (document.body.offsetHeight/2) - stats.height/2;
	},

	increaseStat: function(button){
		if(button.y == yOffset*4){
			defenseVal++;
			defenseText.text = defenseVal.toString();
		}
		else if(button.y == yOffset*3){
			attackVal++;
			attackText.text = attackVal.toString();
		}
		else if(button.y == yOffset*2){
			rangeVal++;
			rangeText.text = rangeVal.toString();
		}
		else if(button.y == yOffset){
			moveVal++;
			moveText.text = moveVal.toString();
		}
		else if(button.y == 0){
			hitPointsVal++;
			hitPointsText.text = hitPointsVal.toString();
		}

	},

	decreaseStat: function(button){
		if(button.y == yOffset*4){
			if(defenseVal > 0){
				defenseVal--;
				defenseText.text = defenseVal.toString();
			}
		}
		else if(button.y == yOffset*3){
			if(attackVal > 0){
				attackVal--;
				attackText.text = attackVal.toString();
			}
		}
		else if(button.y == yOffset*2){
			if(rangeVal > 1){
				rangeVal--;
				rangeText.text = rangeVal.toString();
			}
		}
		else if(button.y == yOffset){
			if(moveVal > 0){
				moveVal--;
				moveText.text = moveVal.toString();
			}
		}
		else if(button.y == 0){
			if(hitPointsVal > 1){
				hitPointsVal--;
				hitPointsText.text = hitPointsVal.toString();
			}
		}
	}
}<commit_msg>set limit to stat points but need to make that visible to user<commit_after>var characterBuilder = function(game){};

characterBuilder.prototype = {
	create: function(){
		totalStatPoints = 15;
		hitPointsVal = 1;
		moveVal = 0;
		rangeVal = 1;
		attackVal = 0;
		defenseVal = 0;

		xOffset = 250;
		yOffset = 120;

		this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
		this.scale.pageAlignHorizontally = true;
		this.scale.pageAlignVertically = true;
		this.scale.setScreenSize(true);
		game.stage.backgroundColor = "#7d7d7d";

		character = game.add.sprite(document.body.offsetWidth/2,
									document.body.offsetHeight/2, "character");
		character.anchor.setTo(0.5, 0.5);
		character.scale.setTo(0.5, 0.5);

		stats = game.add.group();

		hitPointsTile = game.add.sprite(xOffset, 0, "hitpoints");
		hitPointsTile.scale.setTo(0.85, 0.85);
		hitPointsTile.anchor.setTo(0.5, 0.5);
		moveTile = game.add.sprite(xOffset, yOffset, "move");
		moveTile.scale.setTo(0.85, 0.85);
		moveTile.anchor.setTo(0.5, 0.5);
		rangeTile = game.add.sprite(xOffset, yOffset*2, "range");
		rangeTile.scale.setTo(0.85, 0.85);
		rangeTile.anchor.setTo(0.5, 0.5);
		attackTile = game.add.sprite(xOffset, yOffset*3, "attack");
		attackTile.scale.setTo(0.85, 0.85);
		attackTile.anchor.setTo(0.5, 0.5);
		defenseTile = game.add.sprite(xOffset, yOffset*4, "defense");
		defenseTile.scale.setTo(0.85, 0.85);
		defenseTile.anchor.setTo(0.5, 0.5);

		stats.add(hitPointsTile);
		stats.add(moveTile);
		stats.add(rangeTile);
		stats.add(attackTile);
		stats.add(defenseTile);

		var style = {font: "32px Arial", fill: "#000000", align: "center"};

		hitPointsText = game.add.text(hitPointsTile.x, hitPointsTile.y,
									 hitPointsVal.toString(), style);
		hitPointsText.anchor.set(0.5);

		moveText = game.add.text(moveTile.x, moveTile.y + 25,
								 moveVal.toString(), style);
		moveText.anchor.set(0.5);

		rangeText = game.add.text(rangeTile.x, rangeTile.y + 25,
								  rangeVal.toString(), style);
		rangeText.anchor.set(0.5);

		attackText = game.add.text(attackTile.x, attackTile.y + 25,
								   attackVal.toString(), style);
		attackText.anchor.set(0.5);

		defenseText = game.add.text(defenseTile.x, defenseTile.y + 25,
								 	defenseVal.toString(), style);
		defenseText.anchor.set(0.5);

		stats.add(hitPointsText);
		stats.add(moveText);
		stats.add(rangeText);
		stats.add(attackText);
		stats.add(defenseText);

		// creates plus and minus buttons
		for(var i = 0; i < 5; i++){
			var minusButton = game.add.button(xOffset-75, yOffset*i, "minus",
										this.decreaseStat, this);
			minusButton.scale.setTo(0.4, 0.4);
			minusButton.anchor.setTo(0.5, 0.5);
			minusButton.input.useHandCursor = true;

			var plusButton = game.add.button(xOffset+75, yOffset*i, "plus",
										this.increaseStat, this);
			plusButton.scale.setTo(0.4, 0.4);
			plusButton.anchor.setTo(0.5, 0.5);
			plusButton.input.useHandCursor = true;

			stats.add(minusButton);
			stats.add(plusButton);
		}

		// centers stats on y axis EXCEPT NOT REALLY
		stats.y = (document.body.offsetHeight/2) - stats.height/2;
	},

	increaseStat: function(button){
		if(totalStatPoints > 0){
			if(button.y == yOffset*4){
				defenseVal++;
				totalStatPoints--;
				defenseText.text = defenseVal.toString();
			}
			else if(button.y == yOffset*3){
				attackVal++;
				totalStatPoints--;
				attackText.text = attackVal.toString();
			}
			else if(button.y == yOffset*2){
				rangeVal++;
				totalStatPoints--;
				rangeText.text = rangeVal.toString();
			}
			else if(button.y == yOffset){
				moveVal++;
				totalStatPoints--;
				moveText.text = moveVal.toString();
			}
			else if(button.y == 0){
				hitPointsVal++;
				totalStatPoints--;
				hitPointsText.text = hitPointsVal.toString();
			}
		}

	},

	decreaseStat: function(button){
		if(button.y == yOffset*4){
			if(defenseVal > 0){
				defenseVal--;
				totalStatPoints++;
				defenseText.text = defenseVal.toString();
			}
		}
		else if(button.y == yOffset*3){
			if(attackVal > 0){
				attackVal--;
				totalStatPoints++;
				attackText.text = attackVal.toString();
			}
		}
		else if(button.y == yOffset*2){
			if(rangeVal > 1){
				rangeVal--;
				totalStatPoints++;
				rangeText.text = rangeVal.toString();
			}
		}
		else if(button.y == yOffset){
			if(moveVal > 0){
				moveVal--;
				totalStatPoints++;
				moveText.text = moveVal.toString();
			}
		}
		else if(button.y == 0){
			if(hitPointsVal > 1){
				hitPointsVal--;
				totalStatPoints++;
				hitPointsText.text = hitPointsVal.toString();
			}
		}
	}
}<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var util = require('util');
var utils = require('../util/utils')

//Convert to pascal case
var pascalCase = function(input) {

}
var reqopt = function(coverage) {
    coverage['OptionalImplicitQuery'] = 0;
    coverage['OptionalImplicitHeader'] = 0;
    coverage['OptionalImplicitBody'] = 0;
    coverage['OptionalIntegerParameter'] = 0;
    coverage['OptionalIntegerProperty'] = 0;
    coverage['OptionalIntegerHeader'] = 0;
    coverage['OptionalStringParameter'] = 0;
    coverage['OptionalStringProperty'] = 0;
    coverage['OptionalStringHeader'] = 0;
    coverage['OptionalClassParameter'] = 0;
    coverage['OptionalClassProperty'] = 0;
    coverage['OptionalArrayParameter'] = 0;
    coverage['OptionalArrayProperty'] = 0;
    coverage['OptionalArrayHeader'] = 0;
    coverage['OptionalGlobalQuery'] = 0;

    router.get('/implicit/required/path/:pathParameter', function(req, res, next) {
        utils.send400(res, next, 'Client library failed to throw when an implicitly required path parameter is not provided.');
    });

    router.put('/implicit/optional/:scenario', function(req, res, next) {
        if (req.params.scenario === 'query') {
            if (!req.query.queryParameter) {
                coverage['OptionalImplicitQuery']++;
                res.status(200).end();
            } else {
                utils.send400(res, next, 'Please send a null to optional query.');
            }
        } else if (req.params.scenario === 'header') {
            if (!req.get('headerParameter')) {
                coverage['OptionalImplicitHeader']++;
                res.status(200).end();
            } else {
                utils.send400(res, next, 'Please send a null to optional header.');
            }
        } else if (req.params.scenario === 'body') {
            if (!req.body) {
                coverage['OptionalImplicitBody']++;
                res.status(200).end();
            } else {
                utils.send400(res, next, 'Please send a null to optional body.');
            }
        } else {
            utils.send400(res, next, 'Must specify either it\'s "required" or "optional", "' + req.params.required + '" provided.');
        }
    });

    router.put('/required/:type/:scenario', function(req, res, next) {
        utils.send400(res, next, 'Client library failed to throw when a required value type is not provided.');
    });

    router.post('/optional/:type/:scenario', function(req, res, next) {
        var covered = "Optional" + utils.toPascalCase(req.params.type) + utils.toPascalCase(req.params.scenario);
        console.log('scenario: ' + covered + '\n');
        if (req.params.scenario === 'parameter') {
            if (!req.body) {
                coverage[covered]++;
                res.status(200).end();
            } else {
                utils.send400(res, next, 'Please send a null to optional ' + req.params.type + ' body.');
            }
        } else if (req.params.scenario === 'property') {
            if (req.body && !req.body['value']) {
                coverage[covered]++;
                res.status(200).end();
            } else {
                utils.send400(res, next, 'Please send an ' + req.params.type + ' wrapper with ' + req.params.type + ' value \'null\'');
            }
        } else if (req.params.scenario === 'header') {
            if (!req.get('headerParameter')) {
                coverage[covered]++;
                res.status(200).end();
            } else {
                utils.send400(res, next, 'Please send a null to optional ' + req.params.type + ' header.');
            }
        } else if (req.params.scenario === 'response') {
            coverage[covered]++;
            res.status(200).end('null');
        } else if (req.params.scenario === 'responseProperty') {
            coverage[covered]++;
            res.status(200).end('{"value": null }');
        } else if (req.params.scenario === 'responseHeader') {
            coverage[covered]++;
            res.status(200).set('value', null).end();
        }
    });

    router.get('/global/required/path/:required_global_path', function(req, res, next) {
        utils.send400(res, next, 'Client library failed to throw when an implicitly required path parameter is not provided.');
    });

    router.get('/global/required/query', function(req, res, next) {
        utils.send400(res, next, 'Client library failed to throw when an explicitly required query parameter is not provided.');
    });

    router.get('/global/optional/query', function(req, res, next) {
        if (!req.query.optional_global_query) {
            coverage["OptionalGlobalQuery"]++;
            res.status(200).end();
        } else {
            utils.send400(res, next, 'Please send a null to optional query parameter');
        }
    });
};

reqopt.prototype.router = router;

module.exports = reqopt;<commit_msg>Fixed test to support flattening<commit_after>var express = require('express');
var router = express.Router();
var util = require('util');
var utils = require('../util/utils')

//Convert to pascal case
var pascalCase = function(input) {

}
var reqopt = function(coverage) {
    coverage['OptionalImplicitQuery'] = 0;
    coverage['OptionalImplicitHeader'] = 0;
    coverage['OptionalImplicitBody'] = 0;
    coverage['OptionalIntegerParameter'] = 0;
    coverage['OptionalIntegerProperty'] = 0;
    coverage['OptionalIntegerHeader'] = 0;
    coverage['OptionalStringParameter'] = 0;
    coverage['OptionalStringProperty'] = 0;
    coverage['OptionalStringHeader'] = 0;
    coverage['OptionalClassParameter'] = 0;
    coverage['OptionalClassProperty'] = 0;
    coverage['OptionalArrayParameter'] = 0;
    coverage['OptionalArrayProperty'] = 0;
    coverage['OptionalArrayHeader'] = 0;
    coverage['OptionalGlobalQuery'] = 0;

    router.get('/implicit/required/path/:pathParameter', function(req, res, next) {
        utils.send400(res, next, 'Client library failed to throw when an implicitly required path parameter is not provided.');
    });

    router.put('/implicit/optional/:scenario', function(req, res, next) {
        if (req.params.scenario === 'query') {
            if (!req.query.queryParameter) {
                coverage['OptionalImplicitQuery']++;
                res.status(200).end();
            } else {
                utils.send400(res, next, 'Please send a null to optional query.');
            }
        } else if (req.params.scenario === 'header') {
            if (!req.get('headerParameter')) {
                coverage['OptionalImplicitHeader']++;
                res.status(200).end();
            } else {
                utils.send400(res, next, 'Please send a null to optional header.');
            }
        } else if (req.params.scenario === 'body') {
            if (!req.body) {
                coverage['OptionalImplicitBody']++;
                res.status(200).end();
            } else {
                utils.send400(res, next, 'Please send a null to optional body.');
            }
        } else {
            utils.send400(res, next, 'Must specify either it\'s "required" or "optional", "' + req.params.required + '" provided.');
        }
    });

    router.put('/required/:type/:scenario', function(req, res, next) {
        utils.send400(res, next, 'Client library failed to throw when a required value type is not provided.');
    });

    router.post('/optional/:type/:scenario', function(req, res, next) {
        var covered = "Optional" + utils.toPascalCase(req.params.type) + utils.toPascalCase(req.params.scenario);
        console.log('scenario: ' + covered + '\n');
        if (req.params.scenario === 'parameter') {
            if (!req.body) {
                coverage[covered]++;
                res.status(200).end();
            } else {
                utils.send400(res, next, 'Please send a null to optional ' + req.params.type + ' body.');
            }
        } else if (req.params.scenario === 'property') {
            if (!req.body || (req.body && !req.body['value'])) {
                coverage[covered]++;
                res.status(200).end();
            } else {
                utils.send400(res, next, 'Please send an ' + req.params.type + ' wrapper with ' + req.params.type + ' value \'null\'');
            }
        } else if (req.params.scenario === 'header') {
            if (!req.get('headerParameter')) {
                coverage[covered]++;
                res.status(200).end();
            } else {
                utils.send400(res, next, 'Please send a null to optional ' + req.params.type + ' header.');
            }
        } else if (req.params.scenario === 'response') {
            coverage[covered]++;
            res.status(200).end('null');
        } else if (req.params.scenario === 'responseProperty') {
            coverage[covered]++;
            res.status(200).end('{"value": null }');
        } else if (req.params.scenario === 'responseHeader') {
            coverage[covered]++;
            res.status(200).set('value', null).end();
        }
    });

    router.get('/global/required/path/:required_global_path', function(req, res, next) {
        utils.send400(res, next, 'Client library failed to throw when an implicitly required path parameter is not provided.');
    });

    router.get('/global/required/query', function(req, res, next) {
        utils.send400(res, next, 'Client library failed to throw when an explicitly required query parameter is not provided.');
    });

    router.get('/global/optional/query', function(req, res, next) {
        if (!req.query.optional_global_query) {
            coverage["OptionalGlobalQuery"]++;
            res.status(200).end();
        } else {
            utils.send400(res, next, 'Please send a null to optional query parameter');
        }
    });
};

reqopt.prototype.router = router;

module.exports = reqopt;<|endoftext|>


<commit_before>var slackMsgs = require('./slackMsgs.js');
var url = require('url');
var Trello = require('node-trello');
var Promise = require('bluebird');
var mongo = require('mongoskin');

var uri = process.env.MONGODB_URI;
var trelloKey = process.env.HUBOT_TRELLO_KEY;
// promisify mongoskin with bluebird
Object.keys(mongo).forEach(function (key) {
    var value = mongo[key];
    if (typeof value === "function") {
        Promise.promisifyAll(value);
        Promise.promisifyAll(value.prototype);
    }
});
Promise.promisifyAll(mongo);
// connect to mLab database
var db = mongo.MongoClient.connect(uri);

var bcrypt = require('bcryptjs');
var request = require('request-promise');
var encryption = require('./encryption.js');

var app_key = process.env.HUBOT_TRELLO_KEY;
var oauth_secret = process.env.HUBOT_TRELLO_OAUTH;

module.exports = function (robot) {

    var oauth_secrets = {};
    var loginCallback = `https://andreasbot.herokuapp.com/hubot/trello-token`;
    var scope = 'read,write,account'
    var TrelloOAuth = require('./trello-oauth.js')
    var tOAuth = new TrelloOAuth(app_key, oauth_secret, loginCallback, 'Hubot', scope);

    robot.respond(/trello auth/, function (res) {
        let userId = res.message.user.id;
        tOAuth.getRequestToken(function (err, data) {
            oauth_secrets['username'] = res.message.user.name;
            oauth_secrets['id'] = res.message.user.id;
            oauth_secrets[data.oauth_token] = data.oauth_token_secret;

            res.reply(data.redirect);
        })
    })

    robot.router.get('/hubot/trello-token', function (req, res_r) {
        let args = req.query;
        let query = url.parse(req.url, true).query;
        let token = query.oauth_token;
        args['oauth_token_secret'] = oauth_secrets[token];
        tOAuth.getAccessToken(args, function (err, data) {
            if (err) throw err;
            let userName = oauth_secrets['username'];
            let userId = oauth_secrets['id'];
            let token = encryption.encrypt(data['oauth_access_token']); // encrypt token before storing it
            // TODO: encryption -> return promise
            // TODO: get trello username and save
            //TODO error
            var trelloUsername = data.username
            db.bind('users');
            db.users.findAndModify({_id:userId},["_id",1],{ $push: {trello_token: token } },
            {upsert: true}, function (err, result) {
                if (err) throw err;
                if (result) {
                    robot.logger.info(`User's Token Added to DB!`)
                };
            })

        })
        res_r.redirect('/a');
    });

    /**********************************************************/
    /* DEPRECATED */
    robot.respond(/trello get token/i, function (res_r) {

        let scope = 'read,write,account';
        let name = 'Hubot';
        let expr = '30days';
        let cb_method = 'fragment';
        let return_url = 'https://andreasbot.herokuapp.com/hubot/trello-token';
        let url = `https://trello.com/1/authorize?expiration=${expr}&name=${name}&scope=${scope}&key=${app_key}&response_type=token&callback_method=${cb_method}&return_url=${return_url}`;
        var msg = slackMsgs.basicMessage();

        msg.attachments[0].pretext = "Please get a token to authorize your Trello account";
        msg.attachments[0].title = "Trello Token";
        msg.attachments[0].title_link = url;
        msg.attachments[0].text = "Copy the token from the link above and run\n *trello add token <YOUR TOKEN>*";
        msg.attachments[0].footer = "Trello";
        msg.attachments[0].footer_icon = "https://d2k1ftgv7pobq7.cloudfront.net/meta/u/res/images/b428584f224c42e98d158dad366351b0/trello-mark-blue.png";
        res_r.send(msg);
    })

    /**********************************************************/
    /* DEPRECATED */
    robot.respond(/trello add token (.*)/i, function (res_r) {
        var token = res_r.match[1];
        //***IMPORTANT***
        // the .env assignment doesnt work with HEROKU!
        // must set up a heroku client and communicate through their api
        process.env['HUBOT_TRELLO_TOKEN'] = token;
    })
}<commit_msg>db - findAndModify4<commit_after>var slackMsgs = require('./slackMsgs.js');
var url = require('url');
var Trello = require('node-trello');
var Promise = require('bluebird');
var mongo = require('mongoskin');

var uri = process.env.MONGODB_URI;
var trelloKey = process.env.HUBOT_TRELLO_KEY;
// promisify mongoskin with bluebird
Object.keys(mongo).forEach(function (key) {
    var value = mongo[key];
    if (typeof value === "function") {
        Promise.promisifyAll(value);
        Promise.promisifyAll(value.prototype);
    }
});
Promise.promisifyAll(mongo);
// connect to mLab database
var db = mongo.MongoClient.connect(uri);

var bcrypt = require('bcryptjs');
var request = require('request-promise');
var encryption = require('./encryption.js');

var app_key = process.env.HUBOT_TRELLO_KEY;
var oauth_secret = process.env.HUBOT_TRELLO_OAUTH;

module.exports = function (robot) {

    var oauth_secrets = {};
    var loginCallback = `https://andreasbot.herokuapp.com/hubot/trello-token`;
    var scope = 'read,write,account'
    var TrelloOAuth = require('./trello-oauth.js')
    var tOAuth = new TrelloOAuth(app_key, oauth_secret, loginCallback, 'Hubot', scope);

    robot.respond(/trello auth/, function (res) {
        let userId = res.message.user.id;
        tOAuth.getRequestToken(function (err, data) {
            oauth_secrets['username'] = res.message.user.name;
            oauth_secrets['id'] = res.message.user.id;
            oauth_secrets[data.oauth_token] = data.oauth_token_secret;

            res.reply(data.redirect);
        })
    })

    robot.router.get('/hubot/trello-token', function (req, res_r) {
        let args = req.query;
        let query = url.parse(req.url, true).query;
        let token = query.oauth_token;
        args['oauth_token_secret'] = oauth_secrets[token];
        tOAuth.getAccessToken(args, function (err, data) {
            if (err) throw err;
            let userName = oauth_secrets['username'];
            let userId = oauth_secrets['id'];
            let token = encryption.encrypt(data['oauth_access_token']); // encrypt token before storing it
            // TODO: encryption -> return promise
            // TODO: get trello username and save
            //TODO error
            var trelloUsername = data.username
            db.bind('users');
            db.users.findAndModify({_id:userId},["_id",1],{ $push: {trello_token: token } },
            {upsert: true}, function (err, result) {
                if (err) throw err;
                if (result) {
                    robot.logger.info(`User's Token Added to DB!\n`, result)
                };
            })

        })
        res_r.redirect('/a');
    });

    /**********************************************************/
    /* DEPRECATED */
    robot.respond(/trello get token/i, function (res_r) {

        let scope = 'read,write,account';
        let name = 'Hubot';
        let expr = '30days';
        let cb_method = 'fragment';
        let return_url = 'https://andreasbot.herokuapp.com/hubot/trello-token';
        let url = `https://trello.com/1/authorize?expiration=${expr}&name=${name}&scope=${scope}&key=${app_key}&response_type=token&callback_method=${cb_method}&return_url=${return_url}`;
        var msg = slackMsgs.basicMessage();

        msg.attachments[0].pretext = "Please get a token to authorize your Trello account";
        msg.attachments[0].title = "Trello Token";
        msg.attachments[0].title_link = url;
        msg.attachments[0].text = "Copy the token from the link above and run\n *trello add token <YOUR TOKEN>*";
        msg.attachments[0].footer = "Trello";
        msg.attachments[0].footer_icon = "https://d2k1ftgv7pobq7.cloudfront.net/meta/u/res/images/b428584f224c42e98d158dad366351b0/trello-mark-blue.png";
        res_r.send(msg);
    })

    /**********************************************************/
    /* DEPRECATED */
    robot.respond(/trello add token (.*)/i, function (res_r) {
        var token = res_r.match[1];
        //***IMPORTANT***
        // the .env assignment doesnt work with HEROKU!
        // must set up a heroku client and communicate through their api
        process.env['HUBOT_TRELLO_TOKEN'] = token;
    })
}<|endoftext|>