<commit_before>Template.latestActivitiesByTypeTable.helpers({
  tableData: function () {
    // Set instance variable for consistency
    var instance = Template.instance();

    // Get the parent template
    var parent = instance.parent();

    // Get latest residents activity from parent template
    var latestResidentActivities = parent.latestResidentsActivityByType.get();

    if (latestResidentActivities) {
      return latestResidentActivities;
    }

    // Columns name, timeAgo
  }
});
<commit_msg>Add basic table data toggle<commit_after>Template.latestActivitiesByTypeTable.helpers({
  tableData: function () {
    // Set instance variable for consistency
    var instance = Template.instance();

    var latestResidentActivities = instance.parent().latestResidentsActivityByType.get();

    if (latestResidentActivities) {
      return latestResidentActivities;
    } else {
      return [];
    }
  }
});

Template.latestActivitiesByTypeTable.created = function () {
  // Set instance variable for consistency
  instance = Template.instance();

  instance.autorun(function () {

  });
};
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* 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.
*/

'use strict';

// MODULES //

var tape = require( 'tape' );
var EPS = require( '@stdlib/constants/math/float64-eps' );
var abs = require( '@stdlib/math/base/special/abs' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var incrwmean = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof incrwmean, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function returns an accumulator function', function test( t ) {
	t.equal( typeof incrwmean(), 'function', 'returns a function' );
	t.end();
});

tape( 'the initial accumulated value is `null`', function test( t ) {
	var acc = incrwmean();
	t.equal( acc(), null, 'returns expected value' );
	t.end();
});

tape( 'the accumulator function incrementally computes a weighted arithmetic mean', function test( t ) {
	var expected;
	var actual;
	var delta;
	var dataX;
	var dataW;
	var xwSum;
	var wSum;
	var acc;
	var tol;
	var N;
	var x;
	var w;
	var i;

	dataX = [ 2.0, 3.0, 2.0, 4.0, 3.0, 4.0 ];
	dataW = [ 1.0, 2.0, 0.1, 1.8, 9.9, 3.6 ];
	N = dataX.length;

	acc = incrwmean();

	xwSum = 0;
	wSum = 0;
	for ( i = 0; i < N; i++ ) {
		x = dataX[ i ];
		w = dataW[ i ];
		xwSum += x * w;
		wSum += w;
		expected = xwSum / wSum;
		actual = acc( x, w );
		delta = abs( actual - expected );
		tol = EPS * abs( expected );
		t.ok( delta <= tol, 'within tolerance. x: ' + x + '. Value: ' + actual + '. Expected: ' + expected + '. Tolerance: ' + tol + '.' );
	}
	t.end();
});

tape( 'if not provided arguments, the accumulator function returns the current weighted mean', function test( t ) {
	var dataX;
	var dataW;
	var acc;
	var i;

	dataX = [ 2.0, 3.0, 1.0 ];
	dataW = [ 2.0, 2.0, 1.0 ];
	acc = incrwmean();
	for ( i = 0; i < dataX.length; i++ ) {
		acc( dataX[ i ], dataW[ i ] );
	}
	t.equal( acc(), 2.2, 'returns the current accumulated mean' );
	t.end();
});

tape( 'if not provided a weight, the accumulator function returns `NaN`', function test( t ) {
	var acc = incrwmean();
	t.equal( isnan( acc( 2.0 ) ), true, 'returns NaN' );
	t.equal( isnan( acc( 3.14 ) ), true, 'returns NaN' );
	t.end();
});

tape( 'if provided `NaN` for either a value or a weight, the accumulator function returns `NaN`', function test( t ) {
	var acc = incrwmean();
	t.equal( isnan( acc( 2.0, NaN ) ), true, 'returns NaN' );
	t.equal( isnan( acc( 3.14, NaN ) ), true, 'returns NaN' );

	acc = incrwmean();
	t.equal( isnan( acc( NaN, 1.0 ) ), true, 'returns NaN' );
	t.equal( isnan( acc( NaN, 1.0 ) ), true, 'returns NaN' );

	acc = incrwmean();
	t.equal( isnan( acc( NaN, NaN ) ), true, 'returns NaN' );
	t.equal( isnan( acc( NaN, NaN ) ), true, 'returns NaN' );
	t.end();
});
<commit_msg>Add decimals<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* 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.
*/

'use strict';

// MODULES //

var tape = require( 'tape' );
var EPS = require( '@stdlib/constants/math/float64-eps' );
var abs = require( '@stdlib/math/base/special/abs' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var incrwmean = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof incrwmean, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function returns an accumulator function', function test( t ) {
	t.equal( typeof incrwmean(), 'function', 'returns a function' );
	t.end();
});

tape( 'the initial accumulated value is `null`', function test( t ) {
	var acc = incrwmean();
	t.equal( acc(), null, 'returns expected value' );
	t.end();
});

tape( 'the accumulator function incrementally computes a weighted arithmetic mean', function test( t ) {
	var expected;
	var actual;
	var delta;
	var dataX;
	var dataW;
	var xwSum;
	var wSum;
	var acc;
	var tol;
	var N;
	var x;
	var w;
	var i;

	dataX = [ 2.0, 3.0, 2.0, 4.0, 3.0, 4.0 ];
	dataW = [ 1.0, 2.0, 0.1, 1.8, 9.9, 3.6 ];
	N = dataX.length;

	acc = incrwmean();

	xwSum = 0.0;
	wSum = 0.0;
	for ( i = 0; i < N; i++ ) {
		x = dataX[ i ];
		w = dataW[ i ];
		xwSum += x * w;
		wSum += w;
		expected = xwSum / wSum;
		actual = acc( x, w );
		delta = abs( actual - expected );
		tol = EPS * abs( expected );
		t.ok( delta <= tol, 'within tolerance. x: ' + x + '. Value: ' + actual + '. Expected: ' + expected + '. Tolerance: ' + tol + '.' );
	}
	t.end();
});

tape( 'if not provided arguments, the accumulator function returns the current weighted mean', function test( t ) {
	var dataX;
	var dataW;
	var acc;
	var i;

	dataX = [ 2.0, 3.0, 1.0 ];
	dataW = [ 2.0, 2.0, 1.0 ];
	acc = incrwmean();
	for ( i = 0; i < dataX.length; i++ ) {
		acc( dataX[ i ], dataW[ i ] );
	}
	t.equal( acc(), 2.2, 'returns the current accumulated mean' );
	t.end();
});

tape( 'if not provided a weight, the accumulator function returns `NaN`', function test( t ) {
	var acc = incrwmean();
	t.equal( isnan( acc( 2.0 ) ), true, 'returns NaN' );
	t.equal( isnan( acc( 3.14 ) ), true, 'returns NaN' );
	t.end();
});

tape( 'if provided `NaN` for either a value or a weight, the accumulator function returns `NaN`', function test( t ) {
	var acc = incrwmean();
	t.equal( isnan( acc( 2.0, NaN ) ), true, 'returns NaN' );
	t.equal( isnan( acc( 3.14, NaN ) ), true, 'returns NaN' );

	acc = incrwmean();
	t.equal( isnan( acc( NaN, 1.0 ) ), true, 'returns NaN' );
	t.equal( isnan( acc( NaN, 1.0 ) ), true, 'returns NaN' );

	acc = incrwmean();
	t.equal( isnan( acc( NaN, NaN ) ), true, 'returns NaN' );
	t.equal( isnan( acc( NaN, NaN ) ), true, 'returns NaN' );
	t.end();
});
<|endoftext|>


<commit_before>angular.module('Cyclear').controller('riderlistCtrl', function ($scope, $http, $filter, $timeout, $route, $routeParams) {

    $scope.initialLoad = false;
    $scope.loaded = false;

    $scope.filter = {};
    $scope.filter.name = null;
    $scope.filter.excludeWithTeam = false;

    $scope.riders = [];

    $scope.pagination = {};
    $scope.pagination.currentPage = 1;
    // keep this in sync with getPages() to prevent a new watch begin triggered on pagination-changes
    $scope.pagination.options = [2, 3, 4, 5, 6];
    $scope.data;
    $scope.pages;

    alert("fixme: dubbele lookup, pagination-maximum uitrekenen");

    var getRiders = function (initial) {
        var routeparams = {_format: 'json', seizoen: seizoenSlug };
        if (!initial) {
            routeparams.filter = $scope.filter.name;
            routeparams.excludeWithTeam = $scope.filter.excludeWithTeam;
            routeparams.page = $scope.pagination.currentPage;
        }
        $http.get(Routing.generate('rider_index', routeparams))
            .success(function (data) {
                $scope.riders = data.items;
                $scope.data = data;
                $scope.getPages();
                $scope.initialLoad = true;
            }).error(function (reason, status) {

            });
    }

    /** Bootstrap **/
    getRiders(true);

    var timer;
    $scope.$watch('[filter, pagination]', function (newValue, oldValue) {
        if (!$scope.initialLoad) {
            return;
        }
        // do we need to reset the pagination?
        if (newValue[0].name != oldValue[0].name) {
            // looks like this does not trigger a new watch?
            $scope.pagination.currentPage = 1;
        }

        // still time requests even though we cancel them later on through Angular.
        if (timer) {
            $timeout.cancel(timer);
        }
        if (newValue) {
            timer = $timeout(function () {
                getRiders(false);
            }, 500);
        } else if (!newValue && oldValue) {
            timer = $timeout(function () {
                getRiders(false);
            }, 500);
        }
    }, true);

    $scope.getPages = function () {
        var pages = [];
        for (var x = 1; x <= Math.ceil($scope.data.total_count / $scope.data.num_items_per_page); x++) {
            pages.push(x);
        }
        $scope.pages = pages;
        var max = 6;
        var i = 1;
        $scope.pagination.options = [];
        if ($scope.pagination.currentPage > 1) {
            max = 5;
            if ($scope.pagination.currentPage > 2) {
                $scope.pagination.options.push($scope.pagination.currentPage - 1);
                max = 4;
            }
            $scope.pagination.options.push($scope.pagination.currentPage);
        }
        while (i < pages.length) {
            $scope.pagination.options.push(i + $scope.pagination.currentPage);
            i++;
            if (i >= max) {
                break;
            }
        }
        return pages;
    }

    $scope.setPage = function (pageNr) {
        if (pageNr < 1) {
            return;
        }
        $scope.pagination.currentPage = parseInt(pageNr, 10);
    }

    $scope.getUrl = function (slug) {
        return Routing.generate('renner_show', {seizoen: seizoenSlug, renner: slug});
    }

});
<commit_msg>remove comm.<commit_after>angular.module('Cyclear').controller('riderlistCtrl', function ($scope, $http, $filter, $timeout, $route, $routeParams) {

    $scope.initialLoad = false;
    $scope.loaded = false;

    $scope.filter = {};
    $scope.filter.name = null;
    $scope.filter.excludeWithTeam = false;

    $scope.riders = [];

    $scope.pagination = {};
    $scope.pagination.currentPage = 1;
    // keep this in sync with getPages() to prevent a new watch begin triggered on pagination-changes
    $scope.pagination.options = [2, 3, 4, 5, 6];
    $scope.data;
    $scope.pages;

    var getRiders = function (initial) {
        var routeparams = {_format: 'json', seizoen: seizoenSlug };
        if (!initial) {
            routeparams.filter = $scope.filter.name;
            routeparams.excludeWithTeam = $scope.filter.excludeWithTeam;
            routeparams.page = $scope.pagination.currentPage;
        }
        $http.get(Routing.generate('rider_index', routeparams))
            .success(function (data) {
                $scope.riders = data.items;
                $scope.data = data;
                $scope.getPages();
                $scope.initialLoad = true;
            }).error(function (reason, status) {

            });
    }

    /** Bootstrap **/
    getRiders(true);

    var timer;
    $scope.$watch('[filter, pagination]', function (newValue, oldValue) {
        if (!$scope.initialLoad) {
            return;
        }
        // do we need to reset the pagination?
        if (newValue[0].name != oldValue[0].name) {
            // looks like this does not trigger a new watch?
            $scope.pagination.currentPage = 1;
        }

        // still time requests even though we cancel them later on through Angular.
        if (timer) {
            $timeout.cancel(timer);
        }
        if (newValue) {
            timer = $timeout(function () {
                getRiders(false);
            }, 500);
        } else if (!newValue && oldValue) {
            timer = $timeout(function () {
                getRiders(false);
            }, 500);
        }
    }, true);

    $scope.getPages = function () {
        var pages = [];
        for (var x = 1; x <= Math.ceil($scope.data.total_count / $scope.data.num_items_per_page); x++) {
            pages.push(x);
        }
        $scope.pages = pages;
        var max = 6;
        var i = 1;
        $scope.pagination.options = [];
        if ($scope.pagination.currentPage > 1) {
            max = 5;
            if ($scope.pagination.currentPage > 2) {
                $scope.pagination.options.push($scope.pagination.currentPage - 1);
                max = 4;
            }
            $scope.pagination.options.push($scope.pagination.currentPage);
        }
        while (i < pages.length) {
            $scope.pagination.options.push(i + $scope.pagination.currentPage);
            i++;
            if (i >= max) {
                break;
            }
        }
        return pages;
    }

    $scope.setPage = function (pageNr) {
        if (pageNr < 1) {
            return;
        }
        $scope.pagination.currentPage = parseInt(pageNr, 10);
    }

    $scope.getUrl = function (slug) {
        return Routing.generate('renner_show', {seizoen: seizoenSlug, renner: slug});
    }

});
<|endoftext|>


<commit_before>angular
  .module('lnPatterns')
  .factory('lnOGravityFormParser', lnOGravityFormParser);

/**
 *  TODO:
 *    - Render all 'Advanced' fields in the WP GF Form setup
 *    - Render all 'Post' fields in the WP GF Form setup
 *    - Render all 'Pricing' fields in the WP GF Form setup
 *
 *    - Add in paged form support
 *      - Render progress indicator if specified
 *      - Move buttons into page footers and out of form footer
 *      - Detect page number and use either Next or Submit button if it's the final page
 *
 *    - Consider how to re-structure this to use a more intelligent method map for
 *      input type parsing
 */

/*@ngInject*/
function lnOGravityFormParser($log, isValidParameterFilter) {

  var formTemplate = '' +
      '
' +
      '
' +
      '
{{title}}
' +
      '{{description}}' +
      '
' +
      '
' +
      '{{body}}' +
      '
' +
      '
' +
      '{{submit}}' +
      '
' +
      '
'
    ;

  // Public API
  //

  return {
    parse: parse
  };

  function parse(data) {
    $log.debug('lnOGravityFormParser.parse() ->', data.response);

    if (angular.isUndefined(data.response)) {
      $log.error('lnOGravityFormParser.parse() -> Form data unavailable!');
      return;
    }

    return angular
      .copy(formTemplate)
      .replace(/{{title}}/gi, data.response.title)
      .replace(/{{description}}/gi, data.response.description)
      .replace(/{{body}}/gi, parseAllFields(data.response.fields))
      .replace(/{{submit}}/gi, parseSubmitButton(data.response.button.text));
  }

  // Internal
  //

  // Fields from the 'Standard' panel in the GF Form builder
  //

  function parseSectionBreak(data) {
    return '
{{label}}
'
      .replace(/{{label}}/gi, data.label);
  }

  function parseRequiredFlag() {
    return '*';
  }

  function parseLabel(isFor, text, required) {
    return '{{text}}{{required}}'
      .replace(/{{for}}/gi, isFor)
      .replace(/{{text}}/gi, text)
      .replace(/{{required}}/gi, required === true ? parseRequiredFlag() : '');
  }

  function parseTextarea(data) {
    return '<textarea name="{{name}}" id="{{id}}" placeholder="{{placeholder}}" value="{{value}}"></textarea>'
      .replace(/{{name}}/gi, data.name)
      .replace(/{{id}}/gi, data.id)
      .replace(/{{value}}/gi, data.value)
      .replace(/{{placeholder}}/gi, data.placeholder)
      .replace(/{{required}}/gi, data.isRequired);
  }

  function parseInput(data) {
    var _hidden = data.type === 'hidden';

    return '<input type="{{type}}" name="{{name}}" id="{{id}}" value="{{value}}" required="{{required}}" placeholder="{{placeholder}}" class="{{hidden}}">'
      .replace(/{{type}}/gi, data.type)
      .replace(/{{id}}/gi, data.id)
      .replace(/{{name}}/gi, data.name)
      .replace(/{{value}}/gi, data.value)
      .replace(/{{placeholder}}/gi, data.placeholder)
      .replace(/{{required}}/gi, data.isRequired)
      .replace(/{{selected}}/gi, data.isSelected)
      .replace(/{{hidden}}/gi, _hidden ? 'ng-hide' : '');
  }

  function parseGroupInput(data) {
    return '<input type="{{type}}" id="{{id}}" name="{{name}}"  value="{{value}}" {{checked}}>'
      .replace(/{{type}}/gi, data.type)
      .replace(/{{id}}/gi, data.id)
      .replace(/{{name}}/gi, data.name)
      .replace(/{{value}}/gi, data.value)
      .replace(/{{checked}}/gi, data.isSelected === true ? 'checked' : '');
  }

  function parseGroupInputList(data, startIndex, nameHasIndexSuffix) {
    var _list = '
';
    var _index = startIndex || 0;

    angular.forEach(data.choices, function (choice) {
      choice.type = data.type;
      choice.id = 'choice_' + data.formId + '_' + data.id + '_' + _index;
      choice.name = 'input_' + data.id;

      if (nameHasIndexSuffix === true) {
        choice.name += '.' + _index;
      }

      _list += '
'
        + parseGroupInput(choice)
        + parseLabel(choice.id, choice.text, false)
        + '
';

      _index += 1;
    });

    _list += '
';

    return _list;
  }

  function parseSelectOption(data) {
    return '<option value="{{value}}" {{selected}}>{{text}}</option>'
      .replace(/{{value}}/gi, data.value)
      .replace(/{{selected}}/gi, data.isSelected === true ? 'selected="selected"' : '')
      .replace(/{{text}}/gi, data.text);
  }

  function parseSelectList(data, isMultiple) {
    var _list = '<select {{multiple}} name="{{name}}" id="{{id}}">';
    var _isMultiple = isMultiple === true;

    angular.forEach(data.choices, function (choice) {
      _list += parseSelectOption(choice);
    });

    _list += '</select>';

    return _list
      .replace(/{{multiple}}/gi, _isMultiple ? 'multiple="multiple"' : '')
      .replace(/{{name}}/gi, data.name)
      .replace(/{{id}}/gi, data.id);
  }

  // Fields from the 'Advanced' panel in the GF Form builder
  //

  /*
   function parseName() {

   }

   function parseDate() {

   }

   function parseTime() {

   }

   function parsePhone() {

   }

   function parseAddress() {

   }

   function parseWebsite() {

   }
   */

  // NOTE: This is currently implemented as a standard input, but actually has it's own type.
  function parseEmail(data) {
    return parseInput(data);
  }

  /*
   function parseFileupload() {

   }

   function parseList() {

   }
   */

  // Fields from the 'Post' panel in the GF Form builder
  //

  // Submit / Next button
  //

  function parseSubmitButton(text) {
    return '<button type="submit" ng-disabled="!$ctrl.form.$valid" class="submit">{{text}}</button>'
      .replace(/{{text}}/gi, text || 'Submit');
  }

  // Conglomeate methods
  //

  function parseField(fieldHTML, labelHTML, isHidden, formId, originalId) {
    return '
{{label}}{{field}}
'
      .replace(/{{hidden}}/gi, isHidden ? ' ng-hide' : '')
      .replace(/{{id}}/gi, 'field_' + formId + '_' + originalId)
      .replace(/{{label}}/gi, labelHTML)
      .replace(/{{field}}/gi, fieldHTML);
  }

  /**
   * TODO: think about how to re-structure this to reduce complexity
   *       and increase clarity
   */
  function parseAllFields(fieldsData) {
    var _fields = '
';

    angular.forEach(fieldsData, function (field) {
      var _fieldHTML;
      var _labelHTML;
      var _hidden = false;
      var _hasLabel = true;
      var _originalId = angular.copy(field.id);

      switch (field.type) {

        // 'Standard' field types
        case 'text':
        case 'number':
        case 'hidden':
          _hidden = field.type === 'hidden';
          field.id = 'input_' + field.id;
          field.name = isValidParameterFilter(field.name) ? field.name : field.id;
          field.value = isValidParameterFilter(field.value) ? field.value : '';
          _fieldHTML = parseInput(field);
          break;
        case 'textarea':
          field.id = 'input_' + field.id;
          field.name = isValidParameterFilter(field.name) ? field.name : field.id;
          field.value = isValidParameterFilter(field.value) ? field.value : '';
          _fieldHTML = parseTextarea(field);
          break;
        case 'radio':
          _fieldHTML = parseGroupInputList(field);
          break;
        case 'checkbox':
          _fieldHTML = parseGroupInputList(field, 1, true);
          break;
        case 'select':
          field.id = 'input_' + field.id;
          field.name = field.id;
          _fieldHTML = parseSelectList(field);
          break;
        case 'multiselect':
          field.id = 'input_' + field.id;
          field.name = field.id + '[]';
          _fieldHTML = parseSelectList(field, true);
          break;
        case 'html':
          _hasLabel = false;
          _fieldHTML = field.content || ''; // Just render the HTML as-is
          break;
        case 'section':
          _hasLabel = false;
          _fieldHTML = parseSectionBreak(field);
          break;

        /*
         case 'page':
         _fieldHTML = parsePage(field);
         */

        // TODO: 'Advanced' field types
        /*
         case 'name':
         _fieldHTML = parseName(field);
         break;
         case 'date':
         _fieldHTML = parseDate(field);
         break;
         case 'time':
         _fieldHTML = parseTime(field);
         break;
         case 'phone':
         _fieldHTML = parsePhone(field);
         break;
         case 'address':
         _fieldHTML = parseAddress(field);
         break;
         */

        case 'email':
          field.id = 'input_' + field.id;
          field.name = isValidParameterFilter(field.name) ? field.name : field.id;
          field.value = isValidParameterFilter(field.value) ? field.value : '';
          _fieldHTML = parseEmail(field);
          break;

        /*
         case 'website':
         _fieldHTML = parseWebsite(field);
         break;
         case 'fileupload':
         _fieldHTML = parseFileupload(field);
         break;
         case 'list':
         _fieldHTML = parseList(field);
         break;
         */

        // TODO: 'Post' field types
        /*
         case 'post_title':
         break;
         case 'post_content':
         break;
         case 'post_excerpt':
         break;
         case 'post_tags':
         break;
         case 'post_category':
         break;
         case 'post_image':
         break;
         case 'post_custom_field':
         break;
         */

        // TODO: 'Price' field types
        /*
         case 'product':
         break;
         case 'quantity':
         break;
         case 'option':
         break;
         case 'shipping':
         break;
         case 'total':
         break;
         */
        // If we hit this, it's probably worth just going home and crying...
        default:
          break;
      }

      if (angular.isDefined(_fieldHTML)) {
        _labelHTML = (!_hidden && _hasLabel) ? parseLabel(field.id, field.label, field.isRequired) : '';
        _fields += parseField(_fieldHTML, _labelHTML, _hidden, field.formId, _originalId);
      }
    });

    _fields += '
';

    return _fields;
  }

  /*
   function parsePage() {

   }

   function parsePages() {

   }
   */
}
<commit_msg>fix merge<commit_after>angular
  .module('lnPatterns')
  .factory('lnOGravityFormParser', lnOGravityFormParser);

/**
 *  TODO:
 *    - Render all 'Advanced' fields in the WP GF Form setup
 *    - Render all 'Post' fields in the WP GF Form setup
 *    - Render all 'Pricing' fields in the WP GF Form setup
 *
 *    - Add in paged form support
 *      - Render progress indicator if specified
 *      - Move buttons into page footers and out of form footer
 *      - Detect page number and use either Next or Submit button if it's the final page
 *
 *    - Consider how to re-structure this to use a more intelligent method map for
 *      input type parsing
 */

/*@ngInject*/
function lnOGravityFormParser($log, isValidParameterFilter) {

  var formTemplate = '' +
      '
' +
      '
' +
      '
{{title}}
' +
      '{{description}}' +
      '
' +
      '
' +
      '{{body}}' +
      '
' +
      '
' +
      '{{submit}}' +
      '
' +
      '
'
    ;

  // Public API
  //

  return {
    parse: parse
  };

  function parse(data) {
    $log.debug('lnOGravityFormParser.parse() ->', data.response);

    if (angular.isUndefined(data.response)) {
      $log.error('lnOGravityFormParser.parse() -> Form data unavailable!');
      return;
    }

    return angular
      .copy(formTemplate)
      .replace(/{{title}}/gi, data.response.title)
      .replace(/{{description}}/gi, data.response.description)
      .replace(/{{body}}/gi, parseAllFields(data.response.fields))
      .replace(/{{submit}}/gi, parseSubmitButton(data.response.button.text));
  }

  // Internal
  //

  // Fields from the 'Standard' panel in the GF Form builder
  //

  function parseSectionBreak(data) {
    return '
{{label}}
'
      .replace(/{{label}}/gi, data.label);
  }

  function parseRequiredFlag() {
    return '*';
  }

  function parseLabel(isFor, text, required) {
    return '{{text}}{{required}}'
      .replace(/{{for}}/gi, isFor)
      .replace(/{{text}}/gi, text)
      .replace(/{{required}}/gi, required === true ? parseRequiredFlag() : '');
  }

  function parseTextarea(data) {
    return '<textarea name="{{name}}" id="{{id}}" placeholder="{{placeholder}}" value="{{value}}"></textarea>'
      .replace(/{{name}}/gi, data.name)
      .replace(/{{id}}/gi, data.id)
      .replace(/{{value}}/gi, data.value)
      .replace(/{{placeholder}}/gi, data.placeholder)
      .replace(/{{required}}/gi, data.isRequired);
  }

  function parseInput(data) {
    var _hidden = data.type === 'hidden';

    return '<input type="{{type}}" name="{{name}}" id="{{id}}" value="{{value}}" required="{{required}}" placeholder="{{placeholder}}" class="{{hidden}}">'
      .replace(/{{type}}/gi, data.type)
      .replace(/{{id}}/gi, data.id)
      .replace(/{{name}}/gi, data.name)
      .replace(/{{value}}/gi, data.value)
      .replace(/{{placeholder}}/gi, data.placeholder)
      .replace(/{{required}}/gi, data.isRequired)
      .replace(/{{selected}}/gi, data.isSelected)
      .replace(/{{hidden}}/gi, _hidden ? 'ng-hide' : '');
  }

  function parseGroupInput(data) {
    return '<input type="{{type}}" id="{{id}}" name="{{name}}"  value="{{value}}" {{checked}}>'
      .replace(/{{type}}/gi, data.type)
      .replace(/{{id}}/gi, data.id)
      .replace(/{{name}}/gi, data.name)
      .replace(/{{value}}/gi, data.value)
      .replace(/{{checked}}/gi, data.isSelected === true ? 'checked' : '');
  }

  function parseGroupInputList(data, startIndex, nameHasIndexSuffix) {
    var _list = '
';
    var _index = startIndex || 0;

    angular.forEach(data.choices, function (choice) {
      choice.type = data.type;
      choice.id = 'choice_' + data.formId + '_' + data.id + '_' + _index;
      choice.name = 'input_' + data.id;

      if (nameHasIndexSuffix === true) {
        choice.name += '.' + _index;
      }

      _list += '
'
        + parseGroupInput(choice)
        + parseLabel(choice.id, choice.text, false)
        + '
';

      _index += 1;
    });

    _list += '
';

    return _list;
  }

  function parseSelectOption(data) {
    return '<option value="{{value}}" {{selected}}>{{text}}</option>'
      .replace(/{{value}}/gi, data.value)
      .replace(/{{selected}}/gi, data.isSelected === true ? 'selected="selected"' : '')
      .replace(/{{text}}/gi, data.text);
  }

  function parseSelectList(data, isMultiple) {
    var _list = '<select {{multiple}} name="{{name}}" id="{{id}}">';
    var _isMultiple = isMultiple === true;

    angular.forEach(data.choices, function (choice) {
      _list += parseSelectOption(choice);
    });

    _list += '</select>';

    return _list
      .replace(/{{multiple}}/gi, _isMultiple ? 'multiple="multiple"' : '')
      .replace(/{{name}}/gi, data.name)
      .replace(/{{id}}/gi, data.id);
  }

  // Fields from the 'Advanced' panel in the GF Form builder
  //

<<<<<<<
  HEAD:lib / organisms / gravity - form / gravity - form.parser.form.js
  /*
   function parseName() {

   }

   function parseDate() {

   }

   function parseTime() {

   }

   function parsePhone() {

   }

   function parseAddress() {

   }

   function parseWebsite() {

   }
   */

  // NOTE: This is currently implemented as a standard input, but actually has it's own type.
  function parseEmail(data) {
    return parseInput(data);
  }

  /*
   function parseFileupload() {

   }

   function parseList() {

   }
   */
======
  =
    function parseName(data) {
      return '';
    }

  function parseDate(data) {
    return '';
  }

  function parseTime(data) {
    return '';
  }

  function parsePhone(data) {
    return '';
  }

  function parseAddress(data) {
    return '';
  }

  function parseWebsite() {
    return '';
  }

  // NOTE: This is currently implemented as a standard input, but actually has it's own type.
  function parseEmail(data) {
    return parseInput(data);
  }

  function parseFileupload() {
    return '';
  }

  function parseList() {
    return '';
  }

>>>>>>>
  3
  c86437a45af88d5fd287f30efeee320cc81acbe:lib / organisms / gravity - form / gravity - form.parser.js

  // Fields from the 'Post' panel in the GF Form builder
  //

  // Submit / Next button
  //

  function parseSubmitButton(text) {
    return '<button type="submit" ng-disabled="!$ctrl.form.$valid" class="submit">{{text}}</button>'
      .replace(/{{text}}/gi, text || 'Submit');
  }

  // Conglomeate methods
  //

  function parseField(fieldHTML, labelHTML, isHidden, formId, originalId) {
    return '
{{label}}{{field}}
'
      .replace(/{{hidden}}/gi, isHidden ? ' ng-hide' : '')
      .replace(/{{id}}/gi, 'field_' + formId + '_' + originalId)
      .replace(/{{label}}/gi, labelHTML)
      .replace(/{{field}}/gi, fieldHTML);
  }

  /**
   * TODO: think about how to re-structure this to reduce complexity
   *       and increase clarity
   */
  function parseAllFields(fieldsData) {
    var _fields = '
';

    angular.forEach(fieldsData, function (field) {
      var _fieldHTML;
      var _labelHTML;
      var _hidden = false;
      var _hasLabel = true;
      var _originalId = angular.copy(field.id);

      switch (field.type) {

        // 'Standard' field types
        case 'text':
        case 'number':
        case 'hidden':
          _hidden = field.type === 'hidden';
          field.id = 'input_' + field.id;
          field.name = isValidParameterFilter(field.name) ? field.name : field.id;
          field.value = isValidParameterFilter(field.value) ? field.value : '';
          _fieldHTML = parseInput(field);
          break;
        case 'textarea':
          field.id = 'input_' + field.id;
          field.name = isValidParameterFilter(field.name) ? field.name : field.id;
          field.value = isValidParameterFilter(field.value) ? field.value : '';
          _fieldHTML = parseTextarea(field);
          break;
        case 'radio':
          _fieldHTML = parseGroupInputList(field);
          break;
        case 'checkbox':
          _fieldHTML = parseGroupInputList(field, 1, true);
          break;
        case 'select':
          field.id = 'input_' + field.id;
          field.name = field.id;
          _fieldHTML = parseSelectList(field);
          break;
        case 'multiselect':
          field.id = 'input_' + field.id;
          field.name = field.id + '[]';
          _fieldHTML = parseSelectList(field, true);
          break;
        case 'html':
          _hasLabel = false;
          _fieldHTML = field.content || ''; // Just render the HTML as-is
          break;
        case 'section':
          _hasLabel = false;
          _fieldHTML = parseSectionBreak(field);
          break;

        <<<<<<<
          HEAD:lib / organisms / gravity - form / gravity - form.parser.form.js
          /*
           case 'page':
           _fieldHTML = parsePage(field);
           */

          // TODO: 'Advanced' field types
          /*
           case 'name':
           _fieldHTML = parseName(field);
           break;
           case 'date':
           _fieldHTML = parseDate(field);
           break;
           case 'time':
           _fieldHTML = parseTime(field);
           break;
           case 'phone':
           _fieldHTML = parsePhone(field);
           break;
           case 'address':
           _fieldHTML = parseAddress(field);
           break;
           */

          === === =
        case 'page':
          _fieldHTML = parsePage(field);

        // TODO: 'Advanced' field types
        case 'name':
          _fieldHTML = parseName(field);
          break;
        case 'date':
          _fieldHTML = parseDate(field);
          break;
        case 'time':
          _fieldHTML = parseTime(field);
          break;
        case 'phone':
          _fieldHTML = parsePhone(field);
          break;
        case 'address':
          _fieldHTML = parseAddress(field);
          break;
        >>>>>>>
          3
          c86437a45af88d5fd287f30efeee320cc81acbe:lib / organisms / gravity - form / gravity - form.parser.js
        case 'email':
          field.id = 'input_' + field.id;
          field.name = isValidParameterFilter(field.name) ? field.name : field.id;
          field.value = isValidParameterFilter(field.value) ? field.value : '';
          _fieldHTML = parseEmail(field);
          break;
        <<<<<<<
          HEAD:lib / organisms / gravity - form / gravity - form.parser.form.js

          /*
           case 'website':
           _fieldHTML = parseWebsite(field);
           break;
           case 'fileupload':
           _fieldHTML = parseFileupload(field);
           break;
           case 'list':
           _fieldHTML = parseList(field);
           break;
           */

          // TODO: 'Post' field types
          /*
           case 'post_title':
           break;
           case 'post_content':
           break;
           case 'post_excerpt':
           break;
           case 'post_tags':
           break;
           case 'post_category':
           break;
           case 'post_image':
           break;
           case 'post_custom_field':
           break;
           */

          // TODO: 'Price' field types
          /*
           case 'product':
           break;
           case 'quantity':
           break;
           case 'option':
           break;
           case 'shipping':
           break;
           case 'total':
           break;
           */
          === === =
        case 'website':
          _fieldHTML = parseWebsite(field);
          break;
        case 'fileupload':
          _fieldHTML = parseFileupload(field);
          break;
        case 'list':
          _fieldHTML = parseList(field);
          break;

        // TODO: 'Post' field types
        case 'post_title':
          break;
        case 'post_content':
          break;
        case 'post_excerpt':
          break;
        case 'post_tags':
          break;
        case 'post_category':
          break;
        case 'post_image':
          break;
        case 'post_custom_field':
          break;

        // TODO: 'Price' field types
        case 'product':
          break;
        case 'quantity':
          break;
        case 'option':
          break;
        case 'shipping':
          break;
        case 'total':
          break;

        >>>>>>>
          3
          c86437a45af88d5fd287f30efeee320cc81acbe:lib / organisms / gravity - form / gravity - form.parser.js
        // If we hit this, it's probably worth just going home and crying...
        default:
          break;
      }

      if (angular.isDefined(_fieldHTML)) {
        _labelHTML = (!_hidden && _hasLabel) ? parseLabel(field.id, field.label, field.isRequired) : '';
        _fields += parseField(_fieldHTML, _labelHTML, _hidden, field.formId, _originalId);
      }
    });

    _fields += '
';

    return _fields;
  }

<<<<<<>>>>>>
  3
  c86437a45af88d5fd287f30efeee320cc81acbe:lib / organisms / gravity - form / gravity - form.parser.js
}
<|endoftext|>


<commit_before>const test = require('tape');
const analytics = require('./analytics');
const nacp0447d77e7ae7465eafd88d59a07069c0 = require('./examples/nacp_0447d77e-7ae7-465e-afd8-8d59a07069c0.json');
const nacp510ed202bcb8486ebea0a9750c9fdcb3 = require('./examples/nacp_510ed202-bcb8-486e-bea0-a9750c9fdcb3.json');
const nacp727b186f085741e694a4fd71475f580b = require('./examples/nacp_727b186f-0857-41e6-94a4-fd71475f580b.json');

test('declarations.com.ua.opendata nacp510ed202bcb8486ebea0a9750c9fdcb3 analytics check', (t) => {
  const declaration = nacp0447d77e7ae7465eafd88d59a07069c0;
  t.equal(analytics.getYear(declaration), 2016, 'getYear');
  t.equal(analytics.getBankAccount(declaration), 0, 'getBankAccount');
  t.equal(analytics.getCash(declaration), 0, 'getCash');
  t.equal(analytics.getCarAmount(declaration), 0, 'getCarAmount');
  t.equal(analytics.getIncome(declaration), 87885, 'getIncome');
  t.equal(analytics.getFlatArea(declaration), 32.95, 'getFlatArea');
  t.equal(analytics.getFlatAmount(declaration), 1, 'getFlatAmount');
  t.equal(analytics.getHouseArea(declaration), 0, 'getHouseArea');
  t.equal(analytics.getHouseAmount(declaration), 0, 'getHouseAmount');
  t.equal(analytics.getLandArea(declaration), 0, 'getLandArea');
  t.equal(analytics.getLandAmount(declaration), 0, 'getLandAmount');
  t.equal(analytics.getFamilyIncome(declaration), 55303, 'getFamilyIncome');
  t.equal(analytics.getFamilyCarAmount(declaration), 0, 'getFamilyCarAmount');
  t.equal(analytics.getFamilyFlatArea(declaration), 0, 'getFamilyFlatArea');
  t.equal(analytics.getFamilyFlatAmount(declaration), 0, 'getFamilyFlatAmount');
  t.equal(analytics.getFamilyHouseAmount(declaration), 0, 'getFamilyHouseAmount');
  t.equal(analytics.getFamilyFlatAmount(declaration), 0, 'getFamilyFlatAmount');
  t.equal(analytics.getFamilyLandArea(declaration), 0, 'getFamilyLandArea');
  t.equal(analytics.getFamilyLandAmount(declaration), 0, 'getFamilyLandAmount');
  t.end();
});

test('declarations.com.ua.opendata nacp510ed202bcb8486ebea0a9750c9fdcb3 analytics check', (t) => {
  const declaration = nacp510ed202bcb8486ebea0a9750c9fdcb3;
  t.equal(analytics.getYear(declaration), 2015, 'getYear');
  t.equal(analytics.getBankAccount(declaration), 0, 'getBankAccount');
  t.equal(analytics.getCash(declaration), 0, 'getCash');
  t.equal(analytics.getCarAmount(declaration), 2, 'getCarAmount');
  t.equal(analytics.getIncome(declaration), 267794, 'getIncome');
  t.equal(analytics.getFlatArea(declaration), 26.05, 'getFlatArea');
  t.equal(analytics.getFlatAmount(declaration), 1, 'getFlatAmount');
  t.equal(analytics.getHouseArea(declaration), 0, 'getHouseArea');
  t.equal(analytics.getHouseAmount(declaration), 0, 'getHouseAmount');
  t.equal(analytics.getLandArea(declaration), 1101, 'getLandArea');
  t.equal(analytics.getLandAmount(declaration), 1, 'getLandAmount');
  t.equal(analytics.getFamilyIncome(declaration), 46118, 'getFamilyIncome');
  t.equal(analytics.getFamilyCarAmount(declaration), 0, 'getFamilyCarAmount');
  t.equal(analytics.getFamilyFlatArea(declaration), 0, 'getFamilyFlatArea');
  t.equal(analytics.getFamilyFlatAmount(declaration), 0, 'getFamilyFlatAmount');
  t.equal(analytics.getFamilyHouseAmount(declaration), 0, 'getFamilyHouseAmount');
  t.equal(analytics.getFamilyFlatAmount(declaration), 0, 'getFamilyFlatAmount');
  t.equal(analytics.getFamilyLandArea(declaration), 0, 'getFamilyLandArea');
  t.equal(analytics.getFamilyLandAmount(declaration), 0, 'getFamilyLandAmount');
  t.end();
});

test('declarations.com.ua.opendata nacp727b186f085741e694a4fd71475f580b analytics check', (t) => {
  const declaration = nacp727b186f085741e694a4fd71475f580b;
  t.equal(analytics.getYear(declaration), 2015, 'getYear');
  t.equal(analytics.getBankAccount(declaration), 0, 'getBankAccount');
  t.equal(analytics.getCash(declaration), 0, 'getCash');
  t.equal(analytics.getCarAmount(declaration), 2, 'getCarAmount');
  t.equal(analytics.getIncome(declaration), 267794, 'getIncome');
  t.equal(analytics.getFlatArea(declaration), 26.05, 'getFlatArea');
  t.equal(analytics.getFlatAmount(declaration), 1, 'getFlatAmount');
  t.equal(analytics.getHouseArea(declaration), 0, 'getHouseArea');
  t.equal(analytics.getHouseAmount(declaration), 0, 'getHouseAmount');
  t.equal(analytics.getLandArea(declaration), 1101, 'getLandArea');
  t.equal(analytics.getLandAmount(declaration), 1, 'getLandAmount');
  t.equal(analytics.getFamilyIncome(declaration), 46118, 'getFamilyIncome');
  t.equal(analytics.getFamilyCarAmount(declaration), 0, 'getFamilyCarAmount');
  t.equal(analytics.getFamilyFlatArea(declaration), 0, 'getFamilyFlatArea');
  t.equal(analytics.getFamilyFlatAmount(declaration), 0, 'getFamilyFlatAmount');
  t.equal(analytics.getFamilyHouseAmount(declaration), 0, 'getFamilyHouseAmount');
  t.equal(analytics.getFamilyFlatAmount(declaration), 0, 'getFamilyFlatAmount');
  t.equal(analytics.getFamilyLandArea(declaration), 0, 'getFamilyLandArea');
  t.equal(analytics.getFamilyLandAmount(declaration), 0, 'getFamilyLandAmount');
  t.end();
});
<commit_msg>Refactor<commit_after>const test = require('tape');
const analytics = require('./analytics');
const nacp0447d77e7ae7465eafd88d59a07069c0 = require('./examples/nacp_0447d77e-7ae7-465e-afd8-8d59a07069c0.json');
const nacp510ed202bcb8486ebea0a9750c9fdcb3 = require('./examples/nacp_510ed202-bcb8-486e-bea0-a9750c9fdcb3.json');
const nacp727b186f085741e694a4fd71475f580b = require('./examples/nacp_727b186f-0857-41e6-94a4-fd71475f580b.json');

test('declarations.com.ua.opendata nacp510ed202bcb8486ebea0a9750c9fdcb3 analytics check', (t) => {
  const declaration = nacp0447d77e7ae7465eafd88d59a07069c0;
  t.equal(analytics.getYear(declaration), 2016, 'getYear');
  t.equal(analytics.getBankAccount(declaration), 0, 'getBankAccount');
  t.equal(analytics.getCash(declaration), 0, 'getCash');
  t.equal(analytics.getCarAmount(declaration), 0, 'getCarAmount');
  t.equal(analytics.getIncome(declaration), 87885, 'getIncome');
  t.equal(analytics.getFlatArea(declaration), 32.95, 'getFlatArea');
  t.equal(analytics.getFlatAmount(declaration), 1, 'getFlatAmount');
  t.equal(analytics.getHouseArea(declaration), 0, 'getHouseArea');
  t.equal(analytics.getHouseAmount(declaration), 0, 'getHouseAmount');
  t.equal(analytics.getLandArea(declaration), 0, 'getLandArea');
  t.equal(analytics.getLandAmount(declaration), 0, 'getLandAmount');
  t.equal(analytics.getFamilyIncome(declaration), 55303, 'getFamilyIncome');
  t.equal(analytics.getFamilyCarAmount(declaration), 0, 'getFamilyCarAmount');
  t.equal(analytics.getFamilyFlatArea(declaration), 0, 'getFamilyFlatArea');
  t.equal(analytics.getFamilyFlatAmount(declaration), 0, 'getFamilyFlatAmount');
  t.equal(analytics.getFamilyHouseAmount(declaration), 0, 'getFamilyHouseAmount');
  t.equal(analytics.getFamilyFlatAmount(declaration), 0, 'getFamilyFlatAmount');
  t.equal(analytics.getFamilyLandArea(declaration), 0, 'getFamilyLandArea');
  t.equal(analytics.getFamilyLandAmount(declaration), 0, 'getFamilyLandAmount');
  t.end();
});

test('declarations.com.ua.opendata nacp510ed202bcb8486ebea0a9750c9fdcb3 analytics check', (t) => {
  const declaration = nacp510ed202bcb8486ebea0a9750c9fdcb3;
  t.equal(analytics.getYear(declaration), 2015, 'getYear');
  t.equal(analytics.getBankAccount(declaration), 0, 'getBankAccount');
  t.equal(analytics.getCash(declaration), 0, 'getCash');
  t.equal(analytics.getCarAmount(declaration), 2, 'getCarAmount');
  t.equal(analytics.getIncome(declaration), 267794, 'getIncome');
  t.equal(analytics.getFlatArea(declaration), 26.05, 'getFlatArea');
  t.equal(analytics.getFlatAmount(declaration), 1, 'getFlatAmount');
  t.equal(analytics.getHouseArea(declaration), 0, 'getHouseArea');
  t.equal(analytics.getHouseAmount(declaration), 0, 'getHouseAmount');
  t.equal(analytics.getLandArea(declaration), 1101, 'getLandArea');
  t.equal(analytics.getLandAmount(declaration), 1, 'getLandAmount');
  t.equal(analytics.getFamilyIncome(declaration), 46118, 'getFamilyIncome');
  t.equal(analytics.getFamilyCarAmount(declaration), 0, 'getFamilyCarAmount');
  t.equal(analytics.getFamilyFlatArea(declaration), 0, 'getFamilyFlatArea');
  t.equal(analytics.getFamilyFlatAmount(declaration), 0, 'getFamilyFlatAmount');
  t.equal(analytics.getFamilyHouseAmount(declaration), 0, 'getFamilyHouseAmount');
  t.equal(analytics.getFamilyFlatAmount(declaration), 0, 'getFamilyFlatAmount');
  t.equal(analytics.getFamilyLandArea(declaration), 0, 'getFamilyLandArea');
  t.equal(analytics.getFamilyLandAmount(declaration), 0, 'getFamilyLandAmount');
  t.end();
});

test('declarations.com.ua.opendata nacp727b186f085741e694a4fd71475f580b analytics check', (t) => {
  const declaration = nacp727b186f085741e694a4fd71475f580b;
  t.equal(analytics.getYear(declaration), 2015, 'getYear');
  t.equal(analytics.getBankAccount(declaration), 0, 'getBankAccount');
  t.equal(analytics.getCash(declaration), 0, 'getCash');
  t.equal(analytics.getCarAmount(declaration), 2, 'getCarAmount');
  t.equal(analytics.getIncome(declaration), 267794, 'getIncome');
  t.equal(analytics.getFlatArea(declaration), 26.05, 'getFlatArea');
  t.equal(analytics.getFlatAmount(declaration), 1, 'getFlatAmount');
  t.equal(analytics.getHouseArea(declaration), 0, 'getHouseArea');
  t.equal(analytics.getHouseAmount(declaration), 0, 'getHouseAmount');
  t.equal(analytics.getLandArea(declaration), 1101, 'getLandArea');
  t.equal(analytics.getLandAmount(declaration), 1, 'getLandAmount');
  t.equal(analytics.getFamilyIncome(declaration), 46118, 'getFamilyIncome');
  t.equal(analytics.getFamilyCarAmount(declaration), 0, 'getFamilyCarAmount');
  t.equal(analytics.getFamilyFlatArea(declaration), 0, 'getFamilyFlatArea');
  t.equal(analytics.getFamilyFlatAmount(declaration), 0, 'getFamilyFlatAmount');
  t.equal(analytics.getFamilyHouseAmount(declaration), 0, 'getFamilyHouseAmount');
  t.equal(analytics.getFamilyFlatAmount(declaration), 0, 'getFamilyFlatAmount');
  t.equal(analytics.getFamilyLandArea(declaration), 0, 'getFamilyLandArea');
  t.equal(analytics.getFamilyLandAmount(declaration), 0, 'getFamilyLandAmount');
  t.end();
});
<|endoftext|>


<commit_before>import { Phaser, Input } from 'phaser'

export default class extends Phaser.Sprite {
    constructor ({ game, x, y, asset }) {
        super(game, x, y, asset, 1)
        this.anchor.setTo(0.5);
        this.speed = 5;
        this.direction = this.speed;
        this.setUpKeyboard();
        this.setUpAnimations();
        game.physics.arcade.enable(this);
        this.body.collideWorldBounds = true;
        this.touchingGround = false;
        this.breatheTween = game.add.tween(this.scale).to({ y: 0.95 }, 500, Phaser.Easing.Sinusoidal.None, false, 0, 0, true);
    }

    update () {
        this.touchingGround = game.physics.arcade.collide(this, game.blockingLayer);
        this.handleMove();
    }

    setUpKeyboard() {
        this.cursors = game.input.keyboard.createCursorKeys();
    }

    handleMove() {
        if (this.cursors.right.isDown) {
            //this.left += this.direction;
            if ( this.body.velocity.x <= 100) {
                this.body.velocity.x += this.direction;
            }
            if (this.touchingGround) {
                this.animations.play('run');
            }
            this.scale.x = 1;
        } else if (this.cursors.left.isDown) {
            // this.left += this.direction * -1;
            if (this.body.velocity.x >= -100) {
                this.body.velocity.x -= this.direction;
            }
            if (this.touchingGround) {
                this.animations.play('run');
            }
            this.scale.x = -1;
        } else {
            this.body.velocity.x = this.body.velocity.x * 0.75;
            this.animations.stop();
            this.frame = 1;
            this.breatheTween.start();
        }

        if (this.cursors.up.isDown && this.touchingGround) {
            // this.top += this.direction * -1;
            this.body.velocity.y -= 200;
            this.animations.play('jump');
        }

        if (this.isFalling()) {
            this.frame = 7;
        }
    }

    setUpAnimations() {
        this.animations.add('walk', [1,2,3,4], 10, false);
        this.animations.add('run', [14,15,17], 10, false);
        this.animations.add('jump', [4,5], 10, false);
        this.animations.add('falling', [5,7], 10, false);
    }

    isFalling() {
        if (this.body.velocity.y > 0) {
            return true;
        } else {
            return false;
        }
    }
}
<commit_msg>The character backflips when jumping<commit_after>import { Phaser, Input } from 'phaser'

export default class extends Phaser.Sprite {
    constructor ({ game, x, y, asset }) {
        super(game, x, y, asset, 1)
        this.anchor.setTo(0.5);
        this.speed = 5;
        this.direction = this.speed;
        this.setUpKeyboard();
        this.setUpAnimations();
        game.physics.arcade.enable(this);
        this.body.collideWorldBounds = true;
        this.touchingGround = false;
        this.facingDirection = 0;
        this.breatheTween = game.add.tween(this.scale).to({ y: 0.95 }, 500, Phaser.Easing.Sinusoidal.None, false, 0, 0, true);
        this.backflip = game.add.tween(this).to({ angle: 360 }, 1200, Phaser.Easing.Bounce.None, false, 0, 0, false);
        this.frontflip = game.add.tween(this).to({ angle: -360 }, 1200, Phaser.Easing.Bounce.None, false, 0, 0, false);
    }

    update () {
        this.touchingGround = game.physics.arcade.collide(this, game.blockingLayer);
        this.handleMove();
    }

    setUpKeyboard() {
        this.cursors = game.input.keyboard.createCursorKeys();
    }

    handleMove() {
        if (this.cursors.right.isDown) {
            //this.left += this.direction;
            if ( this.body.velocity.x <= 100) {
                this.body.velocity.x += this.direction;
            }
            if (this.touchingGround) {
                this.animations.play('run');
            }
            this.scale.x = 1;
            this.facingDirection = 1;
        } else if (this.cursors.left.isDown) {
            // this.left += this.direction * -1;
            if (this.body.velocity.x >= -100) {
                this.body.velocity.x -= this.direction;
            }
            if (this.touchingGround) {
                this.animations.play('run');
            }
            this.scale.x = -1;
            this.facingDirection = -1;
        } else {
            this.body.velocity.x = this.body.velocity.x * 0.75;
            this.animations.stop();
            this.frame = 1;
            this.breatheTween.start();
        }

        if (this.cursors.up.isDown && this.touchingGround) {
            // this.top += this.direction * -1;
            this.body.velocity.y -= 200;
            this.animations.play('jump');
            if (this.facingDirection === 1) {
                this.frontflip.start();
            } else if (this.facingDirection === -1) {
                this.backflip.start();
            }
        }

        if (this.isFalling()) {
            this.frame = 7;
        }
    }

    setUpAnimations() {
        this.animations.add('walk', [1,2,3,4], 10, false);
        this.animations.add('run', [14,15,17], 10, false);
        this.animations.add('jump', [4,5], 10, false);
        this.animations.add('falling', [5,7], 10, false);
    }

    isFalling() {
        if (this.body.velocity.y > 0) {
            return true;
        } else {
            return false;
        }
    }
}
<|endoftext|>


<commit_before>/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef */

/**
 * @class easyXDM.stack.RpcBehavior
 * This uses a protocol similar to JSON-RPC to expose local methods and to invoke remote methods and have responses returned over the the string based transport stack.

 * Local methods can be both asynchronous and synchronous.

 * Remote methods can be set up to return a response or not.
 * @extends easyXDM.stack.StackElement
 * @namespace easyXDM.stack
 * @constructor
 * @param {Object} proxy The object to apply the methods to.
 * @param {easyXDM.configuration.RpcConfiguration} config The definition of the local and remote interface to implement.
 * @cfg {easyXDM.configuration.LocalConfiguration} local The local interface to expose.
 * @cfg {easyXDM.configuration.RemoteConfiguration} remote The remote methods to expose through the proxy.
 * @cfg {Object} serializer The serializer to use for serializing and deserializing the JSON. Should be compatible with the HTML5 JSON object. Optional, will default to window.JSON.
 */
easyXDM.stack.RpcBehavior = function(proxy, config){
    // #ifdef debug
    var trace = easyXDM.Debug.getTracer("easyXDM.stack.RpcBehavior");
    // #endif
    var pub, serializer = config.serializer || easyXDM.JSON;
    var _callbackCounter = 0, _callbacks = {};

    /**
     * Creates a method that implements the given definition
     * @private
     * @param {easyXDM.configuration.Methods.Method} The method configuration
     * @param {String} method The name of the method
     */
    function _createMethod(definition, method){
        var slice = Array.prototype.slice;
        if (definition.isVoid) {
            // #ifdef debug
            trace("creating void method " + method);
            // #endif
            // No need to register a callback
            return function(){
                // #ifdef debug
                trace("executing void method " + method);
                // #endif
                // Send the method request
                pub.down.outgoing(serializer.stringify({
                    id: null,
                    method: method,
                    params: slice.call(arguments, 0)
                }));
            };
        }
        else {
            // #ifdef debug
            trace("creating method " + method);
            // #endif
            // We need to extract and register the callback
            return function(){
                // #ifdef debug
                trace("executing method " + method);
                // #endif
                var l = arguments.length, callback, args;
                if (l > 1 && typeof arguments[l - 2] === "function") {
                    callback = {
                        success: arguments[l - 2],
                        error: arguments[l - 1]
                    };
                    args = slice.call(arguments, 0, l - 2);
                }
                else if (l > 0) {
                    callback = {
                        success: arguments[l - 1]
                    };
                    args = slice.call(arguments, 0, l - 1);
                }
                _callbacks["" + (++_callbackCounter)] = callback;
                // Send the method request
                pub.down.outgoing(serializer.stringify({
                    method: method,
                    id: _callbackCounter,
                    params: args
                }));
            };
        }
    }

    /**
     * Executes the exposed method
     * @private
     * @param {String} method The name of the method
     * @param {Number} id The callback id to use
     * @param {Function} method The exposed implementation
     * @param {Array} params The parameters supplied by the remote end
     */
    function _executeMethod(method, id, fn, params, reply){
        if (!fn) {
            // no such method
            reply({
                jsonrpc: "2.0",
                id: id,
                error: {
                    code: -32601
                }
            });
            return;
        }
        if (fn.isAsync) {
            // #ifdef debug
            trace("requested to execute async method " + method);
            // #endif
            // The method is async, we need to add a success callback
            params.push(function(result){
                // Send back the result
                reply({
                    jsonrpc: "2.0",
                    id: id,
                    result: result
                });
            });
            // and an error callback
            params.push(function(message){
                // Send back the result
                reply({
                    jsonrpc: "2.0",
                    id: id,
                    error: {
                        code: 32099,
                        message: message
                    }
                });
            });
            // Call local method
            try {
                fn.method.apply(fn.scope, params);
            }
            catch (ex1) {
                reply({
                    jsonrpc: "2.0",
                    id: id,
                    error: {
                        code: 32099,
                        message: ex1.message
                    }
                });
            }
        }
        else {
            if (fn.isVoid) {
                // #ifdef debug
                trace("requested to execute void method " + method);
                // #endif
                // Call local method
                fn.method.apply(fn.scope, params);
            }
            else {
                // #ifdef debug
                trace("requested to execute method " + method);
                // #endif
                // Call local method and send back the response
                var response;
                try {
                    response = {
                        jsonrpc: "2.0",
                        id: id,
                        result: fn.method.apply(fn.scope, params)
                    };
                }
                catch (ex2) {
                    response = {
                        jsonrpc: "2.0",
                        id: id,
                        error: {
                            code: 32099,
                            message: ex2.message
                        }
                    };
                }
                reply(response);
            }
        }
    }

    return (pub = {
        incoming: function(message, origin){
            var data = serializer.parse(message);
            if (data.method) {
                // #ifdef debug
                trace("received request to execute method " + data.method + (data.id ? (" using callback id " + data.id) : ""));
                // #endif
                // A method call from the remote end
                var reply = function(data){
                    pub.down.outgoing(serializer.stringify(data));
                };
                if (config.handle) {
                    config.handle(data, reply);
                }
                else {
                    _executeMethod(data.method, data.id, config.local[data.method], data.params, reply);
                }
            }
            else {
                // #ifdef debug
                trace("received return value destined to callback with id " + data.id);
                // #endif
                // A method response from the other end
                var callback = _callbacks[data.id];
                if (data.result && callback.success) {
                    callback.success(data.result);
                }
                else if (data.error) {
                    if (callback.error) {
                        callback.error(data.error);
                    }
                    // #ifdef debug
                    else {
                        trace("unhandled error returned.");
                    }
                    // #endif
                }
                delete _callbacks[data.id];
            }
        },
        init: function(){
            // #ifdef debug
            trace("init");
            // #endif
            if (config.remote) {
                // #ifdef debug
                trace("creating concrete implementations");
                // #endif
                // Implement the remote sides exposed methods
                for (var method in config.remote) {
                    if (config.remote.hasOwnProperty(method)) {
                        proxy[method] = _createMethod(config.remote[method], method);
                    }
                }
            }
            pub.down.init();
        },
        destroy: function(){
            // #ifdef debug
            trace("destroy");
            // #endif
            for (var method in config.remote) {
                if (config.remote.hasOwnProperty(method) && proxy.hasOwnProperty(method)) {
                    delete proxy[method];
                }
            }
            pub.down.destroy();
        }
    });
};
<commit_msg>Refactored RpcBehavior to make it simpler and smaller<commit_after>/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef */

/**
 * @class easyXDM.stack.RpcBehavior
 * This uses a protocol similar to JSON-RPC to expose local methods and to invoke remote methods and have responses returned over the the string based transport stack.

 * Local methods can be both asynchronous and synchronous.

 * Remote methods can be set up to return a response or not.
 * @extends easyXDM.stack.StackElement
 * @namespace easyXDM.stack
 * @constructor
 * @param {Object} proxy The object to apply the methods to.
 * @param {easyXDM.configuration.RpcConfiguration} config The definition of the local and remote interface to implement.
 * @cfg {easyXDM.configuration.LocalConfiguration} local The local interface to expose.
 * @cfg {easyXDM.configuration.RemoteConfiguration} remote The remote methods to expose through the proxy.
 * @cfg {Object} serializer The serializer to use for serializing and deserializing the JSON. Should be compatible with the HTML5 JSON object. Optional, will default to window.JSON.
 */
easyXDM.stack.RpcBehavior = function(proxy, config){
    // #ifdef debug
    var trace = easyXDM.Debug.getTracer("easyXDM.stack.RpcBehavior");
    // #endif
    var pub, serializer = config.serializer || easyXDM.JSON;
    var _callbackCounter = 0, _callbacks = {};

    /**
     * Serializes and sends the message
     * @private
     * @param {Object} data The JSON-RPC message to be sent. The jsonrpc property will be added.
     */
    function _send(data){
        data.jsonrpc = "2.0";
        pub.down.outgoing(serializer.stringify(data));
    }

    /**
     * Creates a method that implements the given definition
     * @private
     * @param {easyXDM.configuration.Methods.Method} The method configuration
     * @param {String} method The name of the method
     * @return {Function} A stub capable of proxying the requested method call
     */
    function _createMethod(definition, method){
        var slice = Array.prototype.slice;

        if (definition.isVoid) {
            // #ifdef debug
            trace("creating void method " + method);
            // #endif
            // No need to register a callback, this is equal to a Notification
            return function(){
                // #ifdef debug
                trace("executing void method " + method);
                // #endif
                // Send the method request
                _send({
                    method: method,
                    params: slice.call(arguments, 0)
                });
            };
        }
        else {
            // #ifdef debug
            trace("creating method " + method);
            // #endif
            // We need to extract and register the callback
            return function(){
                // #ifdef debug
                trace("executing method " + method);
                // #endif
                var l = arguments.length, callback, args;
                if (l > 1 && typeof arguments[l - 2] === "function") {
                    callback = {
                        success: arguments[l - 2],
                        error: arguments[l - 1]
                    };
                    args = slice.call(arguments, 0, l - 2);
                }
                else
                    if (l > 0) {
                        callback = {
                            success: arguments[l - 1]
                        };
                        args = slice.call(arguments, 0, l - 1);
                    }
                _callbacks["" + (++_callbackCounter)] = callback;
                // Send the method request
                _send({
                    method: method,
                    id: _callbackCounter,
                    params: args
                });
            };
        }
    }

    /**
     * Executes the exposed method
     * @private
     * @param {String} method The name of the method
     * @param {Number} id The callback id to use
     * @param {Function} method The exposed implementation
     * @param {Array} params The parameters supplied by the remote end
     */
    function _executeMethod(method, id, fn, params){
        if (!fn) {
            // no such method
            _send({
                id: id,
                error: {
                    code: -32601
                }
            });
            return;
        }
        if (fn.isAsync) {
            // #ifdef debug
            trace("requested to execute async method " + method);
            // #endif
            // The method is async, we need to add a success callback
            params.push(function(result){
                // Send back the result
                _send({
                    id: id,
                    result: result
                });
            });
            // and an error callback
            params.push(function(message){
                // Send back the result
                _send({
                    id: id,
                    error: {
                        code: 32099,
                        message: message
                    }
                });
            });
            // Call local method
            try {
                fn.method.apply(fn.scope, params);
            }
            catch (ex1) {
                _send({
                    id: id,
                    error: {
                        code: 32099,
                        message: ex1.message
                    }
                });
            }
        }
        else {
            if (fn.isVoid) {
                // #ifdef debug
                trace("requested to execute void method " + method);
                // #endif
                // Call local method
                fn.method.apply(fn.scope, params);
            }
            else {
                // #ifdef debug
                trace("requested to execute method " + method);
                // #endif
                // Call local method and send back the response
                var response;
                try {
                    response = {
                        id: id,
                        result: fn.method.apply(fn.scope, params)
                    };
                }
                catch (ex2) {
                    response = {
                        id: id,
                        error: {
                            code: 32099,
                            message: ex2.message
                        }
                    };
                }
                _send(response);
            }
        }
    }

    return (pub = {
        incoming: function(message, origin){
            var data = serializer.parse(message);
            if (data.method) {
                // #ifdef debug
                trace("received request to execute method " + data.method + (data.id ? (" using callback id " + data.id) : ""));
                // #endif
                // A method call from the remote end
                if (config.handle) {
                    config.handle(data, _send);
                }
                else {
                    _executeMethod(data.method, data.id, config.local[data.method], data.params);
                }
            }
            else {
                // #ifdef debug
                trace("received return value destined to callback with id " + data.id);
                // #endif
                // A method response from the other end
                var callback = _callbacks[data.id];
                if (data.result && callback.success) {
                    callback.success(data.result);
                }
                else
                    if (data.error) {
                        if (callback.error) {
                            callback.error(data.error);
                        }
                        // #ifdef debug
                        else {
                            trace("unhandled error returned.");
                        }
                    // #endif
                    }
                delete _callbacks[data.id];
            }
        },
        init: function(){
            // #ifdef debug
            trace("init");
            // #endif
            if (config.remote) {
                // #ifdef debug
                trace("creating concrete implementations");
                // #endif
                // Implement the remote sides exposed methods
                for (var method in config.remote) {
                    if (config.remote.hasOwnProperty(method)) {
                        proxy[method] = _createMethod(config.remote[method], method);
                    }
                }
            }
            pub.down.init();
        },
        destroy: function(){
            // #ifdef debug
            trace("destroy");
            // #endif
            for (var method in config.remote) {
                if (config.remote.hasOwnProperty(method) && proxy.hasOwnProperty(method)) {
                    delete proxy[method];
                }
            }
            pub.down.destroy();
        }
    });
};
<|endoftext|>


<commit_before>'use strict';

module.exports = function(metrics) {
  const videoMetrics = {};
  if (!metrics.VisualReadiness) {
    metrics.VisualReadiness =
      Number(metrics.LastVisualChange) - Number(metrics.FirstVisualChange);
  }
  // Jack in that Visual Complete 85%, 95% and 99%
  if (metrics.VisualProgress) {
    const eachLine = metrics.VisualProgress.split(',');
    for (const timeAndPercentage of eachLine) {
      const [timestamp, percent] = timeAndPercentage.split('=');
      if (parseInt(percent, 10) >= 85 && !metrics.VisualComplete85) {
        metrics.VisualComplete85 = parseInt(timestamp, 10);
      }
      if (parseInt(percent, 10) >= 95 && !metrics.VisualComplete95) {
        metrics.VisualComplete95 = parseInt(timestamp, 10);
      }
      if (parseInt(percent, 10) >= 99 && !metrics.VisualComplete99) {
        metrics.VisualComplete99 = parseInt(timestamp, 10);
      }

      // Oh noo the painting on the screen goes backward
      // see https://github.com/sitespeedio/sitespeed.io/issues/2259#issuecomment-456878707
      if (metrics.VisualComplete85 && parseInt(percent, 10) < 85) {
        metrics.VisualComplete85 = undefined;
        metrics.VisualComplete95 = undefined;
        metrics.VisualComplete95 = undefined;
      } else if (metrics.VisualComplete95 && parseInt(percent, 10) < 95) {
        metrics.VisualComplete95 = undefined;
        metrics.VisualComplete95 = undefined;
      } else if (metrics.VisualComplete99 && parseInt(percent, 10) < 99) {
        metrics.VisualComplete99 = undefined;
      }
    }
  }
  if (metrics.videoRecordingStart) {
    videoMetrics.videoRecordingStart = metrics.videoRecordingStart;
    delete metrics.videoRecordingStart;
  }
  videoMetrics.visualMetrics = metrics;
  return videoMetrics;
};
<commit_msg>Record orange frame duration in browsertime (#1165)<commit_after>'use strict';

module.exports = function(metrics) {
  const videoMetrics = {};
  if (!metrics.VisualReadiness) {
    metrics.VisualReadiness =
      Number(metrics.LastVisualChange) - Number(metrics.FirstVisualChange);
  }
  // Jack in that Visual Complete 85%, 95% and 99%
  if (metrics.VisualProgress) {
    const eachLine = metrics.VisualProgress.split(',');
    for (const timeAndPercentage of eachLine) {
      const [timestamp, percent] = timeAndPercentage.split('=');
      if (parseInt(percent, 10) >= 85 && !metrics.VisualComplete85) {
        metrics.VisualComplete85 = parseInt(timestamp, 10);
      }
      if (parseInt(percent, 10) >= 95 && !metrics.VisualComplete95) {
        metrics.VisualComplete95 = parseInt(timestamp, 10);
      }
      if (parseInt(percent, 10) >= 99 && !metrics.VisualComplete99) {
        metrics.VisualComplete99 = parseInt(timestamp, 10);
      }

      // Oh noo the painting on the screen goes backward
      // see https://github.com/sitespeedio/sitespeed.io/issues/2259#issuecomment-456878707
      if (metrics.VisualComplete85 && parseInt(percent, 10) < 85) {
        metrics.VisualComplete85 = undefined;
        metrics.VisualComplete95 = undefined;
        metrics.VisualComplete95 = undefined;
      } else if (metrics.VisualComplete95 && parseInt(percent, 10) < 95) {
        metrics.VisualComplete95 = undefined;
        metrics.VisualComplete95 = undefined;
      } else if (metrics.VisualComplete99 && parseInt(percent, 10) < 99) {
        metrics.VisualComplete99 = undefined;
      }
    }
  }
  if (metrics.videoRecordingStart) {
    videoMetrics.videoRecordingStart = metrics.videoRecordingStart;
  }
  videoMetrics.visualMetrics = metrics;
  return videoMetrics;
};
<|endoftext|>


<commit_before>var App = App || {};
App.LoadAssetsState = App.LoadAssetsState || {};

App.LoadAssetsState = (function () {
    "use strict";

    // constructor: Run only once at compile time
    var fn = function (game) {
        Phaser.State.call(this, game);
    };
    fn.prototype = Object.create(Phaser.State.prototype);
    fn.prototype.constructor = fn;

    // init: Run every time this state is started or restart:
    fn.prototype.init = function () {
        this.game.assets = this.game.assets || {};
        this.game.assetsMustLoad = this.game.assetsMustLoad || {};
        this.game.assetsPreLoad = this.game.assetsPreLoad || {};
        this.game.assetsLoaded = this.game.assetsLoaded || {};
        this.game.assetsNextState = this.game.assetsNextState || "DefaultNextState";
    };

    // preload: Call "preload_TYPE" routine on each asset
    fn.prototype.preload = function () {
        for (var type in this.game.assetsMustLoad) {
            this.game.assetsLoaded[type] = this.game.assetsLoaded[type] || {};
            var handler = this["preload_" + type];
            if (handler && "function" === typeof handler) {
                this.game.assetsPreLoad[type] = this.game.assetsPreLoad[type] || {};
                for (var key in this.game.assetsMustLoad[type]) {
                    if (!this.game.assetsLoaded[type][key] &&
                        !this.game.assetsPreLoad[type][key]) {
                        var data = this.game.assetsMustLoad[type][key];
                        this.game.assetsPreLoad[type][key] = this["preload_" + type](key,data);
                    }
                    delete this.game.assetsMustLoad[type][key];
                }
            }
            else {
                console.log('Asset handler "preload_' + type + '" not defined');
            }
            delete this.game.assetsMustLoad[type];
        }
    };

    // create: Call "process_TYPE" routine on each asset once preload is complete
    fn.prototype.create = function () {
        for (var type in this.game.assetsPreLoad) {
            this.game.assetsLoaded[type] = this.game.assetsLoaded[type] || {};
            var handler = this["process_" + type];
            if (handler && "function" === typeof handler) {
                for (var key in this.game.assetsPreLoad[type]) {
                    if (!this.game.assetsLoaded[type][key]) {
                        this.game.assetsLoaded[type][key] = 1;
                        var preload_data = this.game.assetsPreLoad[type][key];
                        this["process_" + type](key,preload_data);
                    }
                    delete this.game.assetsPreLoad[type][key];
                }
            }
            else {
                console.log('WARNING: Asset handler "process_' + type + '" not defined');
            }
            delete this.game.assetsPreLoad[type];
        }

        if (_.keys(this.game.assetsMustLoad).length) {
            // Found more assets to left to load?
            // Need to run through this process again:
            console.log("Restarting STATE because found more assets not loaded yet",this.game.assetsMustLoad);
            this.game.state.restart();
        }
        else {
            // Everything is loaded?
            // Finally we can process to the next state:
            this.game.state.start(this.game.assetsNextState);
        }
    };

    // preload_TYPE(KEY,DATA):
    //   Define how to preload TYPE asset into KEY from DATA
    // process_TYPE:
    //   Now that asset has been loaded, populate final Object into game.assets.KEY, if appropriate
    //   If other assets are required to be loaded, then also populate
    //   this.game.assetsMustLoad.<NEWTYPE>.<NEWKEY> with more dependency DATA assets

    // preload_assets
    fn.prototype.preload_assets = function(key, data) {
        console.log("loadAssets.preload_assets",key,data)
        game.load.json(key, data);
        return data;
    };

    // process_assets
    fn.prototype.process_assets = function(key, data) {
        var assetsRequire = this.game.cache.getJSON(key);
        console.log("Must Load More Assets:",assetsRequire);
        // Merge assetsRequire into assetsMustLoad
        for (var type in assetsRequire) {
            this.game.assetsMustLoad[type] = this.game.assetsMustLoad[type] || {};
            for (var k in assetsRequire[type]) {
                this.game.assetsMustLoad[type][k] = assetsRequire[type][k];
            }
        }
        this.game.assets[key] = assetsRequire;
    };

    // preload_spritesheet
    fn.prototype.preload_spritesheet = function(key, data) {
        console.log("loadAssets.preload_spritesheet",key,data)
        this.game.load.spritesheet(key, data.file, data.frameWidth, data.frameHeight);
        return data;
    };

    // process_spritesheet
    fn.prototype.process_spritesheet = function(key, data) {
        console.log("loadAssets.process_spritesheet",key,data)
        //this.game.assets[key] = Object.create(Phaser.Sprite.prototype);
    };

    // preload_sound
    fn.prototype.preload_sound = function(key, data) {
        this.game.load.audio(key, data.file);
        return data;
    };

    // process_sound
    fn.prototype.process_sound = function(key, data) {
        // nothing to do yet
    };

    return fn;
})();
<commit_msg>Define preload_atlas and process_atlas methods.<commit_after>var App = App || {};
App.LoadAssetsState = App.LoadAssetsState || {};

App.LoadAssetsState = (function () {
    "use strict";

    // constructor: Run only once at compile time
    var fn = function (game) {
        Phaser.State.call(this, game);
    };
    fn.prototype = Object.create(Phaser.State.prototype);
    fn.prototype.constructor = fn;

    // init: Run every time this state is started or restart:
    fn.prototype.init = function () {
        this.game.assets = this.game.assets || {};
        this.game.assetsMustLoad = this.game.assetsMustLoad || {};
        this.game.assetsPreLoad = this.game.assetsPreLoad || {};
        this.game.assetsLoaded = this.game.assetsLoaded || {};
        this.game.assetsNextState = this.game.assetsNextState || "DefaultNextState";
    };

    // preload: Call "preload_TYPE" routine on each asset
    fn.prototype.preload = function () {
        for (var type in this.game.assetsMustLoad) {
            this.game.assetsLoaded[type] = this.game.assetsLoaded[type] || {};
            var handler = this["preload_" + type];
            if (handler && "function" === typeof handler) {
                this.game.assetsPreLoad[type] = this.game.assetsPreLoad[type] || {};
                for (var key in this.game.assetsMustLoad[type]) {
                    if (!this.game.assetsLoaded[type][key] &&
                        !this.game.assetsPreLoad[type][key]) {
                        var data = this.game.assetsMustLoad[type][key];
                        this.game.assetsPreLoad[type][key] = this["preload_" + type](key,data);
                    }
                    delete this.game.assetsMustLoad[type][key];
                }
            }
            else {
                console.log('Asset handler "preload_' + type + '" not defined');
            }
            delete this.game.assetsMustLoad[type];
        }
    };

    // create: Call "process_TYPE" routine on each asset once preload is complete
    fn.prototype.create = function () {
        for (var type in this.game.assetsPreLoad) {
            this.game.assetsLoaded[type] = this.game.assetsLoaded[type] || {};
            var handler = this["process_" + type];
            if (handler && "function" === typeof handler) {
                for (var key in this.game.assetsPreLoad[type]) {
                    if (!this.game.assetsLoaded[type][key]) {
                        this.game.assetsLoaded[type][key] = 1;
                        var preload_data = this.game.assetsPreLoad[type][key];
                        this["process_" + type](key,preload_data);
                    }
                    delete this.game.assetsPreLoad[type][key];
                }
            }
            else {
                console.log('WARNING: Asset handler "process_' + type + '" not defined');
            }
            delete this.game.assetsPreLoad[type];
        }

        if (_.keys(this.game.assetsMustLoad).length) {
            // Found more assets to left to load?
            // Need to run through this process again:
            console.log("Restarting STATE because found more assets not loaded yet",this.game.assetsMustLoad);
            this.game.state.restart();
        }
        else {
            // Everything is loaded?
            // Finally we can process to the next state:
            this.game.state.start(this.game.assetsNextState);
        }
    };

    // preload_TYPE(KEY,DATA):
    //   Define how to preload TYPE asset into KEY from DATA
    // process_TYPE:
    //   Now that asset has been loaded, populate final Object into game.assets.KEY, if appropriate
    //   If other assets are required to be loaded, then also populate
    //   this.game.assetsMustLoad.<NEWTYPE>.<NEWKEY> with more dependency DATA assets

    // preload_assets
    fn.prototype.preload_assets = function(key, data) {
        console.log("loadAssets.preload_assets",key,data)
        game.load.json(key, data);
        return data;
    };

    // process_assets
    fn.prototype.process_assets = function(key, data) {
        var assetsRequire = this.game.cache.getJSON(key);
        console.log("Must Load More Assets:",assetsRequire);
        // Merge assetsRequire into assetsMustLoad
        for (var type in assetsRequire) {
            this.game.assetsMustLoad[type] = this.game.assetsMustLoad[type] || {};
            for (var k in assetsRequire[type]) {
                this.game.assetsMustLoad[type][k] = assetsRequire[type][k];
            }
        }
        this.game.assets[key] = assetsRequire;
    };

    // preload_spritesheet
    fn.prototype.preload_spritesheet = function(key, data) {
        console.log("loadAssets.preload_spritesheet",key,data)
        this.game.load.spritesheet(key, data.file, data.frameWidth, data.frameHeight);
        return data;
    };

    // process_spritesheet
    fn.prototype.process_spritesheet = function(key, data) {
        console.log("loadAssets.process_spritesheet",key,data)
        //this.game.assets[key] = Object.create(Phaser.Sprite.prototype);
    };

    // preload_atlas
    fn.prototype.preload_atlas = function(key, data) {
        console.log("loadAssets.preload_atlas",key,data)
        this.game.load.atlas(key, data.file, data.json, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH);
        return data;
    };

    // process_assets
    fn.prototype.process_atlas = function(key, data) {
        console.log("loadAssets.process_atlas",key,data)
        // nothing to do yet
    };

    // preload_sound
    fn.prototype.preload_sound = function(key, data) {
        this.game.load.audio(key, data.file);
        return data;
    };

    // process_sound
    fn.prototype.process_sound = function(key, data) {
        // nothing to do yet
    };

    return fn;
})();
<|endoftext|>


<commit_before>//http://www.html5rocks.com/en/tutorials/doodles/gamepad/gamepad-tester/tester.html
//useful for testing the buttons and finding the numbers
//
//Requires the https://github.com/kallaspriit/HTML5-JavaScript-Gamepad-Controller-Library
//library.
var GAMEPAD = {};
var GamePad = function (cockpit) {

  var gamepad = new Gamepad();
  var gp = { cockpit: cockpit };
  var isSupported = function () {
  };
  var ignoreInputUntil = 0;
  gp.getPositions = function () {
    window.requestAnimationFrame(updateStatus);
    return padStatus.position;
  };
  gamepad.bind(Gamepad.Event.BUTTON_DOWN, function (e) {
    if (GAMEPAD[e.control] !== undefined)
      GAMEPAD[e.control].BUTTON_DOWN();
  });
  gamepad.bind(Gamepad.Event.AXIS_CHANGED, function (e) {
    if (new Date().getTime() < ignoreInputUntil)
      return;
    //avoids inacurrate readings when the gamepad has just been connected from affecting the ROV
    if (GAMEPAD[e.axis] !== undefined)
      GAMEPAD[e.axis].AXIS_CHANGED(e.value);
  });
  var updateStatus = function () {
    window.requestAnimationFrame(updateStatus);
  };
  gamepad.bind(Gamepad.Event.CONNECTED, function (device) {
    ignoreInputUntil = new Date().getTime() + 1000;
    console.log('Controller connected', device);
    gp.cockpit.emit('gamepad.connected');
  });
  gamepad.bind(Gamepad.Event.DISCONNECTED, function (device) {
    console.log('Controller disconnected', device);
    gp.cockpit.emit('gamepad.disconnected');
  });
  gamepad.bind(Gamepad.Event.UNSUPPORTED, function (device) {
    console.log('Unsupported controller connected', device);
  });
  gp.isAvailable = function () {
    if (gamepad.count() === 0)
      return false;
    return true;
  };
  if (!gamepad.init()) {
    console.log('Your browser does not support gamepads, get the latest Google Chrome or Firefox.');
  }
  if (gp.isAvailable()) {
    //send an initial is connected if already plugged in.
    setTimeout(function () {
      gp.cockpit.emit('gamepad.connected');
    }, 1000);
  }
  return gp;
};<commit_msg>Adding BUTTON_UP for gamepad<commit_after>//http://www.html5rocks.com/en/tutorials/doodles/gamepad/gamepad-tester/tester.html
//useful for testing the buttons and finding the numbers
//
//Requires the https://github.com/kallaspriit/HTML5-JavaScript-Gamepad-Controller-Library
//library.
var GAMEPAD = {};
var GamePad = function (cockpit) {

  var gamepad = new Gamepad();
  var gp = { cockpit: cockpit };
  var isSupported = function () {
  };
  var ignoreInputUntil = 0;
  gp.getPositions = function () {
    window.requestAnimationFrame(updateStatus);
    return padStatus.position;
  };
  gamepad.bind(Gamepad.Event.BUTTON_DOWN, function (e) {
    if (GAMEPAD[e.control] !== undefined)
      GAMEPAD[e.control].BUTTON_DOWN();
  });
  gamepad.bind(Gamepad.Event.BUTTON_UP, function (e) {
    if (GAMEPAD[e.control] !== undefined) {
      if (GAMEPAD[e.control].BUTTON_UP !== undefined) {
        GAMEPAD[e.control].BUTTON_UP();
      }
    }
  });
  gamepad.bind(Gamepad.Event.AXIS_CHANGED, function (e) {
    if (new Date().getTime() < ignoreInputUntil)
      return;
    //avoids inacurrate readings when the gamepad has just been connected from affecting the ROV
    if (GAMEPAD[e.axis] !== undefined)
      GAMEPAD[e.axis].AXIS_CHANGED(e.value);
  });
  var updateStatus = function () {
    window.requestAnimationFrame(updateStatus);
  };
  gamepad.bind(Gamepad.Event.CONNECTED, function (device) {
    ignoreInputUntil = new Date().getTime() + 1000;
    console.log('Controller connected', device);
    gp.cockpit.emit('gamepad.connected');
  });
  gamepad.bind(Gamepad.Event.DISCONNECTED, function (device) {
    console.log('Controller disconnected', device);
    gp.cockpit.emit('gamepad.disconnected');
  });
  gamepad.bind(Gamepad.Event.UNSUPPORTED, function (device) {
    console.log('Unsupported controller connected', device);
  });
  gp.isAvailable = function () {
    if (gamepad.count() === 0)
      return false;
    return true;
  };
  if (!gamepad.init()) {
    console.log('Your browser does not support gamepads, get the latest Google Chrome or Firefox.');
  }
  if (gp.isAvailable()) {
    //send an initial is connected if already plugged in.
    setTimeout(function () {
      gp.cockpit.emit('gamepad.connected');
    }, 1000);
  }
  return gp;
};<|endoftext|>