<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2019 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

var Class = require('../../utils/Class');
var Events = require('../events');
var File = require('../File');
var GetFastValue = require('../../utils/object/GetFastValue');
var GetURL = require('../GetURL');
var IsPlainObject = require('../../utils/object/IsPlainObject');

/**
 * @classdesc
 * A single Audio File suitable for loading by the Loader.
 *
 * These are created when you use the Phaser.Loader.LoaderPlugin#audio method and are not typically created directly.
 *
 * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#audio.
 *
 * @class HTML5AudioFile
 * @extends Phaser.Loader.File
 * @memberof Phaser.Loader.FileTypes
 * @constructor
 * @since 3.0.0
 *
 * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file.
 * @param {(string|Phaser.Loader.FileTypes.AudioFileConfig)} key - The key to use for this file, or a file configuration object.
 * @param {string} [urlConfig] - The absolute or relative URL to load this file from.
 * @param {Phaser.Loader.Types.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file.
 */
var HTML5AudioFile = new Class({

    Extends: File,

    initialize:

    function HTML5AudioFile (loader, key, urlConfig, audioConfig)
    {
        if (IsPlainObject(key))
        {
            var config = key;

            key = GetFastValue(config, 'key');
            audioConfig = GetFastValue(config, 'config', audioConfig);
        }

        var fileConfig = {
            type: 'audio',
            cache: loader.cacheManager.audio,
            extension: urlConfig.type,
            key: key,
            url: urlConfig.url,
            config: audioConfig
        };

        File.call(this, loader, fileConfig);

        //  New properties specific to this class
        this.locked = 'ontouchstart' in window;
        this.loaded = false;
        this.filesLoaded = 0;
        this.filesTotal = 0;
    },

    /**
     * Called when the file finishes loading.
     *
     * @method Phaser.Loader.FileTypes.HTML5AudioFile#onLoad
     * @since 3.0.0
     */
    onLoad: function ()
    {
        if (this.loaded)
        {
            return;
        }

        this.loaded = true;

        this.loader.nextFile(this, true);
    },

    /**
     * Called if the file errors while loading.
     *
     * @method Phaser.Loader.FileTypes.HTML5AudioFile#onError
     * @since 3.0.0
     */
    onError: function ()
    {
        for (var i = 0; i < this.data.length; i++)
        {
            var audio = this.data[i];

            audio.oncanplaythrough = null;
            audio.onerror = null;
        }

        this.loader.nextFile(this, false);
    },

    /**
     * Called during the file load progress. Is sent a DOM ProgressEvent.
     *
     * @method Phaser.Loader.FileTypes.HTML5AudioFile#onProgress
     * @fires Phaser.Loader.Events#FILE_PROGRESS
     * @since 3.0.0
     */
    onProgress: function (event)
    {
        var audio = event.target;

        audio.oncanplaythrough = null;
        audio.onerror = null;

        this.filesLoaded++;

        this.percentComplete = Math.min((this.filesLoaded / this.filesTotal), 1);

        this.loader.emit(Events.FILE_PROGRESS, this, this.percentComplete);

        if (this.filesLoaded === this.filesTotal)
        {
            this.onLoad();
        }
    },

    /**
     * Called by the Loader, starts the actual file downloading.
     * During the load the methods onLoad, onError and onProgress are called, based on the XHR events.
     * You shouldn't normally call this method directly, it's meant to be invoked by the Loader.
     *
     * @method Phaser.Loader.FileTypes.HTML5AudioFile#load
     * @since 3.0.0
     */
    load: function ()
    {
        this.data = [];

        var instances = (this.config && this.config.instances) || 1;

        this.filesTotal = instances;
        this.filesLoaded = 0;
        this.percentComplete = 0;

        for (var i = 0; i < instances; i++)
        {
            var audio = new Audio();

            audio.dataset.name = this.key + ('0' + i).slice(-2);
            audio.dataset.used = 'false';

            if (this.locked)
            {
                audio.dataset.locked = 'true';
            }
            else
            {
                audio.dataset.locked = 'false';

                audio.preload = 'auto';
                audio.oncanplaythrough = this.onProgress.bind(this);
                audio.onerror = this.onError.bind(this);
            }

            this.data.push(audio);
        }

        for (i = 0; i < this.data.length; i++)
        {
            audio = this.data[i];
            audio.src = GetURL(this, this.loader.baseURL);

            if (!this.locked)
            {
                audio.load();
            }
        }

        if (this.locked)
        {
            //  This is super-dangerous but works. Race condition potential high.
            //  Is there another way?
            setTimeout(this.onLoad.bind(this));
        }
    }

});

module.exports = HTML5AudioFile;
<commit_msg>Declared dataset as object for internet explorer 10<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2019 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

var Class = require('../../utils/Class');
var Events = require('../events');
var File = require('../File');
var GetFastValue = require('../../utils/object/GetFastValue');
var GetURL = require('../GetURL');
var IsPlainObject = require('../../utils/object/IsPlainObject');

/**
 * @classdesc
 * A single Audio File suitable for loading by the Loader.
 *
 * These are created when you use the Phaser.Loader.LoaderPlugin#audio method and are not typically created directly.
 *
 * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#audio.
 *
 * @class HTML5AudioFile
 * @extends Phaser.Loader.File
 * @memberof Phaser.Loader.FileTypes
 * @constructor
 * @since 3.0.0
 *
 * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file.
 * @param {(string|Phaser.Loader.FileTypes.AudioFileConfig)} key - The key to use for this file, or a file configuration object.
 * @param {string} [urlConfig] - The absolute or relative URL to load this file from.
 * @param {Phaser.Loader.Types.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file.
 */
var HTML5AudioFile = new Class({

    Extends: File,

    initialize:

    function HTML5AudioFile (loader, key, urlConfig, audioConfig)
    {
        if (IsPlainObject(key))
        {
            var config = key;

            key = GetFastValue(config, 'key');
            audioConfig = GetFastValue(config, 'config', audioConfig);
        }

        var fileConfig = {
            type: 'audio',
            cache: loader.cacheManager.audio,
            extension: urlConfig.type,
            key: key,
            url: urlConfig.url,
            config: audioConfig
        };

        File.call(this, loader, fileConfig);

        //  New properties specific to this class
        this.locked = 'ontouchstart' in window;
        this.loaded = false;
        this.filesLoaded = 0;
        this.filesTotal = 0;
    },

    /**
     * Called when the file finishes loading.
     *
     * @method Phaser.Loader.FileTypes.HTML5AudioFile#onLoad
     * @since 3.0.0
     */
    onLoad: function ()
    {
        if (this.loaded)
        {
            return;
        }

        this.loaded = true;

        this.loader.nextFile(this, true);
    },

    /**
     * Called if the file errors while loading.
     *
     * @method Phaser.Loader.FileTypes.HTML5AudioFile#onError
     * @since 3.0.0
     */
    onError: function ()
    {
        for (var i = 0; i < this.data.length; i++)
        {
            var audio = this.data[i];

            audio.oncanplaythrough = null;
            audio.onerror = null;
        }

        this.loader.nextFile(this, false);
    },

    /**
     * Called during the file load progress. Is sent a DOM ProgressEvent.
     *
     * @method Phaser.Loader.FileTypes.HTML5AudioFile#onProgress
     * @fires Phaser.Loader.Events#FILE_PROGRESS
     * @since 3.0.0
     */
    onProgress: function (event)
    {
        var audio = event.target;

        audio.oncanplaythrough = null;
        audio.onerror = null;

        this.filesLoaded++;

        this.percentComplete = Math.min((this.filesLoaded / this.filesTotal), 1);

        this.loader.emit(Events.FILE_PROGRESS, this, this.percentComplete);

        if (this.filesLoaded === this.filesTotal)
        {
            this.onLoad();
        }
    },

    /**
     * Called by the Loader, starts the actual file downloading.
     * During the load the methods onLoad, onError and onProgress are called, based on the XHR events.
     * You shouldn't normally call this method directly, it's meant to be invoked by the Loader.
     *
     * @method Phaser.Loader.FileTypes.HTML5AudioFile#load
     * @since 3.0.0
     */
    load: function ()
    {
        this.data = [];

        var instances = (this.config && this.config.instances) || 1;

        this.filesTotal = instances;
        this.filesLoaded = 0;
        this.percentComplete = 0;

        for (var i = 0; i < instances; i++)
        {
            var audio = new Audio();
            audio.dataset = {};
            audio.dataset.name = this.key + ('0' + i).slice(-2);
            audio.dataset.used = 'false';

            if (this.locked)
            {
                audio.dataset.locked = 'true';
            }
            else
            {
                audio.dataset.locked = 'false';

                audio.preload = 'auto';
                audio.oncanplaythrough = this.onProgress.bind(this);
                audio.onerror = this.onError.bind(this);
            }

            this.data.push(audio);
        }

        for (i = 0; i < this.data.length; i++)
        {
            audio = this.data[i];
            audio.src = GetURL(this, this.loader.baseURL);

            if (!this.locked)
            {
                audio.load();
            }
        }

        if (this.locked)
        {
            //  This is super-dangerous but works. Race condition potential high.
            //  Is there another way?
            setTimeout(this.onLoad.bind(this));
        }
    }

});

module.exports = HTML5AudioFile;
<|endoftext|>


<commit_before>var Class = require('../../utils/Class');
var File = require('../File');
var GetFastValue = require('../../utils/object/GetFastValue');
var GetURL = require('../GetURL');

//  Phaser.Loader.FileTypes.HTML5AudioFile

var HTML5AudioFile = new Class({

    Extends: File,

    initialize:

        function HTML5AudioFile (key, url, path, config)
        {
            var fileConfig = {
                type: 'audio',
                extension: GetFastValue(url, 'type', ''),
                key: key,
                url: GetFastValue(url, 'uri', url),
                path: path,
                config: config
            };

            File.call(this, fileConfig);
        },

    onLoad: function ()
    {
        this.callback(this, true);
    },

    onError: function (event)
    {
        for (var i = 0; i < this.data.length; i++)
        {
            var audio = this.data[i];
            audio.oncanplaythrough = null;
            audio.onerror = null;
        }

        this.callback(this, false);
    },

    onProgress: function (event)
    {
        var audio = event.target;
        audio.oncanplaythrough = null;
        audio.onerror = null;

        if(++this.filesLoaded === this.filesTotal)
        {
            this.onLoad();
        }

        this.percentComplete = Math.min((this.filesLoaded / this.filesTotal), 1);
    },

    //  Called by the Loader, starts the actual file downloading
    load: function (callback, baseURL)
    {
        this.callback = callback;

        this.data = [];

        var instances = (this.config && this.config.instances) || 1;

        this.filesTotal = instances;
        this.filesLoaded = 0;
        this.percentComplete = 0;

        for(var i = 0; i < instances; i++)
        {
            var audio = new Audio();
            audio.name = this.key + ('0' + i).slice(-2); // Useful for debugging
            audio.dataset.used = 'false';

            if (!('ontouchstart' in window))
            {
                audio.preload = 'auto';
                audio.oncanplaythrough = this.onProgress.bind(this);
                audio.onerror = this.onError.bind(this);
            }

            this.data.push(audio);
        }

        for (i = 0; i < this.data.length; i++)
        {
            audio = this.data[i];
            audio.src = GetURL(this, baseURL || '');
            audio.load();
        }
    }

});

module.exports = HTML5AudioFile;
<commit_msg>Skipping calling load method on an audio tag on mobile devices<commit_after>var Class = require('../../utils/Class');
var File = require('../File');
var GetFastValue = require('../../utils/object/GetFastValue');
var GetURL = require('../GetURL');

//  Phaser.Loader.FileTypes.HTML5AudioFile

var HTML5AudioFile = new Class({

    Extends: File,

    initialize:

        function HTML5AudioFile (key, url, path, config)
        {
            var fileConfig = {
                type: 'audio',
                extension: GetFastValue(url, 'type', ''),
                key: key,
                url: GetFastValue(url, 'uri', url),
                path: path,
                config: config
            };

            File.call(this, fileConfig);
        },

    onLoad: function ()
    {
        this.callback(this, true);
    },

    onError: function (event)
    {
        for (var i = 0; i < this.data.length; i++)
        {
            var audio = this.data[i];
            audio.oncanplaythrough = null;
            audio.onerror = null;
        }

        this.callback(this, false);
    },

    onProgress: function (event)
    {
        var audio = event.target;
        audio.oncanplaythrough = null;
        audio.onerror = null;

        if(++this.filesLoaded === this.filesTotal)
        {
            this.onLoad();
        }

        this.percentComplete = Math.min((this.filesLoaded / this.filesTotal), 1);
    },

    //  Called by the Loader, starts the actual file downloading
    load: function (callback, baseURL)
    {
        this.callback = callback;

        this.data = [];

        var instances = (this.config && this.config.instances) || 1;

        this.filesTotal = instances;
        this.filesLoaded = 0;
        this.percentComplete = 0;

        var touchLocked = 'ontouchstart' in window;

        for(var i = 0; i < instances; i++)
        {
            var audio = new Audio();
            audio.name = this.key + ('0' + i).slice(-2); // Useful for debugging
            audio.dataset.used = 'false';

            if (!touchLocked)
            {
                audio.preload = 'auto';
                audio.oncanplaythrough = this.onProgress.bind(this);
                audio.onerror = this.onError.bind(this);
            }

            this.data.push(audio);
        }

        for (i = 0; i < this.data.length; i++)
        {
            audio = this.data[i];
            audio.src = GetURL(this, baseURL || '');

            if (!touchLocked)
            {
                audio.load();
            }
        }
    }

});

module.exports = HTML5AudioFile;
<|endoftext|>


<commit_before>import { LinearFilter } from '../constants.js';
import { FileLoader } from './FileLoader.js';
import { CompressedTexture } from '../textures/CompressedTexture.js';
import { Loader } from './Loader.js';

/**
 * Abstract Base class to block based textures loader (dds, pvr, ...)
 *
 * Sub classes have to implement the parse() method which will be used in load().
 */

function CompressedTextureLoader( manager ) {

	Loader.call( this, manager );

}

CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: CompressedTextureLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		const scope = this;

		const images = [];

		const texture = new CompressedTexture();
		texture.image = images;

		const loader = new FileLoader( this.manager );
		loader.setPath( this.path );
		loader.setResponseType( 'arraybuffer' );
		loader.setRequestHeader( this.requestHeader );
		loader.setWithCredentials( scope.withCredentials );

		let loaded = 0;

		function loadTexture( i ) {

			loader.load( url[ i ], function ( buffer ) {

				const texDatas = scope.parse( buffer, true );

				images[ i ] = {
					width: texDatas.width,
					height: texDatas.height,
					format: texDatas.format,
					mipmaps: texDatas.mipmaps
				};

				loaded += 1;

				if ( loaded === 6 ) {

					if ( texDatas.mipmapCount === 1 )
						texture.minFilter = LinearFilter;

					texture.format = texDatas.format;
					texture.needsUpdate = true;

					if ( onLoad ) onLoad( texture );

				}

			}, onProgress, onError );

		}

		if ( Array.isArray( url ) ) {

			for ( let i = 0, il = url.length; i < il; ++ i ) {

				loadTexture( i );

			}

		} else {

			// compressed cubemap texture stored in a single DDS file

			loader.load( url, function ( buffer ) {

				const texDatas = scope.parse( buffer, true );

				if ( texDatas.isCubemap ) {

					const faces = texDatas.mipmaps.length / texDatas.mipmapCount;

					for ( let f = 0; f < faces; f ++ ) {

						images[ f ] = { mipmaps: [] };

						for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {

							images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
							images[ f ].format = texDatas.format;
							images[ f ].width = texDatas.width;
							images[ f ].height = texDatas.height;

						}

					}

				} else {

					texture.image.width = texDatas.width;
					texture.image.height = texDatas.height;
					texture.mipmaps = texDatas.mipmaps;

				}

				if ( texDatas.mipmapCount === 1 ) {

					texture.minFilter = LinearFilter;

				}

				texture.format = texDatas.format;
				texture.needsUpdate = true;

				if ( onLoad ) onLoad( texture );

			}, onProgress, onError );

		}

		return texture;

	}

} );

export { CompressedTextureLoader };
<commit_msg>CompressedTextureLoader: Fix type of CompressedTexture.image.<commit_after>import { LinearFilter } from '../constants.js';
import { FileLoader } from './FileLoader.js';
import { CompressedTexture } from '../textures/CompressedTexture.js';
import { Loader } from './Loader.js';

/**
 * Abstract Base class to block based textures loader (dds, pvr, ...)
 *
 * Sub classes have to implement the parse() method which will be used in load().
 */

function CompressedTextureLoader( manager ) {

	Loader.call( this, manager );

}

CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: CompressedTextureLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		const scope = this;

		const images = [];

		const texture = new CompressedTexture();

		const loader = new FileLoader( this.manager );
		loader.setPath( this.path );
		loader.setResponseType( 'arraybuffer' );
		loader.setRequestHeader( this.requestHeader );
		loader.setWithCredentials( scope.withCredentials );

		let loaded = 0;

		function loadTexture( i ) {

			loader.load( url[ i ], function ( buffer ) {

				const texDatas = scope.parse( buffer, true );

				images[ i ] = {
					width: texDatas.width,
					height: texDatas.height,
					format: texDatas.format,
					mipmaps: texDatas.mipmaps
				};

				loaded += 1;

				if ( loaded === 6 ) {

					if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;

					texture.image = images;
					texture.format = texDatas.format;
					texture.needsUpdate = true;

					if ( onLoad ) onLoad( texture );

				}

			}, onProgress, onError );

		}

		if ( Array.isArray( url ) ) {

			for ( let i = 0, il = url.length; i < il; ++ i ) {

				loadTexture( i );

			}

		} else {

			// compressed cubemap texture stored in a single DDS file

			loader.load( url, function ( buffer ) {

				const texDatas = scope.parse( buffer, true );

				if ( texDatas.isCubemap ) {

					const faces = texDatas.mipmaps.length / texDatas.mipmapCount;

					for ( let f = 0; f < faces; f ++ ) {

						images[ f ] = { mipmaps: [] };

						for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {

							images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
							images[ f ].format = texDatas.format;
							images[ f ].width = texDatas.width;
							images[ f ].height = texDatas.height;

						}

					}

					texture.image = images;

				} else {

					texture.image.width = texDatas.width;
					texture.image.height = texDatas.height;
					texture.mipmaps = texDatas.mipmaps;

				}

				if ( texDatas.mipmapCount === 1 ) {

					texture.minFilter = LinearFilter;

				}

				texture.format = texDatas.format;
				texture.needsUpdate = true;

				if ( onLoad ) onLoad( texture );

			}, onProgress, onError );

		}

		return texture;

	}

} );

export { CompressedTextureLoader };
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { login } from 'reducers/auth';

class Demo extends PureComponent {
  static defaultProps = {
    loading: false,
    login() {},
  };
  componentDidMount() {
    this.props.login();
  }
  render() {
    const { loading, test } = this.props;

    return (

        {test}
        {loading && Loading...}
        ---
        component03

    );
  }
}

export default connect(
  reducers => ({
    loading: reducers.auth.get('loading', false),
    test: reducers.auth.get('test'),
  }),
  {
    login,
  }
)(Demo);
<commit_msg>Remove dead code<commit_after>import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { login } from 'reducers/auth';

class Demo extends PureComponent {
  static defaultProps = {
    loading: false,
    login() {},
  };
  componentDidMount() {
    this.props.login();
  }
  render() {
    const { loading } = this.props;

    return (

        {loading && Loading...}

    );
  }
}

export default connect(
  reducers => ({
    loading: reducers.auth.get('loading', false),
  }),
  {
    login,
  }
)(Demo);
<|endoftext|>


<commit_before>'use strict';

var toArray   = require('es5-ext/array/to-array')
  , uniq      = require('es5-ext/array/#/uniq')
  , pluck     = require('es5-ext/function/pluck')
  , d         = require('d')
  , DbjsError = require('../error')
  , isGetter  = require('../utils/is-getter')
  , serialize = require('../serialize/value')

  , getPrototypeOf = Object.getPrototypeOf
  , defineProperties = Object.defineProperties
  , getMessage = pluck('message');

module.exports = function (descriptor) {
	defineProperties(descriptor, {
		_validateDeleteValue_: d(function (obj, sKey) {
			var nuValue;
			if (this._reverse_) return this._reverse_._validateDelete_(obj);
			if (this.nested) {
				throw new DbjsError("Cannot delete nested object",
					'NESTED_DELETE');
			}
			if (this.multiple) {
				throw new DbjsError("Cannot delete multiple property",
					'MULTIPLE_DELETE');
			}
			if (!this.required) return sKey;
			if (this.hasOwnProperty('_value_')) {
				nuValue = getPrototypeOf(this)._resolveInner_(obj, sKey);
			} else {
				nuValue = this._resolveValueValue_(obj, sKey);
			}
			if (nuValue == null) {
				throw new DbjsError("Property is required", 'VALUE_REQUIRED');
			}
			if (isGetter(nuValue)) return sKey;
			if (this._normalizeValue_(nuValue) == null) {
				throw new DbjsError("Property is required", 'VALUE_REQUIRED');
			}
			return sKey;
		}),
		_validateSetValue_: d(function (obj, sKey, value) {
			if (value === undefined) {
				throw new DbjsError("Cannot set value to undefined", 'SET_UNDEFINED');
			}
			if (this._reverse_) return this._reverse_._validateSet_(obj, value);
			if (this.nested) {
				throw new DbjsError("Nested objects cannot be overriden",
					'NESTED_OVERRIDE');
			}
			if (isGetter(value)) return value;
			if (this.multiple) return this._validateMultiple_(obj, sKey, value);
			if (value === null) {
				if (this.required) {
					throw new DbjsError("Property is required", 'VALUE_REQUIRED');
				}
				return value;
			}
			value = this.type.validate(value, this);
			if (this.unique) this._validateUnique_(obj, sKey, value);
			return value;
		}),
		_validateUnique_: d(function (obj, sKey, value) {
			var vKey = serialize(value), mapData, desc, l;
			desc = obj.__descriptors__[sKey];
			if (!desc) return value;
			desc = desc.__descriptors__.unique;
			while (!desc.hasOwnProperty('_value_')) desc = getPrototypeOf(desc);
			mapData = desc.object._getReverseMap_(sKey).__mapValuesData__;
			if (!mapData[vKey]) return value;
			mapData = mapData[vKey].__setData__;
			l = mapData.length;
			if (!l) return value;
			if ((l === 1) && (mapData[0] === obj)) return value;
			throw new DbjsError(value + " is already assigned to other object",
				'VALUE_NOT_UNIQUE');
		}),
		_validateMultiple_: d(function (obj, sKey, value) {
			var errors, set, iKey;
			if (value == null) {
				throw new DbjsError("Cannot set multiple property to " + value,
					'MULTIPLE_NULL');
			}
			value = toArray(value);
			if (!value.length) {
				if (this.required) {
					set = getPrototypeOf(obj).__multiples__[sKey];
					if (set) {
						for (iKey in set) {
							if (!set[iKey]._value_) continue;
							if (obj._normalize_(set[iKey].key) == null) continue;
							return value; //jslint: ignore
						}
					}
					throw new DbjsError("Property is required. List must not be empty",
						'MULTIPLE_REQUIRED');
				}
				return value;
			}
			value = uniq.call(value).map(function (value) {
				if (value == null) {
					if (!errors) errors = [];
					errors.push(new DbjsError(value + " is not a value",
						'MULTIPLE_NULL_VALUE'));
					return;
				}
				try {
					value = this.type.validate(value, this);
				} catch (e) {
					if (e.name !== 'DbjsError') throw e;
					if (!errors) errors = [];
					errors.push(e);
					return;
				}
				if (this.unique) {
					try {
						this._validateUnique_(obj, sKey, value);
					} catch (e2) {
						if (e2.name !== 'DbjsError') throw e2;
						if (!errors) errors = [];
						errors.push(e2);
						return;
					}
				}
				return value;
			}, this);
			if (!errors) return value;
			throw new DbjsError("Some values are invalid:\n\t" +
				errors.map(getMessage).join('\t\n'), 'MULTIPLE_ERRORS',
				{ errors: errors });
		})
	});
};
<commit_msg>-- whitespace<commit_after>'use strict';

var toArray   = require('es5-ext/array/to-array')
  , uniq      = require('es5-ext/array/#/uniq')
  , pluck     = require('es5-ext/function/pluck')
  , d         = require('d')
  , DbjsError = require('../error')
  , isGetter  = require('../utils/is-getter')
  , serialize = require('../serialize/value')

  , getPrototypeOf = Object.getPrototypeOf
  , defineProperties = Object.defineProperties
  , getMessage = pluck('message');

module.exports = function (descriptor) {
	defineProperties(descriptor, {
		_validateDeleteValue_: d(function (obj, sKey) {
			var nuValue;
			if (this._reverse_) return this._reverse_._validateDelete_(obj);
			if (this.nested) throw new DbjsError("Cannot delete nested object", 'NESTED_DELETE');
			if (this.multiple) throw new DbjsError("Cannot delete multiple property", 'MULTIPLE_DELETE');
			if (!this.required) return sKey;
			if (this.hasOwnProperty('_value_')) nuValue = getPrototypeOf(this)._resolveInner_(obj, sKey);
			else nuValue = this._resolveValueValue_(obj, sKey);
			if (nuValue == null) throw new DbjsError("Property is required", 'VALUE_REQUIRED');
			if (isGetter(nuValue)) return sKey;
			if (this._normalizeValue_(nuValue) == null) {
				throw new DbjsError("Property is required", 'VALUE_REQUIRED');
			}
			return sKey;
		}),
		_validateSetValue_: d(function (obj, sKey, value) {
			if (value === undefined) {
				throw new DbjsError("Cannot set value to undefined", 'SET_UNDEFINED');
			}
			if (this._reverse_) return this._reverse_._validateSet_(obj, value);
			if (this.nested) {
				throw new DbjsError("Nested objects cannot be overriden", 'NESTED_OVERRIDE');
			}
			if (isGetter(value)) return value;
			if (this.multiple) return this._validateMultiple_(obj, sKey, value);
			if (value === null) {
				if (this.required) throw new DbjsError("Property is required", 'VALUE_REQUIRED');
				return value;
			}
			value = this.type.validate(value, this);
			if (this.unique) this._validateUnique_(obj, sKey, value);
			return value;
		}),
		_validateUnique_: d(function (obj, sKey, value) {
			var vKey = serialize(value), mapData, desc, l;
			desc = obj.__descriptors__[sKey];
			if (!desc) return value;
			desc = desc.__descriptors__.unique;
			while (!desc.hasOwnProperty('_value_')) desc = getPrototypeOf(desc);
			mapData = desc.object._getReverseMap_(sKey).__mapValuesData__;
			if (!mapData[vKey]) return value;
			mapData = mapData[vKey].__setData__;
			l = mapData.length;
			if (!l) return value;
			if ((l === 1) && (mapData[0] === obj)) return value;
			throw new DbjsError(value + " is already assigned to other object", 'VALUE_NOT_UNIQUE');
		}),
		_validateMultiple_: d(function (obj, sKey, value) {
			var errors, set, iKey;
			if (value == null) {
				throw new DbjsError("Cannot set multiple property to " + value, 'MULTIPLE_NULL');
			}
			value = toArray(value);
			if (!value.length) {
				if (this.required) {
					set = getPrototypeOf(obj).__multiples__[sKey];
					if (set) {
						for (iKey in set) {
							if (!set[iKey]._value_) continue;
							if (obj._normalize_(set[iKey].key) == null) continue;
							return value; //jslint: ignore
						}
					}
					throw new DbjsError("Property is required. List must not be empty", 'MULTIPLE_REQUIRED');
				}
				return value;
			}
			value = uniq.call(value).map(function (value) {
				if (value == null) {
					if (!errors) errors = [];
					errors.push(new DbjsError(value + " is not a value", 'MULTIPLE_NULL_VALUE'));
					return;
				}
				try {
					value = this.type.validate(value, this);
				} catch (e) {
					if (e.name !== 'DbjsError') throw e;
					if (!errors) errors = [];
					errors.push(e);
					return;
				}
				if (this.unique) {
					try {
						this._validateUnique_(obj, sKey, value);
					} catch (e2) {
						if (e2.name !== 'DbjsError') throw e2;
						if (!errors) errors = [];
						errors.push(e2);
						return;
					}
				}
				return value;
			}, this);
			if (!errors) return value;
			throw new DbjsError("Some values are invalid:\n\t" +
				errors.map(getMessage).join('\t\n'), 'MULTIPLE_ERRORS', { errors: errors });
		})
	});
};
<|endoftext|>


<commit_before>define([
    'src/util/api',
    'src/util/ui',
    './libs'
], function (API, UI, libs) {
    var OCLE = libs.OCLE;
    var CCE = libs.CCE;

    class MF {
        constructor(sample) {
            this.sample = sample;

            // if no mf we calculate from molfile
            if (!this.getMF()) {
                this.fromMolfile();
            }
        }

        fromMolfile() {
            var chemcalc = this._chemcalcFromMolfile();
            if (chemcalc && this.previousEMMolfile !== chemcalc.em) {
                this.previousEMMolfile = chemcalc.em;
                this.setMF(chemcalc.mf);

                // var general = API.getData('general');
                // API.getData('mf').setValue(chemcalc.mf, true);
                // API.getData('em').setValue(chemcalc.em, true);
                // API.getData('mw').setValue(chemcalc.mw, true);
                // general.triggerChange();
                console.log('Changed mf to ', chemcalc.mf)
            }
            API.createData('mfBGColor', 'white');
        }

        _chemcalcFromMolfile() {
            var molfile = this.getMolfile();
            if (molfile) {
                var molecule = OCLE.Molecule.fromMolfile(molfile);
                var mf = molecule.getMolecularFormula().formula;
                try {
                    return CCE.analyseMF(mf);
                } catch (e) {
                    UI.showNotification('Could not calculate molecular formula: ' + e);
                }
            }
            return undefined;
        }

        getMF() {
            return String(this.sample.getChildSync(['$content', 'general', 'mf']));
        }

        getMolfile() {
            return String(this.sample.getChildSync(['$content', 'general', 'molfile']));
        }

        setMF(mf) {
            this.sample.setChildSync(['$content','general','mf'], mf);
        }

        setMW(mw) {
            this.sample.setChildSync(['$content','general','mw'], mw);
        }

        setEM(em) {
            this.sample.setChildSync(['$content','general','em'], em);
        }

        fromMF() {
            var chemcalc = CCE.analyseMF(this.getMF());
            console.log('new MF', chemcalc);
            if (chemcalc && this.previousEMMF !== chemcalc.em) {
                this.previousEMMF = chemcalc.em;
                this.setMW(chemcalc.mw);
                this.setEM(chemcalc.em);
                // var general = API.getData('general');
                // general.mw = chemcalc.mw;
                // general.em = chemcalc.em;
                // general.triggerChange();
            }
        }

        _mfColor() {
            var existingMF = this.getMF();
            if (molfile) {
                var molecule = OCLE.Molecule.fromMolfile(molfile);
                var mf = molecule.getMolecularFormula().formula;
                var existingMW = existingMF ? CCE.analyseMF(existingMF).mw : 0;
                var newMW = mf ? CCE.analyseMF(mf).mw : 0;
                if (newMW != existingMW) {
                    API.createData('mfBGColor', 'pink');
                } else {
                    API.createData('mfBGColor', 'white');
                }
            } else {
                API.createData('mfBGColor', 'white');
            }
        }

        handleAction(action) {
            if (!action) return;
            switch (action.name) {

                default:
                    return false;
            }
            return true;
        }
    }

    return MF;
});<commit_msg>Update MF.js<commit_after>define([
    'src/util/api',
    'src/util/ui',
    './libs'
], function (API, UI, libs) {
    var OCLE = libs.OCLE;
    var CCE = libs.CCE;

    class MF {
        constructor(sample) {
            this.sample = sample;

            // if no mf we calculate from molfile
            if (!this.getMF()) {
                this.fromMolfile();
            }
        }

        fromMolfile() {
            var chemcalc = this._chemcalcFromMolfile();
            if (chemcalc && this.previousEMMolfile !== chemcalc.em) {
                this.previousEMMolfile = chemcalc.em;
                this.setMF(chemcalc.mf);

                // var general = API.getData('general');
                // API.getData('mf').setValue(chemcalc.mf, true);
                // API.getData('em').setValue(chemcalc.em, true);
                // API.getData('mw').setValue(chemcalc.mw, true);
                // general.triggerChange();
                console.log('Changed mf to ', chemcalc.mf)
            }
            API.createData('mfBGColor', 'white');
        }

        _chemcalcFromMolfile() {
            var molfile = this.getMolfile();
            if (molfile) {
                var molecule = OCLE.Molecule.fromMolfile(molfile);
                var mf = molecule.getMolecularFormula().formula;
                try {
                    return CCE.analyseMF(mf);
                } catch (e) {
                    UI.showNotification('Could not calculate molecular formula: ' + e);
                }
            }
            return undefined;
        }

        getMF() {
            return String(this.sample.getChildSync(['$content', 'general', 'mf']));
        }

        getMolfile() {
            return String(this.sample.getChildSync(['$content', 'general', 'molfile']));
        }

        setMF(mf) {
            this.sample.setChildSync(['$content','general','mf'], mf);
        }

        setMW(mw) {
            this.sample.setChildSync(['$content','general','mw'], mw);
        }

        setEM(em) {
            this.sample.setChildSync(['$content','general','em'], em);
        }

        fromMF() {
            if (! this.getMF()) {
                this.previousEMMF = 0;
                this.setMW(0);
                this.setEM(0);
                return;
            }
            var chemcalc = CCE.analyseMF(this.getMF());
            console.log('new MF', chemcalc);
            if (chemcalc && this.previousEMMF !== chemcalc.em) {
                this.previousEMMF = chemcalc.em;
                this.setMW(chemcalc.mw);
                this.setEM(chemcalc.em);

            }
        }

        _mfColor() {
            var existingMF = this.getMF();
            if (molfile) {
                var molecule = OCLE.Molecule.fromMolfile(molfile);
                var mf = molecule.getMolecularFormula().formula;
                var existingMW = existingMF ? CCE.analyseMF(existingMF).mw : 0;
                var newMW = mf ? CCE.analyseMF(mf).mw : 0;
                if (newMW != existingMW) {
                    API.createData('mfBGColor', 'pink');
                } else {
                    API.createData('mfBGColor', 'white');
                }
            } else {
                API.createData('mfBGColor', 'white');
            }
        }

        handleAction(action) {
            if (!action) return;
            switch (action.name) {

                default:
                    return false;
            }
            return true;
        }
    }

    return MF;
});
<|endoftext|>


<commit_before>/*jslint browser: true, devel: true, sloppy: true,
    plusplus: true, nomen: true, regexp: true */
/*global $: false, jQuery: false */

var tld_list = ['gmail.com'];
$.validator.addMethod("fromDomain", function (value, element, param) {
    console.log("foo");
    console.log(value);
    var splitted = value.split("@");
    var tld = splitted[splitted.length - 1];
    return false;
    return $.inArray(tld, tld_list) !== -1;
},
    "Please use your company email address to sign up. Otherwise, we won’t be able to connect you with your coworkers.");

$(document).ready(function(){
    $("#email_signup").validate({
        rules: {
            email: {
                required: true,
                email: true,
            }
        },
        errorLabelContainer: "#errors",
        errorElement: "div",
        errorClass: "alert",

    });
});
<commit_msg>Fix wtf control flow in signup.js<commit_after>/*jslint browser: true, devel: true, sloppy: true,
    plusplus: true, nomen: true, regexp: true */
/*global $: false, jQuery: false */

var tld_list = ['gmail.com'];
$.validator.addMethod("fromDomain", function (value, element, param) {
    console.log("foo");
    console.log(value);
    var splitted = value.split("@");
    var tld = splitted[splitted.length - 1];
    return $.inArray(tld, tld_list) !== -1;
},
    "Please use your company email address to sign up. Otherwise, we won’t be able to connect you with your coworkers.");

$(document).ready(function(){
    $("#email_signup").validate({
        rules: {
            email: {
                required: true,
                email: true,
            }
        },
        errorLabelContainer: "#errors",
        errorElement: "div",
        errorClass: "alert",

    });
});
<|endoftext|>


<commit_before>import DS from 'ember-data';

var Article = DS.Model.extend({
  body: DS.attr('string')
});

export default Article;
<commit_msg>feat: added property for urlDecodedId on Article model<commit_after>import DS from 'ember-data';

var Article = DS.Model.extend({
  body: DS.attr('string'),

  urlDecodedId: function(){
    return decodeURIComponent(this.get('id'));
  }.property('id')
});

export default Article;
<|endoftext|>


<commit_before>/* Database schema for comments*/

// load the things we need
var mongoose = require('mongoose');
var Comment = require('../models/comment');
// define the schema for our user model
var commentSchema = mongoose.Schema({
  id: { type: String, default: "http://giv-geosoft2a.uni-muenster.de:3000/comments/"+this._id},
  title: { type: String },
  dataset: { type: mongoose.Schema.Types.ObjectId, ref: 'Dataset' },
  url: String,
  text: String,
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  authorName: String,
  rating: {type: Number, default: 0},
  date: { type: Date, default: Date.now },
  comment: { type: mongoose.Schema.Types.ObjectId, ref: 'Comment' },
  comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
  markerCoords: [{ type: Number }],
  boundingBox: [{ type: Number}],
  temporalComponent: [ {type: String }]

})

commentSchema.virtual('dateString').get(function () {
  var d = this.date;
  var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");
  var curr_date = d.getDate();
  var curr_month = d.getMonth();
  var curr_year = d.getFullYear();
  var h = d.getHours();
  var m = d.getMinutes();
  if (m.toString().length==1) {
    var result = curr_date + "." + m_names[curr_month]  + " " + curr_year + "  " + h + ":" + "0" + m;
  } else {
    var result = curr_date + "." + m_names[curr_month]  + " " + curr_year + "  " + h + ":" + m;
  }

  return result;
})

/*
commentSchema.virtual('url').get(function () {
  this.populate('dataset').exec(function(err, comment) {
      if (err) return handleError(err)
      return comment.dataset.url
  })
})
*/
/*
commentSchema.virtual('author').get(function () {
  this.populate('user').exec(function(err, comment) {
      if (err) return handleError(err)
      return comment.user.local.username
  })
})
*/
/*
commentSchema.virtual('author').get(function () {
      mongoose.model('Comment').findOne({ title: this.title })
      .populate('user')
      .exec(function(err, comment) {
          if (err) return handleError(err);
          console.log("Method:" + comment.user.local.username)
          return comment.user.local.username
      });
})*/

/*
commentSchema.virtual('author').get(function () {
    mongoose.model('Comment').findOne({ title : this.title })
      .populate('user')
      .exec(function(err, comment) {
        if (comment.user) {
          console.log("Method:" + comment.user.local.username);
          return comment.user.local.username;
        }  else {
          return "Anonymous"
        }
      });

     }
   )
*/

commentSchema.virtual('username').get(function () {

  mongoose.model('Comment').findOne({ title : this.title }).populate('user').exec(function(err,comment) {
    if (comment.user!=undefined) {
      console.log(comment.user.local.username)
      return comment.user.local.username
    } else {
      return "Anonymous"
    }
  })
  })
/*
  var comment = ""
  return query.exec(function(err, com) {
      if (com.user) {
    console.log("Ja")
      return query.populate('user').exec(function(err, comment) {
      return comment.user.local.username

  })
  } else {
    return "Anonymous"
  }
  })
*/

/*
commentSchema.virtual('username2').get(function () {
  return this.findAuthor(function(err, comment) {
                        if (comment.user) {
                          return comment.user.local.username;
                        }  else {
                          return "Anonymous"
                        }
                      } )
  })

commentSchema.methods.findAuthor = function (cb) {

      mongoose.model('Comment').findOne({ title : this.title })
      .populate('user')
      .exec(cb);
  }

/*
commentSchema.methods.findSimilarTypes = function (cb) {
  return this.model('Comment').find({ title: this.title }, cb);
}

commentSchema.statics = {

  load: function (comment) {
      mongoose.model('Comment').findOne({ title : comment.title })
      .populate('user')
      .exec(function(err, comment) {
        if (comment.user) {
          console.log("Method:" + comment.user.local.username);
          return comment.user.local.username;
        }  else {
          return "Anonymous"
        }
      });
  }

  }
  */
commentSchema.set('toJSON', { virtuals: true });
commentSchema.set('toObject', { virtuals: true });
// create the model for users and expose it to our app
module.exports = mongoose.model('Comment', commentSchema);
<commit_msg>Update comment.js<commit_after>/* Database schema for comments*/

var mongoose = require('mongoose');
var Comment = require('../models/comment');
// define the schema for our user model
var commentSchema = mongoose.Schema({
  title: { type: String },
  dataset: { type: mongoose.Schema.Types.ObjectId, ref: 'Dataset' },
  url: String,
  text: String,
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  authorName: String,
  rating: {type: Number, default: 0},
  date: { type: Date, default: Date.now },
  comment: { type: mongoose.Schema.Types.ObjectId, ref: 'Comment' },
  comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
  markerCoords: [{ type: Number }],
  boundingBox: [{ type: Number}],
  temporalComponent: [ {type: String }]

})

// show date in following fromat: 01. January 2015
commentSchema.virtual('dateString').get(function () {
  var d = this.date;
  var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December");
  var curr_date = d.getDate();
  var curr_month = d.getMonth();
  var curr_year = d.getFullYear();
  var h = d.getHours();
  var m = d.getMinutes();
  if (m.toString().length==1) {
    var result = curr_date + "." + m_names[curr_month]  + " " + curr_year + "  " + h + ":" + "0" + m;
  } else {
    var result = curr_date + "." + m_names[curr_month]  + " " + curr_year + "  " + h + ":" + m;
  }
  return result;
})

commentSchema.set('toJSON', { virtuals: true });
commentSchema.set('toObject', { virtuals: true });
// create the model for comments and expose it to the app
module.exports = mongoose.model('Comment', commentSchema);
<|endoftext|>


<commit_before>/*
 * Apache 2.0 License
 *
 * Copyright (c) Sebastian Katzer 2017
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apache License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://opensource.org/licenses/Apache-2.0/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 */

var exec    = require('cordova/exec'),
    channel = require('cordova/channel');

// Default values
exports._defaults = {
    id:      0,
    text:    '',
    title:   '',
    sound:   'res://platform_default',
    badge:   undefined,
    data:    undefined,
    icon:    undefined,
    trigger: { type: 'calendar' },
    actions: [],
    actionGroupId: undefined,
    attachments: [],
    progressBar: false
};

// Listener
exports._listener = {};

/**
 * Merge platform specific properties into the default ones.
 *
 * @return [ Void ]
 */
exports.applyPlatformSpecificOptions = function () {
    var defaults = this._defaults;

    switch (device.platform) {
    case 'Android':
        defaults.icon        = 'res://ic_popup_reminder';
        defaults.smallIcon   = undefined;
        defaults.ongoing     = false;
        defaults.autoClear   = true;
        defaults.led         = undefined;
        defaults.color       = undefined;
        break;
    }
};

/**
 * Merge custom properties with the default values.
 *
 * @param [ Object ] options Set of custom values.
 *
 * @retrun [ Object ]
 */
exports.mergeWithDefaults = function (options) {
    var defaults = this.getDefaults();

    options.text = this.getValueFor(options, 'text', 'message');
    options.data = this.getValueFor(options, 'data', 'json');

    if (defaults.hasOwnProperty('autoClear')) {
        options.autoClear = this.getValueFor(options, 'autoClear', 'autoCancel');
    }

    if (options.autoClear !== true && options.ongoing) {
        options.autoClear = false;
    }

    for (var key in defaults) {
        if (options[key] === null || options[key] === undefined) {
            if (options.hasOwnProperty(key) && ['data','sound'].indexOf(key) > -1) {
                options[key] = undefined;
            } else {
                options[key] = defaults[key];
            }
        }
    }

    for (key in options) {
        if (!defaults.hasOwnProperty(key)) {
            // delete options[key];
            console.warn('Unknown property: ' + key);
        }
    }

    return options;
};

/**
 * Convert the passed values to their required type.
 *
 * @param [ Object ] options Properties to convert for.
 *
 * @return [ Object ] The converted property list
 */
exports.convertProperties = function (options) {

    if (options.id) {
        if (isNaN(options.id)) {
            options.id = this.getDefaults().id;
            console.warn('Id is not a number: ' + options.id);
        } else {
            options.id = Number(options.id);
        }
    }

    if (options.title) {
        options.title = options.title.toString();
    }

    if (options.text) {
        options.text  = options.text.toString();
    }

    if (options.badge) {
        if (isNaN(options.badge)) {
            options.badge = this.getDefaults().badge;
            console.warn('Badge number is not a number: ' + options.id);
        } else {
            options.badge = Number(options.badge);
        }
    }

    if (typeof options.data == 'object') {
        options.data = JSON.stringify(options.data);
    }

    this.convertTrigger(options);
    this.convertActions(options);
    this.convertProgressBar(options);

    return options;
};

/**
 * Convert the passed values to their required type, modifying them
 * directly for Android and passing the converted list back for iOS.
 *
 * @param [ Map ] options Set of custom values.
 *
 * @return [ Map ] Interaction object with category & actions.
 */
exports.convertActions = function (options) {

    if (!options.actions)
        return null;

    var actions = [];

    for (var i = 0, action; i < options.actions.length; i++) {
        action = options.actions[i];

        if (!action.id) {
            console.warn(
                'Action with title ' + action.title + ' has no id and will not be added.');
            continue;
        }

        action.id = action.id.toString();

        actions.push(action);
    }

    options.category = (options.category || 'DEFAULT_GROUP').toString();
    options.actions  = actions;

    return options;
};

/**
 * Convert the passed values for the trigger to their required type.
 *
 * @param [ Map ] options Set of custom values.
 *
 * @return [ Map ] Interaction object with trigger spec.
 */
exports.convertTrigger = function (options) {
    var cfg      = options.trigger,
        isDate   = Date.prototype.isPrototypeOf(cfg),
        isObject = Object.prototype.isPrototypeOf(cfg),
        trigger  = !isDate && isObject ? cfg : {},
        date     = this.getValueFor(trigger, 'at', 'firstAt', 'date');

    if (!trigger.type) {
        trigger.type = trigger.center ? 'location' : 'calendar';
    }

    var isCal = trigger.type == 'calendar';

    if (isCal && !date) {
        date = this.getValueFor(options, 'at', 'firstAt', 'date') || new Date();
    }

    if (isCal) {
        date = typeof date == 'object' ? date.getTime() : date;
        trigger.at = Math.round(date / 1000);
    }

    if (isCal && !trigger.every && options.every) {
        trigger.every = options.every;
    }

    if (!trigger.count && device.platform == 'windows') {
        trigger.count = trigger.every ? 5 : 1;
    }

    if (trigger.every && device.platform == 'windows') {
        trigger.every = trigger.every.toString();
    }

    if (!isCal) {
        trigger.notifyOnEntry = !!trigger.notifyOnEntry;
        trigger.notifyOnExit  = trigger.notifyOnExit === true;
        trigger.radius        = trigger.radius || 5;
    }

    delete options.every;
    delete options.at;
    delete options.firstAt;
    delete options.date;

    options.trigger = trigger;

    return options;
};

/**
 * Convert the passed values for the progressBar to their required type.
 *
 * @param [ Map ] options Set of custom values.
 *
 * @return [ Map ] Interaction object with trigger spec.
 */
exports.convertProgressBar = function (options) {
    var cfg = options.progressBar;

    if (typeof cfg === 'boolean') {
        options.progressBar = { enabled: cfg };
    }

    return options;
};

/**
 * Create a callback function to get executed within a specific scope.
 *
 * @param [ Function ] fn    The function to be exec as the callback.
 * @param [ Object ]   scope The callback function's scope.
 *
 * @return [ Function ]
 */
exports.createCallbackFn = function (fn, scope) {

    if (typeof fn != 'function')
        return;

    return function () {
        fn.apply(scope || this, arguments);
    };
};

/**
 * Convert the IDs to numbers.
 *
 * @param [ Array ] ids
 *
 * @return [ Array<Number> ]
 */
exports.convertIds = function (ids) {
    var convertedIds = [];

    for (var i = 0; i < ids.length; i++) {
        convertedIds.push(Number(ids[i]));
    }

    return convertedIds;
};

/**
 * First found value for the given keys.
 *
 * @param [ Object ]         options Object with key-value properties.
 * @param [ *Array<String> ] keys    List of keys.
 *
 * @return [ Object ]
 */
exports.getValueFor = function (options) {
    var keys = Array.apply(null, arguments).slice(1);

    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];

        if (options.hasOwnProperty(key)) {
            return options[key];
        }
    }
};

/**
 * Fire the event with given arguments.
 *
 * @param [ String ] event The event's name.
 * @param [ *Array]  args  The callback's arguments.
 *
 * @return [ Void]
 */
exports.fireEvent = function (event) {
    var args     = Array.apply(null, arguments).slice(1),
        listener = this._listener[event];

    if (!listener)
        return;

    for (var i = 0; i < listener.length; i++) {
        var fn    = listener[i][0],
            scope = listener[i][1];

        fn.apply(scope, args);
    }
};

/**
 * Execute the native counterpart.
 *
 * @param [ String ]  action   The name of the action.
 * @param [ Array ]   args     Array of arguments.
 * @param [ Function] callback The callback function.
 * @param [ Object ] scope     The scope for the function.
 *
 * @return [ Void ]
 */
exports.exec = function (action, args, callback, scope) {
    var fn = this.createCallbackFn(callback, scope),
        params = [];

    if (Array.isArray(args)) {
        params = args;
    } else if (args) {
        params.push(args);
    }

    exec(fn, null, 'LocalNotification', action, params);
};

// Called after 'deviceready' event
channel.deviceready.subscribe(function () {
    // Device is ready now, the listeners are registered
    // and all queued events can be executed.
    exports.exec('ready');
});

// Called before 'deviceready' event
channel.onCordovaReady.subscribe(function () {
    // Set launchDetails object
    exports.exec('launch');
    // Device plugin is ready now
    channel.onCordovaInfoReady.subscribe(function () {
        // Merge platform specifics into defaults
        exports.applyPlatformSpecificOptions();
    });
});
<commit_msg>Some fixes in convertTrigger to only include valid value-pairs<commit_after>/*
 * Apache 2.0 License
 *
 * Copyright (c) Sebastian Katzer 2017
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apache License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://opensource.org/licenses/Apache-2.0/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 */

var exec    = require('cordova/exec'),
    channel = require('cordova/channel');

// Default values
exports._defaults = {
    id:      0,
    text:    '',
    title:   '',
    sound:   'res://platform_default',
    badge:   undefined,
    data:    undefined,
    icon:    undefined,
    trigger: { type: 'calendar' },
    actions: [],
    actionGroupId: undefined,
    attachments: [],
    progressBar: false
};

// Listener
exports._listener = {};

/**
 * Merge platform specific properties into the default ones.
 *
 * @return [ Void ]
 */
exports.applyPlatformSpecificOptions = function () {
    var defaults = this._defaults;

    switch (device.platform) {
    case 'Android':
        defaults.icon        = 'res://ic_popup_reminder';
        defaults.smallIcon   = undefined;
        defaults.ongoing     = false;
        defaults.autoClear   = true;
        defaults.led         = undefined;
        defaults.color       = undefined;
        break;
    }
};

/**
 * Merge custom properties with the default values.
 *
 * @param [ Object ] options Set of custom values.
 *
 * @retrun [ Object ]
 */
exports.mergeWithDefaults = function (options) {
    var defaults = this.getDefaults();

    options.text = this.getValueFor(options, 'text', 'message');
    options.data = this.getValueFor(options, 'data', 'json');

    if (defaults.hasOwnProperty('autoClear')) {
        options.autoClear = this.getValueFor(options, 'autoClear', 'autoCancel');
    }

    if (options.autoClear !== true && options.ongoing) {
        options.autoClear = false;
    }

    for (var key in defaults) {
        if (options[key] === null || options[key] === undefined) {
            if (options.hasOwnProperty(key) && ['data','sound'].indexOf(key) > -1) {
                options[key] = undefined;
            } else {
                options[key] = defaults[key];
            }
        }
    }

    for (key in options) {
        if (!defaults.hasOwnProperty(key)) {
            // delete options[key];
            console.warn('Unknown property: ' + key);
        }
    }

    return options;
};

/**
 * Convert the passed values to their required type.
 *
 * @param [ Object ] options Properties to convert for.
 *
 * @return [ Object ] The converted property list
 */
exports.convertProperties = function (options) {

    if (options.id) {
        if (isNaN(options.id)) {
            options.id = this.getDefaults().id;
            console.warn('Id is not a number: ' + options.id);
        } else {
            options.id = Number(options.id);
        }
    }

    if (options.title) {
        options.title = options.title.toString();
    }

    if (options.text) {
        options.text  = options.text.toString();
    }

    if (options.badge) {
        if (isNaN(options.badge)) {
            options.badge = this.getDefaults().badge;
            console.warn('Badge number is not a number: ' + options.id);
        } else {
            options.badge = Number(options.badge);
        }
    }

    if (typeof options.data == 'object') {
        options.data = JSON.stringify(options.data);
    }

    this.convertTrigger(options);
    this.convertActions(options);
    this.convertProgressBar(options);

    return options;
};

/**
 * Convert the passed values to their required type, modifying them
 * directly for Android and passing the converted list back for iOS.
 *
 * @param [ Map ] options Set of custom values.
 *
 * @return [ Map ] Interaction object with category & actions.
 */
exports.convertActions = function (options) {

    if (!options.actions)
        return null;

    var actions = [];

    for (var i = 0, action; i < options.actions.length; i++) {
        action = options.actions[i];

        if (!action.id) {
            console.warn(
                'Action with title ' + action.title + ' has no id and will not be added.');
            continue;
        }

        action.id = action.id.toString();

        actions.push(action);
    }

    options.category = (options.category || 'DEFAULT_GROUP').toString();
    options.actions  = actions;

    return options;
};

/**
 * Convert the passed values for the trigger to their required type.
 *
 * @param [ Map ] options Set of custom values.
 *
 * @return [ Map ] Interaction object with trigger spec.
 */
exports.convertTrigger = function (options) {
    var trigger  = options.trigger || {},
        date     = this.getValueFor(trigger, 'at', 'firstAt', 'date');

    if (!trigger.type) {
        trigger.type = trigger.center ? 'location' : 'calendar';
    }

    var isCal = trigger.type == 'calendar';

    if (isCal && !date) {
        date = this.getValueFor(options, 'at', 'firstAt', 'date');
    }

    if (isCal && !trigger.every && options.every) {
        trigger.every = options.every;
    }

    if (isCal && (trigger.in || trigger.every)) {
        date = null;
    }

    if (isCal && date) {
        date       = typeof date == 'object' ? date.getTime() : date;
        trigger.at = Math.round(date / 1000);
    }

    if (!trigger.count && device.platform == 'windows') {
        trigger.count = trigger.every ? 5 : 1;
    }

    if (trigger.every && device.platform == 'windows') {
        trigger.every = trigger.every.toString();
    }

    if (!isCal) {
        trigger.notifyOnEntry = !!trigger.notifyOnEntry;
        trigger.notifyOnExit  = trigger.notifyOnExit === true;
        trigger.radius        = trigger.radius || 5;
    }

    if (!isCal || trigger.at) {
        delete trigger.every;
    }

    delete options.every;
    delete options.at;
    delete options.firstAt;
    delete options.date;

    options.trigger = trigger;

    return options;
};

/**
 * Convert the passed values for the progressBar to their required type.
 *
 * @param [ Map ] options Set of custom values.
 *
 * @return [ Map ] Interaction object with trigger spec.
 */
exports.convertProgressBar = function (options) {
    var cfg = options.progressBar;

    if (typeof cfg === 'boolean') {
        options.progressBar = { enabled: cfg };
    }

    return options;
};

/**
 * Create a callback function to get executed within a specific scope.
 *
 * @param [ Function ] fn    The function to be exec as the callback.
 * @param [ Object ]   scope The callback function's scope.
 *
 * @return [ Function ]
 */
exports.createCallbackFn = function (fn, scope) {

    if (typeof fn != 'function')
        return;

    return function () {
        fn.apply(scope || this, arguments);
    };
};

/**
 * Convert the IDs to numbers.
 *
 * @param [ Array ] ids
 *
 * @return [ Array<Number> ]
 */
exports.convertIds = function (ids) {
    var convertedIds = [];

    for (var i = 0; i < ids.length; i++) {
        convertedIds.push(Number(ids[i]));
    }

    return convertedIds;
};

/**
 * First found value for the given keys.
 *
 * @param [ Object ]         options Object with key-value properties.
 * @param [ *Array<String> ] keys    List of keys.
 *
 * @return [ Object ]
 */
exports.getValueFor = function (options) {
    var keys = Array.apply(null, arguments).slice(1);

    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];

        if (options.hasOwnProperty(key)) {
            return options[key];
        }
    }
};

/**
 * Fire the event with given arguments.
 *
 * @param [ String ] event The event's name.
 * @param [ *Array]  args  The callback's arguments.
 *
 * @return [ Void]
 */
exports.fireEvent = function (event) {
    var args     = Array.apply(null, arguments).slice(1),
        listener = this._listener[event];

    if (!listener)
        return;

    for (var i = 0; i < listener.length; i++) {
        var fn    = listener[i][0],
            scope = listener[i][1];

        fn.apply(scope, args);
    }
};

/**
 * Execute the native counterpart.
 *
 * @param [ String ]  action   The name of the action.
 * @param [ Array ]   args     Array of arguments.
 * @param [ Function] callback The callback function.
 * @param [ Object ] scope     The scope for the function.
 *
 * @return [ Void ]
 */
exports.exec = function (action, args, callback, scope) {
    var fn = this.createCallbackFn(callback, scope),
        params = [];

    if (Array.isArray(args)) {
        params = args;
    } else if (args) {
        params.push(args);
    }

    exec(fn, null, 'LocalNotification', action, params);
};

// Called after 'deviceready' event
channel.deviceready.subscribe(function () {
    // Device is ready now, the listeners are registered
    // and all queued events can be executed.
    exports.exec('ready');
});

// Called before 'deviceready' event
channel.onCordovaReady.subscribe(function () {
    // Set launchDetails object
    exports.exec('launch');
    // Device plugin is ready now
    channel.onCordovaInfoReady.subscribe(function () {
        // Merge platform specifics into defaults
        exports.applyPlatformSpecificOptions();
    });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var glob = require('glob');
var args = require('optimist').argv;
var chokidar = require('chokidar');

var componentIndex = path.join('src', 'component-index.js');
var componentsDir = path.join('src', 'components');
var componentGlob = '**/*.js';
var prevFiles = [];

function reskindex() {
    var files = glob.sync(componentGlob, {cwd: componentsDir}).sort();
    if (!filesHaveChanged(files, prevFiles)) {
        return;
    }
    prevFiles = files;

    var header = args.h || args.header;
    var packageJson = JSON.parse(fs.readFileSync('./package.json'));

    var strm = fs.createWriteStream(componentIndex);

    if (header) {
       strm.write(fs.readFileSync(header));
       strm.write('\n');
    }

    strm.write("/*\n");
    strm.write(" * THIS FILE IS AUTO-GENERATED\n");
    strm.write(" * You can edit it you like, but your changes will be overwritten,\n");
    strm.write(" * so you'd just be trying to swim upstream like a salmon.\n");
    strm.write(" * You are not a salmon.\n");
    strm.write(" */\n\n");

    if (packageJson['matrix-react-parent']) {
        strm.write(
            "module.exports.components = require('"+
            packageJson['matrix-react-parent']+
            "/lib/component-index').components;\n\n"
        );
    } else {
        strm.write("module.exports.components = {};\n");
    }

    for (var i = 0; i < files.length; ++i) {
        var file = files[i].replace('.js', '');

        var moduleName = (file.replace(/\//g, '.'));
        var importName = moduleName.replace(/\./g, "$");

        strm.write("import " + importName + " from './components/" + file + "';\n");
        strm.write(importName + " && (module.exports.components['"+moduleName+"'] = " + importName + ");");
        strm.write('\n');
        strm.uncork();
    }

    strm.end();
    console.log('Reskindex: completed');
}

// Expects both arrays of file names to be sorted
function filesHaveChanged(files, prevFiles) {
    if (files.length !== prevFiles.length) {
        return true;
    }
    // Check for name changes
    for (var i = 0; i < files.length; i++) {
        if (prevFiles[i] !== files[i]) {
            return true;
        }
    }
    return false;
}

// -w indicates watch mode where any FS events will trigger reskindex
if (!args.w) {
    reskindex();
    return;
}

var watchDebouncer = null;
chokidar.watch(path.join(componentsDir, componentGlob)).on('all', (event, path) => {
    if (path === componentIndex) return;
    if (watchDebouncer) clearTimeout(watchDebouncer);
    watchDebouncer = setTimeout(reskindex, 1000);
});
<commit_msg>Reskindex to a temp file, to confuse the babel watcher less (#908)<commit_after>#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var glob = require('glob');
var args = require('optimist').argv;
var chokidar = require('chokidar');

var componentIndex = path.join('src', 'component-index.js');
var componentIndexTmp = componentIndex+".tmp";
var componentsDir = path.join('src', 'components');
var componentGlob = '**/*.js';
var prevFiles = [];

function reskindex() {
    var files = glob.sync(componentGlob, {cwd: componentsDir}).sort();
    if (!filesHaveChanged(files, prevFiles)) {
        return;
    }
    prevFiles = files;

    var header = args.h || args.header;
    var packageJson = JSON.parse(fs.readFileSync('./package.json'));

    var strm = fs.createWriteStream(componentIndexTmp);

    if (header) {
       strm.write(fs.readFileSync(header));
       strm.write('\n');
    }

    strm.write("/*\n");
    strm.write(" * THIS FILE IS AUTO-GENERATED\n");
    strm.write(" * You can edit it you like, but your changes will be overwritten,\n");
    strm.write(" * so you'd just be trying to swim upstream like a salmon.\n");
    strm.write(" * You are not a salmon.\n");
    strm.write(" */\n\n");

    if (packageJson['matrix-react-parent']) {
        const parentIndex = packageJson['matrix-react-parent'] +
              '/lib/component-index';
        strm.write(
`let components = require('${parentIndex}').components;
if (!components) {
    throw new Error("'${parentIndex}' didn't export components");
}
`);
    } else {
        strm.write("let components = {};\n");
    }

    for (var i = 0; i < files.length; ++i) {
        var file = files[i].replace('.js', '');

        var moduleName = (file.replace(/\//g, '.'));
        var importName = moduleName.replace(/\./g, "$");

        strm.write("import " + importName + " from './components/" + file + "';\n");
        strm.write(importName + " && (components['"+moduleName+"'] = " + importName + ");");
        strm.write('\n');
        strm.uncork();
    }

    strm.write("export {components};\n");
    strm.end();
    fs.rename(componentIndexTmp, componentIndex, function(err) {
        if(err) {
            console.error("Error moving new index into place: " + err);
        } else {
            console.log('Reskindex: completed');
        }
    });
}

// Expects both arrays of file names to be sorted
function filesHaveChanged(files, prevFiles) {
    if (files.length !== prevFiles.length) {
        return true;
    }
    // Check for name changes
    for (var i = 0; i < files.length; i++) {
        if (prevFiles[i] !== files[i]) {
            return true;
        }
    }
    return false;
}

// -w indicates watch mode where any FS events will trigger reskindex
if (!args.w) {
    reskindex();
    return;
}

var watchDebouncer = null;
chokidar.watch(path.join(componentsDir, componentGlob)).on('all', (event, path) => {
    if (path === componentIndex) return;
    if (watchDebouncer) clearTimeout(watchDebouncer);
    watchDebouncer = setTimeout(reskindex, 1000);
});
<|endoftext|>


<commit_before>
var failureTitleText = "so here are some screen captures instead ";
var failureDialog = "Your Browser is missing the following Technologies:";

function Loader(  params ){

    this.params = _.defaults( params || {}, {
      numberToLoad:   0,
      loadGif:        "img/loadJpg.jpg",
      videoWidth: 500,
      videoHeight: 281,
      neededTech:     ['webGL','audio','mobile']
    });

    this.neededTech = this.params.neededTech;

    this.numberLoaded = 0;
    this.numberToLoad = this.params.numberToLoad;

    //screen.lockOrientation('landscape');

    window.addEventListener("orientationchange", function(){
    console.log(screen.orientation); // e.g. portrait
    });

    this.curtain = document.createElement('div');
    this.curtain.id = "curtain";

    this.splash = document.createElement('img');
    this.splash.id = "splash";
    this.splash.src = "img/splash.png";
    this.curtain.appendChild(this.splash);

    document.body.appendChild( this.curtain );

    this.menu = document.createElement('div');
    this.menu.id = "menu";

    this.menulogo = document.createElement('img');
    this.menulogo.id = "menulogo";
    this.menulogo.src = "img/menulogo.png";

    this.menuflex = document.createElement('div');
    this.menuflex.id = "menuflex";

    this.scbutton1 = document.createElement('button');
    this.scbutton1.className = "scenebuttons";
    this.scbutton1.id = "scbutton1";
    this.scbutton1.innerHTML = "SPACESPHERE";

    this.scbutton2 = document.createElement('button');
    this.scbutton2.className = "scenebuttons";
    this.scbutton2.id = "scbutton2";
    this.scbutton2.innerHTML = "CONNECTIONS";

    this.scbutton3 = document.createElement('button');
    this.scbutton3.className = "scenebuttons";
    this.scbutton3.id = "scbutton3";
    this.scbutton2.innerHTML = "CREDITS";

    this.menuflex.appendChild(this.menulogo);
    this.menuflex.appendChild(this.scbutton1);
    this.menuflex.appendChild(this.scbutton2);
    this.menuflex.appendChild(this.scbutton3);

    this.menu.appendChild(this.menuflex);
    document.body.appendChild( this.menu );

    //
    // this.loadingGif     = document.createElement( 'img' );
    // this.loadingGif.src = this.params.loadGif;
    // this.loadingGif.id  = 'loadingGif';

    //this.OBJLoader = new THREE.OBJLoader();

    //this.addStartButton();

    // Conditions are things that will check each time something
    // new is loaded, allowing us to start putting together certain parts
    // of the program after a specific condition is made
    this.conditions = [];

    // Failures are things that the browser doesn't have.
    // If there are a non 0 number of failures the user will be alerted
    this.failures = [];

    this.detect();

  }

  Loader.prototype = {

    addLoadInfo: function(s){

      this.loadInfo.innerHTML = s;
    },

    addToLoadBar: function(){

      this.numberToLoad ++;

      this.updateLoadBar();

    },

    updateLoadBar: function(){

      this.loadBarAddAmount = window.innerWidth / (this.numberToLoad+1);

      var loadBarWidth = this.loadBarAddAmount * this.numberLoaded;
      this.loadBar.style.width = loadBarWidth + "px";

    },

    loadBarAdd: function(){

      var oldWidth = parseInt( this.loadBar.style.width );
      var newWidth = oldWidth + this.loadBarAddAmount;

      this.loadBar.style.width = newWidth + "px";

      this.numberLoaded ++;

      this.checkConditions();

      if( this.numberLoaded == this.numberToLoad ){
        this.onFinishedLoading();
      }

    },

    beginLoading: function(){this.addToLoadBar();},
    endLoading: function(){this.loadBarAdd();},
    addLoad: function(){this.addToLoadBar(); },
    onLoad: function(){this.loadBarAdd(); },

    // This will run through all of our saved conditions
    // and trigger whatever is necessary when we need to
    checkConditions: function(){

      for( var i = 0; i < this.conditions.length; i++ ){

        console.log( 'conditions checked' );
        var c = this.conditions[i];

        console.log( c );
        console.log( c[0] );
        if( c[0] ){
          c[1];
          this.conditions.splice( i , 1 );
        }

      }

    },

    addCondition: function( condition , callback ){
      this.conditions.push( [ condition , callback ] );
    },

    addFailureDialog: function(){

      console.log( 'FAILS');
      this.failureDialog = document.createElement('div');
      this.failureDialog.id = "failureDialog";

      this.curtain.appendChild( this.failureDialog );

      var failureTitle = document.createElement('div');
      failureTitle.id = "failureTitle";
      failureTitle.innerHTML = failureTitleText;

      //"But you can still watch the video version:";

      var failureReasons = document.createElement('h2');
      failureTitle.id = "failureReaons";
      failureReasons.innerHTML = failureDialog;
      //'Best viewed on Chrome. This project requires:';

      var failureReasons = document.createElement('p');
      failureReasons.id = "failureReasons";
      failureReasons.innerHTML = "You do not have the required technologies to view this experience";

      this.failureList = document.createElement('p');
      this.failureList.id = "failureList";

      this.failureVideo = document.createElement('div');

      var w = window.innerWidth / 1.618;
      var string = '
'

      string += '
'

      string += '
'

      string += '
'

      string += '
'

      string += '
'

      string += '
'

        96993970

      this.failureVideo.innerHTML = string;

      /*this.failureImg = document.createElement( 'img' );
      this.failureImg.src = failureImg;
      this.failureImg.id = 'failureImg';
      this.failureLink.appendChild( this.failureImg );*/
      this.failureDialog.appendChild( failureReasons );
      this.failureDialog.appendChild( this.failureList );
      this.failureDialog.appendChild( failureTitle);
      this.failureDialog.appendChild( this.failureVideo );

     // throw new Error('This is not an error. This is just to abort javascript');

    },

    addFailure: function( failureName , failureLink ){

      if( !this.failureDialog )
        this.addFailureDialog();

      var failure = document.createElement('a');

      failure.href = failureLink;
      failure.target = '_blank';
      failure.innerHTML = "||    " + failureName+ "   ||";

      console.log('FAILURE');
      this.failureList.appendChild( failure );

      //var failureName =
      this.failures.push( [failureName,failureLink] );

      var xHalf = this.failureDialog.clientWidth / 2;
      var yHalf = this.failureDialog.clientHeight / 2 ;

      var wHalf = window.innerWidth / 2;
      var hHalf = window.innerHeight / 2;

      var top = hHalf - yHalf;
      var left = wHalf - xHalf;

      console.log( top );
      if( top < 5 ) top = 5;
      if( left < 5 ) left = 5;

      this.failureDialog.style.top  = top + "px";
      this.failureDialog.style.left = left + "px";

      console.log( this.failureDialog.clientHeight );

    },

    onFinishedLoading: function(){

      var self = this;

      if( !this.failures.length ){

        //$("#startInfo").fadeIn(1000);
        // this.startInfo
        //this.onStart();
        //
        this.liftCurtain();

      }

    },

    addStartButton: function(){

      var info = "Move mouse to rotate
 Hold mouse to accelerate
 Catch critters to grow.
"

      var button = document.createElement('a');
      button.id = "startButton";
      button.innerHTML = 'START';

      this.startInfo = document.createElement('div');
      this.startInfo.id = "startInfo";
      this.startInfo.innerHTML = info;

      this.startInfo.appendChild( button );

      this.curtain.appendChild( this.startInfo );

    },

    liftCurtain: function(){

      var self = this;

      this._onStart();

       //link.deactivate();
     // G.hoverOver(0);

      $(this.curtain).fadeOut(1000,function(){
       // self._onStart();
       //
       //G.links[4].deactivate();
      });

    },

    _onStart: function(){

      if( !this.hasStarted ){
        this.onStart();
      }else{
        console.log( 'ALREADY STARTED!!!!' );
      }

      this.hasStarted = true;

    },

    onStart:function(){},

    setNavigator: function(){

      window.navigator.getUserMedia = window.navigator.getUserMedia || window.navigator.webkitGetUserMedia || window.navigator.mozGetUserMedia || window.navigator.msGetUserMedia;

      //this.womb.navigator = window.navigator;

    },

    detect: function(){

      for(var i = 0 ; i < this.neededTech.length; i++ ){

        var tech = this.neededTech[i];
        if( tech == 'webGL' )
          this.detectWebGL();
        else if( tech == 'audio' )
          this.detectWebAudioAPI();
        else if( tech == 'mobile' )
          this.detectMobile();

      }

      if( this.failures.length > 0 ){

        throw new Error('This is not an error. This is just to abort javascript');

      }

    },

    detectWebGL: function(){

      var webGL = function() { try { return !! window.WebGLRenderingContext && !! document.createElement( 'canvas' ).getContext( 'experimental-webgl' ); } catch( e ) { return false; } };

      var gl = webGL();

      if( false )
        this.addFailure( "WebGL" ,'http://get.webgl.org/');

    },

    detectWebAudioAPI: function(){

      if( false){
      //try {
      //  window.AudioContext = window.AudioContext;//||window.webkitAudioContext;
      //}catch(e) {
        this.addFailure( 'Non Webkit Audio API' ,'http://caniuse.com/audio-api' );
      }

    },

    detectMobile: function(){

      var detectM = function () {
        if( navigator.userAgent.match(/Android/i)
        || navigator.userAgent.match(/webOS/i)
        || navigator.userAgent.match(/iPhone/i)
        || navigator.userAgent.match(/iPad/i)
        || navigator.userAgent.match(/iPod/i)
        || navigator.userAgent.match(/BlackBerry/i)
        || navigator.userAgent.match(/Windows Phone/i)
        ){
          return true;
        } else {
          return false;
        }
      }

      var mobile = detectM();

      if( false )
        this.addFailure( "Non Mobile" , "http://cabbibo.tumblr.com" );

    }

  }
<commit_msg>textfix2<commit_after>
var failureTitleText = "so here are some screen captures instead ";
var failureDialog = "Your Browser is missing the following Technologies:";

function Loader(  params ){

    this.params = _.defaults( params || {}, {
      numberToLoad:   0,
      loadGif:        "img/loadJpg.jpg",
      videoWidth: 500,
      videoHeight: 281,
      neededTech:     ['webGL','audio','mobile']
    });

    this.neededTech = this.params.neededTech;

    this.numberLoaded = 0;
    this.numberToLoad = this.params.numberToLoad;

    //screen.lockOrientation('landscape');

    window.addEventListener("orientationchange", function(){
    console.log(screen.orientation); // e.g. portrait
    });

    this.curtain = document.createElement('div');
    this.curtain.id = "curtain";

    this.splash = document.createElement('img');
    this.splash.id = "splash";
    this.splash.src = "img/splash.png";
    this.curtain.appendChild(this.splash);

    document.body.appendChild( this.curtain );

    this.menu = document.createElement('div');
    this.menu.id = "menu";

    this.menulogo = document.createElement('img');
    this.menulogo.id = "menulogo";
    this.menulogo.src = "img/menulogo.png";

    this.menuflex = document.createElement('div');
    this.menuflex.id = "menuflex";

    this.scbutton1 = document.createElement('button');
    this.scbutton1.className = "scenebuttons";
    this.scbutton1.id = "scbutton1";
    this.scbutton1.innerHTML = "SPACESPHERE";

    this.scbutton2 = document.createElement('button');
    this.scbutton2.className = "scenebuttons";
    this.scbutton2.id = "scbutton2";
    this.scbutton2.innerHTML = "CONNECTIONS";

    this.scbutton3 = document.createElement('button');
    this.scbutton3.className = "scenebuttons";
    this.scbutton3.id = "scbutton3";
    this.scbutton3.innerHTML = "CREDITS";

    this.menuflex.appendChild(this.menulogo);
    this.menuflex.appendChild(this.scbutton1);
    this.menuflex.appendChild(this.scbutton2);
    this.menuflex.appendChild(this.scbutton3);

    this.menu.appendChild(this.menuflex);
    document.body.appendChild( this.menu );

    //
    // this.loadingGif     = document.createElement( 'img' );
    // this.loadingGif.src = this.params.loadGif;
    // this.loadingGif.id  = 'loadingGif';

    //this.OBJLoader = new THREE.OBJLoader();

    //this.addStartButton();

    // Conditions are things that will check each time something
    // new is loaded, allowing us to start putting together certain parts
    // of the program after a specific condition is made
    this.conditions = [];

    // Failures are things that the browser doesn't have.
    // If there are a non 0 number of failures the user will be alerted
    this.failures = [];

    this.detect();

  }

  Loader.prototype = {

    addLoadInfo: function(s){

      this.loadInfo.innerHTML = s;
    },

    addToLoadBar: function(){

      this.numberToLoad ++;

      this.updateLoadBar();

    },

    updateLoadBar: function(){

      this.loadBarAddAmount = window.innerWidth / (this.numberToLoad+1);

      var loadBarWidth = this.loadBarAddAmount * this.numberLoaded;
      this.loadBar.style.width = loadBarWidth + "px";

    },

    loadBarAdd: function(){

      var oldWidth = parseInt( this.loadBar.style.width );
      var newWidth = oldWidth + this.loadBarAddAmount;

      this.loadBar.style.width = newWidth + "px";

      this.numberLoaded ++;

      this.checkConditions();

      if( this.numberLoaded == this.numberToLoad ){
        this.onFinishedLoading();
      }

    },

    beginLoading: function(){this.addToLoadBar();},
    endLoading: function(){this.loadBarAdd();},
    addLoad: function(){this.addToLoadBar(); },
    onLoad: function(){this.loadBarAdd(); },

    // This will run through all of our saved conditions
    // and trigger whatever is necessary when we need to
    checkConditions: function(){

      for( var i = 0; i < this.conditions.length; i++ ){

        console.log( 'conditions checked' );
        var c = this.conditions[i];

        console.log( c );
        console.log( c[0] );
        if( c[0] ){
          c[1];
          this.conditions.splice( i , 1 );
        }

      }

    },

    addCondition: function( condition , callback ){
      this.conditions.push( [ condition , callback ] );
    },

    addFailureDialog: function(){

      console.log( 'FAILS');
      this.failureDialog = document.createElement('div');
      this.failureDialog.id = "failureDialog";

      this.curtain.appendChild( this.failureDialog );

      var failureTitle = document.createElement('div');
      failureTitle.id = "failureTitle";
      failureTitle.innerHTML = failureTitleText;

      //"But you can still watch the video version:";

      var failureReasons = document.createElement('h2');
      failureTitle.id = "failureReaons";
      failureReasons.innerHTML = failureDialog;
      //'Best viewed on Chrome. This project requires:';

      var failureReasons = document.createElement('p');
      failureReasons.id = "failureReasons";
      failureReasons.innerHTML = "You do not have the required technologies to view this experience";

      this.failureList = document.createElement('p');
      this.failureList.id = "failureList";

      this.failureVideo = document.createElement('div');

      var w = window.innerWidth / 1.618;
      var string = '
'

      string += '
'

      string += '
'

      string += '
'

      string += '
'

      string += '
'

      string += '
'

        96993970

      this.failureVideo.innerHTML = string;

      /*this.failureImg = document.createElement( 'img' );
      this.failureImg.src = failureImg;
      this.failureImg.id = 'failureImg';
      this.failureLink.appendChild( this.failureImg );*/
      this.failureDialog.appendChild( failureReasons );
      this.failureDialog.appendChild( this.failureList );
      this.failureDialog.appendChild( failureTitle);
      this.failureDialog.appendChild( this.failureVideo );

     // throw new Error('This is not an error. This is just to abort javascript');

    },

    addFailure: function( failureName , failureLink ){

      if( !this.failureDialog )
        this.addFailureDialog();

      var failure = document.createElement('a');

      failure.href = failureLink;
      failure.target = '_blank';
      failure.innerHTML = "||    " + failureName+ "   ||";

      console.log('FAILURE');
      this.failureList.appendChild( failure );

      //var failureName =
      this.failures.push( [failureName,failureLink] );

      var xHalf = this.failureDialog.clientWidth / 2;
      var yHalf = this.failureDialog.clientHeight / 2 ;

      var wHalf = window.innerWidth / 2;
      var hHalf = window.innerHeight / 2;

      var top = hHalf - yHalf;
      var left = wHalf - xHalf;

      console.log( top );
      if( top < 5 ) top = 5;
      if( left < 5 ) left = 5;

      this.failureDialog.style.top  = top + "px";
      this.failureDialog.style.left = left + "px";

      console.log( this.failureDialog.clientHeight );

    },

    onFinishedLoading: function(){

      var self = this;

      if( !this.failures.length ){

        //$("#startInfo").fadeIn(1000);
        // this.startInfo
        //this.onStart();
        //
        this.liftCurtain();

      }

    },

    addStartButton: function(){

      var info = "Move mouse to rotate
 Hold mouse to accelerate
 Catch critters to grow.
"

      var button = document.createElement('a');
      button.id = "startButton";
      button.innerHTML = 'START';

      this.startInfo = document.createElement('div');
      this.startInfo.id = "startInfo";
      this.startInfo.innerHTML = info;

      this.startInfo.appendChild( button );

      this.curtain.appendChild( this.startInfo );

    },

    liftCurtain: function(){

      var self = this;

      this._onStart();

       //link.deactivate();
     // G.hoverOver(0);

      $(this.curtain).fadeOut(1000,function(){
       // self._onStart();
       //
       //G.links[4].deactivate();
      });

    },

    _onStart: function(){

      if( !this.hasStarted ){
        this.onStart();
      }else{
        console.log( 'ALREADY STARTED!!!!' );
      }

      this.hasStarted = true;

    },

    onStart:function(){},

    setNavigator: function(){

      window.navigator.getUserMedia = window.navigator.getUserMedia || window.navigator.webkitGetUserMedia || window.navigator.mozGetUserMedia || window.navigator.msGetUserMedia;

      //this.womb.navigator = window.navigator;

    },

    detect: function(){

      for(var i = 0 ; i < this.neededTech.length; i++ ){

        var tech = this.neededTech[i];
        if( tech == 'webGL' )
          this.detectWebGL();
        else if( tech == 'audio' )
          this.detectWebAudioAPI();
        else if( tech == 'mobile' )
          this.detectMobile();

      }

      if( this.failures.length > 0 ){

        throw new Error('This is not an error. This is just to abort javascript');

      }

    },

    detectWebGL: function(){

      var webGL = function() { try { return !! window.WebGLRenderingContext && !! document.createElement( 'canvas' ).getContext( 'experimental-webgl' ); } catch( e ) { return false; } };

      var gl = webGL();

      if( false )
        this.addFailure( "WebGL" ,'http://get.webgl.org/');

    },

    detectWebAudioAPI: function(){

      if( false){
      //try {
      //  window.AudioContext = window.AudioContext;//||window.webkitAudioContext;
      //}catch(e) {
        this.addFailure( 'Non Webkit Audio API' ,'http://caniuse.com/audio-api' );
      }

    },

    detectMobile: function(){

      var detectM = function () {
        if( navigator.userAgent.match(/Android/i)
        || navigator.userAgent.match(/webOS/i)
        || navigator.userAgent.match(/iPhone/i)
        || navigator.userAgent.match(/iPad/i)
        || navigator.userAgent.match(/iPod/i)
        || navigator.userAgent.match(/BlackBerry/i)
        || navigator.userAgent.match(/Windows Phone/i)
        ){
          return true;
        } else {
          return false;
        }
      }

      var mobile = detectM();

      if( false )
        this.addFailure( "Non Mobile" , "http://cabbibo.tumblr.com" );

    }

  }
<|endoftext|>


<commit_before>
// Node
if (typeof module !== 'undefined' && module.exports) {
    var numeral = require('../../numeral');
    var expect = require('chai').expect;
}

describe('Percentage', function() {
    after(function() {
        numeral.reset();
    });

    it('should format to percentages', function() {
        var tests = [
                [0,'0%','0%'],
                [null,'0 %','0 %'],
                [1,'0%','100%'],
                [0.974878234,'0.000%','97.488%'],
                [-0.43,'0 %','-43 %'],
                [0.43,'(0.00[0]%)','43.00%']
            ],
            i;

        for (i = 0; i < tests.length; i++) {
            expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]);
        }
    });

    it('should unformat to percentages', function() {
        var tests = [
                ['0%', 0],
                ['100%', 1],
                ['97.488%', 0.97488],
                ['-43 %', -0.43],
                ['43.00%', 0.43]
            ],
            i;

        for (i = 0; i < tests.length; i++) {
            expect(numeral(tests[i][0]).value()).to.equal(tests[i][1]);
        }
    });
});
<commit_msg>Tests for the new option: default, enforced true, an enforced false<commit_after>
// Node
if (typeof module !== 'undefined' && module.exports) {
    var numeral = require('../../numeral');
    var expect = require('chai').expect;
}

describe('Percentage', function() {
    after(function() {
        numeral.reset();
    });

    it('should format to percentages with 100 upscale default', function() {
        var tests = [
                [0,'0%','0%'],
                [null,'0 %','0 %'],
                [1,'0%','100%'],
                [0.974878234,'0.000%','97.488%'],
                [-0.43,'0 %','-43 %'],
                [0.43,'(0.00[0]%)','43.00%']
            ],
            i;

        for (i = 0; i < tests.length; i++) {
            expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]);
        }
    });

    it('should unformat to percentages with 100 downscale default', function() {
        var tests = [
                ['0%', 0],
                ['100%', 1],
                ['97.488%', 0.97488],
                ['-43 %', -0.43],
                ['43.00%', 0.43]
            ],
            i;

        for (i = 0; i < tests.length; i++) {
            expect(numeral(tests[i][0]).value()).to.equal(tests[i][1]);
        }
    });

    it('should format to percentages with 100 upscale enforced', function() {
        var tests = [
                [0,'0%','0%'],
                [null,'0 %','0 %'],
                [1,'0%','100%'],
                [0.974878234,'0.000%','97.488%'],
                [-0.43,'0 %','-43 %'],
                [0.43,'(0.00[0]%)','43.00%']
            ],
            i;

        for (i = 0; i < tests.length; i++) {
            numeral.options.scalePercentBy100 = true;
            expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]);
        }
    });

    it('should unformat to percentages with 100 downscale enforced', function() {
        var tests = [
                ['0%', 0],
                ['100%', 1],
                ['97.488%', 0.97488],
                ['-43 %', -0.43],
                ['43.00%', 0.43]
            ],
            i;

        for (i = 0; i < tests.length; i++) {
            numeral.options.scalePercentBy100 = true;
            expect(numeral(tests[i][0]).value()).to.equal(tests[i][1]);
        }
    });

    it('should format to percentages without 100 upscale', function() {
        var tests = [
                [0,'0%','0%'],
                [null,'0 %','0 %'],
                [1,'0%','1%'],
                [97.4878234,'0.000%','97.488%'],
                [-43.0,'0 %','-43 %'],
                [43.0,'(0.00[0]%)','43.00%']
            ],
            i;

        for (i = 0; i < tests.length; i++) {
            numeral.options.scalePercentBy100 = false;
            expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]);
        }
    });

    it('should unformat to percentages without 100 downscale', function() {
        var tests = [
                ['0%', 0],
                ['100%', 100.0],
                ['97.488%', 97.488],
                ['-43 %', -43.0],
                ['43.00%', 43.0]
            ],
            i;

        for (i = 0; i < tests.length; i++) {
            numeral.options.scalePercentBy100 = false;
            expect(numeral(tests[i][0]).value()).to.equal(tests[i][1]);
        }
    });
});
<|endoftext|>