<commit_before>$( document ).ready(function() {
  generate();
  twitter();

  function generate(){
    var quotes = ["There are two types of people in this world.  Those that enter a room and say 'Here I am!' and those that enter a room and say 'There you are!'.@Unknown","Because it's there.@George Mallory on climbing mountains","Footsteps always follow us, whenever it is snowing.  They always show us where we've been, but never where we're going.@Winnie the Pooh's A-Z","For I know the plans that I have for you.@The Lord, Jer 29:11","The only way to climb properly is to realize that just getting up a route is nothing, the way it is done is everything.@Royal Robbins","Small minds discuss people.  Average minds discuss events.  Great minds discuss ideas.@Unkown","The significant problems we face cannot be solved at the same level of thinking we were at when we created them.@Albert Einstein","We must not cease from exploration and the end of all our exploring will be to arrive where we began and to know the place for the first time.@T S Eliot","One man asked another on the death of a mutual friend, 'How much did he leave?' His friend responded, 'He left it all.'@Proverb","It is more noble to give yourself completely to one individual than to labor diligently for the salvation of the masses.@Dag Hammarskjold, Sec. Gen. of the UN","Maps are a way of organizing wonder.@Edward Tufte","I have decided to make my life my argument.@Albert Schweitzer","Now it's a sqirt mecca for mystery artist, but back then it was just magic.@Jim Snyder on Kayaking","Knowledge keeps about as well as fish.@Alfred North Whitehead","It all began, I said, when I decided that some experts don't really know enough to make a pronouncement of doom on a human being.  And I said I hoped they would be careful about what they said to others; they might be believed and that coud be the beginning of the end.@Norman Cousins, Anatomy of an Illness","Do not go gentle into that good night.  Rage, rage against the dying of the light.@Dylan Thomas","For you will look smart and feel ignorant and the patient will not know which day it is for you and you will pretend to be smart out of ignorance.@John Stone, Gaudeamus Igitur"
];

    randomQuote = quotes[Math.floor(Math.random()*quotes.length)];
    quoteAuthor=randomQuote.split("@");
    $('.saying').text(quoteAuthor[0]);
    $('.author').text(quoteAuthor[1]);
var i=0;
    //console.log(saying);
  }
count=-1;
var flowers=function() {
count++;
console.log(count);
var imgArray = new Array();

imgArray[0]= new Image();
imgArray[0].src = 'images/F1.gif';
imgArray[1]= new Image();
imgArray[1].src = 'images/F2.gif';
imgArray[2]= new Image();
imgArray[2].src = 'images/F3.gif';
imgArray[3]= new Image();
imgArray[3].src = 'images/F4.gif';
imgArray[4]= new Image();
imgArray[4].src = 'images/F5.gif';
imgArray[5]= new Image();
imgArray[5].src = 'images/F6.gif';
imgArray[6]= new Image();
imgArray[6].src = 'images/F7.gif';
imgArray[7]= new Image();
imgArray[7].src = 'images/F8.gif';
imgArray[8]= new Image();
imgArray[8].src = 'images/F9.gif';
imgArray[9]= new Image();
imgArray[9].src = 'images/F10.gif';
imgArray[10]= new Image();
imgArray[10].src = 'images/F11.gif';
imgArray[11]= new Image();
imgArray[11].src = 'images/F12.gif';
imgArray[12]= new Image();
imgArray[12].src = 'images/F13.gif';
imgArray[13]= new Image();
imgArray[13].src = 'images/F14.gif';
imgArray[14]= new Image();
imgArray[14].src = 'images/F15.gif';
imgArray[15]= new Image();
imgArray[15].src = 'images/F16.gif';
imgArray[16]= new Image();
imgArray[16].src = 'images/F17.gif';
imgArray[17]= new Image();
imgArray[17].src = 'images/F18.gif';
imgArray[18]= new Image();
imgArray[18].src = 'images/F19.gif';
imgArray[19]= new Image();
imgArray[19].src = 'images/F20.gif';
imgArray[20]= new Image();
imgArray[20].src = 'images/F21.gif';
imgArray[21]= new Image();
imgArray[21].src = 'images/F22.gif';
imgArray[22]= new Image();
imgArray[22].src = 'images/F23.gif';
imgArray[23]= new Image();
imgArray[23].src = 'images/F24.gif';
imgArray[24]= new Image();
imgArray[24].src = 'images/F25.gif';

for(i=0;i<imgArray.length - count;i++){
 $('.imgFlower').attr('src',imgArray[i].src);
   if(count===24){
    count=count-24;
   }

}

}

  function twitter(){

  var twitterQuote=quoteAuthor;
  var tweetLink='http://twitter.com/home?status= ' +encodeURIComponent(twitterQuote);
  window.open(tweetLink,'_blank');
}

$(".button").on( "click", function() {

    generate();
    flowers();
});

$(".tweet").on( "click", function() {
    twitter();
});

});

   <commit_msg>quote-generator changes<commit_after>$( document ).ready(function() {
  generate();
  twitter();

  function generate(){
    var quotes = ["There are two types of people in this world.  Those that enter a room and say 'Here I am!' and those that enter a room and say 'There you are!'.@Unknown","Because it's there.@George Mallory on climbing mountains","Footsteps always follow us, whenever it is snowing.  They always show us where we've been, but never where we're going.@Winnie the Pooh's A-Z","For I know the plans that I have for you.@The Lord, Jer 29:11","The only way to climb properly is to realize that just getting up a route is nothing, the way it is done is everything.@Royal Robbins","Small minds discuss people.  Average minds discuss events.  Great minds discuss ideas.@Unkown","The significant problems we face cannot be solved at the same level of thinking we were at when we created them.@Albert Einstein","We must not cease from exploration and the end of all our exploring will be to arrive where we began and to know the place for the first time.@T S Eliot","One man asked another on the death of a mutual friend, 'How much did he leave?' His friend responded, 'He left it all.'@Proverb","It is more noble to give yourself completely to one individual than to labor diligently for the salvation of the masses.@Dag Hammarskjold, Sec. Gen. of the UN","Maps are a way of organizing wonder.@Edward Tufte","I have decided to make my life my argument.@Albert Schweitzer","Now it's a sqirt mecca for mystery artist, but back then it was just magic.@Jim Snyder on Kayaking","Knowledge keeps about as well as fish.@Alfred North Whitehead","It all began, I said, when I decided that some experts don't really know enough to make a pronouncement of doom on a human being.  And I said I hoped they would be careful about what they said to others; they might be believed and that coud be the beginning of the end.@Norman Cousins, Anatomy of an Illness","Do not go gentle into that good night.  Rage, rage against the dying of the light.@Dylan Thomas","For you will look smart and feel ignorant and the patient will not know which day it is for you and you will pretend to be smart out of ignorance.@John Stone, Gaudeamus Igitur"
];

    randomQuote = quotes[Math.floor(Math.random()*quotes.length)];
    quoteAuthor=randomQuote.split("@");
    $('.saying').text(quoteAuthor[0]);
    $('.author').text(quoteAuthor[1]);
var i=0;
    //console.log(saying);
  }
count=-1;
var flowers=function() {
count++;
console.log(count);
var imgArray = new Array();

imgArray[0]= new Image();
imgArray[0].src = 'images/F1.gif';
imgArray[1]= new Image();
imgArray[1].src = 'images/F2.gif';
imgArray[2]= new Image();
imgArray[2].src = 'images/F3.gif';
imgArray[3]= new Image();
imgArray[3].src = 'images/F4.gif';
imgArray[4]= new Image();
imgArray[4].src = 'images/F5.gif';
imgArray[5]= new Image();
imgArray[5].src = 'images/F6.gif';
imgArray[6]= new Image();
imgArray[6].src = 'images/F7.gif';
imgArray[7]= new Image();
imgArray[7].src = 'images/F8.gif';
imgArray[8]= new Image();
imgArray[8].src = 'images/F9.gif';
imgArray[9]= new Image();
imgArray[9].src = 'images/F10.gif';
imgArray[10]= new Image();
imgArray[10].src = 'images/F11.gif';
imgArray[11]= new Image();
imgArray[11].src = 'images/F12.gif';
imgArray[12]= new Image();
imgArray[12].src = 'images/F13.gif';
imgArray[13]= new Image();
imgArray[13].src = 'images/F14.gif';
imgArray[14]= new Image();
imgArray[14].src = 'images/F15.gif';
imgArray[15]= new Image();
imgArray[15].src = 'images/F16.gif';
imgArray[16]= new Image();
imgArray[16].src = 'images/F17.gif';
imgArray[17]= new Image();
imgArray[17].src = 'images/F18.gif';
imgArray[18]= new Image();
imgArray[18].src = 'images/F19.gif';
imgArray[19]= new Image();
imgArray[19].src = 'images/F20.gif';
imgArray[20]= new Image();
imgArray[20].src = 'images/F21.gif';
imgArray[21]= new Image();
imgArray[21].src = 'images/F22.gif';
imgArray[22]= new Image();
imgArray[22].src = 'images/F23.gif';
imgArray[23]= new Image();
imgArray[23].src = 'images/F24.gif';
imgArray[24]= new Image();
imgArray[24].src = 'images/F25.gif';

for(i=0;i<imgArray.length - count;i++){
 $('.imgFlower').attr('src',imgArray[i].src);
   if(count===24){
    count=count-24;
   }
}

}

  function twitter(){

  var twitterQuote=quoteAuthor;
  var tweetLink='http://twitter.com/home?status= ' +encodeURIComponent(twitterQuote);
  window.open(tweetLink,'_blank');
}

$(".button").on( "click", function() {

    generate();
    flowers();
});

$(".tweet").on( "click", function() {
    twitter();
});

});

   <|endoftext|>


<commit_before>'use strict';

const os = require('os');
const fetch = require('node-fetch');
const sentry = require('@sentry/node');

async function captureException(error) {
  try {
    sentry.captureException(error);
    await sentry.flush();
  } catch (err) {
    /** ignore errors*/
    return Promise.resolve();
  }
}

async function captureError(message) {
  try {
    sentry.captureMessage(message, 'error');
    await sentry.flush();
  } catch (err) {
    /** ignore errors*/
    return Promise.resolve();
  }
}

function captureStderr(name, error) {
  if (error && error.stderr && error.stderr.trim() !== '') {
    error.stderr
      .trim()
      .split('\n')
      .forEach(line => {
        sentry.addBreadcrumb({
          category: 'stderr',
          message: line,
          level: 'error',
        });
      });
  }

  return captureError(name);
}

function trackEvent(event, body) {
  try {
    return fetch('https://analytics.strapi.io/track', {
      method: 'POST',
      body: JSON.stringify({
        event,
        ...body,
      }),
      timeout: 1000,
      headers: { 'Content-Type': 'application/json' },
    }).catch(() => {});
  } catch (err) {
    /** ignore errors*/
    return Promise.resolve();
  }
}

function trackError({ scope, error }) {
  try {
    return trackEvent('didNotCreateProject', {
      uuid: scope.uuid,
      deviceId: scope.deviceId,
      properties: {
        error: typeof error == 'string' ? error : error && error.message,
        os: os.type(),
        platform: os.platform(),
        release: os.release(),
        version: scope.strapiVersion,
        nodeVersion: process.version,
        docker: scope.docker,
        useYarn: scope.useYarn,
      },
    });
  } catch (err) {
    /** ignore errors*/
    return Promise.resolve();
  }
}

function trackUsage({ event, scope, error }) {
  try {
    return trackEvent(event, {
      uuid: scope.uuid,
      deviceId: scope.deviceId,
      properties: {
        error: typeof error == 'string' ? error : error && error.message,
        os: os.type(),
        os_platform: os.platform(),
        os_release: os.release(),
        node_version: process.version,
        version: scope.strapiVersion,
        docker: scope.docker,
        useYarn: scope.useYarn.toString(),
      },
    });
  } catch (err) {
    /** ignore errors*/
    return Promise.resolve();
  }
}

module.exports = {
  trackError,
  trackUsage,
  captureException,
  captureStderr,
};
<commit_msg>Add noRun property in global scope (#7030)<commit_after>'use strict';

const os = require('os');
const fetch = require('node-fetch');
const sentry = require('@sentry/node');

async function captureException(error) {
  try {
    sentry.captureException(error);
    await sentry.flush();
  } catch (err) {
    /** ignore errors*/
    return Promise.resolve();
  }
}

async function captureError(message) {
  try {
    sentry.captureMessage(message, 'error');
    await sentry.flush();
  } catch (err) {
    /** ignore errors*/
    return Promise.resolve();
  }
}

function captureStderr(name, error) {
  if (error && error.stderr && error.stderr.trim() !== '') {
    error.stderr
      .trim()
      .split('\n')
      .forEach(line => {
        sentry.addBreadcrumb({
          category: 'stderr',
          message: line,
          level: 'error',
        });
      });
  }

  return captureError(name);
}

function trackEvent(event, body) {
  try {
    return fetch('https://analytics.strapi.io/track', {
      method: 'POST',
      body: JSON.stringify({
        event,
        ...body,
      }),
      timeout: 1000,
      headers: { 'Content-Type': 'application/json' },
    }).catch(() => {});
  } catch (err) {
    /** ignore errors*/
    return Promise.resolve();
  }
}

function trackError({ scope, error }) {
  try {
    return trackEvent('didNotCreateProject', {
      uuid: scope.uuid,
      deviceId: scope.deviceId,
      properties: {
        error: typeof error == 'string' ? error : error && error.message,
        os: os.type(),
        platform: os.platform(),
        release: os.release(),
        version: scope.strapiVersion,
        nodeVersion: process.version,
        docker: scope.docker,
        useYarn: scope.useYarn,
      },
    });
  } catch (err) {
    /** ignore errors*/
    return Promise.resolve();
  }
}

function trackUsage({ event, scope, error }) {
  try {
    return trackEvent(event, {
      uuid: scope.uuid,
      deviceId: scope.deviceId,
      properties: {
        error: typeof error == 'string' ? error : error && error.message,
        os: os.type(),
        os_platform: os.platform(),
        os_release: os.release(),
        node_version: process.version,
        version: scope.strapiVersion,
        docker: scope.docker,
        useYarn: scope.useYarn.toString(),
        noRun: (scope.runQuickstartApp !== true).toString(),
      },
    });
  } catch (err) {
    /** ignore errors*/
    return Promise.resolve();
  }
}

module.exports = {
  trackError,
  trackUsage,
  captureException,
  captureStderr,
};
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react';
import {TransitionMotion, spring} from 'react-motion';

import Logo from 'components/Logo/Logo';
import Nav from './components/Nav';

import css from './styleguide.css';

const ROUTES = [
  'home',
  'colours',
  'type',
  'grids',
  'blocks',
  'buttons',
  'forms',
  'overlays',
  'panels',
  'icons',
];

let oldRouteName = '';
let newRouteName = '';

const physics = [160, 18];

export default class Styleguide extends React.Component {
  constructor(props) {
    super(props);
    this.getStyles = this.getStyles.bind(this);
    this.willEnter = this.willEnter.bind(this);
    this.willLeave = this.willLeave.bind(this);
  }

  componentWillMount() {
    if (this.props.children) {
      oldRouteName = this.props.children.props.location.pathname;
    }
  }
  componentWillReceiveProps(nextProps) {
    // Some dumb logic just so we know which transition to use
    if (!this.props.children && !nextProps.children) {
      oldRouteName = 'home';
      return;
    }

    if (!this.props.children) {
      oldRouteName = 'home';
      newRouteName = nextProps.children.props.location.pathname;
      return;
    }
    if (!nextProps.children) {
      oldRouteName = this.props.children.props.location.pathname;
      newRouteName = 'home';
      return;
    }
    const _oldRouteName = this.props.children.props.location.pathname;
    const _newRouteName = nextProps.children.props.location.pathname;
    if (_oldRouteName !== _newRouteName) {
      oldRouteName = _oldRouteName;
      newRouteName = _newRouteName;
    }
  }

  getStyles() {
    const {children} = this.props;
    return {
      [children.type.displayName]: {
        opacity: spring(1),
        x: spring(0, physics),
        child: children,
      },
    };
  }

  willEnter() {
    const {children} = this.props;
    const oldIndex = ROUTES.indexOf(oldRouteName.replace('/', ''));
    const newIndex = ROUTES.indexOf(newRouteName.replace('/', ''));
    return {
      opacity: spring(0),
      x: spring(newIndex > oldIndex ? 120 : -120, physics),
      child: children,
    };
  }

  willLeave(key, config) {
    const oldIndex = ROUTES.indexOf(oldRouteName.replace('/', ''));
    const newIndex = ROUTES.indexOf(newRouteName.replace('/', ''));
    return {
      opacity: spring(0),
      x: spring(newIndex > oldIndex ? -120 : 120, physics),
      child: config.child,
    };
  }

  render() {
    return (

            <Logo className={css.logo} size="small" type="horizontal"/>

              Loggins

          <TransitionMotion styles={this.getStyles()}
                            willEnter={this.willEnter}
                            willLeave={this.willLeave}>
            {interpolatedcss =>

                {Object.keys(interpolatedcss).map((key, i) => {
                  const {child, opacity, x} = interpolatedcss[key];
                  return (
                    <div key={i} style={{
                      opacity,
                      transform: `translate3d(${x}%, 0,0)`,
                    }}>
                      {child}

                  );
                })}

            }
          </TransitionMotion>

    );
  }
}

Styleguide.propTypes = {
  children: PropTypes.any,
};
<commit_msg>Fix wrong section order<commit_after>import React, {PropTypes} from 'react';
import {TransitionMotion, spring} from 'react-motion';

import Logo from 'components/Logo/Logo';
import Nav from './components/Nav';

import css from './styleguide.css';

const ROUTES = [
  'home',
  'colours',
  'type',
  'grids',
  'blocks',
  'buttons',
  'overlays',
  'forms',
  'panels',
  'icons',
];

let oldRouteName = '';
let newRouteName = '';

const physics = [160, 18];

export default class Styleguide extends React.Component {
  constructor(props) {
    super(props);
    this.getStyles = this.getStyles.bind(this);
    this.willEnter = this.willEnter.bind(this);
    this.willLeave = this.willLeave.bind(this);
  }

  componentWillMount() {
    if (this.props.children) {
      oldRouteName = this.props.children.props.location.pathname;
    }
  }
  componentWillReceiveProps(nextProps) {
    // Some dumb logic just so we know which transition to use
    if (!this.props.children && !nextProps.children) {
      oldRouteName = 'home';
      return;
    }

    if (!this.props.children) {
      oldRouteName = 'home';
      newRouteName = nextProps.children.props.location.pathname;
      return;
    }
    if (!nextProps.children) {
      oldRouteName = this.props.children.props.location.pathname;
      newRouteName = 'home';
      return;
    }
    const _oldRouteName = this.props.children.props.location.pathname;
    const _newRouteName = nextProps.children.props.location.pathname;
    if (_oldRouteName !== _newRouteName) {
      oldRouteName = _oldRouteName;
      newRouteName = _newRouteName;
    }
  }

  getStyles() {
    const {children} = this.props;
    return {
      [children.type.displayName]: {
        opacity: spring(1),
        x: spring(0, physics),
        child: children,
      },
    };
  }

  willEnter() {
    const {children} = this.props;
    const oldIndex = ROUTES.indexOf(oldRouteName.replace('/', ''));
    const newIndex = ROUTES.indexOf(newRouteName.replace('/', ''));
    return {
      opacity: spring(0),
      x: spring(newIndex > oldIndex ? 120 : -120, physics),
      child: children,
    };
  }

  willLeave(key, config) {
    const oldIndex = ROUTES.indexOf(oldRouteName.replace('/', ''));
    const newIndex = ROUTES.indexOf(newRouteName.replace('/', ''));
    return {
      opacity: spring(0),
      x: spring(newIndex > oldIndex ? -120 : 120, physics),
      child: config.child,
    };
  }

  render() {
    return (

            <Logo className={css.logo} size="small" type="horizontal"/>

              Loggins

          <TransitionMotion styles={this.getStyles()}
                            willEnter={this.willEnter}
                            willLeave={this.willLeave}>
            {interpolatedcss =>

                {Object.keys(interpolatedcss).map((key, i) => {
                  const {child, opacity, x} = interpolatedcss[key];
                  return (
                    <div key={i} style={{
                      opacity,
                      transform: `translate3d(${x}%, 0,0)`,
                    }}>
                      {child}

                  );
                })}

            }
          </TransitionMotion>

    );
  }
}

Styleguide.propTypes = {
  children: PropTypes.any,
};
<|endoftext|>


<commit_before>exports = module.exports = function(serializeClientCb, deserializeClientCb, s) {
  var StateStore = require('../lib/txn/state');

  var store = new StateStore(s);
  store.serializeClient(serializeClientCb);
  store.deserializeClient(deserializeClientCb);

  return store;
};

exports['@implements'] = 'http://schema.modulate.io/js/aaa/oauth2/TransactionStore';
exports['@singleton'] = true;
exports['@require'] = [
  './szx/serializeclientcb',
  './szx/deserializeclientcb',
  'http://i.bixbyjs.org/http/flows/StateStore'
];
<commit_msg>Use flowstate components for state storage.<commit_after>exports = module.exports = function(serializeClientCb, deserializeClientCb, s) {
  var StateStore = require('../lib/txn/state');

  var store = new StateStore(s);
  store.serializeClient(serializeClientCb);
  store.deserializeClient(deserializeClientCb);

  return store;
};

exports['@implements'] = 'http://schema.modulate.io/js/aaa/oauth2/TransactionStore';
exports['@singleton'] = true;
exports['@require'] = [
  './szx/serializeclientcb',
  './szx/deserializeclientcb',
  'http://i.bixbyjs.org/http/ua/flows/StateStore'
];
<|endoftext|>


<commit_before>/*global define*/
define([
        './defaultValue',
        './defined',
        './DeveloperError',
        './GeometryType',
        './PrimitiveType'
    ], function(
        defaultValue,
        defined,
        DeveloperError,
        GeometryType,
        PrimitiveType) {
    "use strict";

    /**
     * A geometry representation with attributes forming vertices and optional index data
     * defining primitives.  Geometries and an {@link Appearance}, which describes the shading,
     * can be assigned to a {@link Primitive} for visualization.  A Primitive can
     * be created from many heterogeneous - in many cases - geometries for performance.
     *

     * Geometries can be transformed and optimized using functions in {@link GeometryPipeline}.
     *

     *
     * @alias Geometry
     * @constructor
     *
     * @param {Object} options Object with the following properties:
     * @param {GeometryAttributes} options.attributes Attributes, which make up the geometry's vertices.
     * @param {PrimitiveType} [options.primitiveType=PrimitiveType.TRIANGLES] The type of primitives in the geometry.
     * @param {Uint16Array|Uint32Array} [options.indices] Optional index data that determines the primitives in the geometry.
     * @param {BoundingSphere} [options.boundingSphere] An optional bounding sphere that fully enclosed the geometry.
     *
     * @see PolygonGeometry
     * @see RectangleGeometry
     * @see EllipseGeometry
     * @see CircleGeometry
     * @see WallGeometry
     * @see SimplePolylineGeometry
     * @see BoxGeometry
     * @see EllipsoidGeometry
     *
     * @demo {@link http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Geometry%20and%20Appearances.html|Geometry and Appearances Demo}
     *
     * @example
     * // Create geometry with a position attribute and indexed lines.
     * var positions = new Float64Array([
     *   0.0, 0.0, 0.0,
     *   7500000.0, 0.0, 0.0,
     *   0.0, 7500000.0, 0.0
     * ]);
     *
     * var geometry = new Cesium.Geometry({
     *   attributes : {
     *     position : new Cesium.GeometryAttribute({
     *       componentDatatype : Cesium.ComponentDatatype.DOUBLE,
     *       componentsPerAttribute : 3,
     *       values : positions
     *     })
     *   },
     *   indices : new Uint16Array([0, 1, 1, 2, 2, 0]),
     *   primitiveType : Cesium.PrimitiveType.LINES,
     *   boundingSphere : Cesium.BoundingSphere.fromVertices(positions)
     * });
     */
    function Geometry(options) {
        options = defaultValue(options, defaultValue.EMPTY_OBJECT);

        //>>includeStart('debug', pragmas.debug);
        if (!defined(options.attributes)) {
            throw new DeveloperError('options.attributes is required.');
        }
        //>>includeEnd('debug');

        /**
         * Attributes, which make up the geometry's vertices.  Each property in this object corresponds to a
         * {@link GeometryAttribute} containing the attribute's data.
         *

         * Attributes are always stored non-interleaved in a Geometry.
         *

         *

         * There are reserved attribute names with well-known semantics.  The following attributes
         * are created by a Geometry (depending on the provided {@link VertexFormat}.
         *

         *
position - 3D vertex position.  64-bit floating-point (for precision).  3 components per attribute.  See {@link VertexFormat#position}.

         *
normal - Normal (normalized), commonly used for lighting.  32-bit floating-point.  3 components per attribute.  See {@link VertexFormat#normal}.

         *
st - 2D texture coordinate.  32-bit floating-point.  2 components per attribute.  See {@link VertexFormat#st}.

         *
binormal - Binormal (normalized), used for tangent-space effects like bump mapping.  32-bit floating-point.  3 components per attribute.  See {@link VertexFormat#binormal}.

         *
tangent - Tangent (normalized), used for tangent-space effects like bump mapping.  32-bit floating-point.  3 components per attribute.  See {@link VertexFormat#tangent}.

         *

         *

         *

         * The following attribute names are generally not created by a Geometry, but are added
         * to a Geometry by a {@link Primitive} or {@link GeometryPipeline} functions to prepare
         * the geometry for rendering.
         *

         *
position3DHigh - High 32 bits for encoded 64-bit position computed with {@link GeometryPipeline.encodeAttribute}.  32-bit floating-point.  4 components per attribute.

         *
position3DLow - Low 32 bits for encoded 64-bit position computed with {@link GeometryPipeline.encodeAttribute}.  32-bit floating-point.  4 components per attribute.

         *
position3DHigh - High 32 bits for encoded 64-bit 2D (Columbus view) position computed with {@link GeometryPipeline.encodeAttribute}.  32-bit floating-point.  4 components per attribute.

         *
position2DLow - Low 32 bits for encoded 64-bit 2D (Columbus view) position computed with {@link GeometryPipeline.encodeAttribute}.  32-bit floating-point.  4 components per attribute.

         *
color - RGBA color (normalized) usually from {@link GeometryInstance#color}.  32-bit floating-point.  4 components per attribute.

         *
pickColor - RGBA color used for picking.  32-bit floating-point.  4 components per attribute.

         *

         *

         *
         * @type GeometryAttributes
         *
         * @default undefined
         *
         *
         * @example
         * geometry.attributes.position = new Cesium.GeometryAttribute({
         *   componentDatatype : Cesium.ComponentDatatype.FLOAT,
         *   componentsPerAttribute : 3,
         *   values : new Float32Array(0)
         * });
         * @see GeometryAttribute
         * @see VertexFormat
         */
        this.attributes = options.attributes;

        /**
         * Optional index data that - along with {@link Geometry#primitiveType} -
         * determines the primitives in the geometry.
         *
         * @type Array
         *
         * @default undefined
         */
        this.indices = options.indices;

        /**
         * The type of primitives in the geometry.  This is most often {@link PrimitiveType.TRIANGLES},
         * but can varying based on the specific geometry.
         *
         * @type PrimitiveType
         *
         * @default undefined
         */
        this.primitiveType = defaultValue(options.primitiveType, PrimitiveType.TRIANGLES);

        /**
         * An optional bounding sphere that fully encloses the geometry.  This is
         * commonly used for culling.
         *
         * @type BoundingSphere
         *
         * @default undefined
         */
        this.boundingSphere = options.boundingSphere;

        /**
         * @private
         */
        this.geometryType = defaultValue(options.geometryType, GeometryType.NONE);

        /**
         * @private
         */
        this.boundingSphereCV = undefined;
    }

    /**
     * Computes the number of vertices in a geometry.  The runtime is linear with
     * respect to the number of attributes in a vertex, not the number of vertices.
     *
     * @param {Geometry} geometry The geometry.
     * @returns {Number} The number of vertices in the geometry.
     *
     * @example
     * var numVertices = Cesium.Geometry.computeNumberOfVertices(geometry);
     */
    Geometry.computeNumberOfVertices = function(geometry) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(geometry)) {
            throw new DeveloperError('geometry is required.');
        }
        //>>includeEnd('debug');

        var numberOfVertices = -1;
        for ( var property in geometry.attributes) {
            if (geometry.attributes.hasOwnProperty(property) &&
                    defined(geometry.attributes[property]) &&
                    defined(geometry.attributes[property].values)) {

                var attribute = geometry.attributes[property];
                var num = attribute.values.length / attribute.componentsPerAttribute;
                if ((numberOfVertices !== num) && (numberOfVertices !== -1)) {
                    throw new DeveloperError('All attribute lists must have the same number of attributes.');
                }
                numberOfVertices = num;
            }
        }

        return numberOfVertices;
    };

    return Geometry;
});
<commit_msg>Update Geometry.js<commit_after>/*global define*/
define([
        './defaultValue',
        './defined',
        './DeveloperError',
        './GeometryType',
        './PrimitiveType'
    ], function(
        defaultValue,
        defined,
        DeveloperError,
        GeometryType,
        PrimitiveType) {
    "use strict";

    /**
     * A geometry representation with attributes forming vertices and optional index data
     * defining primitives.  Geometries and an {@link Appearance}, which describes the shading,
     * can be assigned to a {@link Primitive} for visualization.  A Primitive can
     * be created from many heterogeneous - in many cases - geometries for performance.
     *

     * Geometries can be transformed and optimized using functions in {@link GeometryPipeline}.
     *

     *
     * @alias Geometry
     * @constructor
     *
     * @param {Object} options Object with the following properties:
     * @param {GeometryAttributes} options.attributes Attributes, which make up the geometry's vertices.
     * @param {PrimitiveType} [options.primitiveType=PrimitiveType.TRIANGLES] The type of primitives in the geometry.
     * @param {Uint16Array|Uint32Array} [options.indices] Optional index data that determines the primitives in the geometry.
     * @param {BoundingSphere} [options.boundingSphere] An optional bounding sphere that fully enclosed the geometry.
     *
     * @see PolygonGeometry
     * @see RectangleGeometry
     * @see EllipseGeometry
     * @see CircleGeometry
     * @see WallGeometry
     * @see SimplePolylineGeometry
     * @see BoxGeometry
     * @see EllipsoidGeometry
     *
     * @demo {@link http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Geometry%20and%20Appearances.html|Geometry and Appearances Demo}
     *
     * @example
     * // Create geometry with a position attribute and indexed lines.
     * var positions = new Float64Array([
     *   0.0, 0.0, 0.0,
     *   7500000.0, 0.0, 0.0,
     *   0.0, 7500000.0, 0.0
     * ]);
     *
     * var geometry = new Cesium.Geometry({
     *   attributes : {
     *     position : new Cesium.GeometryAttribute({
     *       componentDatatype : Cesium.ComponentDatatype.DOUBLE,
     *       componentsPerAttribute : 3,
     *       values : positions
     *     })
     *   },
     *   indices : new Uint16Array([0, 1, 1, 2, 2, 0]),
     *   primitiveType : Cesium.PrimitiveType.LINES,
     *   boundingSphere : Cesium.BoundingSphere.fromVertices(positions)
     * });
     */
    function Geometry(options) {
        options = defaultValue(options, defaultValue.EMPTY_OBJECT);

        //>>includeStart('debug', pragmas.debug);
        if (!defined(options.attributes)) {
            throw new DeveloperError('options.attributes is required.');
        }
        //>>includeEnd('debug');

        /**
         * Attributes, which make up the geometry's vertices.  Each property in this object corresponds to a
         * {@link GeometryAttribute} containing the attribute's data.
         *

         * Attributes are always stored non-interleaved in a Geometry.
         *

         *

         * There are reserved attribute names with well-known semantics.  The following attributes
         * are created by a Geometry (depending on the provided {@link VertexFormat}.
         *

         *
position - 3D vertex position.  64-bit floating-point (for precision).  3 components per attribute.  See {@link VertexFormat#position}.

         *
normal - Normal (normalized), commonly used for lighting.  32-bit floating-point.  3 components per attribute.  See {@link VertexFormat#normal}.

         *
st - 2D texture coordinate.  32-bit floating-point.  2 components per attribute.  See {@link VertexFormat#st}.

         *
binormal - Binormal (normalized), used for tangent-space effects like bump mapping.  32-bit floating-point.  3 components per attribute.  See {@link VertexFormat#binormal}.

         *
tangent - Tangent (normalized), used for tangent-space effects like bump mapping.  32-bit floating-point.  3 components per attribute.  See {@link VertexFormat#tangent}.

         *

         *

         *

         * The following attribute names are generally not created by a Geometry, but are added
         * to a Geometry by a {@link Primitive} or {@link GeometryPipeline} functions to prepare
         * the geometry for rendering.
         *

         *
position3DHigh - High 32 bits for encoded 64-bit position computed with {@link GeometryPipeline.encodeAttribute}.  32-bit floating-point.  4 components per attribute.

         *
position3DLow - Low 32 bits for encoded 64-bit position computed with {@link GeometryPipeline.encodeAttribute}.  32-bit floating-point.  4 components per attribute.

         *
position3DHigh - High 32 bits for encoded 64-bit 2D (Columbus view) position computed with {@link GeometryPipeline.encodeAttribute}.  32-bit floating-point.  4 components per attribute.

         *
position2DLow - Low 32 bits for encoded 64-bit 2D (Columbus view) position computed with {@link GeometryPipeline.encodeAttribute}.  32-bit floating-point.  4 components per attribute.

         *
color - RGBA color (normalized) usually from {@link GeometryInstance#color}.  32-bit floating-point.  4 components per attribute.

         *
pickColor - RGBA color used for picking.  32-bit floating-point.  4 components per attribute.

         *

         *

         *
         * @type GeometryAttributes
         *
         * @default undefined
         *
         *
         * @example
         * geometry.attributes.position = new Cesium.GeometryAttribute({
         *   componentDatatype : Cesium.ComponentDatatype.FLOAT,
         *   componentsPerAttribute : 3,
         *   values : new Float32Array(0)
         * });
         *
         * @see GeometryAttribute
         * @see VertexFormat
         */
        this.attributes = options.attributes;

        /**
         * Optional index data that - along with {@link Geometry#primitiveType} -
         * determines the primitives in the geometry.
         *
         * @type Array
         *
         * @default undefined
         */
        this.indices = options.indices;

        /**
         * The type of primitives in the geometry.  This is most often {@link PrimitiveType.TRIANGLES},
         * but can varying based on the specific geometry.
         *
         * @type PrimitiveType
         *
         * @default undefined
         */
        this.primitiveType = defaultValue(options.primitiveType, PrimitiveType.TRIANGLES);

        /**
         * An optional bounding sphere that fully encloses the geometry.  This is
         * commonly used for culling.
         *
         * @type BoundingSphere
         *
         * @default undefined
         */
        this.boundingSphere = options.boundingSphere;

        /**
         * @private
         */
        this.geometryType = defaultValue(options.geometryType, GeometryType.NONE);

        /**
         * @private
         */
        this.boundingSphereCV = undefined;
    }

    /**
     * Computes the number of vertices in a geometry.  The runtime is linear with
     * respect to the number of attributes in a vertex, not the number of vertices.
     *
     * @param {Geometry} geometry The geometry.
     * @returns {Number} The number of vertices in the geometry.
     *
     * @example
     * var numVertices = Cesium.Geometry.computeNumberOfVertices(geometry);
     */
    Geometry.computeNumberOfVertices = function(geometry) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(geometry)) {
            throw new DeveloperError('geometry is required.');
        }
        //>>includeEnd('debug');

        var numberOfVertices = -1;
        for ( var property in geometry.attributes) {
            if (geometry.attributes.hasOwnProperty(property) &&
                    defined(geometry.attributes[property]) &&
                    defined(geometry.attributes[property].values)) {

                var attribute = geometry.attributes[property];
                var num = attribute.values.length / attribute.componentsPerAttribute;
                if ((numberOfVertices !== num) && (numberOfVertices !== -1)) {
                    throw new DeveloperError('All attribute lists must have the same number of attributes.');
                }
                numberOfVertices = num;
            }
        }

        return numberOfVertices;
    };

    return Geometry;
});
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies
 */
var acl = require('acl');

// Using the memory backend
acl = new acl(new acl.memoryBackend());

/**
 * Invoke Polls Permissions
 */
exports.invokeRolesPolicies = function() {
  acl.allow([{
    roles: ['admin'],
    allows: [{
      resources: '/api/polls',
      permissions: '*'
    }, {
      resources: '/api/polls/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findOpts/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findCmts/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findTags/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findVotes/:pollId',findOwnerVote
      permissions: '*'
    }, {
      resources: '/api/findOwnerVote/:pollId',
      permissions: '*'
    }]
  }, {
    roles: ['user'],
    allows: [{
      resources: '/api/polls',
      permissions: ['get', 'post']
    }, {
      resources: '/api/polls/:pollId',
      permissions: ['get', 'put']
    }, {
      resources: '/api/findOpts/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findCmts/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findTags/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findVotes/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findOwnerVote/:pollId',
      permissions: '*'
    }]
  }, {
    roles: ['guest'],
    allows: [{
      resources: '/api/polls',
      permissions: ['get']
    }, {
      resources: '/api/polls/:pollId',
      permissions: ['get']
    }, {
      resources: '/api/findOpts/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findCmts/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findTags/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findVotes/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findOwnerVote/:pollId',
      permissions: '*'
    }]
  }]);
};

/**
 * Check If Polls Policy Allows
 */
exports.isAllowed = function(req, res, next) {
  var roles = (req.user) ? req.user.roles : ['guest'];

  // If an Poll is being processed and the current user created it then allow any manipulation
  if (req.poll && req.user && req.poll.user && req.poll.user.id === req.user.id) {
    return next();
  }

  // Check for user roles
  acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function(err, isAllowed) {
    if (err) {
      // An authorization error occurred
      return res.status(500).send('Unexpected authorization error');
    } else {
      if (isAllowed) {
        // Access granted! Invoke next middleware
        return next();
      } else {
        return res.status(403).json({
          message: 'User is not authorized'
        });
      }
    }
  });
};
<commit_msg>Commited from lenh at 2017年 6月 20日 火曜日 11:46:23<commit_after>'use strict';

/**
 * Module dependencies
 */
var acl = require('acl');

// Using the memory backend
acl = new acl(new acl.memoryBackend());

/**
 * Invoke Polls Permissions
 */
exports.invokeRolesPolicies = function() {
  acl.allow([{
    roles: ['admin'],
    allows: [{
      resources: '/api/polls',
      permissions: '*'
    }, {
      resources: '/api/polls/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findOpts/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findCmts/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findTags/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findVotes/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findOwnerVote/:pollId',
      permissions: '*'
    }]
  }, {
    roles: ['user'],
    allows: [{
      resources: '/api/polls',
      permissions: ['get', 'post']
    }, {
      resources: '/api/polls/:pollId',
      permissions: ['get', 'put']
    }, {
      resources: '/api/findOpts/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findCmts/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findTags/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findVotes/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findOwnerVote/:pollId',
      permissions: '*'
    }]
  }, {
    roles: ['guest'],
    allows: [{
      resources: '/api/polls',
      permissions: ['get']
    }, {
      resources: '/api/polls/:pollId',
      permissions: ['get']
    }, {
      resources: '/api/findOpts/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findCmts/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findTags/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findVotes/:pollId',
      permissions: '*'
    }, {
      resources: '/api/findOwnerVote/:pollId',
      permissions: '*'
    }]
  }]);
};

/**
 * Check If Polls Policy Allows
 */
exports.isAllowed = function(req, res, next) {
  var roles = (req.user) ? req.user.roles : ['guest'];

  // If an Poll is being processed and the current user created it then allow any manipulation
  if (req.poll && req.user && req.poll.user && req.poll.user.id === req.user.id) {
    return next();
  }

  // Check for user roles
  acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function(err, isAllowed) {
    if (err) {
      // An authorization error occurred
      return res.status(500).send('Unexpected authorization error');
    } else {
      if (isAllowed) {
        // Access granted! Invoke next middleware
        return next();
      } else {
        return res.status(403).json({
          message: 'User is not authorized'
        });
      }
    }
  });
};
<|endoftext|>


<commit_before>#!/usr/bin/env babel-node

const board = require("./board.js")
const Board = board.Board

// Testing

function testEq(name, foo, bar) {
  if (foo != bar) {
    throw ("in " + name + " test: " + foo + " != " + bar)
  }
}

var b = new Board()
testEq("pieceForSquare", "K", b.pieceForSquare("e1"))
testEq("colorForCoords", board.WHITE, b.colorForCoords(6, 1))
testEq("colorForCoords", board.BLACK, b.colorForCoords(3, 7))
testEq("colorForCoords", board.EMPTY, b.colorForCoords(2, 2))
testEq("knightMoves", 2, b.knightMoves(1, 0).length)
testEq("kingMoves", 0, b.kingMoves(4, 0).length)
testEq("bishopMoves", 8, b.bishopMoves(3, 3).length)
testEq("rookMoves", 11, b.rookMoves(3, 3).length)
testEq("queenMoves", 19, b.queenMoves(3, 3).length)
testEq("validMovesIgnoringCheck", 20, b.validMovesIgnoringCheck().length)
testEq("movesIntoCheck", false, b.movesIntoCheck(0, 1, 0, 2))
testEq("validMoves", 20, b.validMoves().length)
testEq("isValidMove", true, b.isValidMove(0, 1, 0, 3))

board.testCheckmate("scholars mate", [
  "e2e4", "e7e5",
  "f1c4", "h7h6",
  "d1f3", "h6h5",
  "f3f7"])

board.testCheckmate("fools mate", [
  "f2f4", "e7e5",
  "g2g4", "d8h4"])

board.testCheckmate("kingside castling", [
  "e2e4", "e7e5",
  "f1c4", "f8c5",
  "d2d3", "g8f6",
  "d1g4", "e8g8",
  "c1h6", "a7a5",
  "g4g7"])

board.testCheckmate("en passant", [
  "e2e3", "e7e5",
  "f1c4", "e5e4",
  "d2d4", "e4d3",
  "d1f3", "a7a5",
  "f3f7"])

board.newBoard("queenside castling", [
  "d2d4", "d7d5",
  "d1d3", "d8d6",
  "c1d2", "c8d7",
  "b1c3", "b8c6",
  "e1c1", "e8c8"])

board.newBoard("kingside castling moves rook", [
  "e2e4", "e7e5",
  "f1e2", "f8e7",
  "g1f3", "g8f6",
  "e1g1", "e8g8",
  "f1e1", "f8e8"])

board.newBoard("queenside castling moves rook", [
  "d2d4", "d7d5",
  "d1d3", "d8d6",
  "c1e3", "c8e6",
  "b1c3", "b8c6",
  "e1c1", "e8c8",
  "d1e1", "d8e8"])

var b = board.newBoard("validMovesFrom includes captures", [
  "e2e4", "d7d5"])
testEq("ed is valid", true, b.isValidMove(4, 3, 3, 4))
testEq("two valid pawn moves", 2, b.validMovesFrom(4, 3).length)
<commit_msg>caught a bug<commit_after>#!/usr/bin/env babel-node

const board = require("./board.js")
const Board = board.Board

// Testing

function testEq(name, foo, bar) {
  if (foo != bar) {
    throw ("in " + name + " test: " + foo + " != " + bar)
  }
}

var b = new Board()
testEq("pieceForSquare", "K", b.pieceForSquare("e1"))
testEq("colorForCoords", board.WHITE, b.colorForCoords(6, 1))
testEq("colorForCoords", board.BLACK, b.colorForCoords(3, 7))
testEq("colorForCoords", board.EMPTY, b.colorForCoords(2, 2))
testEq("knightMoves", 2, b.knightMoves(1, 0).length)
testEq("kingMoves", 0, b.kingMoves(4, 0).length)
testEq("bishopMoves", 8, b.bishopMoves(3, 3).length)
testEq("rookMoves", 11, b.rookMoves(3, 3).length)
testEq("queenMoves", 19, b.queenMoves(3, 3).length)
testEq("validMovesIgnoringCheck", 20, b.validMovesIgnoringCheck().length)
testEq("movesIntoCheck", false, b.movesIntoCheck(0, 1, 0, 2))
testEq("validMoves", 20, b.validMoves().length)
testEq("isValidMove", true, b.isValidMove(0, 1, 0, 3))

board.testCheckmate("scholars mate", [
  "e2e4", "e7e5",
  "f1c4", "h7h6",
  "d1f3", "h6h5",
  "f3f7"])

board.testCheckmate("fools mate", [
  "f2f4", "e7e5",
  "g2g4", "d8h4"])

board.testCheckmate("kingside castling", [
  "e2e4", "e7e5",
  "f1c4", "f8c5",
  "d2d3", "g8f6",
  "d1g4", "e8g8",
  "c1h6", "a7a5",
  "g4g7"])

board.testCheckmate("en passant", [
  "e2e3", "e7e5",
  "f1c4", "e5e4",
  "d2d4", "e4d3",
  "d1f3", "a7a5",
  "f3f7"])

board.newBoard("queenside castling", [
  "d2d4", "d7d5",
  "d1d3", "d8d6",
  "c1d2", "c8d7",
  "b1c3", "b8c6",
  "e1c1", "e8c8"])

board.newBoard("kingside castling moves rook", [
  "e2e4", "e7e5",
  "f1e2", "f8e7",
  "g1f3", "g8f6",
  "e1g1", "e8g8",
  "f1e1", "f8e8"])

board.newBoard("queenside castling moves rook", [
  "d2d4", "d7d5",
  "d1d3", "d8d6",
  "c1e3", "c8e6",
  "b1c3", "b8c6",
  "e1c1", "e8c8",
  "d1e1", "d8e8"])

board.newBoard("white castling after black moves king", [
  "e2e4", "e7e5",
  "f1e2", "f8d6",
  "g1f3", "e8e7",
  "e1g1"])

var b = board.newBoard("validMovesFrom includes captures", [
  "e2e4", "d7d5"])
testEq("ed is valid", true, b.isValidMove(4, 3, 3, 4))
testEq("two valid pawn moves", 2, b.validMovesFrom(4, 3).length)
<|endoftext|>


<commit_before>// 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.

define([
       "app",

       // Modules
       "addons/fauxton/base",
       "spin"
],

function(app, Fauxton) {
  var FauxtonAPI = app.module();

  FauxtonAPI.moduleExtensions = {
    Routes: {
    }
  };

  FauxtonAPI.addonExtensions = {
    initialize: function() {}
  };

  // List of JSHINT errors to ignore
  // Gets around problem of anonymous functions not being a valid statement
  FauxtonAPI.excludedViewErrors = [
    "Missing name in function declaration.",
    "['{a}'] is better written in dot notation."
  ];

  FauxtonAPI.isIgnorableError = function(msg) {
    return _.contains(FauxtonAPI.excludedViewErrors, msg);
  };

  FauxtonAPI.View = Backbone.View.extend({
    // This should return an array of promises, an empty array, or null
    establish: function() {
      return null;
    },

    loaderClassname: 'loader',

    disableLoader: false,

    forceRender: function () {
      this.hasRendered = false;
    }
  });

  FauxtonAPI.navigate = function(url, _opts) {
    var options = _.extend({trigger: true}, _opts );
    app.router.navigate(url,options);
  };

  FauxtonAPI.beforeUnload = function () {
    app.router.beforeUnload.apply(app.router, arguments);
  };

  FauxtonAPI.removeBeforeUnload = function () {
    app.router.removeBeforeUnload.apply(app.router, arguments);
  };

  FauxtonAPI.addHeaderLink = function(link) {
    app.masterLayout.navBar.addLink(link);
  };

  FauxtonAPI.removeHeaderLink = function(link) {
    app.masterLayout.navBar.removeLink(link);
  };

  FauxtonAPI.Deferred = function() {
    return $.Deferred();
  };

  FauxtonAPI.when = function (deferreds) {
    if (deferreds instanceof Array) {
      return $.when.apply(null, deferreds);
    }

    return $.when(deferreds);
  };

  FauxtonAPI.addRoute = function(route) {
    app.router.route(route.route, route.name, route.callback);
  };

  FauxtonAPI.triggerRouteEvent = function (routeEvent, args) {
    app.router.triggerRouteEvent("route:"+routeEvent, args);
  };

  FauxtonAPI.module = function(extra) {
    return app.module(_.extend(FauxtonAPI.moduleExtensions, extra));
  };

  FauxtonAPI.addon = function(extra) {
    return FauxtonAPI.module(FauxtonAPI.addonExtensions, extra);
  };

  FauxtonAPI.addNotification = function(options) {
    options = _.extend({
      msg: "Notification Event Triggered!",
      type: "info",
      selector: "#global-notifications"
    }, options);
    var view = new Fauxton.Notification(options);

    return view.renderNotification();
  };

  FauxtonAPI.UUID = Backbone.Model.extend({
    initialize: function(options) {
      options = _.extend({count: 1}, options);
      this.count = options.count;
    },

    url: function() {
      return app.host + "/_uuids?count=" + this.count;
    },

    next: function() {
      return this.get("uuids").pop();
    }
  });

  FauxtonAPI.Session = Backbone.Model.extend({
    url: app.host + '/_session',

    user: function () {
      var userCtx = this.get('userCtx');

      if (!userCtx || !userCtx.name) { return null; }

      return {
        name: userCtx.name,
        roles: userCtx.roles
      };
    },

    fetchOnce: function (opt) {
      var options = _.extend({}, opt);

      if (!this._deferred || this._deferred.state() === "rejected" || options.forceFetch ) {
        this._deferred = this.fetch();
      }

      return this._deferred;
    },

    fetchUser: function (opt) {
      var that = this,
      currentUser = this.user();

      return this.fetchOnce(opt).then(function () {
        var user = that.user();

        // Notify anyone listening on these events that either a user has changed
        // or current user is the same
        if (currentUser !== user) {
          that.trigger('session:userChanged');
        } else {
          that.trigger('session:userFetched');
        }

        // this will return the user as a value to all function that calls done on this
        // eg. session.fetchUser().done(user) { .. do something with user ..}
        return user;
      });
    }
  });

  FauxtonAPI.setSession = function (newSession) {
    app.session = FauxtonAPI.session = newSession;
    return FauxtonAPI.session.fetchUser();
  };

  FauxtonAPI.setSession(new FauxtonAPI.Session());

  // This is not exposed externally as it should not need to be accessed or overridden
  var Auth = function (options) {
    this._options = options;
    this.initialize.apply(this, arguments);
  };

  // Piggy-back on Backbone's self-propagating extend function,
  Auth.extend = Backbone.Model.extend;

  _.extend(Auth.prototype, Backbone.Events, {
    authDeniedCb: function() {},

    initialize: function() {
      var that = this;
    },

    authHandlerCb : function (roles) {
      var deferred = $.Deferred();
      deferred.resolve();
      return deferred;
    },

    registerAuth: function (authHandlerCb) {
      this.authHandlerCb = authHandlerCb;
    },

    registerAuthDenied: function (authDeniedCb) {
      this.authDeniedCb = authDeniedCb;
    },

    checkAccess: function (roles) {
      var requiredRoles = roles || [],
      that = this;

      return FauxtonAPI.session.fetchUser().then(function (user) {
        return FauxtonAPI.when(that.authHandlerCb(FauxtonAPI.session, requiredRoles));
      });
    }
  });

  FauxtonAPI.auth = new Auth();

  FauxtonAPI.RouteObject = function(options) {
    this._options = options;

    this._configure(options || {});
    this.initialize.apply(this, arguments);
    this.addEvents();
  };

  var broadcaster = {};
  _.extend(broadcaster, Backbone.Events);

  FauxtonAPI.RouteObject.on = function (eventName, fn) {
    broadcaster.on(eventName, fn);
  };

  /* How Route Object events work
   To listen to a specific route objects events:

   myRouteObject = FauxtonAPI.RouteObject.extend({
    events: {
      "beforeRender": "beforeRenderEvent"
    },

    beforeRenderEvent: function (view, selector) {
      console.log('Hey, beforeRenderEvent triggered',arguments);
    },
   });

    It is also possible to listen to events triggered from all Routeobjects.
    This is great for more general things like adding loaders, hooks.

    FauxtonAPI.RouteObject.on('beforeRender', function (routeObject, view, selector) {
      console.log('hey, this will trigger when any routeobject renders a view');
    });

   Current Events to subscribe to:
    * beforeFullRender -- before a full render is being done
    * beforeEstablish -- before the routeobject calls establish
    * AfterEstablish -- after the routeobject has run establish
    * beforeRender -- before a view is rendered
    * afterRender -- a view is finished being rendered
    * renderComplete -- all rendering is complete

  */

  // Piggy-back on Backbone's self-propagating extend function
  FauxtonAPI.RouteObject.extend = Backbone.Model.extend;

  var routeObjectOptions = ["views", "routes", "events", "roles", "crumbs", "layout", "apiUrl", "establish"];

  _.extend(FauxtonAPI.RouteObject.prototype, Backbone.Events, {
    // Should these be default vals or empty funcs?
    views: {},
    routes: {},
    events: {},
    crumbs: [],
    layout: "with_sidebar",
    apiUrl: null,
    disableLoader: false,
    loaderClassname: 'loader',
    renderedState: false,
    establish: function() {},
    route: function() {},
    roles: [],
    _promises: [],
    initialize: function() {}
  }, {

    renderWith: function(route, masterLayout, args) {
      var routeObject = this,
          triggerBroadcast = _.bind(this.triggerBroadcast, this);

      // Only want to redo the template if its a full render
      if (!this.renderedState) {
        masterLayout.setTemplate(this.layout);
        triggerBroadcast('beforeFullRender');
        $('#primary-navbar li').removeClass('active');

        if (this.selectedHeader) {
          app.selectedHeader = this.selectedHeader;
          $('#primary-navbar li[data-nav-name="' + this.selectedHeader + '"]').addClass('active');
        }
      }

      masterLayout.clearBreadcrumbs();
      var crumbs = this.get('crumbs');

      if (crumbs.length) {
        masterLayout.setBreadcrumbs(new Fauxton.Breadcrumbs({
          crumbs: crumbs
        }));
      }

      triggerBroadcast('beforeEstablish');
      var establishPromise = this.establish();
      this.addPromise(establishPromise);
      FauxtonAPI.when(establishPromise).then(function(resp) {
        triggerBroadcast('afterEstablish');
        _.each(routeObject.getViews(), function(view, selector) {
          if(view.hasRendered) {
            triggerBroadcast('viewHasRendered', view, selector);
            return;
          }

          triggerBroadcast('beforeRender', view, selector);
          var viewPromise = view.establish();
          routeObject.addPromise(viewPromise);
          FauxtonAPI.when(view.establish()).then(function(resp) {
            masterLayout.setView(selector, view);

            masterLayout.renderView(selector);
            triggerBroadcast('afterRender', view, selector);
            }, function(resp) {
              view.establishError = {
                error: true,
                reason: resp
              };

              if (resp && resp.responseText) {
                var errorText = JSON.parse(resp.responseText).reason;
                FauxtonAPI.addNotification({
                  msg: 'An Error occurred: ' + errorText,
                  type: 'error',
                  clear: true
                });
              }

              masterLayout.renderView(selector);
          });

        });
      }.bind(this), function (resp) {
          if (!resp || !resp.responseText) { return; }
          FauxtonAPI.addNotification({
                msg: 'An Error occurred' + JSON.parse(resp.responseText).reason,
                type: 'error',
                clear: true
          });
      });

      if (this.get('apiUrl')){
        masterLayout.apiBar.update(this.get('apiUrl'));
      } else {
        masterLayout.apiBar.hide();
      }

      // Track that we've done a full initial render
      this.renderedState = true;
      triggerBroadcast('renderComplete');
    },

    triggerBroadcast: function (eventName) {
      var args = Array.prototype.slice.call(arguments);
      this.trigger.apply(this, args);

      args.splice(0,1, eventName, this);
      broadcaster.trigger.apply(broadcaster, args);
    },

    get: function(key) {
      return _.isFunction(this[key]) ? this[key]() : this[key];
    },

    addEvents: function(events) {
      events = events || this.get('events');
      _.each(events, function(method, event) {
        if (!_.isFunction(method) && !_.isFunction(this[method])) {
          throw new Error("Invalid method: "+method);
        }
        method = _.isFunction(method) ? method : this[method];

        this.on(event, method);
      }, this);
    },

    _configure: function(options) {
      _.each(_.intersection(_.keys(options), routeObjectOptions), function(key) {
        this[key] = options[key];
      }, this);
    },

    getView: function(selector) {
      return this.views[selector];
    },

    setView: function(selector, view) {
      this.views[selector] = view;
      return view;
    },

    getViews: function() {
      return this.views;
    },

    removeViews: function () {
      _.each(this.views, function (view, selector) {
        view.remove();
        delete this.views[selector];
      }, this);
    },

    addPromise: function (promise) {
      if (_.isEmpty(promise)) { return; }

      if (_.isArray(promise)) {
        return _.each(promise, function (p) {
          this._promises.push(p);
        }, this);
      }

     this._promises.push(promise);
    },

    cleanup: function () {
      this.removeViews();
      this.rejectPromises();
    },

    rejectPromises: function () {
      _.each(this._promises, function (promise) {
        if (promise.state() === "resolved") { return; }
        if (promise.abort) {
          return promise.abort("Route change");
        }

        promise.reject();
      }, this);

      this._promises = [];
    },

    getRouteUrls: function () {
      return _.keys(this.get('routes'));
    },

    hasRoute: function (route) {
      if (this.get('routes')[route]) {
        return true;
      }
      return false;
    },

    routeCallback: function (route, args) {
      var routes = this.get('routes'),
      routeObj = routes[route],
      routeCallback;

      if (typeof routeObj === 'object') {
        routeCallback = this[routeObj.route];
      } else {
        routeCallback = this[routeObj];
      }

      routeCallback.apply(this, args);
    },

    getRouteRoles: function (routeUrl) {
      var route = this.get('routes')[routeUrl];

      if ((typeof route === 'object') && route.roles) {
        return route.roles;
      }

      return this.roles;
    }

  });

  // We could look at moving the spinner code out to its own module
  var routeObjectSpinner;
  FauxtonAPI.RouteObject.on('beforeEstablish', function (routeObject) {
    if (!routeObject.disableLoader){
      var opts = {
        lines: 16, // The number of lines to draw
        length: 8, // The length of each line
        width: 4, // The line thickness
        radius: 12, // The radius of the inner circle
        color: '#333', // #rbg or #rrggbb
        speed: 1, // Rounds per second
        trail: 10, // Afterglow percentage
        shadow: false // Whether to render a shadow
     };

     if (!$('.spinner').length) {
       $('

')
        .appendTo('#app-container');
     }

     routeObjectSpinner = new Spinner(opts).spin();
     $('.spinner').append(routeObjectSpinner.el);
   }
  });

  var removeRouteObjectSpinner = function () {
    if (routeObjectSpinner) {
      routeObjectSpinner.stop();
      $('.spinner').remove();
    }
  };

  var removeViewSpinner = function () {
    if (viewSpinner){
      viewSpinner.stop();
      $('.spinner').remove();
    }
  };

  var viewSpinner;
  FauxtonAPI.RouteObject.on('beforeRender', function (routeObject, view, selector) {
    removeRouteObjectSpinner();

    if (!view.disableLoader){
      var opts = {
        lines: 16, // The number of lines to draw
        length: 8, // The length of each line
        width: 4, // The line thickness
        radius: 12, // The radius of the inner circle
        color: '#333', // #rbg or #rrggbb
        speed: 1, // Rounds per second
        trail: 10, // Afterglow percentage
        shadow: false // Whether to render a shadow
      };

      viewSpinner = new Spinner(opts).spin();
      $('

')
        .appendTo(selector)
        .append(viewSpinner.el);
    }
  });

  FauxtonAPI.RouteObject.on('afterRender', function (routeObject, view, selector) {
    removeViewSpinner();
  });

  FauxtonAPI.RouteObject.on('viewHasRendered', function () {
    removeViewSpinner();
    removeRouteObjectSpinner();
  });

  var extensions = _.extend({}, Backbone.Events);
  // Can look at a remove function later.
  FauxtonAPI.registerExtension = function (name, view) {
    if (!extensions[name]) {
      extensions[name] = [];
    }

    extensions.trigger('add:' + name, view);
    extensions[name].push(view);
  };

  FauxtonAPI.getExtensions = function (name) {
    var views = extensions[name];

    if (!views) {
      views = [];
    }

    return views;
  };

  FauxtonAPI.extensions = extensions;

  app.fauxtonAPI = FauxtonAPI;
  return app.fauxtonAPI;
});
<commit_msg>Testing and improvements<commit_after>// 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.

define([
       "app",

       // Modules
       "addons/fauxton/base",
       "spin"
],

function(app, Fauxton) {
  var FauxtonAPI = app.module();

  FauxtonAPI.moduleExtensions = {
    Routes: {
    }
  };

  FauxtonAPI.addonExtensions = {
    initialize: function() {}
  };

  // List of JSHINT errors to ignore
  // Gets around problem of anonymous functions not being a valid statement
  FauxtonAPI.excludedViewErrors = [
    "Missing name in function declaration.",
    "['{a}'] is better written in dot notation."
  ];

  FauxtonAPI.isIgnorableError = function(msg) {
    return _.contains(FauxtonAPI.excludedViewErrors, msg);
  };

  FauxtonAPI.View = Backbone.View.extend({
    // This should return an array of promises, an empty array, or null
    establish: function() {
      return null;
    },

    loaderClassname: 'loader',

    disableLoader: false,

    forceRender: function () {
      this.hasRendered = false;
    }
  });

  FauxtonAPI.navigate = function(url, _opts) {
    var options = _.extend({trigger: true}, _opts );
    app.router.navigate(url,options);
  };

  FauxtonAPI.beforeUnload = function () {
    app.router.beforeUnload.apply(app.router, arguments);
  };

  FauxtonAPI.removeBeforeUnload = function () {
    app.router.removeBeforeUnload.apply(app.router, arguments);
  };

  FauxtonAPI.addHeaderLink = function(link) {
    app.masterLayout.navBar.addLink(link);
  };

  FauxtonAPI.removeHeaderLink = function(link) {
    app.masterLayout.navBar.removeLink(link);
  };

  FauxtonAPI.Deferred = function() {
    return $.Deferred();
  };

  FauxtonAPI.when = function (deferreds) {
    if (deferreds instanceof Array) {
      return $.when.apply(null, deferreds);
    }

    return $.when(deferreds);
  };

  FauxtonAPI.addRoute = function(route) {
    app.router.route(route.route, route.name, route.callback);
  };

  FauxtonAPI.triggerRouteEvent = function (routeEvent, args) {
    app.router.triggerRouteEvent("route:"+routeEvent, args);
  };

  FauxtonAPI.module = function(extra) {
    return app.module(_.extend(FauxtonAPI.moduleExtensions, extra));
  };

  FauxtonAPI.addon = function(extra) {
    return FauxtonAPI.module(FauxtonAPI.addonExtensions, extra);
  };

  FauxtonAPI.addNotification = function(options) {
    options = _.extend({
      msg: "Notification Event Triggered!",
      type: "info",
      selector: "#global-notifications"
    }, options);
    var view = new Fauxton.Notification(options);

    return view.renderNotification();
  };

  FauxtonAPI.UUID = Backbone.Model.extend({
    initialize: function(options) {
      options = _.extend({count: 1}, options);
      this.count = options.count;
    },

    url: function() {
      return app.host + "/_uuids?count=" + this.count;
    },

    next: function() {
      return this.get("uuids").pop();
    }
  });

  FauxtonAPI.Session = Backbone.Model.extend({
    url: app.host + '/_session',

    user: function () {
      var userCtx = this.get('userCtx');

      if (!userCtx || !userCtx.name) { return null; }

      return {
        name: userCtx.name,
        roles: userCtx.roles
      };
    },

    fetchOnce: function (opt) {
      var options = _.extend({}, opt);

      if (!this._deferred || this._deferred.state() === "rejected" || options.forceFetch ) {
        this._deferred = this.fetch();
      }

      return this._deferred;
    },

    fetchUser: function (opt) {
      var that = this,
      currentUser = this.user();

      return this.fetchOnce(opt).then(function () {
        var user = that.user();

        // Notify anyone listening on these events that either a user has changed
        // or current user is the same
        if (currentUser !== user) {
          that.trigger('session:userChanged');
        } else {
          that.trigger('session:userFetched');
        }

        // this will return the user as a value to all function that calls done on this
        // eg. session.fetchUser().done(user) { .. do something with user ..}
        return user;
      });
    }
  });

  FauxtonAPI.setSession = function (newSession) {
    app.session = FauxtonAPI.session = newSession;
    return FauxtonAPI.session.fetchUser();
  };

  FauxtonAPI.setSession(new FauxtonAPI.Session());

  // This is not exposed externally as it should not need to be accessed or overridden
  var Auth = function (options) {
    this._options = options;
    this.initialize.apply(this, arguments);
  };

  // Piggy-back on Backbone's self-propagating extend function,
  Auth.extend = Backbone.Model.extend;

  _.extend(Auth.prototype, Backbone.Events, {
    authDeniedCb: function() {},

    initialize: function() {
      var that = this;
    },

    authHandlerCb : function (roles) {
      var deferred = $.Deferred();
      deferred.resolve();
      return deferred;
    },

    registerAuth: function (authHandlerCb) {
      this.authHandlerCb = authHandlerCb;
    },

    registerAuthDenied: function (authDeniedCb) {
      this.authDeniedCb = authDeniedCb;
    },

    checkAccess: function (roles) {
      var requiredRoles = roles || [],
      that = this;

      return FauxtonAPI.session.fetchUser().then(function (user) {
        return FauxtonAPI.when(that.authHandlerCb(FauxtonAPI.session, requiredRoles));
      });
    }
  });

  FauxtonAPI.auth = new Auth();

  FauxtonAPI.RouteObject = function(options) {
    this._options = options;

    this._configure(options || {});
    this.initialize.apply(this, arguments);
    this.addEvents();
  };

  var broadcaster = {};
  _.extend(broadcaster, Backbone.Events);

  FauxtonAPI.RouteObject.on = function (eventName, fn) {
    broadcaster.on(eventName, fn);
  };

  /* How Route Object events work
   To listen to a specific route objects events:

   myRouteObject = FauxtonAPI.RouteObject.extend({
    events: {
      "beforeRender": "beforeRenderEvent"
    },

    beforeRenderEvent: function (view, selector) {
      console.log('Hey, beforeRenderEvent triggered',arguments);
    },
   });

    It is also possible to listen to events triggered from all Routeobjects.
    This is great for more general things like adding loaders, hooks.

    FauxtonAPI.RouteObject.on('beforeRender', function (routeObject, view, selector) {
      console.log('hey, this will trigger when any routeobject renders a view');
    });

   Current Events to subscribe to:
    * beforeFullRender -- before a full render is being done
    * beforeEstablish -- before the routeobject calls establish
    * AfterEstablish -- after the routeobject has run establish
    * beforeRender -- before a view is rendered
    * afterRender -- a view is finished being rendered
    * renderComplete -- all rendering is complete

  */

  // Piggy-back on Backbone's self-propagating extend function
  FauxtonAPI.RouteObject.extend = Backbone.Model.extend;

  var routeObjectOptions = ["views", "routes", "events", "roles", "crumbs", "layout", "apiUrl", "establish"];

  _.extend(FauxtonAPI.RouteObject.prototype, Backbone.Events, {
    // Should these be default vals or empty funcs?
    views: {},
    routes: {},
    events: {},
    crumbs: [],
    layout: "with_sidebar",
    apiUrl: null,
    disableLoader: false,
    loaderClassname: 'loader',
    renderedState: false,
    establish: function() {},
    route: function() {},
    roles: [],
    _promises: [],
    initialize: function() {}
  }, {

    renderWith: function(route, masterLayout, args) {
      var routeObject = this,
          triggerBroadcast = _.bind(this.triggerBroadcast, this);

      // Only want to redo the template if its a full render
      if (!this.renderedState) {
        masterLayout.setTemplate(this.layout);
        triggerBroadcast('beforeFullRender');
        $('#primary-navbar li').removeClass('active');

        if (this.selectedHeader) {
          app.selectedHeader = this.selectedHeader;
          $('#primary-navbar li[data-nav-name="' + this.selectedHeader + '"]').addClass('active');
        }
      }

      masterLayout.clearBreadcrumbs();
      var crumbs = this.get('crumbs');

      if (crumbs.length) {
        masterLayout.setBreadcrumbs(new Fauxton.Breadcrumbs({
          crumbs: crumbs
        }));
      }

      triggerBroadcast('beforeEstablish');
      var establishPromise = this.establish();
      this.addPromise(establishPromise);
      FauxtonAPI.when(establishPromise).then(function(resp) {
        triggerBroadcast('afterEstablish');
        _.each(routeObject.getViews(), function(view, selector) {
          if(view.hasRendered) {
            triggerBroadcast('viewHasRendered', view, selector);
            return;
          }

          triggerBroadcast('beforeRender', view, selector);
          var viewPromise = view.establish();
          routeObject.addPromise(viewPromise);
          FauxtonAPI.when(viewPromise).then(function(resp) {
            masterLayout.setView(selector, view);

            masterLayout.renderView(selector);
            triggerBroadcast('afterRender', view, selector);
            }, function(resp) {
              view.establishError = {
                error: true,
                reason: resp
              };

              if (resp && resp.responseText) {
                var errorText = JSON.parse(resp.responseText).reason;
                FauxtonAPI.addNotification({
                  msg: 'An Error occurred: ' + errorText,
                  type: 'error',
                  clear: true
                });
              }

              masterLayout.renderView(selector);
          });

        });
      }.bind(this), function (resp) {
          if (!resp || !resp.responseText) { return; }
          FauxtonAPI.addNotification({
                msg: 'An Error occurred' + JSON.parse(resp.responseText).reason,
                type: 'error',
                clear: true
          });
      });

      if (this.get('apiUrl')){
        masterLayout.apiBar.update(this.get('apiUrl'));
      } else {
        masterLayout.apiBar.hide();
      }

      // Track that we've done a full initial render
      this.renderedState = true;
      triggerBroadcast('renderComplete');
    },

    triggerBroadcast: function (eventName) {
      var args = Array.prototype.slice.call(arguments);
      this.trigger.apply(this, args);

      args.splice(0,1, eventName, this);
      broadcaster.trigger.apply(broadcaster, args);
    },

    get: function(key) {
      return _.isFunction(this[key]) ? this[key]() : this[key];
    },

    addEvents: function(events) {
      events = events || this.get('events');
      _.each(events, function(method, event) {
        if (!_.isFunction(method) && !_.isFunction(this[method])) {
          throw new Error("Invalid method: "+method);
        }
        method = _.isFunction(method) ? method : this[method];

        this.on(event, method);
      }, this);
    },

    _configure: function(options) {
      _.each(_.intersection(_.keys(options), routeObjectOptions), function(key) {
        this[key] = options[key];
      }, this);
    },

    getView: function(selector) {
      return this.views[selector];
    },

    setView: function(selector, view) {
      this.views[selector] = view;
      return view;
    },

    getViews: function() {
      return this.views;
    },

    removeViews: function () {
      _.each(this.views, function (view, selector) {
        view.remove();
        delete this.views[selector];
      }, this);
    },

    addPromise: function (promise) {
      if (_.isEmpty(promise)) { return; }

      if (_.isArray(promise)) {
        return _.each(promise, function (p) {
          this._promises.push(p);
        }, this);
      }

     this._promises.push(promise);
    },

    cleanup: function () {
      this.removeViews();
      this.rejectPromises();
    },

    rejectPromises: function () {
      _.each(this._promises, function (promise) {
        if (promise.state() === "resolved") { return; }
        if (promise.abort) {
          return promise.abort("Route change");
        }

        promise.reject();
      }, this);

      this._promises = [];
    },

    getRouteUrls: function () {
      return _.keys(this.get('routes'));
    },

    hasRoute: function (route) {
      if (this.get('routes')[route]) {
        return true;
      }
      return false;
    },

    routeCallback: function (route, args) {
      var routes = this.get('routes'),
      routeObj = routes[route],
      routeCallback;

      if (typeof routeObj === 'object') {
        routeCallback = this[routeObj.route];
      } else {
        routeCallback = this[routeObj];
      }

      routeCallback.apply(this, args);
    },

    getRouteRoles: function (routeUrl) {
      var route = this.get('routes')[routeUrl];

      if ((typeof route === 'object') && route.roles) {
        return route.roles;
      }

      return this.roles;
    }

  });

  // We could look at moving the spinner code out to its own module
  var routeObjectSpinner;
  FauxtonAPI.RouteObject.on('beforeEstablish', function (routeObject) {
    if (!routeObject.disableLoader){
      var opts = {
        lines: 16, // The number of lines to draw
        length: 8, // The length of each line
        width: 4, // The line thickness
        radius: 12, // The radius of the inner circle
        color: '#333', // #rbg or #rrggbb
        speed: 1, // Rounds per second
        trail: 10, // Afterglow percentage
        shadow: false // Whether to render a shadow
     };

     if (!$('.spinner').length) {
       $('

')
        .appendTo('#app-container');
     }

     routeObjectSpinner = new Spinner(opts).spin();
     $('.spinner').append(routeObjectSpinner.el);
   }
  });

  var removeRouteObjectSpinner = function () {
    if (routeObjectSpinner) {
      routeObjectSpinner.stop();
      $('.spinner').remove();
    }
  };

  var removeViewSpinner = function () {
    if (viewSpinner){
      viewSpinner.stop();
      $('.spinner').remove();
    }
  };

  var viewSpinner;
  FauxtonAPI.RouteObject.on('beforeRender', function (routeObject, view, selector) {
    removeRouteObjectSpinner();

    if (!view.disableLoader){
      var opts = {
        lines: 16, // The number of lines to draw
        length: 8, // The length of each line
        width: 4, // The line thickness
        radius: 12, // The radius of the inner circle
        color: '#333', // #rbg or #rrggbb
        speed: 1, // Rounds per second
        trail: 10, // Afterglow percentage
        shadow: false // Whether to render a shadow
      };

      viewSpinner = new Spinner(opts).spin();
      $('

')
        .appendTo(selector)
        .append(viewSpinner.el);
    }
  });

  FauxtonAPI.RouteObject.on('afterRender', function (routeObject, view, selector) {
    removeViewSpinner();
  });

  FauxtonAPI.RouteObject.on('viewHasRendered', function () {
    removeViewSpinner();
    removeRouteObjectSpinner();
  });

  var extensions = _.extend({}, Backbone.Events);
  // Can look at a remove function later.
  FauxtonAPI.registerExtension = function (name, view) {
    if (!extensions[name]) {
      extensions[name] = [];
    }

    extensions.trigger('add:' + name, view);
    extensions[name].push(view);
  };

  FauxtonAPI.getExtensions = function (name) {
    var views = extensions[name];

    if (!views) {
      views = [];
    }

    return views;
  };

  FauxtonAPI.extensions = extensions;

  app.fauxtonAPI = FauxtonAPI;
  return app.fauxtonAPI;
});
<|endoftext|>


<commit_before>window.usframeLoaded = false
<commit_msg>drop unneeded initialize_window<commit_after><|endoftext|>


<commit_before>process.on('unhandledRejection', err => { throw err })
process.env.NODE_ENV = 'production'

require('dotenv').config({ silent: true })

const chalk = require('chalk')
const path = require('path')
const fs = require('fs-extra')
const { log, createWebpackCompiler, coloredBanner } = require('./_utils')

function copyPublicFolder() {
  const appDir = process.cwd()
  const appPublic = path.join(appDir, 'public')
  const appBuild = path.join(appDir, 'build')
  fs.copySync(appPublic, appBuild, {
    overwrite: true,
    dereference: true,
    filter: file => path.basename(file) !== 'index.html',
  })
}

// Create the production build and print the deployment instructions.
function build() {
  log.info(`Copying ${chalk.cyan('public/')} folder...`)
  copyPublicFolder()

  log.info(`Creating an optimized production build...`)
  const compiler = createWebpackCompiler(() => {
    log.ok(`The ${chalk.cyan('build/')} folder is ready to be deployed.`)
  }, () => {
    log.err(`Aborting`)
    process.exit(2)
  })
  compiler.run(() => {})
}

console.log(coloredBanner('/||||/| accurapp', ['cyan', 'magenta']))
build()
<commit_msg>📄  Add react-dev-utils's file size reporter<commit_after>process.on('unhandledRejection', err => { throw err })
process.env.NODE_ENV = 'production'

require('dotenv').config({ silent: true })

const chalk = require('chalk')
const path = require('path')
const fs = require('fs-extra')
const { measureFileSizesBeforeBuild, printFileSizesAfterBuild } = require('react-dev-utils/FileSizeReporter')
const { log, createWebpackCompiler, coloredBanner } = require('./_utils')

const appDir = process.cwd()
const appPublic = path.join(appDir, 'public')
const appBuild = path.join(appDir, 'build')

function copyPublicFolder() {
  log.info(`Copying ${chalk.cyan('public/')} folder...`)
  fs.copySync(appPublic, appBuild, {
    overwrite: true,
    dereference: true,
    filter: file => path.basename(file) !== 'index.html',
  })
}

// Create the production build and print the deployment instructions.
function build() {
  log.info(`Creating an optimized production build...`)
  const compiler = createWebpackCompiler(() => {
    log.ok(`The ${chalk.cyan('build/')} folder is ready to be deployed.`)
  }, () => {
    log.err(`Aborting`)
    process.exit(2)
  })

  return new Promise((resolve, reject) => {
    compiler.run((err, stats) => {
      if (err) {
        return reject(err)
      }

      return resolve(stats)
    })
  })
}

console.log(coloredBanner('/||||/| accurapp', ['cyan', 'magenta']))

measureFileSizesBeforeBuild(appBuild)
  .then((previousFileSizes) => {
    copyPublicFolder()
    build()
      .then((stats) => {
        log.info('File sizes after gzip:')
        console.log()
        printFileSizesAfterBuild(stats, previousFileSizes, appBuild)
        console.log()
      })
  })
<|endoftext|>


<commit_before><commit_msg>module export to components folder<commit_after><|endoftext|>