<commit_before>"use strict";

angular.module('dreFrontend.fhir')
    .provider("dreFrontendFhirService", function () {

        var _count = 10;

        return {
            setCount: function _set_page_length(count) {
                _count = count;
            },
            $get: function (Restangular, $q, fhirEnv, dreFrontendUtil, $log, _) {

                function _add_page_handlers(bundleResource) {
                    if (bundleResource.resourceType == fhirEnv.bundleType) {
                        var handlers = {};
                        angular.forEach(bundleResource.link,
                            function (_link) {
                                if (_link.relation == "next" || _link.relation == "previous") {
                                    var params = dreFrontendUtil.getURLparams(_link.url);
                                    params._getpagesoffset *= 1;
                                    params._count *= 1;
                                    handlers[_link.relation] = function () {
                                        return Restangular.one('').get(params).then(set_response);
                                    };
                                    handlers['getPage'] = function (offset) {
                                        var page_count = bundleResource.total / params._count + 1;
                                        if (offset >= 0 && offset < page_count) {
                                            var _params = params;
                                            _params._getpagesoffset = params._count * offset;
                                            return Restangular.one('').get(_params).then(set_response);
                                        } else {
                                            return $q.reject("incorrect page number");
                                        }
                                    }
                                }
                            }
                        );
                        angular.extend(bundleResource, handlers);
                    }
                }

                var _details = function() {}

                var loadChildren = function (deep, filter, force) {
                    var children = [];
                    var self = this;
                    filter = filter || "details";
                    var a_filter = [];
                    var r_type = fhirEnv.resourceTypes[this.resourceType];

                    if (r_type && r_type.hasOwnProperty(filter))
                        a_filter = r_type[filter];

                    $log.debug(this.resourceType, filter, a_filter);

                    proceed_reference(
                        this,
                        function (resource, key) {
                            $log.debug(a_filter.length<1 || a_filter.indexOf(key) !==-1, key);
                            if ( a_filter.length<1 || a_filter.indexOf(key) !== -1)
                                children.push(resource.load(force));
                        },
                        deep || fhirEnv.max_resource_nesting );

                    return $q.all(children).then(function(){return self;});
                };

                function _is_valid_resource_type(resourceType) {
                    var res = $q.resolve(resourceType);

                    if (resourceType) {
                        if (fhirEnv.resourceTypes.hasOwnProperty(resourceType))
                            res = $q.resolve(resourceType);
                        else
                            res = $q.reject("unsupported resource type: " + resourceType);
                    }
                    return res;
                }

                function set_response(resource) {
                    function f(r) {
                        angular.extend(r, {
                            loadAll: loadChildren
                        });
                        return _.omit(r, ["base", "link", "search", "text"]);
                    }
                    /* remove unnecessary data */

                    resource = Restangular.stripRestangular(resource);
                    resource = f(resource);

                    if (resource.resourceType === fhirEnv.bundleType) {
                        _add_page_handlers(resource);

                        resource.entry = _.pluck(resource.entry, "resource");

                        _.forEach(resource.entry, function (e, k) {
                            resource.entry[k] = f(e);
                        });
                    }

                    proceed_reference(resource, add_reference_loader, fhirEnv.max_resource_nesting);

                    return resource;
                }

                function proceed_reference(node, callback, deep) {
                    if (deep>=0) {
                        _.forEach(node, function (v,k) {
                            var _type = typeof v;
                            if (v && _type === "object" && v.hasOwnProperty("reference")) {
                                if (callback && typeof callback === "function") callback(v,k);
                            }
                            if (_type === "object" || _type === "array") proceed_reference(v, callback, deep - 1);
                        });
                    }
                }

                function add_reference_loader(obj, field) {
                    angular.extend(obj, {
                        load: function (force) {
                            var self = this;

                            var process_sub_resource = function (sub_resource) {
                                sub_resource = set_response(sub_resource);
                                angular.extend(self, sub_resource);
                                return sub_resource;
                            };

                            if (force || !this.resourceType) {
                                if (obj.reference.match(/^#.+/)) {
                                    /* contained resource */
                                    var data = _.first(_.filter(resource.contains, {"id": obj.reference.substring(1)})) || {};
                                    return process_sub_resource(data);
                                } else {
                                    /* relative reference resource */
                                    var p = obj.reference.split("/");
                                    return Restangular.one(p[0], p[1]).get().then(process_sub_resource);
                                }
                                /*2do: add absolute reference handling */
                            } else {
                                return $q.resolve(this);
                            }
                        }
                    });
                }

                function _search(resourceType, params) {
                    if (typeof params == "undefined") {
                        params = resourceType;
                        resourceType = null;
                    }

                    if (!params._count)
                        angular.extend(params, {"_count": _count});

                    if (resourceType)
                        return _is_valid_resource_type(resourceType)
                            .then(function (resType) {
                                return Restangular.one(resType, '_search').get(params).then(set_response);
                            });
                    else
                        return Restangular.one('_search').get(params).then(set_response);
                }

                function _read(resourceType, id) {
                    var params = (typeof id == 'undefined') ? {"_count": _count} : {};

                    return _is_valid_resource_type(resourceType)
                        .then(function (resType) {
                            return Restangular.one(resType, id).get(params).then(set_response);
                        });
                }

                function _history(resourceType, id, version, params) {
                    return Restangular.one(resourceType, id).one("_history", version).get(params).then(set_response);
                }

                function _create(resourceType, data) {
                    return Restangular.one("").post(resourceType, data);
                }

                function _update(resourceType, id, resource) {
                    return Restangular.one(resourceType, id).customPUT(resource);
                }

                function _delete(resourceType, id) {
                    return $q.reject("not implemented");
                }

                return {
                    search: _search,
                    read: _read,
                    history: _history,
                    create: _create,
                    update: _update,
                    delete: _delete
                };
            }

        };
    });
<commit_msg>tiny fixes<commit_after>"use strict";

angular.module('dreFrontend.fhir')
    .provider("dreFrontendFhirService", function () {

        var _count = 10;

        return {
            setCount: function _set_page_length(count) {
                _count = count;
            },
            $get: function (Restangular, $q, fhirEnv, dreFrontendUtil, $log, _) {

                function _add_page_handlers(bundleResource) {
                    if (bundleResource.resourceType == fhirEnv.bundleType) {
                        var handlers = {};
                        angular.forEach(bundleResource.link,
                            function (_link) {
                                if (_link.relation == "next" || _link.relation == "previous") {
                                    var params = dreFrontendUtil.getURLparams(_link.url);
                                    params._getpagesoffset *= 1;
                                    params._count *= 1;
                                    handlers[_link.relation] = function () {
                                        return Restangular.one('').get(params).then(set_response);
                                    };
                                    handlers['getPage'] = function (offset) {
                                        var page_count = bundleResource.total / params._count + 1;
                                        if (offset >= 0 && offset < page_count) {
                                            var _params = params;
                                            _params._getpagesoffset = params._count * offset;
                                            return Restangular.one('').get(_params).then(set_response);
                                        } else {
                                            return $q.reject("incorrect page number");
                                        }
                                    }
                                }
                            }
                        );
                        angular.extend(bundleResource, handlers);
                    }
                }

                var loadChildren = function (deep, filter, force) {
                    var children = [];
                    var self = this;
                    filter = filter || "details";
                    var a_filter = [];
                    var r_type = fhirEnv.resourceTypes[this.resourceType];

                    if (r_type && r_type.hasOwnProperty(filter))
                        a_filter = r_type[filter];

                    proceed_reference(
                        this,
                        function (resource, key) {
                            if ( a_filter.length<1 || a_filter.indexOf(key) !== -1)
                                children.push(resource.load(force));
                        },
                        deep || fhirEnv.max_resource_nesting );

                    return $q.all(children).then(function(){return self;});
                };

                function _is_valid_resource_type(resourceType) {
                    var res = $q.resolve(resourceType);

                    if (resourceType) {
                        if (fhirEnv.resourceTypes.hasOwnProperty(resourceType))
                            res = $q.resolve(resourceType);
                        else
                            res = $q.reject("unsupported resource type: " + resourceType);
                    }
                    return res;
                }

                function set_response(resource) {
                    function f(r) {
                        angular.extend(r, {
                            loadAll: loadChildren
                        });
                        return _.omit(r, ["base", "link", "search", "text"]);
                    }
                    /* remove unnecessary data */

                    resource = Restangular.stripRestangular(resource);
                    resource = f(resource);

                    if (resource.resourceType === fhirEnv.bundleType) {
                        _add_page_handlers(resource);

                        resource.entry = _.pluck(resource.entry, "resource");

                        _.forEach(resource.entry, function (e, k) {
                            resource.entry[k] = f(e);
                        });
                    }

                    proceed_reference(resource, add_reference_loader, fhirEnv.max_resource_nesting);

                    return resource;
                }

                function proceed_reference(node, callback, deep) {
                    if (deep>=0) {
                        _.forEach(node, function (v,k) {
                            var _type = typeof v;
                            if (v && _type === "object" && v.hasOwnProperty("reference")) {
                                if (callback && typeof callback === "function") callback(v,k);
                            }
                            if (_type === "object" || _type === "array") proceed_reference(v, callback, deep - 1);
                        });
                    }
                }

                function add_reference_loader(obj, field) {
                    angular.extend(obj, {
                        load: function (force) {
                            var self = this;

                            var process_sub_resource = function (sub_resource) {
                                sub_resource = set_response(sub_resource);
                                angular.extend(self, sub_resource);
                                return sub_resource;
                            };

                            if (force || !this.resourceType) {
                                if (obj.reference.match(/^#.+/)) {
                                    /* contained resource */
                                    var data = _.first(_.filter(resource.contains, {"id": obj.reference.substring(1)})) || {};
                                    return process_sub_resource(data);
                                } else {
                                    /* relative reference resource */
                                    var p = obj.reference.split("/");
                                    return Restangular.one(p[0], p[1]).get().then(process_sub_resource);
                                }
                                /*2do: add absolute reference handling */
                            } else {
                                return $q.resolve(this);
                            }
                        }
                    });
                }

                function _search(resourceType, params) {
                    if (typeof params == "undefined") {
                        params = resourceType;
                        resourceType = null;
                    }

                    if (!params._count)
                        angular.extend(params, {"_count": _count});

                    if (resourceType)
                        return _is_valid_resource_type(resourceType)
                            .then(function (resType) {
                                return Restangular.one(resType, '_search').get(params).then(set_response);
                            });
                    else
                        return Restangular.one('_search').get(params).then(set_response);
                }

                function _read(resourceType, id) {
                    var params = (typeof id == 'undefined') ? {"_count": _count} : {};

                    return _is_valid_resource_type(resourceType)
                        .then(function (resType) {
                            return Restangular.one(resType, id).get(params).then(set_response);
                        });
                }

                function _history(resourceType, id, version, params) {
                    return Restangular.one(resourceType, id).one("_history", version).get(params).then(set_response);
                }

                function _create(resourceType, data) {
                    return Restangular.one("").post(resourceType, data);
                }

                function _update(resourceType, id, resource) {
                    return Restangular.one(resourceType, id).customPUT(resource);
                }

                function _delete(resourceType, id) {
                    return $q.reject("not implemented");
                }

                return {
                    search: _search,
                    read: _read,
                    history: _history,
                    create: _create,
                    update: _update,
                    delete: _delete
                };
            }

        };
    });
<|endoftext|>


<commit_before>// @flow

import * as React from 'react';
import styles from '../surveys.css';
import type { SubmissionEntity } from 'app/reducers/surveySubmissions';
import type { SurveyEntity } from 'app/reducers/surveys';
import { DetailNavigation } from '../../utils';
import { Content, ContentSection, ContentMain } from 'app/components/Content';
import { Link } from 'react-router';
import AdminSideBar from '../AdminSideBar';
import type { ActionGrant } from 'app/models';

type Props = {
  submissions: Array<SubmissionEntity>,
  addSubmission: SubmissionEntity => Promise<*>,
  survey: SurveyEntity,
  children: React.Element<*>,
  actionGrant: ActionGrant,
  isSummary: boolean,
  shareSurvey: number => Promise<*>,
  hideSurvey: number => Promise<*>
};

const SubmissionPage = (props: Props) => {
  const { survey, actionGrant, isSummary, hideSurvey, shareSurvey } = props;

  return (
    <Content className={styles.surveyDetail} banner={survey.event.cover}>
      <DetailNavigation title={survey.title} surveyId={Number(survey.id)} />

      <ContentSection>
        <ContentMain>

            <Link
              to={`/surveys/${survey.id}/submissions/summary`}
              className={isSummary ? styles.activeRoute : styles.inactiveRoute}
            >
              Oppsummering
            </Link>
            {' | '}
            <Link
              to={`/surveys/${survey.id}/submissions/individual`}
              className={!isSummary ? styles.activeRoute : styles.inactiveRoute}
            >
              Individuell
            </Link>

          {React.cloneElement(props.children, props)}
        </ContentMain>

        <AdminSideBar
          surveyId={survey.id}
          actionGrant={actionGrant}
          token={survey.token}
          shareSurvey={shareSurvey}
          hideSurvey={hideSurvey}
        />
      </ContentSection>
    </Content>
  );
};

export default SubmissionPage;
<commit_msg>Summary and individual are inverted<commit_after>// @flow

import * as React from 'react';
import styles from '../surveys.css';
import type { SubmissionEntity } from 'app/reducers/surveySubmissions';
import type { SurveyEntity } from 'app/reducers/surveys';
import { DetailNavigation } from '../../utils';
import { Content, ContentSection, ContentMain } from 'app/components/Content';
import { Link } from 'react-router';
import AdminSideBar from '../AdminSideBar';
import type { ActionGrant } from 'app/models';

type Props = {
  submissions: Array<SubmissionEntity>,
  addSubmission: SubmissionEntity => Promise<*>,
  survey: SurveyEntity,
  children: React.Element<*>,
  actionGrant: ActionGrant,
  isSummary: boolean,
  shareSurvey: number => Promise<*>,
  hideSurvey: number => Promise<*>
};

const SubmissionPage = (props: Props) => {
  const { survey, actionGrant, isSummary, hideSurvey, shareSurvey } = props;

  return (
    <Content className={styles.surveyDetail} banner={survey.event.cover}>
      <DetailNavigation title={survey.title} surveyId={Number(survey.id)} />

      <ContentSection>
        <ContentMain>

            <Link
              to={`/surveys/${survey.id}/submissions/summary`}
              className={!isSummary ? styles.activeRoute : styles.inactiveRoute}
            >
              Oppsummering
            </Link>
            {' | '}
            <Link
              to={`/surveys/${survey.id}/submissions/individual`}
              className={isSummary ? styles.activeRoute : styles.inactiveRoute}
            >
              Individuell
            </Link>

          {React.cloneElement(props.children, props)}
        </ContentMain>

        <AdminSideBar
          surveyId={survey.id}
          actionGrant={actionGrant}
          token={survey.token}
          shareSurvey={shareSurvey}
          hideSurvey={hideSurvey}
        />
      </ContentSection>
    </Content>
  );
};

export default SubmissionPage;
<|endoftext|>


<commit_before>var mContainer;
var mCamera, mRenderer;
var mControls;

var mTime = 0.0;

var mScene;

var mTextGeometry;
var mTextBoundingBox;
var mTextWidth, mTextHeight, mTextDepth;
var mParticleSystem;

var mTotalDuration = 9.25;
var mTween;

window.onload = function () {
  init();
};

function init() {
  initTHREE();
  // initControls();
  initTweenControls();
  initText();
  initBufferGeometry();

  mTween = TweenMax.fromTo(window, mTotalDuration * 0.5, {mTime:0},
    {mTime:mTotalDuration, ease:Power1.easeInOut, repeat:-1, yoyo:true});

  requestAnimationFrame(tick);
  window.addEventListener('resize', resize, false);
}

function initTHREE() {
  mRenderer = new THREE.WebGLRenderer({antialias: true});
  mRenderer.setSize(window.innerWidth, window.innerHeight);
  mRenderer.setClearColor(0xffffff);

  mContainer = document.getElementById('three-container');
  mContainer.appendChild(mRenderer.domElement);

  mCamera = new THREE.PerspectiveCamera(10, window.innerWidth / window.innerHeight, 0.1, 5000);
  mCamera.position.set(0, 0, 1400);

  mScene = new THREE.Scene();
  //mScene.add(new THREE.GridHelper(200, 10));
  //mScene.add(new THREE.AxisHelper(20));

  var light;

  light = new THREE.DirectionalLight(0x00ffff);
  light.position.set(0, 1, 0);
  mScene.add(light);

  light = new THREE.DirectionalLight(0xff00ff);
  light.position.set(0, -1, 0);
  mScene.add(light);
}

function initControls() {
  mControls = new THREE.OrbitControls(mCamera, mRenderer.domElement);
}

function initTweenControls() {
  var mouseDown = false;
  var _cx = 0;
  var step = 0.001;

  document.body.style.cursor = 'pointer';

  window.addEventListener('mousedown', function(e) {
    mouseDown = true;
    _cx = e.clientX;

    TweenMax.to(mTween, 2, {timeScale:0});

    document.body.style.cursor = 'ew-resize';
  });
  window.addEventListener('mouseup', function(e) {
    mouseDown = false;
    TweenMax.to(mTween, 2, {timeScale:1});

    document.body.style.cursor = 'pointer';
  });
  window.addEventListener('mousemove', function(e) {
    if (mouseDown === true) {
      var cx = e.clientX;
      var dx = cx - _cx;
      var progress = mTween.progress();
      var p = THREE.Math.clamp((progress + (dx * step)), 0, 1);

      mTween.progress(p);

      _cx = cx;
    }
  });
}

function initText() {
  var text = 'ASHES TO ASHES';
  var size = 14;
  var height = 0;
  var curveSegments = 10;
  var font = 'droid sans';
  var weight = 'bold';
  var style = 'normal';
  var bevelSize = 0.75;
  var bevelThickness = 0.50;

  mTextGeometry = new THREE.TextGeometry(text, {
    size: size,
    height: height,
    curveSegments: curveSegments,

    font: font,
    weight: weight,
    style: style,

    bevelThickness: bevelThickness,
    bevelSize: bevelSize,
    bevelEnabled: true
  });

  mTextGeometry.computeBoundingBox();
  mTextBoundingBox = mTextGeometry.boundingBox;
  mTextWidth = mTextGeometry.boundingBox.max.x - mTextGeometry.boundingBox.min.x;
  mTextHeight = mTextGeometry.boundingBox.max.y - mTextGeometry.boundingBox.min.y;
  mTextDepth = mTextGeometry.boundingBox.max.z - mTextGeometry.boundingBox.min.z;

  console.log('txt size', mTextWidth, mTextHeight, mTextDepth);

  var xOffset = -0.5 * mTextWidth;
  var yOffset = -0.5 * mTextHeight;
  var zOffset = -0.5 * mTextDepth;
  var matrix = new THREE.Matrix4().makeTranslation(xOffset, yOffset, zOffset);

  mTextGeometry.applyMatrix(matrix);

  //var noise = 0.25;
  //
  //mTextGeometry.vertices.forEach(function(v) {
  //  v.x += THREE.Math.randFloatSpread(noise);
  //  v.y += THREE.Math.randFloatSpread(noise);
  //  v.z += THREE.Math.randFloatSpread(noise);
  //});

  THREE.BAS.Utils.separateFaces(mTextGeometry);

  // test mesh
  //var material = new THREE.MeshPhongMaterial({color:0xff00ff});
  //var mesh = new THREE.Mesh(mTextGeometry, material);
  //
  //mScene.add(mesh);
}

function initBufferGeometry() {
  var bufferGeometry = new THREE.BAS.ModelBufferGeometry(mTextGeometry);
  var halfWidth = mTextWidth * 0.5;
  var halfHeight = mTextHeight * 0.5;
  var halfDepth = mTextDepth * 0.5;

  var aAnimation = bufferGeometry.createAttribute('aAnimation', 2);
  // var aCentroid = bufferGeometry.createAttribute('aCentroid', 3);
  // var aRotation = bufferGeometry.createAttribute('aRotation', 4);
  var aControl0 = bufferGeometry.createAttribute('aControl0', 3);
  var aControl1 = bufferGeometry.createAttribute('aControl1', 3);
  var aEndPosition = bufferGeometry.createAttribute('aEndPosition', 3);

  var faceCount = bufferGeometry.faceCount;
  var vertexCount = bufferGeometry.vertexCount;
  var i, i2, i3, i4, v;

  // var axis = new THREE.Vector3();

  for (i = 0, i2 = 0, i3 = 0, i4 = 0; i < faceCount; i++, i2 += 6, i3 += 9, i4 += 12) {
    var face = mTextGeometry.faces[i];
    var centroid = THREE.BAS.Utils.computeCentroid(mTextGeometry, face);
    var dirX = centroid.x > 0 ? 1 : -1;
    var dirY = centroid.y > 0 ? 1 : -1;
    var dirZ = centroid.z > 0 ? 1 : -1;

    // animation
    // var xDelay = THREE.Math.mapLinear(centroid.x, -halfWidth, halfWidth, 0, 0.25);
    // var yDelay = THREE.Math.mapLinear(centroid.y, -halfHeight, halfHeight, 0, 4.0);
    var delay = centroid.length() * THREE.Math.randFloat(0.03, 0.06);
    var duration = THREE.Math.randFloat(2, 4);

    for (v = 0; v < 6; v += 2) {
      aAnimation.array[i2 + v + 0] = delay + Math.random() * 1.0;
      aAnimation.array[i2 + v + 1] = duration;
    }

    // centroid
    // for (v = 0; v < 9; v += 3) {
    //   aCentroid.array[i3 + v + 0] = centroid.x;
    //   aCentroid.array[i3 + v + 1] = centroid.y;
    //   aCentroid.array[i3 + v + 2] = centroid.z;
    // }

    // rotation
    // axis.x = THREE.Math.randFloatSpread(2);
    // axis.y = dirY;
    // axis.z = dirZ;
    // axis.normalize();
    //
    // for (v = 0; v < 12; v += 4) {
    //   aRotation.array[i4 + v + 0] = axis.x;
    //   aRotation.array[i4 + v + 1] = axis.y;
    //   aRotation.array[i4 + v + 2] = axis.z;
    //   aRotation.array[i4 + v + 3] = Math.PI * THREE.Math.randFloat(4, 8);
    // }

    // ctrl
    var c0x = THREE.Math.randFloat(0, 30) * dirX;
    var c0y = THREE.Math.randFloat(60, 120) * dirY;
    var c0z = THREE.Math.randFloat(-20, 20);

    var c1x = THREE.Math.randFloat(30, 60) * dirX;
    var c1y = THREE.Math.randFloat(0, 60) * dirY;
    var c1z = THREE.Math.randFloat(-20, 20);

    for (v = 0; v < 9; v += 3) {
      aControl0.array[i3 + v + 0] = c0x;
      aControl0.array[i3 + v + 1] = c0y;
      aControl0.array[i3 + v + 2] = c0z;

      aControl1.array[i3 + v + 0] = c1x;
      aControl1.array[i3 + v + 1] = c1y;
      aControl1.array[i3 + v + 2] = c1z;
    }

    // end position (just leave at 0)
    // var x = THREE.Math.randFloatSpread(120);
    // var y = THREE.Math.randFloatSpread(120);
    // var z = THREE.Math.randFloatSpread(120);
    // var x = THREE.Math.randFloat(20, 60) * dirX;
    // var y = THREE.Math.randFloat(20, 60) * dirY;
    // var z = THREE.Math.randFloat(0, 10) * dirZ;
    //
    // for (v = 0; v < 9; v += 3) {
    //   aEndPosition.array[i3 + v + 0] = 0;
    //   aEndPosition.array[i3 + v + 1] = 0;
    //   aEndPosition.array[i3 + v + 2] = 0;
    // }
  }

  var material = new THREE.BAS.BasicAnimationMaterial({
      //vertexColors: THREE.VertexColors,
      shading: THREE.FlatShading,
      side: THREE.DoubleSide,
      //wireframe: true,
      defines: {
      },
      uniforms: {
        uTime: {type: 'f', value: 0}
      },
      shaderFunctions: [
        //THREE.BAS.ShaderChunk['ease_out_cubic'],
        THREE.BAS.ShaderChunk['quaternion_rotation'],
        THREE.BAS.ShaderChunk['cubic_bezier']
      ],
      shaderParameters: [
        'uniform float uTime;',
        'attribute vec2 aAnimation;',
        // 'attribute vec3 aCentroid;',
        // 'attribute vec4 aRotation;',
        'attribute vec3 aControl0;',
        'attribute vec3 aControl1;',
        'attribute vec3 aEndPosition;'
      ],
      shaderVertexInit: [
        'float tDelay = aAnimation.x;',
        'float tDuration = aAnimation.y;',
        'float tTime = clamp(uTime - tDelay, 0.0, tDuration);',
        'float tProgress = tTime / tDuration;'
      ],
      shaderTransformNormal: [
      ],
      shaderTransformPosition: [
        // 'vec3 tPosition = transformed - aCentroid;',

        // 'vec4 tQuat = quatFromAxisAngle(aRotation.xyz, aRotation.w * tProgress);',
        // 'tPosition = rotateVector(tQuat, tPosition);',
        // 'tPosition += aCentroid;',

        'vec3 tPosition = transformed;',

        'tPosition *= 1.0 - tProgress;',

        'tPosition += cubicBezier(transformed, aControl0, aControl1, aEndPosition, tProgress);',

        'transformed = tPosition;'
      ]
    },
    {
      // shininess: 120,
      diffuse: 0x000000
      // specular: 0xffd700
    }
  );

  mParticleSystem = new THREE.Mesh(bufferGeometry, material);
  mParticleSystem.frustumCulled = false;
  mScene.add(mParticleSystem);
}

function tick() {
  update();
  render();

  requestAnimationFrame(tick);
}

function update() {
  //mControls.update();

  mParticleSystem.material.uniforms['uTime'].value = mTime;
}

function render() {
  mRenderer.render(mScene, mCamera);
}

function resize() {
  mCamera.aspect = window.innerWidth / window.innerHeight;
  mCamera.updateProjectionMatrix();

  mRenderer.setSize(window.innerWidth, window.innerHeight);
}
<commit_msg>cleanup<commit_after>var mContainer;
var mCamera, mRenderer;
var mControls;

var mTime = 0.0;

var mScene;

var mTextGeometry;
var mTextBoundingBox;
var mTextWidth, mTextHeight, mTextDepth;
var mParticleSystem;

var mTotalDuration = 9.25;
var mTween;

window.onload = function () {
  init();
};

function init() {
  initTHREE();
  // initControls();
  initTweenControls();
  initText();
  initBufferGeometry();

  mTween = TweenMax.fromTo(window, mTotalDuration * 0.5, {mTime:0},
    {mTime:mTotalDuration, ease:Power1.easeInOut, repeat:-1, yoyo:true});

  requestAnimationFrame(tick);
  window.addEventListener('resize', resize, false);
}

function initTHREE() {
  mRenderer = new THREE.WebGLRenderer({antialias: true});
  mRenderer.setSize(window.innerWidth, window.innerHeight);
  mRenderer.setClearColor(0xffffff);

  mContainer = document.getElementById('three-container');
  mContainer.appendChild(mRenderer.domElement);

  mCamera = new THREE.PerspectiveCamera(10, window.innerWidth / window.innerHeight, 0.1, 5000);
  mCamera.position.set(0, 0, 1400);

  mScene = new THREE.Scene();
  //mScene.add(new THREE.GridHelper(200, 10));
  //mScene.add(new THREE.AxisHelper(20));

  var light;

  light = new THREE.DirectionalLight(0x00ffff);
  light.position.set(0, 1, 0);
  mScene.add(light);

  light = new THREE.DirectionalLight(0xff00ff);
  light.position.set(0, -1, 0);
  mScene.add(light);
}

function initControls() {
  mControls = new THREE.OrbitControls(mCamera, mRenderer.domElement);
}

function initTweenControls() {
  var mouseDown = false;
  var _cx = 0;
  var step = 0.001;

  document.body.style.cursor = 'pointer';

  window.addEventListener('mousedown', function(e) {
    mouseDown = true;
    _cx = e.clientX;

    TweenMax.to(mTween, 2, {timeScale:0});

    document.body.style.cursor = 'ew-resize';
  });
  window.addEventListener('mouseup', function(e) {
    mouseDown = false;
    TweenMax.to(mTween, 2, {timeScale:1});

    document.body.style.cursor = 'pointer';
  });
  window.addEventListener('mousemove', function(e) {
    if (mouseDown === true) {
      var cx = e.clientX;
      var dx = cx - _cx;
      var progress = mTween.progress();
      var p = THREE.Math.clamp((progress + (dx * step)), 0, 1);

      mTween.progress(p);

      _cx = cx;
    }
  });
}

function initText() {
  var text = 'PIECE BY PIECE';
  var size = 14;
  var height = 0;
  var curveSegments = 10;
  var font = 'droid sans';
  var weight = 'bold';
  var style = 'normal';
  var bevelSize = 0.75;
  var bevelThickness = 0.50;

  mTextGeometry = new THREE.TextGeometry(text, {
    size: size,
    height: height,
    curveSegments: curveSegments,

    font: font,
    weight: weight,
    style: style,

    bevelThickness: bevelThickness,
    bevelSize: bevelSize,
    bevelEnabled: true
  });

  mTextGeometry.computeBoundingBox();
  mTextBoundingBox = mTextGeometry.boundingBox;
  mTextWidth = mTextGeometry.boundingBox.max.x - mTextGeometry.boundingBox.min.x;
  mTextHeight = mTextGeometry.boundingBox.max.y - mTextGeometry.boundingBox.min.y;
  mTextDepth = mTextGeometry.boundingBox.max.z - mTextGeometry.boundingBox.min.z;

  //console.log('txt size', mTextWidth, mTextHeight, mTextDepth);

  var xOffset = -0.5 * mTextWidth;
  var yOffset = -0.5 * mTextHeight;
  var zOffset = -0.5 * mTextDepth;
  var matrix = new THREE.Matrix4().makeTranslation(xOffset, yOffset, zOffset);

  mTextGeometry.applyMatrix(matrix);

  //var noise = 0.25;
  //
  //mTextGeometry.vertices.forEach(function(v) {
  //  v.x += THREE.Math.randFloatSpread(noise);
  //  v.y += THREE.Math.randFloatSpread(noise);
  //  v.z += THREE.Math.randFloatSpread(noise);
  //});

  THREE.BAS.Utils.separateFaces(mTextGeometry);

  // test mesh
  //var material = new THREE.MeshPhongMaterial({color:0xff00ff});
  //var mesh = new THREE.Mesh(mTextGeometry, material);
  //
  //mScene.add(mesh);
}

function initBufferGeometry() {
  var bufferGeometry = new THREE.BAS.ModelBufferGeometry(mTextGeometry);
  var halfWidth = mTextWidth * 0.5;
  var halfHeight = mTextHeight * 0.5;
  var halfDepth = mTextDepth * 0.5;

  var aAnimation = bufferGeometry.createAttribute('aAnimation', 2);
  // var aCentroid = bufferGeometry.createAttribute('aCentroid', 3);
  // var aRotation = bufferGeometry.createAttribute('aRotation', 4);
  var aControl0 = bufferGeometry.createAttribute('aControl0', 3);
  var aControl1 = bufferGeometry.createAttribute('aControl1', 3);
  var aEndPosition = bufferGeometry.createAttribute('aEndPosition', 3);

  var faceCount = bufferGeometry.faceCount;
  var vertexCount = bufferGeometry.vertexCount;
  var i, i2, i3, i4, v;

  // var axis = new THREE.Vector3();

  for (i = 0, i2 = 0, i3 = 0, i4 = 0; i < faceCount; i++, i2 += 6, i3 += 9, i4 += 12) {
    var face = mTextGeometry.faces[i];
    var centroid = THREE.BAS.Utils.computeCentroid(mTextGeometry, face);
    var dirX = centroid.x > 0 ? 1 : -1;
    var dirY = centroid.y > 0 ? 1 : -1;
    var dirZ = centroid.z > 0 ? 1 : -1;

    // animation
    // var xDelay = THREE.Math.mapLinear(centroid.x, -halfWidth, halfWidth, 0, 0.25);
    // var yDelay = THREE.Math.mapLinear(centroid.y, -halfHeight, halfHeight, 0, 4.0);
    var delay = centroid.length() * THREE.Math.randFloat(0.03, 0.06);
    var duration = THREE.Math.randFloat(2, 4);

    for (v = 0; v < 6; v += 2) {
      aAnimation.array[i2 + v + 0] = delay + Math.random() * 1.0;
      aAnimation.array[i2 + v + 1] = duration;
    }

    // centroid
    // for (v = 0; v < 9; v += 3) {
    //   aCentroid.array[i3 + v + 0] = centroid.x;
    //   aCentroid.array[i3 + v + 1] = centroid.y;
    //   aCentroid.array[i3 + v + 2] = centroid.z;
    // }

    // rotation
    // axis.x = THREE.Math.randFloatSpread(2);
    // axis.y = dirY;
    // axis.z = dirZ;
    // axis.normalize();
    //
    // for (v = 0; v < 12; v += 4) {
    //   aRotation.array[i4 + v + 0] = axis.x;
    //   aRotation.array[i4 + v + 1] = axis.y;
    //   aRotation.array[i4 + v + 2] = axis.z;
    //   aRotation.array[i4 + v + 3] = Math.PI * THREE.Math.randFloat(4, 8);
    // }

    // ctrl
    var c0x = THREE.Math.randFloat(0, 30) * dirX;
    var c0y = THREE.Math.randFloat(60, 120) * dirY;
    var c0z = THREE.Math.randFloat(-20, 20);

    var c1x = THREE.Math.randFloat(30, 60) * dirX;
    var c1y = THREE.Math.randFloat(0, 60) * dirY;
    var c1z = THREE.Math.randFloat(-20, 20);

    for (v = 0; v < 9; v += 3) {
      aControl0.array[i3 + v + 0] = c0x;
      aControl0.array[i3 + v + 1] = c0y;
      aControl0.array[i3 + v + 2] = c0z;

      aControl1.array[i3 + v + 0] = c1x;
      aControl1.array[i3 + v + 1] = c1y;
      aControl1.array[i3 + v + 2] = c1z;
    }

    // end position (just leave at 0)
    // var x = THREE.Math.randFloatSpread(120);
    // var y = THREE.Math.randFloatSpread(120);
    // var z = THREE.Math.randFloatSpread(120);
    // var x = THREE.Math.randFloat(20, 60) * dirX;
    // var y = THREE.Math.randFloat(20, 60) * dirY;
    // var z = THREE.Math.randFloat(0, 10) * dirZ;
    //
    // for (v = 0; v < 9; v += 3) {
    //   aEndPosition.array[i3 + v + 0] = 0;
    //   aEndPosition.array[i3 + v + 1] = 0;
    //   aEndPosition.array[i3 + v + 2] = 0;
    // }
  }

  var material = new THREE.BAS.BasicAnimationMaterial({
      //vertexColors: THREE.VertexColors,
      shading: THREE.FlatShading,
      side: THREE.DoubleSide,
      //wireframe: true,
      defines: {
      },
      uniforms: {
        uTime: {type: 'f', value: 0}
      },
      shaderFunctions: [
        //THREE.BAS.ShaderChunk['ease_out_cubic'],
        THREE.BAS.ShaderChunk['quaternion_rotation'],
        THREE.BAS.ShaderChunk['cubic_bezier']
      ],
      shaderParameters: [
        'uniform float uTime;',
        'attribute vec2 aAnimation;',
        // 'attribute vec3 aCentroid;',
        // 'attribute vec4 aRotation;',
        'attribute vec3 aControl0;',
        'attribute vec3 aControl1;',
        'attribute vec3 aEndPosition;'
      ],
      shaderVertexInit: [
        'float tDelay = aAnimation.x;',
        'float tDuration = aAnimation.y;',
        'float tTime = clamp(uTime - tDelay, 0.0, tDuration);',
        'float tProgress = tTime / tDuration;'
      ],
      shaderTransformNormal: [
      ],
      shaderTransformPosition: [
        // 'vec3 tPosition = transformed - aCentroid;',

        // 'vec4 tQuat = quatFromAxisAngle(aRotation.xyz, aRotation.w * tProgress);',
        // 'tPosition = rotateVector(tQuat, tPosition);',
        // 'tPosition += aCentroid;',

        'vec3 tPosition = transformed;',

        'tPosition *= 1.0 - tProgress;',

        'tPosition += cubicBezier(transformed, aControl0, aControl1, aEndPosition, tProgress);',

        'transformed = tPosition;'
      ]
    },
    {
      // shininess: 120,
      diffuse: 0x000000
      // specular: 0xffd700
    }
  );

  mParticleSystem = new THREE.Mesh(bufferGeometry, material);
  mParticleSystem.frustumCulled = false;
  mScene.add(mParticleSystem);
}

function tick() {
  update();
  render();

  requestAnimationFrame(tick);
}

function update() {
  //mControls.update();

  mParticleSystem.material.uniforms['uTime'].value = mTime;
}

function render() {
  mRenderer.render(mScene, mCamera);
}

function resize() {
  mCamera.aspect = window.innerWidth / window.innerHeight;
  mCamera.updateProjectionMatrix();

  mRenderer.setSize(window.innerWidth, window.innerHeight);
}
<|endoftext|>


<commit_before>"use strict";

const _ = require("lodash");
const fs = require("fs");
const path = require("path");
const { MoleculerError } = require("moleculer").Errors;

module.exports = {
	name: "test",
	settings: {
		rest: ""
	},

	events: {
		"$api.aliases.regenerated"() {
			this.logger.info("Aliases regenerated!");
		}
	},

	actions: {
		hello: {
			rest: "GET /hello",
			handler(ctx) {
				ctx.meta.$responseType = "text/plain";
				return "Hello Moleculer";
			}
		},

		greeter: {
			params: {
				name: "string"
			},
			rest: "GET /greeter",
			handler(ctx) {
				return `Hello ${ctx.params.name}`;
			}
		},

		whoami: {
			handler(ctx) {
				if (ctx.meta.user) {
					return `Hello ${ctx.meta.user.username || "no-name-user"}`;
				} else {
					return "Who are you?";
				}
			}
		},

		echo: {
			handler(ctx) {
				return {
					action: _.omit(ctx.action, ["handler", "service"]),
					params: ctx.params,
					meta: ctx.meta
				};
			}
		},

		redirect(ctx) {
			ctx.meta.$statusCode = 302;
			ctx.meta.$statusMessage = "Redirecting...";
			ctx.meta.$location = "/test/hello";

			return "REDIRECT";
		},

		noContent(ctx) {
			ctx.meta.$statusCode = 204;
		},

		sayHi: {
			rest: {
				method: "GET",
				fullPath: "/hi"
			},
			handler(ctx) {
				return "Hi!";
			}
		},

		utf(ctx) {
			return "ÉÁŰŐÚÖÜÓÍ éáűőúöüóí";
		},

		dangerZone: {
			visibility: "public",
			rest: "dangerZone",
			handler(ctx) {
				return "You cannot call this action via API Gateway!";
			}
		},

		slow(ctx) {
			let time = ctx.params.delay || 5000;
			return this.Promise.resolve().delay(time).then(() => `Done after ${time / 1000} sec!`);
		},

		wrong(ctx) {
			ctx.meta.$responseType = "text/plain";
			ctx.meta.$responseHeaders = {
				"X-Custom-Header": "Custom content"
			};

			throw new MoleculerError("It is a wrong action! I always throw error!");
		},

		stream: {
			handler(ctx) {
				ctx.meta.$responseHeaders = {
					"Content-Disposition": "attachment; filename=\"stream-lorem.txt\""
				};
				const stream = fs.createReadStream(path.join(__dirname, "..", "test", "assets", "lorem.txt"), "utf8");
				setTimeout(() => {
					stream.read(1024);
				}, 100);

				return stream;
			}
		},

		where(ctx) {
			return `Response from ${this.broker.nodeID}`;
		},

		func2: {
			rest : "GET /fixed/:param1/:param2",
			visibility : "published",
			async handler(ctx) {
				return Promise.resolve("func2");
			}
		},

		func1: {
			rest : "GET /:param1/:param2/:param3/:param4?",
			visibility : "published",
			async handler(ctx) {
				return Promise.resolve("func1");
			}
		}
	}
};
<commit_msg>stream example<commit_after>"use strict";

const _ = require("lodash");
const fs = require("fs");
const path = require("path");
const { MoleculerError } = require("moleculer").Errors;

module.exports = {
	name: "test",
	settings: {
		rest: ""
	},

	events: {
		"$api.aliases.regenerated"() {
			this.logger.info("Aliases regenerated!");
		}
	},

	actions: {
		hello: {
			rest: "GET /hello",
			handler(ctx) {
				ctx.meta.$responseType = "text/plain";
				return "Hello Moleculer";
			}
		},

		greeter: {
			params: {
				name: "string"
			},
			rest: "GET /greeter",
			handler(ctx) {
				return `Hello ${ctx.params.name}`;
			}
		},

		whoami: {
			handler(ctx) {
				if (ctx.meta.user) {
					return `Hello ${ctx.meta.user.username || "no-name-user"}`;
				} else {
					return "Who are you?";
				}
			}
		},

		echo: {
			handler(ctx) {
				return {
					action: _.omit(ctx.action, ["handler", "service"]),
					params: ctx.params,
					meta: ctx.meta
				};
			}
		},

		redirect(ctx) {
			ctx.meta.$statusCode = 302;
			ctx.meta.$statusMessage = "Redirecting...";
			ctx.meta.$location = "/test/hello";

			return "REDIRECT";
		},

		noContent(ctx) {
			ctx.meta.$statusCode = 204;
		},

		sayHi: {
			rest: {
				method: "GET",
				fullPath: "/hi"
			},
			handler(ctx) {
				return "Hi!";
			}
		},

		utf(ctx) {
			return "ÉÁŰŐÚÖÜÓÍ éáűőúöüóí";
		},

		dangerZone: {
			visibility: "public",
			rest: "dangerZone",
			handler(ctx) {
				return "You cannot call this action via API Gateway!";
			}
		},

		slow(ctx) {
			let time = ctx.params.delay || 5000;
			return this.Promise.resolve().delay(time).then(() => `Done after ${time / 1000} sec!`);
		},

		wrong(ctx) {
			ctx.meta.$responseType = "text/plain";
			ctx.meta.$responseHeaders = {
				"X-Custom-Header": "Custom content"
			};

			throw new MoleculerError("It is a wrong action! I always throw error!");
		},

		stream: {
			handler(ctx) {
				ctx.meta.$responseHeaders = {
					"Content-Disposition": "attachment; filename=\"stream-lorem.txt\""
				};
				const stream = fs.createReadStream(path.join(__dirname, "..", "test", "assets", "lorem.txt"), "utf8");
				setTimeout(() => {
					stream.read(1024);
				}, 100);

				return stream;
			}
		},

		save: {
			rest: {
				method: "POST",
				path: "/stream",
				type: "stream"
			},
			handler(ctx) {
				this.logger.info("Received stream:", ctx.params);
			}
		},

		where(ctx) {
			return `Response from ${this.broker.nodeID}`;
		},

		func2: {
			rest : "GET /fixed/:param1/:param2",
			visibility : "published",
			async handler(ctx) {
				return Promise.resolve("func2");
			}
		},

		func1: {
			rest : "GET /:param1/:param2/:param3/:param4?",
			visibility : "published",
			async handler(ctx) {
				return Promise.resolve("func1");
			}
		}
	}
};
<|endoftext|>


<commit_before>// Copyright 2020 Google LLC
//
// 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.

/**
 * This application demonstrates how to perform basic operations on
 * subscriptions with the Google Cloud Pub/Sub API.
 *
 * For more information, see the README.md under /pubsub and the documentation
 * at https://cloud.google.com/pubsub/docs.
 */

'use strict';

// sample-metadata:
//   title: Synchronous Pull with delivery attempt.
//   description: Receive messages synchronously with delivery attempt.
//   usage: node synchronousPullWithDeliveryAttempts.js <project-id> <subscription-name-or-id>

function main(
  projectId = 'YOUR_PROJECT_ID',
  subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'
) {
  // [START pubsub_dead_letter_delivery_attempt]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID';

  // Imports the Google Cloud client library. v1 is for the lower level
  // proto access.
  const {v1} = require('@google-cloud/pubsub');

  // Creates a client; cache this for further use.
  const subClient = new v1.SubscriberClient();

  async function synchronousPullWithDeliveryAttempts() {
    // The low level API client requires a name only.
    const formattedSubscription =
      subscriptionNameOrId.indexOf('/') >= 0
        ? subscriptionNameOrId
        : subClient.subscriptionPath(projectId, subscriptionNameOrId);

    // The maximum number of messages returned for this request.
    // Pub/Sub may return fewer than the number specified.
    const request = {
      subscription: formattedSubscription,
      maxMessages: 10,
    };

    // The subscriber pulls a specified number of messages.
    const [response] = await subClient.pull(request);

    // Process the messages.
    const ackIds = [];
    for (const message of response.receivedMessages) {
      console.log(`Received message: ${message.message.data}`);
      console.log(`Delivery Attempt: ${message.deliveryAttempt}`);
      ackIds.push(message.ackId);
    }

    // Acknowledge all of the messages. You could also ackknowledge
    // these individually, but this is more efficient.
    const ackRequest = {
      subscription: formattedSubscription,
      ackIds: ackIds,
    };
    await subClient.acknowledge(ackRequest);

    console.log('Done.');
  }

  synchronousPullWithDeliveryAttempts().catch(console.error);
  // [END pubsub_dead_letter_delivery_attempt]
}

main(...process.argv.slice(2));
<commit_msg>samples: fix typo in comment (#1643)<commit_after>// Copyright 2020 Google LLC
//
// 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.

/**
 * This application demonstrates how to perform basic operations on
 * subscriptions with the Google Cloud Pub/Sub API.
 *
 * For more information, see the README.md under /pubsub and the documentation
 * at https://cloud.google.com/pubsub/docs.
 */

'use strict';

// sample-metadata:
//   title: Synchronous Pull with delivery attempt.
//   description: Receive messages synchronously with delivery attempt.
//   usage: node synchronousPullWithDeliveryAttempts.js <project-id> <subscription-name-or-id>

function main(
  projectId = 'YOUR_PROJECT_ID',
  subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'
) {
  // [START pubsub_dead_letter_delivery_attempt]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID';

  // Imports the Google Cloud client library. v1 is for the lower level
  // proto access.
  const {v1} = require('@google-cloud/pubsub');

  // Creates a client; cache this for further use.
  const subClient = new v1.SubscriberClient();

  async function synchronousPullWithDeliveryAttempts() {
    // The low level API client requires a name only.
    const formattedSubscription =
      subscriptionNameOrId.indexOf('/') >= 0
        ? subscriptionNameOrId
        : subClient.subscriptionPath(projectId, subscriptionNameOrId);

    // The maximum number of messages returned for this request.
    // Pub/Sub may return fewer than the number specified.
    const request = {
      subscription: formattedSubscription,
      maxMessages: 10,
    };

    // The subscriber pulls a specified number of messages.
    const [response] = await subClient.pull(request);

    // Process the messages.
    const ackIds = [];
    for (const message of response.receivedMessages) {
      console.log(`Received message: ${message.message.data}`);
      console.log(`Delivery Attempt: ${message.deliveryAttempt}`);
      ackIds.push(message.ackId);
    }

    // Acknowledge all of the messages. You could also acknowledge
    // these individually, but this is more efficient.
    const ackRequest = {
      subscription: formattedSubscription,
      ackIds: ackIds,
    };
    await subClient.acknowledge(ackRequest);

    console.log('Done.');
  }

  synchronousPullWithDeliveryAttempts().catch(console.error);
  // [END pubsub_dead_letter_delivery_attempt]
}

main(...process.argv.slice(2));
<|endoftext|>


<commit_before>'use strict';

var app = angular.module('myApp.registrations.directives', []);

app.directive('createHolding', ['Holding', 'User', 'Brand', 'locationHelper', '$routeParams', '$location', '$cookies', 'menu', 'gettextCatalog', function(Holding, User, Brand, locationHelper, $routeParams, $location, $cookies, menu, gettextCatalog) {

  var link = function( scope, element, attrs ) {

    var domain = locationHelper.domain();
    var subdomain = locationHelper.subdomain();
    scope.loading = true;

    menu.hideToolbar = false;
    menu.hideBurger = true;
    menu.isOpenLeft = false;
    menu.isOpen = false;

    scope.brand_name = 'CT WiFi';
    scope.user = {};

    var brandCheck = function(id,cname) {
      Brand.query({
        id: id,
        type: 'showcase',
        cname: cname
      }).$promise.then(function(results) {
        if (results.reseller) {
          scope.brand = results;
        }
      }, function() {
      });
    };

    if (domain !== 'ctapp.io' && domain !== 'ctapp.test') {
      var cname;
      if (subdomain) {
        cname = subdomain + '.' + domain;
      } else {
        cname = domain;
      }
      brandCheck(cname, true);
    } else if (subdomain !== 'my' && subdomain !== 'dashboard') {
      brandCheck(subdomain);
    }

    var cookies = $cookies.get('_cth', { domain: domain });
    if (cookies) {
      scope.cookies = JSON.parse(cookies);
    }

    scope.create = function() {
      var c = $cookies.get('_cth');
      if (c) {
        console.log('Preventing dup');
        return;
      }
      scope.invited   = true;
      scope.cookies   = { d: new Date().getTime(), u: scope.user };
      var now         = new Date();
      var ts          = now.setDate(now.getDate() + 1);
      var expires     = new Date(ts);
      var holding_account = {};
      holding_account.email = scope.user.email;
      if (scope.brand) {
        holding_account.brand = scope.brand.id;
      }
      $cookies.put('_cth', JSON.stringify(scope.cookies), { domain: domain, expires: expires } );
      Holding.create({},holding_account).$promise.then(function(data) {
      }, function() {
        scope.clearCookies();
      });
    };

    scope.clearCookies = function() {
      $location.search({});
      scope.loaded    = true;
      scope.email     = undefined;
      scope.loading   = undefined;
      scope.cookies   = undefined;
      $cookies.remove('_cth', { domain: domain });
    };

    if ($routeParams.email) {
      scope.email = true;
      scope.user.email = $routeParams.email;
      scope.create();
    } else {
      scope.loading = undefined;
      scope.loaded = true;
    }

  };

  return {
    link: link,
    scope: {},
    templateUrl: 'components/registrations/_create.html'
  };
}]);

app.directive('buildFlow', ['Holding', '$routeParams', '$location', '$rootScope', 'locationHelper', '$cookies', 'menu', 'Me', 'showErrors', 'showToast', 'gettextCatalog','$timeout', function(Holding, $routeParams, $location, $rootScope, locationHelper, $cookies, menu, Me, showErrors, showToast, gettextCatalog, $timeout) {

  var link = function( scope, element, attrs ) {

    var domain = locationHelper.domain();

    menu.hideToolbar = false;
    menu.hideBurger = true;
    menu.isOpenLeft = false;
    menu.isOpen = false;

    scope.data = { cb1: true };
    scope.loading = true;

    var login = function(domain, loginArgs) {
      $cookies.remove('_cth', { domain: domain });
      $cookies.remove('_cttid', { domain: domain });
      $rootScope.$broadcast('login', loginArgs);
    };

    var getMe = function(data) {
      Me.get({}).$promise.then(function(res) {
        var search = {};
        var loginArgs = { data: res, search: search, path: '/locations/' + data.location_slug};
        var domain = locationHelper.domain();
        login(domain, loginArgs);
        $rootScope.$broadcast('login', loginArgs);
      });
    };

    var finalise = function(data) {
      var timer = $timeout(function() {
        $timeout.cancel(timer);
        getMe(data);
      }, 1000);
    };

    var fin = function(data) {
      for (var i = 1; i <= 4; i++) {
        setTimeout(function(x) { return function() {
          scope.data['cb' + x] = true;
          scope.$apply();
          if (x === 4) {
            finalise(data);
          }
        }; }(i), (1250)*(i));
      }
    };

    var save = function() {
      if (!scope.holding.username) {
        scope.holding.username = scope.holding.email;
      }
      Holding.update({}, {
        id: $routeParams.id,
        holding_account: scope.holding
      }).$promise.then(function(data) {
        $cookies.put('_cta', data.token, {domain: '.' + domain});
        scope.errors = undefined;
        fin(data);
      }, function(err) {
        showErrors(err);
        scope.updating = undefined;
      });
    };

    var init = function(clientID) {
      Holding.get({}, {
        id: $routeParams.id,
        client_id: clientID
      }).$promise.then(function(results) {
        scope.holding = results;
        scope.loading = undefined;
      }, function(err) {
        $cookies.remove('_cth', { domain: domain });
        $cookies.remove('_cttid', { domain: domain });
        $location.path('/create');
      });
    };

    scope.update = function(stage) {
      scope.finalised = true;
      save();
    };

    var getGA = function() {
      var clientID = $cookies.get('_ga');
      init(clientID);
    };

    getGA();
  };

  return {
    link: link,
    scope: {},
    templateUrl: 'components/registrations/_flow.html'
  };
}]);

app.directive('successSignup', ['Holding', '$routeParams', '$location', function(Holding, $routeParams, $location) {

  var link = function( scope, element, attrs ) {
  };

  return {
    link: link,
    scope: {}
  };

}]);
<commit_msg>adds new ct signup<commit_after>'use strict';

var app = angular.module('myApp.registrations.directives', []);

app.directive('createHolding', ['Holding', 'User', 'Brand', 'locationHelper', '$routeParams', '$location', '$cookies', 'menu', 'gettextCatalog', function(Holding, User, Brand, locationHelper, $routeParams, $location, $cookies, menu, gettextCatalog) {

  var link = function( scope, element, attrs ) {

    var domain = locationHelper.domain();
    var subdomain = locationHelper.subdomain();
    scope.loading = true;

    menu.hideToolbar = false;
    menu.hideBurger = true;
    menu.isOpenLeft = false;
    menu.isOpen = false;

    scope.brand_name = 'CT WiFi';
    scope.user = {};

    var brandCheck = function(id,cname) {
      Brand.query({
        id: id,
        type: 'showcase',
        cname: cname
      }).$promise.then(function(results) {
        if (results.reseller) {
          scope.brand = results;
        }
      }, function() {
      });
    };

    if (domain !== 'ctapp.io' && domain !== 'ctapp.test') {
      var cname;
      if (subdomain) {
        cname = subdomain + '.' + domain;
      } else {
        cname = domain;
      }
      brandCheck(cname, true);
    } else if (subdomain !== 'my' && subdomain !== 'dashboard') {
      brandCheck(subdomain);
    }

    var cookies = $cookies.get('_cth', { domain: domain });
    if (cookies) {
      scope.cookies = JSON.parse(cookies);
    }

    scope.create = function() {
      var c = $cookies.get('_cth');
      if (c) {
        console.log('Preventing dup');
        return;
      }
      scope.invited   = true;
      scope.cookies   = { d: new Date().getTime(), u: scope.user };
      var now         = new Date();
      var ts          = now.setDate(now.getDate() + 1);
      var expires     = new Date(ts);
      var holding_account = {};
      holding_account.email = scope.user.email;
      if (scope.brand) {
        holding_account.brand = scope.brand.id;
      }
      $cookies.put('_cth', JSON.stringify(scope.cookies), { domain: domain, expires: expires } );
      Holding.create({},holding_account).$promise.then(function(data) {
      }, function() {
        scope.clearCookies();
      });
    };

    scope.clearCookies = function() {
      $location.search({});
      scope.loaded    = true;
      scope.email     = undefined;
      scope.loading   = undefined;
      scope.cookies   = undefined;
      $cookies.remove('_cth', { domain: domain });
    };

    if ($routeParams.email) {
      scope.email = true;
      scope.user.email = $routeParams.email;
      scope.create();
    } else {
      scope.loading = undefined;
      scope.loaded = true;
    }

  };

  return {
    link: link,
    scope: {},
    templateUrl: 'components/registrations/_create.html'
  };
}]);

app.directive('buildFlow', ['Holding', '$routeParams', '$location', '$rootScope', 'locationHelper', '$cookies', 'menu', 'Me', 'showErrors', 'showToast', 'gettextCatalog','$timeout', function(Holding, $routeParams, $location, $rootScope, locationHelper, $cookies, menu, Me, showErrors, showToast, gettextCatalog, $timeout) {

  var link = function( scope, element, attrs ) {

    var domain = locationHelper.domain();

    menu.hideToolbar = false;
    menu.hideBurger = true;
    menu.isOpenLeft = false;
    menu.isOpen = false;

    scope.data = { cb1: true };
    scope.loading = true;

    var login = function(domain, loginArgs) {
      $cookies.remove('_cth', { domain: domain });
      $cookies.remove('_cttid', { domain: domain });
      $rootScope.$broadcast('login', loginArgs);
    };

    var getMe = function(data) {
      Me.get({}).$promise.then(function(res) {
        var search = {};
        var loginArgs = { data: res, search: search, path: '/locations/' + data.location_slug};
        var domain = locationHelper.domain();
        login(domain, loginArgs);
        $rootScope.$broadcast('login', loginArgs);
      });
    };

    var finalise = function(data) {
      var timer = $timeout(function() {
        $timeout.cancel(timer);
        getMe(data);
      }, 1000);
    };

    var fin = function(data) {
      for (var i = 1; i <= 4; i++) {
        setTimeout(function(x) { return function() {
          scope.data['cb' + x] = true;
          scope.$apply();
          if (x === 4) {
            finalise(data);
          }
        }; }(i), (1250)*(i));
      }
    };

    var save = function() {
      if (!scope.holding.username) {
        scope.holding.username = scope.holding.email;
      }
      Holding.update({}, {
        id: $routeParams.id,
        holding_account: scope.holding
      }).$promise.then(function(data) {
        $cookies.put('_cta', data.token, {domain: '.' + domain});
        scope.errors = undefined;
        fin(data);
      }, function(err) {
        showErrors(err);
        scope.updating = undefined;
      });
    };

    var init = function(clientID) {
      Holding.get({}, {
        id: $routeParams.id,
        client_id: clientID
      }).$promise.then(function(results) {
        scope.holding = results;
        scope.loading = undefined;
      }, function(err) {
        $cookies.remove('_cth', { domain: domain });
        $cookies.remove('_cttid', { domain: domain });
        $location.path('/create');
      });
    };

    scope.update = function(stage) {
      scope.finalised = true;
      save();
    };

    var getGA = function() {
      var clientID = $cookies.get('_ga');
      init(clientID);
    };

    getGA();
  };

  return {
    link: link,
    scope: {},
    templateUrl: 'components/registrations/_flow.html'
  };
}]);

app.directive('successSignup', ['Holding', '$routeParams', '$location', function(Holding, $routeParams, $location) {

  var link = function( scope, element, attrs ) {
  };
  return {
    link: link,
    scope: {}
  };
}]);
<|endoftext|>


<commit_before>import React from 'react'
import {UIProvider} from 'ui'
import JsonDom from './components/JsonDom'
import genSchema from './gensrc/schema'
import schema from './schema'
import resolver from './resolver'
import Hook from 'util/hook'
import {deepMergeToFirst} from 'util/deepMerge'
import {
    CAPABILITY_MANAGE_CMS_PAGES,
    CAPABILITY_MANAGE_CMS_CONTENT,
    CAPABILITY_MANAGE_CMS_TEMPLATE
} from './constants'
import {getCmsPage} from './util/cmsPage'
import {resolveData} from './util/dataResolver'
import {
    InMemoryCache,
    createHttpLink,
    ApolloProvider,
    ApolloClient
} from '@apollo/client'
import configureStore from '../../client/store/index'
import {Provider} from 'react-redux'
import {renderToStringWithData} from '@apollo/client/react/ssr'
import {getHostFromHeaders} from '../../util/host'

const PORT = (process.env.PORT || 3000)

// Hook to add mongodb resolver
Hook.on('resolver', ({db, resolvers}) => {
    deepMergeToFirst(resolvers, resolver(db))
})

// Hook to add mongodb schema
Hook.on('schema', ({schemas}) => {
    schemas.push(schema)
    schemas.push(genSchema)
})

// Hook to add or modify user roles
Hook.on('createUserRoles', ({userRoles}) => {
    userRoles.forEach(userRole => {
        if (['administrator', 'editor', 'demo'].indexOf(userRole.name) >= 0) {
            console.log(`Add capabilities "${CAPABILITY_MANAGE_CMS_PAGES}",${CAPABILITY_MANAGE_CMS_TEMPLATE} and ${CAPABILITY_MANAGE_CMS_CONTENT} for user role "${userRole.name}"`)
            userRole.capabilities.push(CAPABILITY_MANAGE_CMS_PAGES, CAPABILITY_MANAGE_CMS_CONTENT, CAPABILITY_MANAGE_CMS_TEMPLATE)
        }else if( userRole.name === 'author'){
            console.log(`Add capability ${CAPABILITY_MANAGE_CMS_CONTENT} and ${CAPABILITY_MANAGE_CMS_PAGES} for user role "${userRole.name}"`)
            userRole.capabilities.push(CAPABILITY_MANAGE_CMS_CONTENT, CAPABILITY_MANAGE_CMS_PAGES)
        }else if( userRole.name === 'contributor'){
            console.log(`Add capability ${CAPABILITY_MANAGE_CMS_CONTENT} for user role "${userRole.name}"`)
            userRole.capabilities.push(CAPABILITY_MANAGE_CMS_CONTENT)
        }
    })
})

Hook.on('cmsTemplateRenderer', async ({db, context, body, slug, req}) => {

    let cmsPages = await getCmsPage({db, context, slug, checkHostrules: false})
    if (!cmsPages.results) {
        throw new Error(`Template ${slug} doesn't exist`)
    }
    let mailContext
    try {
        mailContext = JSON.parse(body)
    } catch (e) {
        throw new Error(`Error in body: ${e.message}`)
        mailContext = {}
    }
    const scope = {page: {slug}}
    const {template, script, dataResolver} = cmsPages.results[0]
    const {resolvedData} = await resolveData({db, context, dataResolver, scope})

    console.log('sendmail', mailContext)
    try {
        const client = new ApolloClient({
            ssrMode: true,
            // Remember that this is the interface the SSR server will use to connect to the
            // API server, so we need to ensure it isn't firewalled, etc
            link: createHttpLink({
                uri: 'http://localhost:' + PORT + '/graphql',
                credentials: 'same-origin'
            }),
            cache: new InMemoryCache()
        })

        const {store} = configureStore()

        const loc = {pathname: '', search:'', origin: ''}
        if( req){
            const host = getHostFromHeaders(req.headers)
            loc.origin = req.isHttps ? 'https://' : 'http://' + host
        }
        window.location = globalThis.location = loc

        return await renderToStringWithData(<UIProvider>
            <Provider store={store}>
                <ApolloProvider client={client}>
                    <JsonDom template={template}
                             script={script}
                             location={loc}
                             history={{location:loc}}
                             slug={slug}
                             _props={{context: mailContext}}
                             resolvedData={JSON.stringify(resolvedData)}
                             editMode={false}/>
                </ApolloProvider>
            </Provider>
        </UIProvider>)
    } catch (e) {
        throw new Error(`Error in template: ${e.message}`)
    }
    return body

})
<commit_msg>Small improvements<commit_after>import React from 'react'
import {UIProvider} from 'ui'
import JsonDom from './components/JsonDom'
import genSchema from './gensrc/schema'
import schema from './schema'
import resolver from './resolver'
import Hook from 'util/hook'
import {deepMergeToFirst} from 'util/deepMerge'
import {
    CAPABILITY_MANAGE_CMS_PAGES,
    CAPABILITY_MANAGE_CMS_CONTENT,
    CAPABILITY_MANAGE_CMS_TEMPLATE
} from './constants'
import {getCmsPage} from './util/cmsPage'
import {resolveData} from './util/dataResolver'
import {
    InMemoryCache,
    createHttpLink,
    ApolloProvider,
    ApolloClient
} from '@apollo/client'
import configureStore from '../../client/store/index'
import {Provider} from 'react-redux'
import {renderToStringWithData} from '@apollo/client/react/ssr'
import {getHostFromHeaders} from '../../util/host'

const PORT = (process.env.PORT || 3000)

// Hook to add mongodb resolver
Hook.on('resolver', ({db, resolvers}) => {
    deepMergeToFirst(resolvers, resolver(db))
})

// Hook to add mongodb schema
Hook.on('schema', ({schemas}) => {
    schemas.push(schema)
    schemas.push(genSchema)
})

// Hook to add or modify user roles
Hook.on('createUserRoles', ({userRoles}) => {
    userRoles.forEach(userRole => {
        if (['administrator', 'editor', 'demo'].indexOf(userRole.name) >= 0) {
            console.log(`Add capabilities "${CAPABILITY_MANAGE_CMS_PAGES}",${CAPABILITY_MANAGE_CMS_TEMPLATE} and ${CAPABILITY_MANAGE_CMS_CONTENT} for user role "${userRole.name}"`)
            userRole.capabilities.push(CAPABILITY_MANAGE_CMS_PAGES, CAPABILITY_MANAGE_CMS_CONTENT, CAPABILITY_MANAGE_CMS_TEMPLATE)
        }else if( userRole.name === 'author'){
            console.log(`Add capability ${CAPABILITY_MANAGE_CMS_CONTENT} and ${CAPABILITY_MANAGE_CMS_PAGES} for user role "${userRole.name}"`)
            userRole.capabilities.push(CAPABILITY_MANAGE_CMS_CONTENT, CAPABILITY_MANAGE_CMS_PAGES)
        }else if( userRole.name === 'contributor'){
            console.log(`Add capability ${CAPABILITY_MANAGE_CMS_CONTENT} for user role "${userRole.name}"`)
            userRole.capabilities.push(CAPABILITY_MANAGE_CMS_CONTENT)
        }
    })
})

Hook.on('cmsTemplateRenderer', async ({db, context, body, slug, req}) => {

    let cmsPages = await getCmsPage({db, context, slug, checkHostrules: false})
    if (!cmsPages.results) {
        throw new Error(`Template ${slug} doesn't exist`)
    }
    let mailContext
    try {
        mailContext = JSON.parse(body)
    } catch (e) {
        throw new Error(`Error in body: ${e.message}`)
        mailContext = {}
    }
    const scope = {page: {slug}}
    const {template, script, dataResolver} = cmsPages.results[0]
    const {resolvedData} = await resolveData({db, context, dataResolver, scope})

    console.log('sendmail', mailContext)
    try {
        const client = new ApolloClient({
            ssrMode: true,
            // Remember that this is the interface the SSR server will use to connect to the
            // API server, so we need to ensure it isn't firewalled, etc
            link: createHttpLink({
                uri: 'http://localhost:' + PORT + '/graphql',
                credentials: 'same-origin'
            }),
            cache: new InMemoryCache()
        })

        const {store} = configureStore()

        const loc = {pathname: '', search:'', origin: ''}
        if( req){
            const host = getHostFromHeaders(req.headers)
            loc.origin = req.isHttps ? 'https://' : 'http://' + host
        }
        console.log(req, loc)
        window.location = globalThis.location = loc

        return await renderToStringWithData(<UIProvider>
            <Provider store={store}>
                <ApolloProvider client={client}>
                    <JsonDom template={template}
                             script={script}
                             location={loc}
                             history={{location:loc}}
                             slug={slug}
                             _props={{context: mailContext}}
                             resolvedData={JSON.stringify(resolvedData)}
                             editMode={false}/>
                </ApolloProvider>
            </Provider>
        </UIProvider>)
    } catch (e) {
        throw new Error(`Error in template: ${e.message}`)
    }
    return body

})
<|endoftext|>


<commit_before>var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);
var expect = chai.expect;

var mortalityStepDefinitionsWrapper = function () {

    var mortalityPage = require('../support/mortalitypage.po')

    this.When(/^user sees a visualization$/, function () {
        mortalityPage.isVisualizationDisplayed().then(function(value) {
            expect(value).to.equal(true);
        });
    });

    this.Then(/^labels are displayed on both the axes for minimized visualization$/, function () {
       var labelArray = mortalityPage.getAxisLabelsForMinimizedVisualization();
       expect(labelArray[0].getText()).to.eventually.equal('Race');
       expect(labelArray[1].getText()).to.eventually.equal('Deaths');
    });

    this.When(/^user expand visualization$/, function () {
        mortalityPage.expandVisualizationLink.click();
    });

    this.Then(/^labels are displayed on both the axes for expanded visualization$/, function () {
        var labelArray = mortalityPage.getAxisLabelsForExpandedVisualization();
        expect(labelArray[0].getText()).to.eventually.equal('Race');
        expect(labelArray[1].getText()).to.eventually.equal('Deaths');
    });

    this.Given(/^user is on search page$/, function () {
        browser.get('/search/');
    });

    this.Then(/^user sees side filter$/, function () {
        expect(mortalityPage.sideMenu.isDisplayed()).to.eventually.equal(true);
    });

    this.Then(/^there is button to hide filter$/, function () {
        expect(mortalityPage.hideFiltersBtn.isDisplayed()).to.eventually.equal(true);
    });

    this.When(/^user clicks hide filter button$/, function () {
        mortalityPage.hideFiltersBtn.click();
    });

    this.Then(/^side menu slides away$/, function () {
        expect(mortalityPage.sideMenu.getAttribute('class')).to.eventually.include('ng-hide');
    });

    this.Then(/^user sees button to show filters$/, function () {
        expect(mortalityPage.showFiltersBtn.isDisplayed()).to.eventually.equal(true);
    });

    this.When(/^user clicks show filters button$/, function () {
        mortalityPage.showFiltersBtn.click();
    });

    this.Then(/^side menu slides back into view$/, function () {
        expect(mortalityPage.sideMenu.getAttribute('class')).to.not.eventually.include('ng-hide');
    });

    this.When(/^I see the number of deaths in data table$/, function () {
        mortalityPage.getTableHeaders().then(function(value) {
            expect(value).to.contains('Number of Deaths');
        });
    });

    this.Then(/^the percentages are shown for each row are displayed by default$/, function () {
        mortalityPage.getTableRowData(0).then(function(value){
            expect(value[1]).to.equal('8,185 (45.4%)');
        });
    });

    this.When(/^I update criteria in filter options with column "([^"]*)"$/, function (arg1) {
        mortalityPage.selectSideFilter(arg1, 'Column').click();
    });

    this.Then(/^data table is updated and the number of deaths and percentages are updated too$/, function () {
        mortalityPage.getTableRowData(0).then(function (value) {
            expect(value[1]).to.equal('899 (5.0%)');
        });
    });

    this.When(/^I add new data items to row or columns$/, function () {
        mortalityPage.selectSideFilter('Age Groups', 'Row').click();
    });

    this.Then(/^the percentages get re\-calculated based on all the information displayed in a given row$/, function () {
        mortalityPage.getTableRowData(0).then(function(value){
            expect(value[2]).to.equal('86 (18.9%)');
        });
    });

    this.When(/^I see the data table$/, function () {
        expect(mortalityPage.owhTable.isPresent()).to.eventually.equal(true);
        mortalityPage.getTableHeaders().then(function(value) {
            expect(value).to.contains('Number of Deaths');
        });
    });

    this.Then(/^percentages are displayed in the same column\/cell in parenthesis$/, function () {
        mortalityPage.getTableRowData(0).then(function(value){
            expect(value[2]).to.equal('86 (18.9%)');
        });
    });

    this.When(/^I see the quick visualizations$/, function () {
        browser.get('/search');
        mortalityPage.isVisualizationDisplayed().then(function(value) {
            expect(value).to.equal(true);
        });
    });

    this.Then(/^they're displayed same as before and nothing changes$/, function () {
        var labelArray = mortalityPage.getAxisLabelsForMinimizedVisualization();
        expect(labelArray[0].getText()).to.eventually.equal('Race');
        expect(labelArray[1].getText()).to.eventually.equal('Deaths');
        mortalityPage.expandVisualizationLink.click();
        labelArray = mortalityPage.getAxisLabelsForExpandedVisualization();
        expect(labelArray[0].getText()).to.eventually.equal('Race');
        expect(labelArray[1].getText()).to.eventually.equal('Deaths');
    });

   /* this.When(/^I export the data table into excel or csv$/, function () {
        return false;
    });

    this.Then(/^percentages are exported as well$/, function () {
        return false;
    });

    this.Then(/^each percentage is displayed in a separate column \(unlike UI in the application\)$/, function () {
        return false;
    });
*/
    this.When(/^I see the results$/, function () {
        expect(mortalityPage.owhTable.isPresent()).to.eventually.equal(true);
        mortalityPage.getTableHeaders().then(function(value) {
            expect(value).to.contains('Number of Deaths');
        });
    });

    this.Then(/^an option to show\/hide percentages is displayed$/, function () {
        expect(mortalityPage.showOrHidePecentageDiv.isPresent()).to.eventually.equal(true);
        expect(mortalityPage.showPecentageButton.isPresent()).to.eventually.equal(true);
        expect(mortalityPage.hidePecentageButton.isPresent()).to.eventually.equal(true);
    });

    this.Then(/^show\/hide percentages button shouldn't display$/, function () {
        expect(mortalityPage.showOrHidePecentageDiv.isDisplayed()).to.eventually.equal(false);
        expect(mortalityPage.showPecentageButton.isDisplayed()).to.eventually.equal(false);
        expect(mortalityPage.hidePecentageButton.isDisplayed()).to.eventually.equal(false);
    });

    this.Then(/^when that option is toggled, the percentages are either displayed\/hidden$/, function () {
        mortalityPage.hidePecentageButton.click();
        mortalityPage.getTableRowData(0).then(function(value){
            expect(value[2]).to.equal('86');
        });
    });

    /*this.Then(/^this option decides if percentages get exported into the excel\/csv or not$/, function () {
        return false;
    });*/

    this.When(/^I look at the table results$/, function () {
        expect(mortalityPage.owhTable.isPresent()).to.eventually.equal(true);
        mortalityPage.getTableHeaders().then(function(value) {
            expect(value).to.contains('Number of Deaths');
        });
    });

    this.When(/^percentage option is enabled$/, function () {
        mortalityPage.showPecentageButton.click();
    });

    this.Then(/^the Rates and Percentages should have a one decimal precision$/, function () {
        mortalityPage.getTableRowData(0).then(function(value){
            expect(value[2]).to.equal('86 (18.9%)');
        });
    });

    this.When(/^user expands race options$/, function () {
        mortalityPage.raceOptionsLink.click();
    });

    this.When(/^user selects second race option$/, function () {
        mortalityPage.raceOption2Link.click();
    });

    this.Then(/^race options retain their initial ordering$/, function () {
        mortalityPage.getOptions('Race').then(function(elements) {
            elements[3].getOuterHtml().then(function(value) {
                expect(mortalityPage.raceOption2.getOuterHtml()).to.eventually.equal(value);
            });
        });
    });

    this.When(/^I change 'I'm interested in' dropdown value to "([^"]*)"$/, function (arg1) {
        mortalityPage.interestedInSelectBox.element(by.cssContainingText('option', arg1)).click();
    });

    this.Then(/^I should be redirected to YRBS page$/, function () {
        var text = mortalityPage.sideMenu.getText();
        expect(text).to.eventually.contains("Question");
        //expect(text).to.eventually.contains("Select Questions");
        expect(text).to.eventually.contains("Grade");
    });

    this.When(/^the user chooses the option 'Death Rates'$/, function () {
         mortalityPage.deathRatesOption.click();
    });

    this.Then(/^the rates are shown for each row \(with the Total population, from Bridge Race Estimates, as the denominator\) \- and not the total number of deaths shown in the table$/, function () {
        //  mortalityPage.getTableRowData(0).then(function(text){
              //TODO: replace when hooked up to real data
              // expect(text[1]).to.equal('Rate\n885.4\nDeaths\n8,185\nPopulation\n924,416');
        //  });
    });

    this.Then(/^dropdown is in the main search bar$/, function () {
         expect(mortalityPage.mainSearch.element(by.model('ots.selectedShowFilter')).isPresent()).to.eventually.equal(true);
    });

    this.Then(/^the Percentages should have a one decimal precision$/, function () {
        //  mortalityPage.getTableRowData(1).then(function(text) {
              //TODO: need actual data
              // expect(text[1]).to.equal('');
        //  });
    });

    this.Then(/^the following message should be displayed stating that population data is being retrieved from Census "([^"]*)"$/, function (arg1) {
         expect(mortalityPage.deathRateDisclaimer.getText()).to.eventually.equal(arg1);
    });

    this.When(/^user filters by year (\d+)$/, function (arg1) {
        mortalityPage.getOptions('Year').then(function(elements) {
            elements[arg1 - 2000 + 1].click();
        });
    });

    this.When(/^user filters by ethnicity Spaniard$/, function () {
        mortalityPage.ethnicityOption2.click();
    });

    this.Then(/^user should only see total for white race in side filter$/, function () {
        mortalityPage.getSideFilterTotals().then(function(elements) {
            expect(elements[18].getInnerHtml()).to.eventually.equal('611');
        });
    });

    this.When(/^user shows more year filters$/, function () {
        mortalityPage.showMoreYears.click();
    });

    this.When(/^user expands ethnicity filter$/, function () {
        mortalityPage.expandEthnicity.click();
    });
};
module.exports = mortalityStepDefinitionsWrapper;
<commit_msg>OWH-298: make sure other totals are blank in e2e test<commit_after>var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);
var expect = chai.expect;

var mortalityStepDefinitionsWrapper = function () {

    var mortalityPage = require('../support/mortalitypage.po')

    this.When(/^user sees a visualization$/, function () {
        mortalityPage.isVisualizationDisplayed().then(function(value) {
            expect(value).to.equal(true);
        });
    });

    this.Then(/^labels are displayed on both the axes for minimized visualization$/, function () {
       var labelArray = mortalityPage.getAxisLabelsForMinimizedVisualization();
       expect(labelArray[0].getText()).to.eventually.equal('Race');
       expect(labelArray[1].getText()).to.eventually.equal('Deaths');
    });

    this.When(/^user expand visualization$/, function () {
        mortalityPage.expandVisualizationLink.click();
    });

    this.Then(/^labels are displayed on both the axes for expanded visualization$/, function () {
        var labelArray = mortalityPage.getAxisLabelsForExpandedVisualization();
        expect(labelArray[0].getText()).to.eventually.equal('Race');
        expect(labelArray[1].getText()).to.eventually.equal('Deaths');
    });

    this.Given(/^user is on search page$/, function () {
        browser.get('/search/');
    });

    this.Then(/^user sees side filter$/, function () {
        expect(mortalityPage.sideMenu.isDisplayed()).to.eventually.equal(true);
    });

    this.Then(/^there is button to hide filter$/, function () {
        expect(mortalityPage.hideFiltersBtn.isDisplayed()).to.eventually.equal(true);
    });

    this.When(/^user clicks hide filter button$/, function () {
        mortalityPage.hideFiltersBtn.click();
    });

    this.Then(/^side menu slides away$/, function () {
        expect(mortalityPage.sideMenu.getAttribute('class')).to.eventually.include('ng-hide');
    });

    this.Then(/^user sees button to show filters$/, function () {
        expect(mortalityPage.showFiltersBtn.isDisplayed()).to.eventually.equal(true);
    });

    this.When(/^user clicks show filters button$/, function () {
        mortalityPage.showFiltersBtn.click();
    });

    this.Then(/^side menu slides back into view$/, function () {
        expect(mortalityPage.sideMenu.getAttribute('class')).to.not.eventually.include('ng-hide');
    });

    this.When(/^I see the number of deaths in data table$/, function () {
        mortalityPage.getTableHeaders().then(function(value) {
            expect(value).to.contains('Number of Deaths');
        });
    });

    this.Then(/^the percentages are shown for each row are displayed by default$/, function () {
        mortalityPage.getTableRowData(0).then(function(value){
            expect(value[1]).to.equal('8,185 (45.4%)');
        });
    });

    this.When(/^I update criteria in filter options with column "([^"]*)"$/, function (arg1) {
        mortalityPage.selectSideFilter(arg1, 'Column').click();
    });

    this.Then(/^data table is updated and the number of deaths and percentages are updated too$/, function () {
        mortalityPage.getTableRowData(0).then(function (value) {
            expect(value[1]).to.equal('899 (5.0%)');
        });
    });

    this.When(/^I add new data items to row or columns$/, function () {
        mortalityPage.selectSideFilter('Age Groups', 'Row').click();
    });

    this.Then(/^the percentages get re\-calculated based on all the information displayed in a given row$/, function () {
        mortalityPage.getTableRowData(0).then(function(value){
            expect(value[2]).to.equal('86 (18.9%)');
        });
    });

    this.When(/^I see the data table$/, function () {
        expect(mortalityPage.owhTable.isPresent()).to.eventually.equal(true);
        mortalityPage.getTableHeaders().then(function(value) {
            expect(value).to.contains('Number of Deaths');
        });
    });

    this.Then(/^percentages are displayed in the same column\/cell in parenthesis$/, function () {
        mortalityPage.getTableRowData(0).then(function(value){
            expect(value[2]).to.equal('86 (18.9%)');
        });
    });

    this.When(/^I see the quick visualizations$/, function () {
        browser.get('/search');
        mortalityPage.isVisualizationDisplayed().then(function(value) {
            expect(value).to.equal(true);
        });
    });

    this.Then(/^they're displayed same as before and nothing changes$/, function () {
        var labelArray = mortalityPage.getAxisLabelsForMinimizedVisualization();
        expect(labelArray[0].getText()).to.eventually.equal('Race');
        expect(labelArray[1].getText()).to.eventually.equal('Deaths');
        mortalityPage.expandVisualizationLink.click();
        labelArray = mortalityPage.getAxisLabelsForExpandedVisualization();
        expect(labelArray[0].getText()).to.eventually.equal('Race');
        expect(labelArray[1].getText()).to.eventually.equal('Deaths');
    });

   /* this.When(/^I export the data table into excel or csv$/, function () {
        return false;
    });

    this.Then(/^percentages are exported as well$/, function () {
        return false;
    });

    this.Then(/^each percentage is displayed in a separate column \(unlike UI in the application\)$/, function () {
        return false;
    });
*/
    this.When(/^I see the results$/, function () {
        expect(mortalityPage.owhTable.isPresent()).to.eventually.equal(true);
        mortalityPage.getTableHeaders().then(function(value) {
            expect(value).to.contains('Number of Deaths');
        });
    });

    this.Then(/^an option to show\/hide percentages is displayed$/, function () {
        expect(mortalityPage.showOrHidePecentageDiv.isPresent()).to.eventually.equal(true);
        expect(mortalityPage.showPecentageButton.isPresent()).to.eventually.equal(true);
        expect(mortalityPage.hidePecentageButton.isPresent()).to.eventually.equal(true);
    });

    this.Then(/^show\/hide percentages button shouldn't display$/, function () {
        expect(mortalityPage.showOrHidePecentageDiv.isDisplayed()).to.eventually.equal(false);
        expect(mortalityPage.showPecentageButton.isDisplayed()).to.eventually.equal(false);
        expect(mortalityPage.hidePecentageButton.isDisplayed()).to.eventually.equal(false);
    });

    this.Then(/^when that option is toggled, the percentages are either displayed\/hidden$/, function () {
        mortalityPage.hidePecentageButton.click();
        mortalityPage.getTableRowData(0).then(function(value){
            expect(value[2]).to.equal('86');
        });
    });

    /*this.Then(/^this option decides if percentages get exported into the excel\/csv or not$/, function () {
        return false;
    });*/

    this.When(/^I look at the table results$/, function () {
        expect(mortalityPage.owhTable.isPresent()).to.eventually.equal(true);
        mortalityPage.getTableHeaders().then(function(value) {
            expect(value).to.contains('Number of Deaths');
        });
    });

    this.When(/^percentage option is enabled$/, function () {
        mortalityPage.showPecentageButton.click();
    });

    this.Then(/^the Rates and Percentages should have a one decimal precision$/, function () {
        mortalityPage.getTableRowData(0).then(function(value){
            expect(value[2]).to.equal('86 (18.9%)');
        });
    });

    this.When(/^user expands race options$/, function () {
        mortalityPage.raceOptionsLink.click();
    });

    this.When(/^user selects second race option$/, function () {
        mortalityPage.raceOption2Link.click();
    });

    this.Then(/^race options retain their initial ordering$/, function () {
        mortalityPage.getOptions('Race').then(function(elements) {
            elements[3].getOuterHtml().then(function(value) {
                expect(mortalityPage.raceOption2.getOuterHtml()).to.eventually.equal(value);
            });
        });
    });

    this.When(/^I change 'I'm interested in' dropdown value to "([^"]*)"$/, function (arg1) {
        mortalityPage.interestedInSelectBox.element(by.cssContainingText('option', arg1)).click();
    });

    this.Then(/^I should be redirected to YRBS page$/, function () {
        var text = mortalityPage.sideMenu.getText();
        expect(text).to.eventually.contains("Question");
        //expect(text).to.eventually.contains("Select Questions");
        expect(text).to.eventually.contains("Grade");
    });

    this.When(/^the user chooses the option 'Death Rates'$/, function () {
         mortalityPage.deathRatesOption.click();
    });

    this.Then(/^the rates are shown for each row \(with the Total population, from Bridge Race Estimates, as the denominator\) \- and not the total number of deaths shown in the table$/, function () {
        //  mortalityPage.getTableRowData(0).then(function(text){
              //TODO: replace when hooked up to real data
              // expect(text[1]).to.equal('Rate\n885.4\nDeaths\n8,185\nPopulation\n924,416');
        //  });
    });

    this.Then(/^dropdown is in the main search bar$/, function () {
         expect(mortalityPage.mainSearch.element(by.model('ots.selectedShowFilter')).isPresent()).to.eventually.equal(true);
    });

    this.Then(/^the Percentages should have a one decimal precision$/, function () {
        //  mortalityPage.getTableRowData(1).then(function(text) {
              //TODO: need actual data
              // expect(text[1]).to.equal('');
        //  });
    });

    this.Then(/^the following message should be displayed stating that population data is being retrieved from Census "([^"]*)"$/, function (arg1) {
         expect(mortalityPage.deathRateDisclaimer.getText()).to.eventually.equal(arg1);
    });

    this.When(/^user filters by year (\d+)$/, function (arg1) {
        mortalityPage.getOptions('Year').then(function(elements) {
            elements[arg1 - 2000 + 1].click();
        });
    });

    this.When(/^user filters by ethnicity Spaniard$/, function () {
        mortalityPage.ethnicityOption2.click();
    });

    this.Then(/^user should only see total for white race in side filter$/, function () {
        mortalityPage.getSideFilterTotals().then(function(elements) {
            expect(elements[18].getInnerHtml()).to.eventually.equal('611');
            expect(elements[19].getInnerHtml()).to.eventually.equal('');
            expect(elements[20].getInnerHtml()).to.eventually.equal('');
        });
    });

    this.When(/^user shows more year filters$/, function () {
        mortalityPage.showMoreYears.click();
    });

    this.When(/^user expands ethnicity filter$/, function () {
        mortalityPage.expandEthnicity.click();
    });
};
module.exports = mortalityStepDefinitionsWrapper;
<|endoftext|>