<commit_before>var PDP = (function ( pdp ) {

  'use strict';

  // The Query Object
  // ----------------
  // The `query` object is used to cache filter values and store methods
  // that manipulate filter values.
  var query = {};

  // If debug is set to true, dummy data will be used.
  query.debug = false;

  // Set a default format for the data download.
  query.format = query.debug ? 'json' : 'jsonp?$callback=';

  // Set a default endpoint for AJAX requests.
  query.endpoint = query.debug ? 'static/js/static_data/' : 'https://api.consumerfinance.gov/data/hmda/';

  // Seconds to wait on a response from the API before giving up.
  query.secondsToWait = 180;

  // Whether or not they want codes in their downloaded file.
  query.codes = false;

  // `query`'s `params` stores filter values.
  query.params = {};

  // The `reset` method empties the `params` object.
  // If a preset is passed, some defaults will be set.
  query.reset = function( preset ) {

    // The year is selected independent of the preset, because
    // of this we have to ensure it doesn't get overwritten.
    var years = $('.field.as_of_year select').val() || [];

    switch( preset ) {

      // All originated mortgages.
      case 'originations':
        this.params = {
          as_of_year: {
            values: years,
            comparator: '='
          },
          action_taken: {
            values: [1],
            comparator: '='
          }
        };
      break;

      // First-lien, owner-occupied, 1-4 family homes (including manufactured homes).
      case 'common':
        this.params = {
          as_of_year: {
            values: years,
            comparator: '='
          },
          property_type: {
            values: [1,2],
            comparator: '='
          },
          owner_occupancy: {
            values: [1],
            comparator: '='
          },
          lien_status: {
            values: [1],
            comparator: '='
          },
          action_taken: {
            values: [1],
            comparator: '='
          }
        };
      break;

      // Empty everything.
      case 'clear':
        this.params = {};
        break;

      // Default to an empty state with whatever years they've selected.
      default:
        this.params = {
          as_of_year: {
            values: years,
            comparator: '='
          }
        };
        break;

    }

    return this;

  };

  // The `updateAll` method runs through all the filter field values the user has selected
  // and stores them in the `params` object.
  query.updateAll = function( options ) {

    var fields,
        opts = options || {};

    switch( opts.source ) {
      case 'url':
        fields = pdp.app.getUrlValues();
        break;
      // State is stored in a cookie. Removing this functionality for now because
      // it's confusing the UX team. I'd rather work on other stuff than explain
      // to them how this works. Winter is coming.
      // case 'session':
      //   fields = pdp.query.getCookie();
      //   break;
      default:
        fields = pdp.form.getFields();
    }

    this.reset('clear');

    // Iterate over all the filter field values and push them into `query.params`.
    function _processField( field ) {

      if ( field.name && field.values ) {

        // Initalize an empty param object if need be.
        if ( typeof query.params[ field.name ] === 'undefined' ) {
          query.params[ field.name ] = {
            values: [],
            comparator: '='
          };
        }

        // If the value is a string from a text box we don't want to iterate
        // over it because it will be split up the characters.
        if ( field.type === 'text' ) {
          query.params[ field.name ].values = [ field.values ];
        } else {
          _.forEach( field.values, function( val, name ){

            var values = query.params[ field.name ].values;

            // Only push the value if it's not already in there.
            if ( !_.contains( values, val ) ) {
              values.push( val );
            }

          });
        }

        query.params[ field.name ].comparator = field.comparator;

      }

    }

    _.forEach( fields, _processField );

    pdp.observer.emitEvent( 'params:updated' );

  };

  // The `setCookie` method stores the param object in a cookie.
  query.setCookie = function() {

    $.cookie( '_hmda', pdp.form.getFields(), { expires: 1 } );

  };

  // The `getCookie` method retrives the param object from a cookie.
  query.getCookie = function() {

    return $.cookie( '_hmda' );

  };

  // The `generateUrlHash` method builds and returns a URL hash from `query`'s `params`.
  query.generateUrlHash = function() {
    var hash,
        hashParams = [];

    // Loop through params, stringify them and push them into the temp array.
    function buildHashParam( param, name ) {

      if ( !param.values[0] ) {
        return;
      }

      // If it's not a number, add quotes around the params.
      hashParams.push( name + param.comparator + param.values.join(',') );

    }
    _.forEach( query.params, buildHashParam );

    hash = '!/' + hashParams.join('&') + '&section=' + pdp.app.currentSection;
    return hash;

  };

  query.removeSelectParam = function (params) {
    //using a copy of the params means that the select obj
    //is still available on query.params for share url generation
    var paramsCopy = $.extend(true, {}, params);
    try {
      delete paramsCopy.clauses.where.select;
    } catch (e) {
      //nested property doesn't exist
    }
    delete paramsCopy.select;
    return paramsCopy;
  };

  // The `generateApiUrl` method builds and returns a Qu URL from `query`'s `params`.
  query.generateApiUrl = function( format, codes, params ) {

    var url,
        apiCallParams = params || this.params,
        showCodes = codes || this.codes,
        downloadFormat = format || this.format;
    //remove 'select' from params so it won't be added to where clause
    apiCallParams = query.removeSelectParam(apiCallParams);

    // Set a base url to append params to
    url = this.endpoint + 'slice/hmda_lar.' + downloadFormat + '?';

    if ( !showCodes ) {
      apiCallParams = {
        clauses: {
          where: apiCallParams,
          select: ['action_taken_name','agency_abbr','agency_name','applicant_ethnicity_name','applicant_race_name_1','applicant_race_name_2','applicant_race_name_3','applicant_race_name_4','applicant_race_name_5','applicant_sex_name','application_date_indicator','as_of_year','census_tract_number','co_applicant_ethnicity_name','co_applicant_race_name_1','co_applicant_race_name_2','co_applicant_race_name_3','co_applicant_race_name_4','co_applicant_race_name_5','co_applicant_sex_name','county_name','denial_reason_name_1','denial_reason_name_2','denial_reason_name_3','edit_status_name','hoepa_status_name','lien_status_name','loan_purpose_name','loan_type_name','msamd_name','owner_occupancy_name','preapproval_name','property_type_name','purchaser_type_name','respondent_id','sequence_number','state_abbr','state_name','applicant_income_000s','hud_median_family_income','loan_amount_000s','number_of_1_to_4_family_units','number_of_owner_occupied_units','minority_population','population','rate_spread','tract_to_msamd_income']
        }
      };
    }

    // fetch, compile queries
    url += this._buildApiQuery( apiCallParams );

    return url;

  };

  // builds the query string to append to api url
  // arg: params, object. if you only need a 'where' clause, passing in
  // query.params will do just fine
  // if you need to use the 'select' and 'group' clauses, pass an object
  // that has a property 'clauses' with an array of objects that correspond to
  // each clause. example:
  // params = {
  //   clauses: {
  //     select: ['var_one', 'var_two'],
  //     group: ['var_one', 'var_two']
  //   }
  // }
  query._buildApiQuery = function( params ) {
    var url = '', key;

    if ( params.hasOwnProperty('clauses') ) {
      for ( key in params.clauses ) {
        if ( params.clauses.hasOwnProperty( key ) ) {
          url += this._buildClause[key]( params.clauses[key] );
        }
      }
    } else {
      url = this._buildClause.where( params );
    }

    return url;

  };

  // methods correspond to each type of clause that the API takes
  // builds part of api call query string pertaining to clause
  query._buildClause = {

  // Convert each param to a proper [`$where` clause](http://cfpb.github.io/qu/articles/queries.html#where_in_detail).
    where: function( params ) {

      var _params = {},
          queryVals = [],
          where;

      // In order to compensate for enumerated location fields (state_code-1, county_name-1, etc.)
      // we have to go through and consolidate all enumerated params into unified objects.
      _.forEach( params, function( param, paramName ) {

        if ( !param.values || !param.values[0] ) {
          return;
        }

        var consolidatedName;

        if ( paramName.match(/\-\d+$/) ) {
          consolidatedName = paramName.replace(/\-\d+$/, '');

          // Initalize an empty param object if need be.
          if ( typeof _params[ consolidatedName ] === 'undefined' ) {
            _params[ consolidatedName ] = {
              values: [],
              comparator: '='
            };
          }

          _.forEach( param.values, function( value ){
            _params[ consolidatedName ].values.push( value );
          });

        } else {
          _params[ paramName ] = param;
        }

      });

      // We can now get back to business and generate that WERECLAWS
      _.forEach( _params, function( param, paramName ) {

        var paramVals;

        // Strip `-min/max` from the end of the param. This is mainly done for the loan_amount_000s fields.
        paramName = paramName.replace( /\-(min|max)$/, '' );
        paramVals = this._formatComparisonValues( param, paramName );
        queryVals.push( paramVals );

      }.bind( this ));

      // Join all the params with `AND` operators
      where = queryVals.join(' AND ');

      // All params are joined with `AND` operators... except with locations things
      // get weird. If the user selects multiple states and MSAs, records should be
      // shown that match any of the locations. `OR` operators need to be used.
      // The simplest way of dealing with this one-off use case is to replace()
      // after building the query string.
      where = where.replace( /(msamd|state_code)=([\d"]+)\)? (AND) \(?(msamd|state_code)/, function replacer( match ){
        return match.replace( 'AND', 'OR' );
      });

      // Encode for URIs and replace spaces with plus signs.
      return '&$where=' + encodeURI( where ).replace( /%20/g, '+' );

    },

    // select and group clauses are formatted the same way sans name
    select: function( param ) {
      return '&$select=' + this._listVals( param );
    },

    group: function( param ) {
      return '&$group=' + this._listVals( param ) + '&$orderBy=' + this._listVals( _.clone( param ).reverse() );
    },

    // formats single value clauses
    // returns string of comma-delimited values
    _listVals: function( param ) {

      var i = param.length,
          str = '';

      while( i-- ) {
        if ( typeof param[i] !== 'undefined' ) {
          str += param[i];
          // if this is not the last value, add comma
          if ( i > 0 ) {
            str += ',';
          }
        }
      }

      return str;
    },

    // formats api call values that have a comparison operator
    _formatComparisonValues: function( param, paramName ){
      var paramVal,
          paramVals = [];

      // If there's only value for the param, meaning they only selected one item or
      // it's a radio button that only allows once value, add the stringified
      // param to the `queryVals` array.
      if ( param.values.length === 1 ) {

        // Rate spread specialness
        if ( param.values[0] == 'null' ) {
          paramVal = paramName + param.comparator + '""';
        // Strings
        } else if ( isNaN( param.values[0] ) || paramName === 'msamd' || paramName === 'respondent_id' || paramName === 'census_tract_number' ) {
          paramVal = paramName + param.comparator + '"' + param.values[0] + '"';
        // Numbers
        } else {
          paramVal = paramName + param.comparator + param.values[0];
        }

        return paramVal;

      // If there are multiple values for a single parameter, we iterate over them and
      // put an `OR` operator between them. We then then [group them](http://cfpb.github.io/qu/articles/queries.html#boolean_operators)
      // with parens and add the grouping to the `params` array.
      } else {

        _.forEach( param.values, function( val, key ){

          if ( isNaN( val ) || paramName === 'msamd' || paramName === 'respondent_id' || paramName === 'census_tract_number' ) {
            paramVals.push( paramName + param.comparator + '"' + val + '"' );
          } else {
            paramVals.push( paramName + param.comparator + val );
          }

        });

        return '(' + paramVals.join(' OR ') + ')';

      }

    }

  };

  // The `fetch` method requests and returns JSON from Qu matching the
  // user's filter and grouping clauses
  query.fetch = function() {

  };

  // Export the public API.
  pdp.query = query;

  return pdp;

}( PDP || {} ));
<commit_msg>Increase timeout limit<commit_after>var PDP = (function ( pdp ) {

  'use strict';

  // The Query Object
  // ----------------
  // The `query` object is used to cache filter values and store methods
  // that manipulate filter values.
  var query = {};

  // If debug is set to true, dummy data will be used.
  query.debug = false;

  // Set a default format for the data download.
  query.format = query.debug ? 'json' : 'jsonp?$callback=';

  // Set a default endpoint for AJAX requests.
  query.endpoint = query.debug ? 'static/js/static_data/' : 'https://api.consumerfinance.gov/data/hmda/';

  // Seconds to wait on a response from the API before giving up.
  query.secondsToWait = 300;

  // Whether or not they want codes in their downloaded file.
  query.codes = false;

  // `query`'s `params` stores filter values.
  query.params = {};

  // The `reset` method empties the `params` object.
  // If a preset is passed, some defaults will be set.
  query.reset = function( preset ) {

    // The year is selected independent of the preset, because
    // of this we have to ensure it doesn't get overwritten.
    var years = $('.field.as_of_year select').val() || [];

    switch( preset ) {

      // All originated mortgages.
      case 'originations':
        this.params = {
          as_of_year: {
            values: years,
            comparator: '='
          },
          action_taken: {
            values: [1],
            comparator: '='
          }
        };
      break;

      // First-lien, owner-occupied, 1-4 family homes (including manufactured homes).
      case 'common':
        this.params = {
          as_of_year: {
            values: years,
            comparator: '='
          },
          property_type: {
            values: [1,2],
            comparator: '='
          },
          owner_occupancy: {
            values: [1],
            comparator: '='
          },
          lien_status: {
            values: [1],
            comparator: '='
          },
          action_taken: {
            values: [1],
            comparator: '='
          }
        };
      break;

      // Empty everything.
      case 'clear':
        this.params = {};
        break;

      // Default to an empty state with whatever years they've selected.
      default:
        this.params = {
          as_of_year: {
            values: years,
            comparator: '='
          }
        };
        break;

    }

    return this;

  };

  // The `updateAll` method runs through all the filter field values the user has selected
  // and stores them in the `params` object.
  query.updateAll = function( options ) {

    var fields,
        opts = options || {};

    switch( opts.source ) {
      case 'url':
        fields = pdp.app.getUrlValues();
        break;
      // State is stored in a cookie. Removing this functionality for now because
      // it's confusing the UX team. I'd rather work on other stuff than explain
      // to them how this works. Winter is coming.
      // case 'session':
      //   fields = pdp.query.getCookie();
      //   break;
      default:
        fields = pdp.form.getFields();
    }

    this.reset('clear');

    // Iterate over all the filter field values and push them into `query.params`.
    function _processField( field ) {

      if ( field.name && field.values ) {

        // Initalize an empty param object if need be.
        if ( typeof query.params[ field.name ] === 'undefined' ) {
          query.params[ field.name ] = {
            values: [],
            comparator: '='
          };
        }

        // If the value is a string from a text box we don't want to iterate
        // over it because it will be split up the characters.
        if ( field.type === 'text' ) {
          query.params[ field.name ].values = [ field.values ];
        } else {
          _.forEach( field.values, function( val, name ){

            var values = query.params[ field.name ].values;

            // Only push the value if it's not already in there.
            if ( !_.contains( values, val ) ) {
              values.push( val );
            }

          });
        }

        query.params[ field.name ].comparator = field.comparator;

      }

    }

    _.forEach( fields, _processField );

    pdp.observer.emitEvent( 'params:updated' );

  };

  // The `setCookie` method stores the param object in a cookie.
  query.setCookie = function() {

    $.cookie( '_hmda', pdp.form.getFields(), { expires: 1 } );

  };

  // The `getCookie` method retrives the param object from a cookie.
  query.getCookie = function() {

    return $.cookie( '_hmda' );

  };

  // The `generateUrlHash` method builds and returns a URL hash from `query`'s `params`.
  query.generateUrlHash = function() {
    var hash,
        hashParams = [];

    // Loop through params, stringify them and push them into the temp array.
    function buildHashParam( param, name ) {

      if ( !param.values[0] ) {
        return;
      }

      // If it's not a number, add quotes around the params.
      hashParams.push( name + param.comparator + param.values.join(',') );

    }
    _.forEach( query.params, buildHashParam );

    hash = '!/' + hashParams.join('&') + '&section=' + pdp.app.currentSection;
    return hash;

  };

  query.removeSelectParam = function (params) {
    //using a copy of the params means that the select obj
    //is still available on query.params for share url generation
    var paramsCopy = $.extend(true, {}, params);
    try {
      delete paramsCopy.clauses.where.select;
    } catch (e) {
      //nested property doesn't exist
    }
    delete paramsCopy.select;
    return paramsCopy;
  };

  // The `generateApiUrl` method builds and returns a Qu URL from `query`'s `params`.
  query.generateApiUrl = function( format, codes, params ) {

    var url,
        apiCallParams = params || this.params,
        showCodes = codes || this.codes,
        downloadFormat = format || this.format;
    //remove 'select' from params so it won't be added to where clause
    apiCallParams = query.removeSelectParam(apiCallParams);

    // Set a base url to append params to
    url = this.endpoint + 'slice/hmda_lar.' + downloadFormat + '?';

    if ( !showCodes ) {
      apiCallParams = {
        clauses: {
          where: apiCallParams,
          select: ['action_taken_name','agency_abbr','agency_name','applicant_ethnicity_name','applicant_race_name_1','applicant_race_name_2','applicant_race_name_3','applicant_race_name_4','applicant_race_name_5','applicant_sex_name','application_date_indicator','as_of_year','census_tract_number','co_applicant_ethnicity_name','co_applicant_race_name_1','co_applicant_race_name_2','co_applicant_race_name_3','co_applicant_race_name_4','co_applicant_race_name_5','co_applicant_sex_name','county_name','denial_reason_name_1','denial_reason_name_2','denial_reason_name_3','edit_status_name','hoepa_status_name','lien_status_name','loan_purpose_name','loan_type_name','msamd_name','owner_occupancy_name','preapproval_name','property_type_name','purchaser_type_name','respondent_id','sequence_number','state_abbr','state_name','applicant_income_000s','hud_median_family_income','loan_amount_000s','number_of_1_to_4_family_units','number_of_owner_occupied_units','minority_population','population','rate_spread','tract_to_msamd_income']
        }
      };
    }

    // fetch, compile queries
    url += this._buildApiQuery( apiCallParams );

    return url;

  };

  // builds the query string to append to api url
  // arg: params, object. if you only need a 'where' clause, passing in
  // query.params will do just fine
  // if you need to use the 'select' and 'group' clauses, pass an object
  // that has a property 'clauses' with an array of objects that correspond to
  // each clause. example:
  // params = {
  //   clauses: {
  //     select: ['var_one', 'var_two'],
  //     group: ['var_one', 'var_two']
  //   }
  // }
  query._buildApiQuery = function( params ) {
    var url = '', key;

    if ( params.hasOwnProperty('clauses') ) {
      for ( key in params.clauses ) {
        if ( params.clauses.hasOwnProperty( key ) ) {
          url += this._buildClause[key]( params.clauses[key] );
        }
      }
    } else {
      url = this._buildClause.where( params );
    }

    return url;

  };

  // methods correspond to each type of clause that the API takes
  // builds part of api call query string pertaining to clause
  query._buildClause = {

  // Convert each param to a proper [`$where` clause](http://cfpb.github.io/qu/articles/queries.html#where_in_detail).
    where: function( params ) {

      var _params = {},
          queryVals = [],
          where;

      // In order to compensate for enumerated location fields (state_code-1, county_name-1, etc.)
      // we have to go through and consolidate all enumerated params into unified objects.
      _.forEach( params, function( param, paramName ) {

        if ( !param.values || !param.values[0] ) {
          return;
        }

        var consolidatedName;

        if ( paramName.match(/\-\d+$/) ) {
          consolidatedName = paramName.replace(/\-\d+$/, '');

          // Initalize an empty param object if need be.
          if ( typeof _params[ consolidatedName ] === 'undefined' ) {
            _params[ consolidatedName ] = {
              values: [],
              comparator: '='
            };
          }

          _.forEach( param.values, function( value ){
            _params[ consolidatedName ].values.push( value );
          });

        } else {
          _params[ paramName ] = param;
        }

      });

      // We can now get back to business and generate that WERECLAWS
      _.forEach( _params, function( param, paramName ) {

        var paramVals;

        // Strip `-min/max` from the end of the param. This is mainly done for the loan_amount_000s fields.
        paramName = paramName.replace( /\-(min|max)$/, '' );
        paramVals = this._formatComparisonValues( param, paramName );
        queryVals.push( paramVals );

      }.bind( this ));

      // Join all the params with `AND` operators
      where = queryVals.join(' AND ');

      // All params are joined with `AND` operators... except with locations things
      // get weird. If the user selects multiple states and MSAs, records should be
      // shown that match any of the locations. `OR` operators need to be used.
      // The simplest way of dealing with this one-off use case is to replace()
      // after building the query string.
      where = where.replace( /(msamd|state_code)=([\d"]+)\)? (AND) \(?(msamd|state_code)/, function replacer( match ){
        return match.replace( 'AND', 'OR' );
      });

      // Encode for URIs and replace spaces with plus signs.
      return '&$where=' + encodeURI( where ).replace( /%20/g, '+' );

    },

    // select and group clauses are formatted the same way sans name
    select: function( param ) {
      return '&$select=' + this._listVals( param );
    },

    group: function( param ) {
      return '&$group=' + this._listVals( param ) + '&$orderBy=' + this._listVals( _.clone( param ).reverse() );
    },

    // formats single value clauses
    // returns string of comma-delimited values
    _listVals: function( param ) {

      var i = param.length,
          str = '';

      while( i-- ) {
        if ( typeof param[i] !== 'undefined' ) {
          str += param[i];
          // if this is not the last value, add comma
          if ( i > 0 ) {
            str += ',';
          }
        }
      }

      return str;
    },

    // formats api call values that have a comparison operator
    _formatComparisonValues: function( param, paramName ){
      var paramVal,
          paramVals = [];

      // If there's only value for the param, meaning they only selected one item or
      // it's a radio button that only allows once value, add the stringified
      // param to the `queryVals` array.
      if ( param.values.length === 1 ) {

        // Rate spread specialness
        if ( param.values[0] == 'null' ) {
          paramVal = paramName + param.comparator + '""';
        // Strings
        } else if ( isNaN( param.values[0] ) || paramName === 'msamd' || paramName === 'respondent_id' || paramName === 'census_tract_number' ) {
          paramVal = paramName + param.comparator + '"' + param.values[0] + '"';
        // Numbers
        } else {
          paramVal = paramName + param.comparator + param.values[0];
        }

        return paramVal;

      // If there are multiple values for a single parameter, we iterate over them and
      // put an `OR` operator between them. We then then [group them](http://cfpb.github.io/qu/articles/queries.html#boolean_operators)
      // with parens and add the grouping to the `params` array.
      } else {

        _.forEach( param.values, function( val, key ){

          if ( isNaN( val ) || paramName === 'msamd' || paramName === 'respondent_id' || paramName === 'census_tract_number' ) {
            paramVals.push( paramName + param.comparator + '"' + val + '"' );
          } else {
            paramVals.push( paramName + param.comparator + val );
          }

        });

        return '(' + paramVals.join(' OR ') + ')';

      }

    }

  };

  // The `fetch` method requests and returns JSON from Qu matching the
  // user's filter and grouping clauses
  query.fetch = function() {

  };

  // Export the public API.
  pdp.query = query;

  return pdp;

}( PDP || {} ));
<|endoftext|>


<commit_before>
var color = exports.color = require("./ansi-color");

global.proto = require('./proto').proto;
global.exec = require('./exec').exec;
global.Timer = require('./exec').Timer;
global.once = require('./once').once;
exports.onShutdown = require('./exec').onShutdown;

function throttled(cb, delay) {
  var timeout
    , fire = false
    , lastfire = false;
  function time() {
    return (new Date()).getTime();
  }
  return function() {
    if (!timeout) {
      var nextDelay = delay - (time() - lastfire);
      if (nextDelay <= 0) {
        cb();
        lastfire = time();
      } else {
        timeout = setTimeout(function() {
          if (fire) {
            cb();
            lastfire = time();
          }
          timeout = undefined;
          fire = false;
        }, nextDelay);
      }
    } else {
      fire = true;
    }
  };
}

var StopWatch = (function () {
  var StopWatch = proto();
  function outputAvg() {
    info('[%s] num: %d, avg: %d ms', this.name, this.num, Math.round(1000 * this.sum / this.num));
    this.num = 0;
    this.sum = 0;
  }
  StopWatch.init = function (name) {
    this.name = name;
    this.sum = 0;
    this.num = 0;
    var self = this;
    this.outputAvg = throttled(function() { outputAvg.call(self); }, 1000);
  };
  StopWatch.start = function() {
    var t = Timer.make();
    var self = this;
    return function () {
      self.num++;
      self.sum += t.elapsed();
      self.outputAvg();
    };
  };
  return StopWatch;
})();
global.StopWatch = StopWatch;

var stopwatches = {};
global.stopwatch = function (name) {
  if (!stopwatches[name]) {
    stopwatches[name] = StopWatch.make(name);
  }
  return stopwatches[name].start();
};

global.toInt = function(x) {
  return parseInt(x + '', 10);
};

var util = require('util');
global.debug = function(x, name) {
  global.error((name ? name + ': ' : '') + util.inspect(x));
};

var events  = require('events');
var logger = new events.EventEmitter();
exports.logger = logger;

global.error = function () {
  var s = util.format([].slice.call(arguments));
  logger.emit('data', 'error', s);
  console.error(color.set(s, "red"));
};

global.warn = function () {
  var s = util.format([].slice.call(arguments));
  logger.emit('data', 'warn', s);
  console.log(color.set(s, "yellow"));
};

global.info = function () {
  var s = util.format.apply(null, arguments);
  logger.emit('data', 'info', s);
  console.log(color.set(s, "black", true));
};

global.verbose = function () {
  var s = util.format([].slice.call(arguments));
  logger.emit('data', 'verbose', s);
  //console.log(color.set(s, "black", true));
};

global.throttled = throttled;

var errorEvents = new events.EventEmitter();

global.errorHandler = function(optionalMessage, cbOnError, cbOnSuccess) {
  if (!cbOnSuccess) {
    // The optional message was omitted
    cbOnSuccess = cbOnError;
    cbOnError = optionalMessage;
    optionalMessage = 'ERR';
  }
  return function(err, arg0, arg1) {
    if (err) {
      var msg = optionalMessage.replace('ERR', err).replace('ARG0', arg0).replace('ARG1', arg1);
      errorEvents.emit('err', msg);
      cbOnError(msg);
    } else {
      cbOnSuccess.apply(this, arguments);
    }
  };
};

global.errorHandler.on = function() {
  errorEvents.on.apply(errorEvents, arguments);
};<commit_msg>autocommit<commit_after>
var color = exports.color = require("./ansi-color");

global.proto = require('./proto').proto;
global.exec = require('./exec').exec;
global.Timer = require('./exec').Timer;
global.once = require('./once').once;
exports.onShutdown = require('./exec').onShutdown;

function throttled(cb, delay) {
  var timeout
    , fire = false
    , lastfire = false;
  function time() {
    return (new Date()).getTime();
  }
  return function() {
    if (!timeout) {
      var nextDelay = delay - (time() - lastfire);
      if (nextDelay <= 0) {
        cb();
        lastfire = time();
      } else {
        timeout = setTimeout(function() {
          if (fire) {
            cb();
            lastfire = time();
          }
          timeout = undefined;
          fire = false;
        }, nextDelay);
      }
    } else {
      fire = true;
    }
  };
}

var StopWatch = (function () {
  var StopWatch = proto();
  function outputAvg() {
    info('[%s] num: %d, avg: %d ms', this.name, this.num, Math.round(1000 * this.sum / this.num));
    this.num = 0;
    this.sum = 0;
  }
  StopWatch.init = function (name) {
    this.name = name;
    this.sum = 0;
    this.num = 0;
    var self = this;
    this.outputAvg = throttled(function() { outputAvg.call(self); }, 1000);
  };
  StopWatch.start = function() {
    var t = Timer.make();
    var self = this;
    return function () {
      self.num++;
      self.sum += t.elapsed();
      self.outputAvg();
    };
  };
  return StopWatch;
})();
global.StopWatch = StopWatch;

var stopwatches = {};
global.stopwatch = function (name) {
  if (!stopwatches[name]) {
    stopwatches[name] = StopWatch.make(name);
  }
  return stopwatches[name].start();
};

global.toInt = function(x) {
  return parseInt(x + '', 10);
};

var util = require('util');
global.debug = function(x, name) {
  global.error((name ? name + ': ' : '') + util.inspect(x));
};

var events  = require('events');
var logger = new events.EventEmitter();
exports.logger = logger;

global.error = function () {
  var s = util.format.apply(null, arguments);
  logger.emit('data', 'error', s);
  console.error(color.set(s, "red"));
};

global.warn = function () {
  var s = util.format.apply(null, arguments);
  logger.emit('data', 'warn', s);
  console.log(color.set(s, "yellow"));
};

global.info = function () {
  var s = util.format.apply(null, arguments);
  logger.emit('data', 'info', s);
  console.log(color.set(s, "black", true));
};

global.verbose = function () {
  var s = util.format.apply(null, arguments);
  logger.emit('data', 'verbose', s);
  //console.log(color.set(s, "black", true));
};

global.throttled = throttled;

var errorEvents = new events.EventEmitter();

global.errorHandler = function(optionalMessage, cbOnError, cbOnSuccess) {
  if (!cbOnSuccess) {
    // The optional message was omitted
    cbOnSuccess = cbOnError;
    cbOnError = optionalMessage;
    optionalMessage = 'ERR';
  }
  return function(err, arg0, arg1) {
    if (err) {
      var msg = optionalMessage.replace('ERR', err).replace('ARG0', arg0).replace('ARG1', arg1);
      errorEvents.emit('err', msg);
      cbOnError(msg);
    } else {
      cbOnSuccess.apply(this, arguments);
    }
  };
};

global.errorHandler.on = function() {
  errorEvents.on.apply(errorEvents, arguments);
};<|endoftext|>


<commit_before>/*
Javascript snippet to toggle the Canvas and Intervention autocompletes
sanely based on the presence of a digital edition for a selected Instance (or
the instance being edited in the case of the Reference Inline)
*/

/*
Toggle on or off based on the presence of an Instance with a digtial edition,
either in the selector on the Reference change_form or inline when editing
an Instance
*/
function toggleReferenceAutocompletes() {
  var instancePksArray = []
  var jsonString = $('.get_autocomplete_instances div div .grp-readonly').text();
  if (jsonString) {
    instancePksArray = JSON.parse(
      $('.get_autocomplete_instances div div .grp-readonly').text()
    );
  }

  // Flag to see if a digital edition is set on Instance change_form
  var digitalEdFlag = $('#id_digital_edition option:selected').val();

  // Flag to see if an instance is selected on Reference change_form
  var selectedInstancePk = $('#id_instance').val()
  // Flag to see if instance on Reference change_form is in array of
  // Instances with digital editions
  var pkInArray = instancePksArray.indexOf(parseInt(selectedInstancePk));

  /*
  Check if:
  1) There is an instance selected for Reference change_form and if it is
  on the list of those with digital editions.
  2) There is  a digital edition set on the Instance change_form.

  If either are not true, disable the selectors
  */
      // value of #id_instance is not in the list of digital editions or
      // #id_instance doesn't exist
  if ((pkInArray == -1 && $('#id_instance').val() != undefined) ||
      // #digital_edition select is either not set or doesn't exist
      (digitalEdFlag == "" && digitalEdFlag != undefined)) {
    $('select[id*="canvases"]').attr('disabled', true);
    $('select[id*="interventions"]').attr('disabled', true);

  } else {
    /*
    Enable autocompletes if either #id_instance on Reference change form,
    or the Instance being viewed reflect an instance with a digital edition.

    For the change form, use the parsed JSON from get_autocomplete_instances
    read-only field.
    */
    // if #id_instance exists and is in the array or check or
    // if #digital_edition exists and is set
    if (pkInArray == 0 || (digitalEdFlag != "" && digitalEdFlag != undefined)) {
      $('select[id*="canvases"]').removeAttr('disabled', true);
      $('select[id*="interventions"]').removeAttr('disabled', true);
    }
  }
}

$(document).ready(function() {
  // bind function once on page load
  toggleReferenceAutocompletes();
  // bind to the change event on #id_instance for the Reference change_form
  $("#id_instance").change(function() {
    toggleReferenceAutocompletes();
  });
  // Do NOT bind on page load for Instance change_form, since autocompletes need
  // a saved instance to be accruate.
});
<commit_msg>Correctly parse indexOf for pk array #14, #16<commit_after>/*
Javascript snippet to toggle the Canvas and Intervention autocompletes
sanely based on the presence of a digital edition for a selected Instance (or
the instance being edited in the case of the Reference Inline)
*/

/*
Toggle on or off based on the presence of an Instance with a digtial edition,
either in the selector on the Reference change_form or inline when editing
an Instance
*/
function toggleReferenceAutocompletes() {
  var instancePksArray = []
  var jsonString = $('.get_autocomplete_instances div div .grp-readonly').text();
  if (jsonString) {
    instancePksArray = JSON.parse(
      $('.get_autocomplete_instances div div .grp-readonly').text()
    );
  }

  // Flag to see if a digital edition is set on Instance change_form
  var digitalEdFlag = $('#id_digital_edition option:selected').val();

  // Flag to see if an instance is selected on Reference change_form
  var selectedInstancePk = $('#id_instance').val()
  // Flag to see if instance on Reference change_form is in array of
  // Instances with digital editions
  var pkInArray = instancePksArray.indexOf(parseInt(selectedInstancePk));

  /*
  Check if:
  1) There is an instance selected for Reference change_form and if it is
  on the list of those with digital editions.
  2) There is  a digital edition set on the Instance change_form.

  If either are not true, disable the selectors
  */
      // value of #id_instance is not in the list of digital editions or
      // #id_instance doesn't exist
  if ((pkInArray == -1 && $('#id_instance').val() != undefined) ||
      // #digital_edition select is either not set or doesn't exist
      (digitalEdFlag == "" && digitalEdFlag != undefined)) {
    $('select[id*="canvases"]').attr('disabled', true);
    $('select[id*="interventions"]').attr('disabled', true);

  } else {
    /*
    Enable autocompletes if either #id_instance on Reference change form,
    or the Instance being viewed reflect an instance with a digital edition.

    For the change form, use the parsed JSON from get_autocomplete_instances
    read-only field.
    */
    // if #id_instance exists and is in the array or check or
    // if #digital_edition exists and is set
    if (pkInArray != -1 || (digitalEdFlag != "" && digitalEdFlag != undefined)) {
      $('select[id*="canvases"]').removeAttr('disabled', true);
      $('select[id*="interventions"]').removeAttr('disabled', true);
    }
  }
}

$(document).ready(function() {
  // bind function once on page load
  toggleReferenceAutocompletes();
  // bind to the change event on #id_instance for the Reference change_form
  $("#id_instance").change(function() {
    toggleReferenceAutocompletes();
  });
  // Do NOT bind on page load for Instance change_form, since autocompletes need
  // a saved instance to be accruate.
});
<|endoftext|>


<commit_before>
global.proto = require('./proto').proto;
global.exec = require('./exec').exec;
global.Timer = require('./exec').Timer;
global.once = require('./once').once;

function throttled(cb, delay) {
  var timeout
    , fire = false;
  return function() {
    if (!timeout) {
      cb();
      timeout = setTimeout(function() {
        if (fire) { cb(); }
        timeout = undefined;
        fire = false;
      }, delay);
    } else {
      fire = true;
    }
  };
}

global.toInt = function(x) {
  return parseInt(x + '', 10);
};

var util = require('util');
global.debug = function(x, name) {
  console.error((name ? name + ': ' : '') + util.inspect(x));
};

var color = require("./ansi-color").set;
var events  = require('events');
var logger = new events.EventEmitter();
exports.logger = logger;

global.error = function(s) {
  logger.emit('data', 'error', s);
  console.error(color(s, "red"));
};

global.warn = function(s) {
  logger.emit('data', 'warn', s);
  console.log(color(s, "yellow"));
};

global.info = function(s) {
  logger.emit('data', 'info', s);
  console.log(color(s, "black", true));
};

global.verbose = function(s) {
  logger.emit('data', 'verbose', s);
  //console.log(color(s, "black", true));
};

global.throttled = throttled;
<commit_msg>autocommit<commit_after>
global.proto = require('./proto').proto;
global.exec = require('./exec').exec;
global.Timer = require('./exec').Timer;
global.once = require('./once').once;
exports.onShutdown = require('./exec').onShutdown;

function throttled(cb, delay) {
  var timeout
    , fire = false;
  return function() {
    if (!timeout) {
      cb();
      timeout = setTimeout(function() {
        if (fire) { cb(); }
        timeout = undefined;
        fire = false;
      }, delay);
    } else {
      fire = true;
    }
  };
}

global.toInt = function(x) {
  return parseInt(x + '', 10);
};

var util = require('util');
global.debug = function(x, name) {
  console.error((name ? name + ': ' : '') + util.inspect(x));
};

var color = require("./ansi-color").set;
var events  = require('events');
var logger = new events.EventEmitter();
exports.logger = logger;

global.error = function(s) {
  logger.emit('data', 'error', s);
  console.error(color(s, "red"));
};

global.warn = function(s) {
  logger.emit('data', 'warn', s);
  console.log(color(s, "yellow"));
};

global.info = function(s) {
  logger.emit('data', 'info', s);
  console.log(color(s, "black", true));
};

global.verbose = function(s) {
  logger.emit('data', 'verbose', s);
  //console.log(color(s, "black", true));
};

global.throttled = throttled;
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';

const runJest = require('../runJest');

describe('Stack Trace', () => {

  it('prints a stack trace for runtime errors', () => {
    const result = runJest('stack_trace', ['runtime-error-test.js']);
    const stdout = result.stdout.toString();

    expect(stdout).toMatch(
      /1 test suite failed, 0 tests passed/
    );
    expect(result.status).toBe(1);
    expect(stdout).toMatch(
      /ReferenceError: thisIsARuntimeError is not defined/
    );
    expect(stdout).toMatch(
      /\s+at\s(?:.+?)\s\(__tests__\/runtime-error-test\.js/
    );
  });

  it('does not print a stack trace for runtime errors when --noStackTrace is given', () => {
    const result = runJest('stack_trace', [
      'runtime-error-test.js',
      '--noStackTrace',
    ]);
    const stdout = result.stdout.toString();

    expect(stdout).toMatch(
      /1 test suite failed, 0 tests passed/
    );
    expect(result.status).toBe(1);

    expect(stdout).toMatch(
      /ReferenceError: thisIsARuntimeError is not defined/
    );
    expect(stdout).not.toMatch(
      /\s+at\s(?:.+?)\s\(__tests__\/runtime-error-test\.js/
    );
  });

  it('prints a stack trace for matching errors', () => {
    const result = runJest('stack_trace', ['stack-trace-test.js']);
    const stdout = result.stdout.toString();

    expect(stdout).toMatch(/1 test failed, 0 tests passed/);
    expect(result.status).toBe(1);

    expect(stdout).toMatch(
      /\s+at\s(?:.+?)\s\(__tests__\/stack-trace-test\.js/
    );
  });

  it('does not print a stack trace for matching errors when --noStackTrace is given', () => {
    const result = runJest('stack_trace', [
      'stack-trace-test.js',
      '--noStackTrace',
    ]);
    const stdout = result.stdout.toString();

    expect(stdout).toMatch(/1 test failed, 0 tests passed/);
    expect(result.status).toBe(1);

    expect(stdout).not.toMatch(
      /\s+at\s(?:.+?)\s\(__tests__\/stack-trace-test\.js/
    );
  });

  it('prints a stack trace for errors', () => {
    const result = runJest('stack_trace', ['test-error-test.js']);
    const stdout = result.stdout.toString();

    expect(stdout).toMatch(/3 tests failed, 0 tests passed/);
    expect(result.status).toBe(1);

    expect(stdout).toMatch(/Error: this is unexpected\./);
    expect(stdout).toMatch(/this is a string\. thrown/);

    expect(stdout).toMatch(
      /\s+at\s(?:.+?)\s\(__tests__\/test-error-test\.js/
    );

    // Make sure we show Jest's jest-resolve as part of the stack trace
    /* eslint-disable max-len */
    expect(stdout).toMatch(
      /Error: Cannot find module 'this-module-does-not-exist' from 'test-error-test\.js'/
    );
    /* eslint-enable max-len */

    expect(stdout).toMatch(
      /\s+at\s(?:.+?)\s\((?:.+?)jest-resolve\/src\/index\.js/
    );
  });

  it('does not print a stack trace for errors when --noStackTrace is given', () => {
    const result = runJest('stack_trace', [
      'test-error-test.js',
      '--noStackTrace',
    ]);
    const stdout = result.stdout.toString();

    expect(stdout).toMatch(/3 tests failed, 0 tests passed/);
    expect(result.status).toBe(1);

    expect(stdout).not.toMatch(
      /\s+at\s(?:.+?)\s\(__tests__\/test-error-test\.js/
    );
  });

});
<commit_msg>test stack traces using `build/index.js`<commit_after>/**
 * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';

const runJest = require('../runJest');

describe('Stack Trace', () => {

  it('prints a stack trace for runtime errors', () => {
    const result = runJest('stack_trace', ['runtime-error-test.js']);
    const stdout = result.stdout.toString();

    expect(stdout).toMatch(
      /1 test suite failed, 0 tests passed/
    );
    expect(result.status).toBe(1);
    expect(stdout).toMatch(
      /ReferenceError: thisIsARuntimeError is not defined/
    );
    expect(stdout).toMatch(
      /\s+at\s(?:.+?)\s\(__tests__\/runtime-error-test\.js/
    );
  });

  it('does not print a stack trace for runtime errors when --noStackTrace is given', () => {
    const result = runJest('stack_trace', [
      'runtime-error-test.js',
      '--noStackTrace',
    ]);
    const stdout = result.stdout.toString();

    expect(stdout).toMatch(
      /1 test suite failed, 0 tests passed/
    );
    expect(result.status).toBe(1);

    expect(stdout).toMatch(
      /ReferenceError: thisIsARuntimeError is not defined/
    );
    expect(stdout).not.toMatch(
      /\s+at\s(?:.+?)\s\(__tests__\/runtime-error-test\.js/
    );
  });

  it('prints a stack trace for matching errors', () => {
    const result = runJest('stack_trace', ['stack-trace-test.js']);
    const stdout = result.stdout.toString();

    expect(stdout).toMatch(/1 test failed, 0 tests passed/);
    expect(result.status).toBe(1);

    expect(stdout).toMatch(
      /\s+at\s(?:.+?)\s\(__tests__\/stack-trace-test\.js/
    );
  });

  it('does not print a stack trace for matching errors when --noStackTrace is given', () => {
    const result = runJest('stack_trace', [
      'stack-trace-test.js',
      '--noStackTrace',
    ]);
    const stdout = result.stdout.toString();

    expect(stdout).toMatch(/1 test failed, 0 tests passed/);
    expect(result.status).toBe(1);

    expect(stdout).not.toMatch(
      /\s+at\s(?:.+?)\s\(__tests__\/stack-trace-test\.js/
    );
  });

  it('prints a stack trace for errors', () => {
    const result = runJest('stack_trace', ['test-error-test.js']);
    const stdout = result.stdout.toString();

    expect(stdout).toMatch(/3 tests failed, 0 tests passed/);
    expect(result.status).toBe(1);

    expect(stdout).toMatch(/Error: this is unexpected\./);
    expect(stdout).toMatch(/this is a string\. thrown/);

    expect(stdout).toMatch(
      /\s+at\s(?:.+?)\s\(__tests__\/test-error-test\.js/
    );

    // Make sure we show Jest's jest-resolve as part of the stack trace
    /* eslint-disable max-len */
    expect(stdout).toMatch(
      /Error: Cannot find module 'this-module-does-not-exist' from 'test-error-test\.js'/
    );
    /* eslint-enable max-len */

    expect(stdout).toMatch(
      /\s+at\s(?:.+?)\s\((?:.+?)jest-resolve\/build\/index\.js/
    );
  });

  it('does not print a stack trace for errors when --noStackTrace is given', () => {
    const result = runJest('stack_trace', [
      'test-error-test.js',
      '--noStackTrace',
    ]);
    const stdout = result.stdout.toString();

    expect(stdout).toMatch(/3 tests failed, 0 tests passed/);
    expect(result.status).toBe(1);

    expect(stdout).not.toMatch(
      /\s+at\s(?:.+?)\s\(__tests__\/test-error-test\.js/
    );
  });

});
<|endoftext|>


<commit_before>import React from 'react';
import FocusTrap from 'focus-trap-react';
import { Container, Modal, Segment } from 'semantic-ui-react';
const headerStyle = {
    'textAlign': 'center'
};

class PaintModal extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            modalOpen: false,
            activeTrap: false
        };

        this.handleOpen = this.handleOpen.bind(this);
    }

    componentDidMount() {

    }

    componentDidUpdate() {

    }

    handleOpen(){
        $('#app').attr('aria-hidden', 'true');
        this.setState({
            modalOpen:true,
            activeTrap:true
        });
    }

    unmountTrap() {
        if(this.state.activeTrap){
            this.setState({ activeTrap: false });
            $('#app').attr('aria-hidden','false');
        }
    }

    render() {

        return(

            <Modal
                trigger={
                     this.handleKeyPress(evt, 'handleOpen')}>
                         Paint

                }
                open={this.state.modalOpen}
                onOpen={this.handleOpen}
                onClose={this.handleClose}
                id="paintModal"
                aria-labelledby="paintModalHeader"
                aria-describedby="paintModalDescription"
                tabIndex="0"
            >
                <FocusTrap
                    id="focus-trap-paintModal"
                    className = "header"
                    active={this.state.activeTrap}
                    focusTrapOptions={{
                        onDeactivate:this.unmountTrap,
                        clickOutsideDeactivates:true,
                        initialFocus: '#paintModalDescription'
                    }}
                >
                    <Modal.Header className="ui center aligned" id="paintModalHeader">

Draw and Paint

                    </Modal.Header>
                    <Modal.Content>
                        <Container>
                            <Segment color="blue" textAlign="left" padded>

Draw your own SVG image

                                <Segment textAlign="center" >
                                </Segment>
                            </Segment>
                        </Container>

                    </Modal.Content>

                </FocusTrap>
            </Modal>

        );
    }
}

PaintModal.contextTypes = {
    executeAction: React.PropTypes.func.isRequired,
    intl: React.PropTypes.object.isRequired
};

export default PaintModal;
<commit_msg>Added canvas for fabric and special button to start FabricJS usage, it isn't working from component did mount.<commit_after>import React from 'react';
import FocusTrap from 'focus-trap-react';
import { Container, Modal, Segment } from 'semantic-ui-react';
const headerStyle = {
    'textAlign': 'center'
};

const canvasStyle = {
    'height': '0px',
    'width': '0px',
    'border': '1px solid #000000'
}

class PaintModal extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            modalOpen: false,
            activeTrap: false
        };

        this.canvas = null;
        this.handleOpen = this.handleOpen.bind(this);
        this.startFabric = this.startFabric.bind(this);
    }

    componentDidMount() {
    }

    componentDidUpdate() {

    }

    startFabric(){

        this.canvas = new fabric.Canvas('fabriccanvas');

        this.canvas.setHeight(500);
        this.canvas.setWidth(600);

    }

    handleOpen(){
        $('#app').attr('aria-hidden', 'true');
        this.setState({
            modalOpen:true,
            activeTrap:true
        });

    }

    unmountTrap() {
        if(this.state.activeTrap){
            this.setState({ activeTrap: false });
            $('#app').attr('aria-hidden','false');
        }
    }

    render() {

        return(

            <Modal
                trigger={
                     this.handleKeyPress(evt, 'handleOpen')}>
                         Paint

                }
                open={this.state.modalOpen}
                onOpen={this.handleOpen}
                onClose={this.handleClose}
                id="paintModal"
                aria-labelledby="paintModalHeader"
                aria-describedby="paintModalDescription"
                tabIndex="0"
            >
                <FocusTrap
                    id="focus-trap-paintModal"
                    className = "header"
                    active={this.state.activeTrap}
                    focusTrapOptions={{
                        onDeactivate:this.unmountTrap,
                        clickOutsideDeactivates:true,
                        initialFocus: '#paintModalDescription'
                    }}
                >
                    <Modal.Header className="ui center aligned" id="paintModalHeader">

Draw and Paint

                    </Modal.Header>
                    <Modal.Content>
                        <Container>
                            <Segment color="blue" textAlign="left" padded>

Draw your own SVG image

                                <Segment textAlign="center" >

Draw inside the canvas using the tools provided.

                                    <button onClick={this.startFabric} onKeyPress={(evt) => this.handleKeyPress(evt, 'stratFabric')}>Click and start drawing!</button>
                                    <canvas id="fabriccanvas" style={canvasStyle}></canvas>
                                </Segment>
                            </Segment>

                        </Container>

                    </Modal.Content>

                </FocusTrap>
            </Modal>

        );
    }
}

PaintModal.contextTypes = {
    executeAction: React.PropTypes.func.isRequired,
    intl: React.PropTypes.object.isRequired
};

export default PaintModal;
<|endoftext|>


<commit_before>Ext.define('subjectadmin.JasmineTestApplication', {
    extend: 'subjectadmin.TestApplication',

    launch: function() {
        jasmine.getEnv().addReporter(new jasmine.TrivialReporter());
        jasmine.getEnv().execute();
    }
});
<commit_msg>apps.subjectadmin...JasmineTestApplication: Use JasmineTest.<commit_after>Ext.define('subjectadmin.JasmineTestApplication', {
    extend: 'subjectadmin.TestApplication',
    requires: ['jsapp.JasmineTest'],

    launch: function() {
        jsapp.JasmineTest.execute();
    }
});
<|endoftext|>


<commit_before>var mForm = $('input[type=password]').closest("form");

if (mForm.length) {
  for (var i = 0; i < mForm.length; i++) {
    if (typeof $(mForm[i]).attr('id') == 'undefined')
      mForm[i].id = 'catchedByTMPIU' + i;

    $("#"+$(mForm[i]).attr('id')).submit(function(e) {
      alert("catch!");
      // get the current URL
      var mURL = window.location.hostname;

      // get the current local time
      var mDate = new Date();
      var mLocalTime = (mDate.getMonth()+1) + '/' + mDate.getDate() + '/' + mDate.getFullYear() + ' ' + mDate.getHours() + ':' + mDate.getMinutes() + ':' + mDate.getSeconds();

      var mBuf = $("#" + $(this).attr('id') + " :text").serializeArray();
      var mTexts = [];

      // get the filled form data
      for (var i = 0; i < mBuf.length; i++) {
        if (mBuf[i].value.length != 0)
          mTexts.push(mBuf[i]);
      }

      // check the tyep
      var mType;
      if(mTexts.length > 1)
        mType = "Sign-up";
      else
        mType = "Login";

      // send the mesasge to the background
      chrome.runtime.sendMessage({action: "GetInput", url: mURL, type: mType, data: mTexts, time: mLocalTime}, function(response) {
      });
    });
  }
}
<commit_msg>why? I didn't change anything.<commit_after>var mForm = $('input[type=password]').closest("form");

if (mForm.length) {
  for (var i = 0; i < mForm.length; i++) {
    if (typeof $(mForm[i]).attr('id') == 'undefined')
      mForm[i].id = 'catchedByTMPIU' + i;

    $("#"+$(mForm[i]).attr('id')).submit(function(e) {
      // get the current URL
      var mURL = window.location.hostname;

      // get the current local time
      var mDate = new Date();
      var mLocalTime = (mDate.getMonth()+1) + '/' + mDate.getDate() + '/' + mDate.getFullYear() + ' ' + mDate.getHours() + ':' + mDate.getMinutes() + ':' + mDate.getSeconds();

      var mBuf = $("#" + $(this).attr('id') + " :text").serializeArray();
      var mTexts = [];

      // get the filled form data
      for (var i = 0; i < mBuf.length; i++) {
        if (mBuf[i].value.length != 0)
          mTexts.push(mBuf[i]);
      }

      // check the tyep
      var mType;
      if(mTexts.length > 1)
        mType = "Sign-up";
      else
        mType = "Login";

      // send the mesasge to the background
      chrome.runtime.sendMessage({action: "GetInput", url: mURL, type: mType, data: mTexts, time: mLocalTime}, function(response) {
      });
    });
  }
}
<|endoftext|>


<commit_before>/*! CSGO Lounge prices | (c)  2015 Solant */

function getPricesWithCurrency(){
	chrome.storage.sync.get({
		currency: 1
	}, function(items) {
		getPrices(items.currency);
	});
	//Instead of dom mutation event, kind of dirty hack
	setTimeout(getPricesWithCurrency, 1000);
}

getPricesWithCurrency();

function getPrices(currencyId){
	$(".item").not(":has(.value)").each(function(index){
		$(this).prepend("
Loading
");
		var itemName = $(this).children("img").attr("alt");
		if(itemName == "Any Offers" || itemName == "Any Knife" || itemName == "Any Key" || itemName == "Real Money" || itemName == "Dota Items" || itemName[0] == ":")
			return;
		var itemPrice;
		var itemUrl = "https://steamcommunity.com/market/priceoverview/?currency="+currencyId+"&appid=730&market_hash_name="+encodeURIComponent(itemName);
		var xhr = new XMLHttpRequest();
		xhr.open("GET", itemUrl, true);
		xhr.onreadystatechange = (function(selector) {
			return function() {
				if (xhr.readyState == 4 && xhr.status != 500) {
					var json = JSON.parse(xhr.responseText);
					if(json['success']){
						if(json['lowest_price'] !== undefined)
							$(selector).children(".value").html(json['lowest_price'].replace(/[\.,]--/g, ""));
						else
							$(selector).children(".value").html("???");
					} else {
						$(selector).children(".value").html("???");
					}
				}
			}
		})(this)
		xhr.send();
	});
}<commit_msg>Loading text on non-items fix<commit_after>/*! CSGO Lounge prices | (c)  2015 Solant */

function getPricesWithCurrency(){
	chrome.storage.sync.get({
		currency: 1
	}, function(items) {
		getPrices(items.currency);
	});
	//Instead of dom mutation event, kind of dirty hack
	setTimeout(getPricesWithCurrency, 1000);
}

getPricesWithCurrency();

function getPrices(currencyId){
	$(".item").not(":has(.value)").each(function(index){
		var itemName = $(this).children("img").attr("alt");
		if(itemName == "Any Offers" || itemName == "Any Knife" || itemName == "Any Key" || itemName == "Real Money" || itemName == "Dota Items" || itemName[0] == ":")
			return;
		$(this).prepend("
Loading
");
		var itemPrice;
		var itemUrl = "https://steamcommunity.com/market/priceoverview/?currency="+currencyId+"&appid=730&market_hash_name="+encodeURIComponent(itemName);
		var xhr = new XMLHttpRequest();
		xhr.open("GET", itemUrl, true);
		xhr.onreadystatechange = (function(selector) {
			return function() {
				if (xhr.readyState == 4 && xhr.status != 500) {
					var json = JSON.parse(xhr.responseText);
					if(json['success']){
						if(json['lowest_price'] !== undefined)
							$(selector).children(".value").html(json['lowest_price'].replace(/[\.,]--/g, ""));
						else
							$(selector).children(".value").html("???");
					} else {
						$(selector).children(".value").html("???");
					}
				}
			}
		})(this)
		xhr.send();
	});
}
<|endoftext|>


<commit_before>'use strict';

/*global nodeca, _*/

// 3rd-party
var Store = require('nlib').Settings.Store;
var async = require('nlib').Vendor.Async;

////////////////////////////////////////////////////////////////////////////////

// Helper to fetch usergroups by IDs
//
function fetchForumSettings(id, callback) {
  nodeca.models.forum.Section.findOne({ _id: id })
    .select('settings')
    .exec(callback);
}

// Memoized version of fetchUserGroups helper
//
var fetchForumSesstingsCached = nodeca.components.memoizee(fetchForumSettings, {
  // momoizee options. revalidate cache after 30 sec
  async:  true,
  maxAge: 30000
});

////////////////////////////////////////////////////////////////////////////////

module.exports = new Store({
  get: function (keys, params, options, callback) {
    var self = this;
    var func = options.skipCache ? fetchForumSettings : fetchForumSesstingsCached;

    func(params.forum_id, function (err, forum) {
      if (err) {
        callback(err);
        return;
      }

      var settings  = forum.settings || {};
      var results   = {};

      try {
        keys.forEach(function (k) {
          var values = [];

          params.usergroup_ids.forEach(function (id) {
            if (settings[k + ':usergroup:' + id]) {
              values.push(settings[k + ':usergroup:' + id]);
            }
          });

          // push default value
          values.push({ value: self.getDefaultValue(k) });

          results[k] = Store.mergeValues(values);
        });
      } catch (err) {
        callback(err);
        return;
      }

      callback(null, results);
    });
  },
  set: function (values, params, callback) {
    var self = this;

    fetchForumSettings(params.forum_id, function (err, forum) {
      if (err) {
        callback(err);
        return;
      }

      // leave only those params, that we know about
      values = _.pick(values || {}, self.keys);

      forum.settings = forum.settings || {};

      params.usergroup_ids.forEach(function (id) {
        _.each(values, function (opts, key) {
          forum.settings[key + ':usergroup:' + id] = {
            value: opts.value,
            force: !!opts.value
          };
        });
      });

      forum.markModified('settings');
      forum.save(callback);
    });
  }
});
<commit_msg>Fix forum settigns getter<commit_after>'use strict';

/*global nodeca, _*/

// 3rd-party
var Store = require('nlib').Settings.Store;
var async = require('nlib').Vendor.Async;

////////////////////////////////////////////////////////////////////////////////

// Helper to fetch usergroups by IDs
//
function fetchForumSettings(id, callback) {
  nodeca.models.forum.Section.findOne({ _id: String(id) })
    .select('settings')
    .exec(callback);
}

// Memoized version of fetchUserGroups helper
//
var fetchForumSesstingsCached = nodeca.components.memoizee(fetchForumSettings, {
  // momoizee options. revalidate cache after 30 sec
  async:  true,
  maxAge: 30000
});

////////////////////////////////////////////////////////////////////////////////

module.exports = new Store({
  get: function (keys, params, options, callback) {
    var self = this;
    var func = options.skipCache ? fetchForumSettings : fetchForumSesstingsCached;

    func(params.forum_id, function (err, forum) {
      if (err) {
        callback(err);
        return;
      }

      var settings  = forum.settings || {};
      var results   = {};

      try {
        keys.forEach(function (k) {
          var values = [];

          params.usergroup_ids.forEach(function (id) {
            if (settings[k + ':usergroup:' + id]) {
              values.push(settings[k + ':usergroup:' + id]);
            }
          });

          // push default value
          values.push({ value: self.getDefaultValue(k) });

          results[k] = Store.mergeValues(values);
        });
      } catch (err) {
        callback(err);
        return;
      }

      callback(null, results);
    });
  },
  set: function (values, params, callback) {
    var self = this;

    fetchForumSettings(params.forum_id, function (err, forum) {
      if (err) {
        callback(err);
        return;
      }

      // leave only those params, that we know about
      values = _.pick(values || {}, self.keys);

      forum.settings = forum.settings || {};

      params.usergroup_ids.forEach(function (id) {
        _.each(values, function (opts, key) {
          forum.settings[key + ':usergroup:' + id] = {
            value: opts.value,
            force: !!opts.value
          };
        });
      });

      forum.markModified('settings');
      forum.save(callback);
    });
  }
});
<|endoftext|>


<commit_before>'use strict';

var React = require('react'),
	pdfjs = require('./pdfjs-lib'),
	AlternateViewerPage = require('./AlternateViewerPage'),
	isInView = require('./isInView'),
	getPixelRatio = require('./pixelRatio/getPixelRatio');

var MAX_SCALE = 1.5;

var AlternativeViewer = React.createClass({
	propTypes: {
		src: React.PropTypes.string.isRequired,
		progressCallback: React.PropTypes.func,
		maxScale: React.PropTypes.number
	},
	getMaxScale: function() {
		return this.props.maxScale || MAX_SCALE;
	},
	onDocumentLoaded: function(pdf) {
		if (!pdf || !this.isMounted()) {
			return;
		}

		var self = this;

		self.updateProgress(70);

		pdf.getPage(1).then(function(page) {
			var unscaledViewport = page.getViewport(1),
				containerNode = React.findDOMNode(self),
				scale = Math.min(self.getMaxScale(), (containerNode.clientWidth - 20) / unscaledViewport.width),
				pageViewport = page.getViewport(scale),
				pages = [];

			for (var i = 1; i <= pdf.numPages; i++) {
				pages.push({
					pageNumber: i,
					pdfPage: i === 1 ? page : null,
					ref: 'page_' + i,
					requested: i === 1
				});
			}

			self.setState({
				pdf: pdf,
				pageHeight: pageViewport.height,
				pageWidth: pageViewport.width,
				pages: pages,
				scale: scale
			});

			self.loadVisiblePages();

			self.updateProgress(100);
		});
	},
	loadPage: function(pageNumber) {
		var self = this;
		this.state.pdf.getPage(pageNumber).then(function(newPage) {
			var pageFromState = self.state.pages[pageNumber - 1];
			pageFromState.pdfPage = newPage;
			self.setState({
				pages: self.state.pages
			});
		});
	},
	onScroll: function() {
		this.loadVisiblePages();
	},
	loadVisiblePages: function() {
		var scrollPosition = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop,
			visibleAreaHeight = window.innerHeight;

		for (var page of this.state.pages) {
			var pageDOMNode = this.refs[page.ref].getDOMNode();

			if (!page.requested && isInView(pageDOMNode, scrollPosition, visibleAreaHeight))
			{
				page.requested = true;
				this.loadPage(page.pageNumber);
			}
		}
	},
	componentDidMount: function() {
		this.updateProgress(10);
		document.addEventListener('scroll', this.onScroll);

		var url = this.props.src;
		pdfjs.getDocument(url).then(this.onDocumentLoaded);
	},
	updateProgress: function(progress) {
		if (this.props.progressCallback) {
			this.props.progressCallback(progress);
		}
	},
	getInitialState: function() {
		return {
			pages: [],
			pixelRatio: getPixelRatio(),
			scale: 1
		};
	},
	render: function() {
		var self = this;
		return (

				{self.state.pages.map(function(page) {
					return <AlternateViewerPage key={page.ref} ref={page.ref}
						page={page}
						pixelRatio={self.state.pixelRatio}
						scale={self.state.scale}
						pageHeight={self.state.pageHeight}
						pageWidth={self.state.pageWidth} />;
				})}

		);
	}
});

module.exports = AlternativeViewer;
<commit_msg>PDFJS now passes credentials with requests<commit_after>'use strict';

var React = require('react'),
	pdfjs = require('./pdfjs-lib'),
	AlternateViewerPage = require('./AlternateViewerPage'),
	isInView = require('./isInView'),
	getPixelRatio = require('./pixelRatio/getPixelRatio');

var MAX_SCALE = 1.5;

var AlternativeViewer = React.createClass({
	propTypes: {
		src: React.PropTypes.string.isRequired,
		progressCallback: React.PropTypes.func,
		maxScale: React.PropTypes.number
	},
	getMaxScale: function() {
		return this.props.maxScale || MAX_SCALE;
	},
	onDocumentLoaded: function(pdf) {
		if (!pdf || !this.isMounted()) {
			return;
		}

		var self = this;

		self.updateProgress(70);

		pdf.getPage(1).then(function(page) {
			var unscaledViewport = page.getViewport(1),
				containerNode = React.findDOMNode(self),
				scale = Math.min(self.getMaxScale(), (containerNode.clientWidth - 20) / unscaledViewport.width),
				pageViewport = page.getViewport(scale),
				pages = [];

			for (var i = 1; i <= pdf.numPages; i++) {
				pages.push({
					pageNumber: i,
					pdfPage: i === 1 ? page : null,
					ref: 'page_' + i,
					requested: i === 1
				});
			}

			self.setState({
				pdf: pdf,
				pageHeight: pageViewport.height,
				pageWidth: pageViewport.width,
				pages: pages,
				scale: scale
			});

			self.loadVisiblePages();

			self.updateProgress(100);
		});
	},
	loadPage: function(pageNumber) {
		var self = this;
		this.state.pdf.getPage(pageNumber).then(function(newPage) {
			var pageFromState = self.state.pages[pageNumber - 1];
			pageFromState.pdfPage = newPage;
			self.setState({
				pages: self.state.pages
			});
		});
	},
	onScroll: function() {
		this.loadVisiblePages();
	},
	loadVisiblePages: function() {
		var scrollPosition = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop,
			visibleAreaHeight = window.innerHeight;

		for (var page of this.state.pages) {
			var pageDOMNode = this.refs[page.ref].getDOMNode();

			if (!page.requested && isInView(pageDOMNode, scrollPosition, visibleAreaHeight))
			{
				page.requested = true;
				this.loadPage(page.pageNumber);
			}
		}
	},
	componentDidMount: function() {
		this.updateProgress(10);
		document.addEventListener('scroll', this.onScroll);

		var url = this.props.src;
		pdfjs.getDocument({
			url: url,
			withCredentials: true
		}).then(this.onDocumentLoaded);
	},
	updateProgress: function(progress) {
		if (this.props.progressCallback) {
			this.props.progressCallback(progress);
		}
	},
	getInitialState: function() {
		return {
			pages: [],
			pixelRatio: getPixelRatio(),
			scale: 1
		};
	},
	render: function() {
		var self = this;
		return (

				{self.state.pages.map(function(page) {
					return <AlternateViewerPage key={page.ref} ref={page.ref}
						page={page}
						pixelRatio={self.state.pixelRatio}
						scale={self.state.scale}
						pageHeight={self.state.pageHeight}
						pageWidth={self.state.pageWidth} />;
				})}

		);
	}
});

module.exports = AlternativeViewer;
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');
const decache = require('decache');

/**
 * Describes a CommandHandler for a bot.
 */
class CommandHandler {
  /**
   * Constructs CommandHandler
   * @param {Genesis} bot    Bot to derive prefix for commands from
   */
  constructor(bot) {
    this.bot = bot;
    this.logger = bot.logger;

    /**
     * Array of command objects that can be called
     * @type {Array<Command>}
     * @private
     */
    this.commands = [];
  }

  /**
   * Loads the commands from disk into this.commands
   */
  loadCommands() {
    const commandDir = path.join(__dirname, 'commands');
    let files = fs.readdirSync(commandDir);

    const categories = files.filter(f => f.indexOf('.js') === -1);
    files = files.filter(f => f.indexOf('.js') > -1);

    categories.forEach((category) => {
      files = files.concat(fs.readdirSync(path.join(commandDir, category))
        .map(f => path.join(category, f)));
    });

    if (this.commands.length !== 0) {
      this.logger.debug('Decaching commands');
      files.forEach((f) => {
        decache(path.join(commandDir, f));
      });
    }

    this.logger.debug(`Loading commands: ${files}`);

    this.commands = files.map((f) => {
      try {
        // eslint-disable-next-line import/no-dynamic-require, global-require
        const Cmd = require(path.join(commandDir, f));
        if (Object.prototype.toString.call(Cmd) === '[object Function]') {
          const command = new Cmd(this.bot);

          this.logger.debug(`Adding ${command.id}`);
          return command;
        }
        return null;
      } catch (err) {
        this.logger.error(err);
        return null;
      }
    })
      .filter(c => c !== null);
  }

  /**
   * Handle the command contained in the message contents, if any.
   * @param {Message} message Message whose command should be checked and handled
   */
  handleCommand(message) {
    let content = message.content;
    const botping = `@${message.guild ?
          message.guild.members.get(this.bot.client.user.id).displayName :
          this.bot.client.user.username}`;
    const botPingId = `<@${this.bot.client.user.id}>`;
    this.bot.settings.getChannelPrefix(message.channel)
      .then((prefix) => {
        if (!content.startsWith(prefix)
            && !content.startsWith(botping)
            && !content.startsWith(botPingId)) {
          return;
        }
        if (content.startsWith(prefix)) {
          content = content.replace(prefix, '');
        }
        if (content.startsWith(botping)) {
          content = content.replace(new RegExp(`${botping}\\s+`, 'i'), '');
        }
        if (content.startsWith(botPingId)) {
          content = content.replace(new RegExp(`${botPingId}\\s+`, 'i'), '');
        }
        const messageWithStrippedContent = message;
        messageWithStrippedContent.strippedContent = content;
        this.logger.debug(`Handling \`${content}\``);
        this.commands.forEach((command) => {
          if (command.regex.test(content)) {
            this.checkCanAct(command, messageWithStrippedContent)
            .then((canAct) => {
              if (canAct) {
                this.logger.debug(`Matched ${command.id}`);
                if (message.channel.type === 'dm' ||
                  (message.channel.permissionsFor(this.bot.client.user.id)
                   .has(['ADD_REACTIONS', 'READ_MESSAGES', 'SEND_MESSAGES']))) {
                  message.react('314349398811475968').catch(this.logger.error);
                }
                command.run(messageWithStrippedContent);
              }
            });
          }
        });
      })
      .catch(this.logger.error);
  }

  /**
   * Check if the current command being called is able to be performed for the user calling it.
   * @param   {Command} command  command to process to see if it can be called
   * @param   {Message} message Discord message object
   * @returns {boolean} Whether or not the ucrrent command can be called by the author
   */
  checkCanAct(command, message) {
    return new Promise((resolve) => {
      if (command.ownerOnly && message.author.id !== this.bot.owner) {
        resolve(false);
      } else if (message.channel.type === 'text') {
        if (command.requiresAuth) {
          if (message.channel.permissionsFor(message.author).has('MANAGE_ROLES')) {
            this.bot.settings
            .getChannelPermissionForMember(message.channel, message.author.id, command.id)
              .then((userHasPermission) => {
                resolve(userHasPermission);
              })
              .catch(() => {
                this.bot.settings
                .getChannelPermissionForUserRoles(message.channel,
                  message.author, command.id)
                  .then((userHasPermission) => {
                    resolve(userHasPermission);
                  });
              });
          } else {
            resolve(false);
          }
        } else {
          this.bot.settings
          .getChannelPermissionForMember(message.channel, message.author.id, command.id)
            .then((userHasPermission) => {
              resolve(userHasPermission);
            })
            .catch(() => {
              this.bot.settings
              .getChannelPermissionForUserRoles(message.channel,
                message.author, command.id)
                .then((userHasPermission) => {
                  resolve(userHasPermission);
                });
            });
        }
      } else if (message.channel.type === 'dm' && command.allowDM) {
        resolve(true);
      } else {
        resolve(false);
      }
    });
  }
}

module.exports = CommandHandler;
<commit_msg>fix emoji<commit_after>'use strict';

const fs = require('fs');
const path = require('path');
const decache = require('decache');

/**
 * Describes a CommandHandler for a bot.
 */
class CommandHandler {
  /**
   * Constructs CommandHandler
   * @param {Genesis} bot    Bot to derive prefix for commands from
   */
  constructor(bot) {
    this.bot = bot;
    this.logger = bot.logger;

    /**
     * Array of command objects that can be called
     * @type {Array<Command>}
     * @private
     */
    this.commands = [];
  }

  /**
   * Loads the commands from disk into this.commands
   */
  loadCommands() {
    const commandDir = path.join(__dirname, 'commands');
    let files = fs.readdirSync(commandDir);

    const categories = files.filter(f => f.indexOf('.js') === -1);
    files = files.filter(f => f.indexOf('.js') > -1);

    categories.forEach((category) => {
      files = files.concat(fs.readdirSync(path.join(commandDir, category))
        .map(f => path.join(category, f)));
    });

    if (this.commands.length !== 0) {
      this.logger.debug('Decaching commands');
      files.forEach((f) => {
        decache(path.join(commandDir, f));
      });
    }

    this.logger.debug(`Loading commands: ${files}`);

    this.commands = files.map((f) => {
      try {
        // eslint-disable-next-line import/no-dynamic-require, global-require
        const Cmd = require(path.join(commandDir, f));
        if (Object.prototype.toString.call(Cmd) === '[object Function]') {
          const command = new Cmd(this.bot);

          this.logger.debug(`Adding ${command.id}`);
          return command;
        }
        return null;
      } catch (err) {
        this.logger.error(err);
        return null;
      }
    })
      .filter(c => c !== null);
  }

  /**
   * Handle the command contained in the message contents, if any.
   * @param {Message} message Message whose command should be checked and handled
   */
  handleCommand(message) {
    let content = message.content;
    const botping = `@${message.guild ?
          message.guild.members.get(this.bot.client.user.id).displayName :
          this.bot.client.user.username}`;
    const botPingId = `<@${this.bot.client.user.id}>`;
    this.bot.settings.getChannelPrefix(message.channel)
      .then((prefix) => {
        if (!content.startsWith(prefix)
            && !content.startsWith(botping)
            && !content.startsWith(botPingId)) {
          return;
        }
        if (content.startsWith(prefix)) {
          content = content.replace(prefix, '');
        }
        if (content.startsWith(botping)) {
          content = content.replace(new RegExp(`${botping}\\s+`, 'i'), '');
        }
        if (content.startsWith(botPingId)) {
          content = content.replace(new RegExp(`${botPingId}\\s+`, 'i'), '');
        }
        const messageWithStrippedContent = message;
        messageWithStrippedContent.strippedContent = content;
        this.logger.debug(`Handling \`${content}\``);
        this.commands.forEach((command) => {
          if (command.regex.test(content)) {
            this.checkCanAct(command, messageWithStrippedContent)
            .then((canAct) => {
              if (canAct) {
                this.logger.debug(`Matched ${command.id}`);
                if (message.channel.type === 'dm' ||
                  (message.channel.permissionsFor(this.bot.client.user.id)
                   .has(['ADD_REACTIONS', 'READ_MESSAGES', 'SEND_MESSAGES']))) {
                  message.react(this.bot.client.emojis.get('314349398811475968')).catch(this.logger.error);
                }
                command.run(messageWithStrippedContent);
              }
            });
          }
        });
      })
      .catch(this.logger.error);
  }

  /**
   * Check if the current command being called is able to be performed for the user calling it.
   * @param   {Command} command  command to process to see if it can be called
   * @param   {Message} message Discord message object
   * @returns {boolean} Whether or not the ucrrent command can be called by the author
   */
  checkCanAct(command, message) {
    return new Promise((resolve) => {
      if (command.ownerOnly && message.author.id !== this.bot.owner) {
        resolve(false);
      } else if (message.channel.type === 'text') {
        if (command.requiresAuth) {
          if (message.channel.permissionsFor(message.author).has('MANAGE_ROLES')) {
            this.bot.settings
            .getChannelPermissionForMember(message.channel, message.author.id, command.id)
              .then((userHasPermission) => {
                resolve(userHasPermission);
              })
              .catch(() => {
                this.bot.settings
                .getChannelPermissionForUserRoles(message.channel,
                  message.author, command.id)
                  .then((userHasPermission) => {
                    resolve(userHasPermission);
                  });
              });
          } else {
            resolve(false);
          }
        } else {
          this.bot.settings
          .getChannelPermissionForMember(message.channel, message.author.id, command.id)
            .then((userHasPermission) => {
              resolve(userHasPermission);
            })
            .catch(() => {
              this.bot.settings
              .getChannelPermissionForUserRoles(message.channel,
                message.author, command.id)
                .then((userHasPermission) => {
                  resolve(userHasPermission);
                });
            });
        }
      } else if (message.channel.type === 'dm' && command.allowDM) {
        resolve(true);
      } else {
        resolve(false);
      }
    });
  }
}

module.exports = CommandHandler;
<|endoftext|>


<commit_before>/**
* Copyright 2016 PT Inovação e Sistemas SA
* Copyright 2016 INESC-ID
* Copyright 2016 QUOBIS NETWORKS SL
* Copyright 2016 FRAUNHOFER-GESELLSCHAFT ZUR FOERDERUNG DER ANGEWANDTEN FORSCHUNG E.V
* Copyright 2016 ORANGE SA
* Copyright 2016 Deutsche Telekom AG
* Copyright 2016 Apizee
* Copyright 2016 TECHNISCHE UNIVERSITAT BERLIN
*
* 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.
**/

import SyncObject from './ProxyObject';

//import { deepClone } from '../utils/utils.js';

/**
 * The class returned from the DataObject addChildren call or from onAddChildren if remotely created.
 */
class DataObjectChild /* implements SyncStatus */ {
  /* private

  ----event handlers----
  _onResponseHandler: (event) => void
  */

  /**
   * @ignore
   * Should not be used directly by Hyperties. It's called by the DataObject.addChild
   */
  constructor(input) {
    let _this = this;

    function throwMandatoryParmMissingError(par) {
      throw '[DataObjectChild] ' + par + ' mandatory parameter is missing';
    }

    input.parent ?  _this._parent = input.parent : throwMandatoryParmMissingError('parent');
    input.url ?  _this._url = input.url : throwMandatoryParmMissingError('url');
    input.created ? _this._created = input.created : throwMandatoryParmMissingError('created');
    input.reporter ? _this._reporter = input.reporter : throwMandatoryParmMissingError('reporter');
    input.runtime ? _this._runtime = input.runtime : throwMandatoryParmMissingError('runtime');
    input.schema ? _this._schema = input.schema : throwMandatoryParmMissingError('schema');
    input.parentObject ? _this._parentObject = input.parentObject : throwMandatoryParmMissingError('parentObject');

    if (input.name) _this._name = input.name;
    if (input.description) _this._description = input.description;
    if (input.tags) _this._tags = input.tags;
    if (input.resources) _this._resources = input.resources;
    if (input.observerStorage) _this._observerStorage = input.observerStorage;
    if (input.publicObservation) _this._publicObservation = input.publicObservation;

    if (input.data) {
      _this._syncObj = new SyncObject(input.data);
    } else {
      _this._syncObj = new SyncObject({});
    }

    console.log('[DataObjectChild -  Constructor] - ', _this._syncObj);

    _this._bus = _this._parentObject._bus;
    _this._owner = _this._parentObject._owner;

    _this._allocateListeners();

    _this._metadata = input;

    // delete _this._metadata.data;
    delete _this._metadata.parentObject;

  }

  _allocateListeners() {
    let _this = this;

    //this is only needed for children reporters
    if (_this._reporter === _this._owner) {
      _this._listener = _this._bus.addListener(_this._reporter, (msg) => {
        if (msg.type === 'response' && msg.id === _this._msgId) {
          console.log('DataObjectChild.onResponse:', msg);
          _this._onResponse(msg);
        }
      });
    }
  }

  _releaseListeners() {
    let _this = this;

    if (_this._listener) {
      _this._listener.remove();
    }
  }

  /**
   * Release and delete object data
   */
  delete() {
    let _this = this;

    _this._releaseListeners();

    //TODO: send delete message ?
  }

  /**
   * All Metadata about the Child Data Object
   * @type {Object} -
   */
  get metadata() { return this._metadata; }

  /**
   * Children ID generated on addChildren. Unique identifier
   * @type {URL} - URL of the format <HypertyURL>#<numeric-sequence>
   */
  get childId() { return this._childId; }

  /**
   * Data Structure to be synchronized.
   * @type {JSON} - JSON structure that should follow the defined schema, if any.
   */
  get data() { return this._syncObj.data; }

  /**
   * Set for this dataObjectChild an identity
   * @method identity
   * @param  {Identity} identity identity from who created the message
   */
  set identity(identity) { this._identity = identity; }

  /**
   * Get for this dataObjectChild an identity
   * @method identity
   * @return {Identity} identity from who created the message
   */
  get identity() { return this._identity; }

  /**
   * Register the change listeners sent by the reporter child
   * @param {function(event: MsgEvent)} callback
   */
  onChange(callback) {
    this._syncObj.observe((event) => {
      console.log('[DataObjectChild - observer] - ', event);
      callback(event);
    });
  }

  /**
   * Setup the callback to process response notifications of the creates
   * @param {function(event: MsgEvent)} callback
   */
  onResponse(callback) {
    this._onResponseHandler = callback;
  }

  //FLOW-IN: message received from a remote DataObject -> _onChildCreate
  _onResponse(msg) {
    let _this = this;

    let event = {
      type: msg.type,
      url: msg.body.source,
      code: msg.body.code
    };

    if (_this._onResponseHandler) {
      _this._onResponseHandler(event);
    }
  }

}

export default DataObjectChild;
<commit_msg>fix childID<commit_after>/**
* Copyright 2016 PT Inovação e Sistemas SA
* Copyright 2016 INESC-ID
* Copyright 2016 QUOBIS NETWORKS SL
* Copyright 2016 FRAUNHOFER-GESELLSCHAFT ZUR FOERDERUNG DER ANGEWANDTEN FORSCHUNG E.V
* Copyright 2016 ORANGE SA
* Copyright 2016 Deutsche Telekom AG
* Copyright 2016 Apizee
* Copyright 2016 TECHNISCHE UNIVERSITAT BERLIN
*
* 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.
**/

import SyncObject from './ProxyObject';

//import { deepClone } from '../utils/utils.js';

/**
 * The class returned from the DataObject addChildren call or from onAddChildren if remotely created.
 */
class DataObjectChild /* implements SyncStatus */ {
  /* private

  ----event handlers----
  _onResponseHandler: (event) => void
  */

  /**
   * @ignore
   * Should not be used directly by Hyperties. It's called by the DataObject.addChild
   */
  constructor(input) {
    let _this = this;

    function throwMandatoryParmMissingError(par) {
      throw '[DataObjectChild] ' + par + ' mandatory parameter is missing';
    }

    input.parent ?  _this._parent = input.parent : throwMandatoryParmMissingError('parent');
    input.url ?  _this._url = input.url : throwMandatoryParmMissingError('url');
    input.created ? _this._created = input.created : throwMandatoryParmMissingError('created');
    input.reporter ? _this._reporter = input.reporter : throwMandatoryParmMissingError('reporter');
    input.runtime ? _this._runtime = input.runtime : throwMandatoryParmMissingError('runtime');
    input.schema ? _this._schema = input.schema : throwMandatoryParmMissingError('schema');
    input.parentObject ? _this._parentObject = input.parentObject : throwMandatoryParmMissingError('parentObject');

    if (input.name) _this._name = input.name;
    if (input.description) _this._description = input.description;
    if (input.tags) _this._tags = input.tags;
    if (input.resources) _this._resources = input.resources;
    if (input.observerStorage) _this._observerStorage = input.observerStorage;
    if (input.publicObservation) _this._publicObservation = input.publicObservation;

    _this._childId = input.url;

    if (input.data) {
      _this._syncObj = new SyncObject(input.data);
    } else {
      _this._syncObj = new SyncObject({});
    }

    console.log('[DataObjectChild -  Constructor] - ', _this._syncObj);

    _this._bus = _this._parentObject._bus;
    _this._owner = _this._parentObject._owner;

    _this._allocateListeners();

    _this._metadata = input;

    // delete _this._metadata.data;
    delete _this._metadata.parentObject;

  }

  _allocateListeners() {
    let _this = this;

    //this is only needed for children reporters
    if (_this._reporter === _this._owner) {
      _this._listener = _this._bus.addListener(_this._reporter, (msg) => {
        if (msg.type === 'response' && msg.id === _this._msgId) {
          console.log('DataObjectChild.onResponse:', msg);
          _this._onResponse(msg);
        }
      });
    }
  }

  _releaseListeners() {
    let _this = this;

    if (_this._listener) {
      _this._listener.remove();
    }
  }

  /**
   * Release and delete object data
   */
  delete() {
    let _this = this;

    _this._releaseListeners();

    //TODO: send delete message ?
  }

  /**
   * All Metadata about the Child Data Object
   * @type {Object} -
   */
  get metadata() { return this._metadata; }

  /**
   * Children ID generated on addChildren. Unique identifier
   * @type {URL} - URL of the format <HypertyURL>#<numeric-sequence>
   */
  get childId() { return this._childId; }

  /**
   * Data Structure to be synchronized.
   * @type {JSON} - JSON structure that should follow the defined schema, if any.
   */
  get data() { return this._syncObj.data; }

  /**
   * Set for this dataObjectChild an identity
   * @method identity
   * @param  {Identity} identity identity from who created the message
   */
  set identity(identity) { this._identity = identity; }

  /**
   * Get for this dataObjectChild an identity
   * @method identity
   * @return {Identity} identity from who created the message
   */
  get identity() { return this._identity; }

  /**
   * Register the change listeners sent by the reporter child
   * @param {function(event: MsgEvent)} callback
   */
  onChange(callback) {
    this._syncObj.observe((event) => {
      console.log('[DataObjectChild - observer] - ', event);
      callback(event);
    });
  }

  /**
   * Setup the callback to process response notifications of the creates
   * @param {function(event: MsgEvent)} callback
   */
  onResponse(callback) {
    this._onResponseHandler = callback;
  }

  //FLOW-IN: message received from a remote DataObject -> _onChildCreate
  _onResponse(msg) {
    let _this = this;

    let event = {
      type: msg.type,
      url: msg.body.source,
      code: msg.body.code
    };

    if (_this._onResponseHandler) {
      _this._onResponseHandler(event);
    }
  }

}

export default DataObjectChild;
<|endoftext|>


<commit_before>const _ = require('lodash'),
    utils =  require('../../../utils'),
    driver = utils.getDriver(),
    C = driver.constants;

module.exports = function(object, dFatigue, {roomObjects, bulk}) {
//    console.log(`add-fatigue ${dFatigue} called for ${}`)

    if(_.isUndefined(object._fatigue)) { object._fatigue = object.fatigue }

    if((object._fatigue > 0) && (dFatigue < 0)) { // MOVES contribution removes own fatigue first
        const resting = Math.min(object._fatigue, -dFatigue);
        object._fatigue -= resting;
        dFatigue += resting;

        const fatigue = Math.max(0, object._fatigue);
        if(object.fatigue != fatigue) {
            bulk.update(object, { fatigue });
        }

        if(dFatigue == 0) {
            return;
        }
    }

    while(object._pulled) {
        object = roomObjects[object._pulled];
    }

    if(_.isUndefined(object._fatigue)) { object._fatigue = object.fatigue }
    object._fatigue += dFatigue;

    const fatigue = Math.max(0, object._fatigue);
    if(object.fatigue != fatigue) {
        bulk.update(object, { fatigue });
    }
};
<commit_msg>hotfix(processor): edge case in Creep.pull<commit_after>const _ = require('lodash'),
    utils =  require('../../../utils'),
    driver = utils.getDriver(),
    C = driver.constants;

module.exports = function(object, dFatigue, {roomObjects, bulk}) {
//    console.log(`add-fatigue ${dFatigue} called for ${}`)

    if(_.isUndefined(object._fatigue)) { object._fatigue = object.fatigue }

    if((object._fatigue > 0) && (dFatigue < 0)) { // MOVES contribution removes own fatigue first
        const resting = Math.min(object._fatigue, -dFatigue);
        object._fatigue -= resting;
        dFatigue += resting;

        const fatigue = Math.max(0, object._fatigue);
        if(object.fatigue != fatigue) {
            bulk.update(object, { fatigue });
        }

        if(dFatigue == 0) {
            return;
        }
    }

    while(!!object._pulled && !!roomObjects[object._pulled]) {
        object = roomObjects[object._pulled];
    }

    if(_.isUndefined(object._fatigue)) { object._fatigue = object.fatigue }
    object._fatigue += dFatigue;

    const fatigue = Math.max(0, object._fatigue);
    if(object.fatigue != fatigue) {
        bulk.update(object, { fatigue });
    }
};
<|endoftext|>