<commit_before>module.exports = function(grunt) {
	grunt.log.writeln('\n---- nwayo report -----');

	var
		// flags
		foundation = grunt.file.exists('css/vendor/foundation/foundation.scss'),
		jshtml     = !!(grunt.file.expand('tmpl/**/*.jshtml').length),

		editor     = grunt.file.exists('css/misc/editor.less'),
		newsletter = grunt.file.exists('misc/newsletter.html'),

		theme      = false,

		// Project configuration.
		tasks = {
			default: ['core_js', 'core_css']
		},

		config = {
			pkg: grunt.file.readJSON('package.json'),

			// cleaner
			clean: {
				builds_tmp: {
					src: ['../assets/builds/*.tmp.*'],
					options: {
						force: true
					}
				}
			},

			// watcher
			watch: {
				all: {
					files: ['gruntfile.js', 'package.json'],
					tasks: 'default'
				},
			}
		},

		// check list report
		checklist = function(name, found) {
			grunt.log.writeln('['+ ((found) ? 'X' : ' ') +'] '+name);
		},

		// get css static libs
		getCssLibs = function(file) {
			var css = [];

			if (foundation) {
				css = [
					'css/libs/normalize.css',
					'../assets/builds/foundation-scss.tmp.css'
				];

			} else if (!theme) {
				css = [
					'css/libs/reset.css',
					'css/libs/normalize.css',
					'css/libs/html5boilerplate.css'
				];
			}

			css.push(file);

			return css;
		}
	;

	checklist('Has theme?', theme);

	// --------------------------------
	// JS
	// --------------------------------
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-requirejs');

	// js hint
	config.jshint = {
		core: {
			src: ['js/**/*.js', '!libs/**/*.js', '!js/vendor/**/*.js']
		}
	};

	// requirejs
	config.requirejs = {
		core: {
			options: {
				baseUrl:  './',
				name:     'js/core',
				include:  ['js/variants'],
				out:      '../assets/builds/core.js',
				optimize: 'uglify', // 'none'
				preserveLicenseComments: false,
				skipModuleInsertion:     true,
				findNestedDependencies:  true,
				pragmasOnSave:           { excludeRequire: true }
			}
		}
	};

	// tasks
	tasks.core_js = [
		'jshint:core',
		'requirejs:core',
		'clean:builds_tmp'
	];

	config.watch.core_js = {
		files: [
			'js/**/*.js',
			'libs/**/*.js'
		],
		tasks: 'core_js'
	};

	// --------------------------------
	// CSS
	// --------------------------------
	grunt.loadNpmTasks('grunt-contrib-less');
	grunt.loadNpmTasks('grunt-contrib-cssmin');

	// less
	config.less = {
		core: { files: { '../assets/builds/core-less.tmp.css': 'css/loader.less' } }
	};

	// css
	config.cssmin = {
		core: { files: { '../assets/builds/core.css': getCssLibs('../assets/builds/core-less.tmp.css') } },
	};

	// task
	tasks.core_css = [
		'less:core',
		'cssmin:core',
		'clean:builds_tmp'
	];

	config.watch.core_css = {
		files: [
			'css/**/*.css',
			'css/**/*.less',
			'!css/misc/**/*'
		],
		tasks: 'core_css'
	};

	// --------------------------------
	// FOUNDATION
	// --------------------------------
	checklist('Foundation', foundation);

	if (foundation) {

		grunt.loadNpmTasks('grunt-contrib-sass');

		config.sass = {
			foundation: { files: { '../assets/builds/foundation-scss.tmp.css': 'css/vendor/foundation/foundation.scss' } },
		};

		tasks.core_css.unshift('sass:foundation');

		config.watch.core_css.files.push('css/**/*.scss');
	}

	// --------------------------------
	// JSHTML
	// --------------------------------
	checklist('JSRender templates', jshtml);

	if (jshtml) {
		grunt.loadNpmTasks('grunt-template-client');

		config.templateclient = {
			core: {
				options: {
					variable: 'nwayo_jshtml',
					prefix: 'window.kafe.dependencies.jQuery.templates(',
					suffix: ')'
				},
				src: ['tmpl/**/*.jshtml'],
				dest: '../assets/builds/templateclient.tmp.js'
			}
		};

		tasks.core_js.unshift('templateclient:core');

		config.watch.core_js.files.push('tmpl/**/*.jshtml');
	}

	// --------------------------------
	// EDITOR
	// --------------------------------
	checklist('Editor styles', editor);

	if (editor) {
		config.less.editor   = { files: { '../assets/builds/editor-less.tmp.css': 'css/misc/editor.less' } };
		config.cssmin.editor = { files: { '../assets/builds/editor.css': getCssLibs('../assets/builds/editor-less.tmp.css') }, };

		grunt.registerTask('editor', [
			'less:editor',
			'cssmin:editor',
			'clean:builds_tmp'
		]);

		tasks.default.push('editor');

		config.watch.editor = {
			files: ['css/misc/editor.less'],
			tasks: 'editor'
		};
	}

	// --------------------------------
	// NEWSLETTER
	// --------------------------------
	checklist('Static newsletter', newsletter);

	if (newsletter) {
		grunt.loadNpmTasks('grunt-inline-css');

		config.less.newsletter = { files: { '../assets/builds/newsletter-less.tmp.css': 'css/misc/newsletter.less' } };
		config.inlinecss = { newsletter: {
			files: { '../assets/builds/newsletter.html': 'misc/newsletter.html' }
		}};

		tasks.newsletter = [
			'less:newsletter',
			'inlinecss:newsletter',
			'clean:builds_tmp'
		];

		tasks.default.push('newsletter');

		config.watch.newsletter = {
			files: ['css/misc/newsletter.less','misc/newsletter.html'],
			tasks: 'newsletter'
		};
	}

	// --------------------------------
	// GRUNT
	// --------------------------------
	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-watch');

	grunt.initConfig(config);

	// tasks
	for (var name in tasks) {
		grunt.registerTask(name, tasks[name]);
	}

	grunt.log.writeln('-----------------------\n');
};

<commit_msg>no message<commit_after>module.exports = function(grunt) {
	grunt.log.writeln('\n---- nwayo report -----');

	var
		// flags
		foundation = grunt.file.exists('css/vendor/foundation/foundation.scss'),
		jshtml     = !!(grunt.file.expand('tmpl/**/*.jshtml').length),

		editor     = grunt.file.exists('css/misc/editor.less'),
		newsletter = grunt.file.exists('misc/newsletter.html'),

		theme      = false,

		// Project configuration.
		tasks = {
			default: ['core_js', 'core_css']
		},

		config = {
			pkg: grunt.file.readJSON('package.json'),

			// cleaner
			clean: {
				builds_tmp: {
					src: ['../assets/builds/*.tmp.*'],
					options: {
						force: true
					}
				}
			},

			// watcher
			watch: {
				all: {
					files: ['gruntfile.js', 'package.json'],
					tasks: 'default'
				},
			}
		},

		// check list report
		checklist = function(name, found) {
			grunt.log.writeln('['+ ((found) ? 'X' : ' ') +'] '+name);
		},

		// get css static libs
		getCssLibs = function(file) {
			var css = [];

			if (foundation) {
				css = [
					'css/libs/normalize.css',
					'../assets/builds/foundation-scss.tmp.css'
				];

			} else if (!theme) {
				css = [
					'css/libs/reset.css',
					'css/libs/normalize.css',
					'css/libs/html5boilerplate.css'
				];
			}

			css.push(file);

			return css;
		}
	;

	checklist('Has theme?', theme);

	// --------------------------------
	// JS
	// --------------------------------
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-requirejs');

	// js hint
	config.jshint = {
		core: {
			src: ['js/**/*.js', '!libs/**/*.js', '!js/vendor/**/*.js']
		}
	};

	// requirejs
	config.requirejs = {
		core: {
			options: {
				baseUrl:  './',
				name:     'js/core',
				include:  ['js/variants'],
				out:      '../assets/builds/core.js',
				optimize: 'uglify', // 'none'
				preserveLicenseComments: false,
				skipModuleInsertion:     true,
				findNestedDependencies:  true,
				pragmasOnSave:           { excludeRequire: true }
			}
		}
	};

	// tasks
	tasks.core_js = [
		'jshint:core',
		'requirejs:core',
		'clean:builds_tmp'
	];

	config.watch.core_js = {
		files: [
			'js/**/*.js',
			'libs/**/*.js'
		],
		tasks: 'core_js'
	};

	// --------------------------------
	// CSS
	// --------------------------------
	grunt.loadNpmTasks('grunt-contrib-less');
	grunt.loadNpmTasks('grunt-contrib-cssmin');

	// less
	config.less = {
		core: { files: { '../assets/builds/core-less.tmp.css': 'css/loader.less' } }
	};

	// css
	config.cssmin = {
		core: { files: { '../assets/builds/core.css': getCssLibs('../assets/builds/core-less.tmp.css') } },
	};

	// task
	tasks.core_css = [
		'less:core',
		'cssmin:core',
		'clean:builds_tmp'
	];

	config.watch.core_css = {
		files: [
			'css/**/*.css',
			'css/**/*.less',
			'!css/misc/**/*'
		],
		tasks: 'core_css'
	};

	// --------------------------------
	// FOUNDATION
	// --------------------------------
	checklist('Foundation', foundation);

	if (foundation) {

		grunt.loadNpmTasks('grunt-contrib-sass');

		config.sass = {
			foundation: { files: { '../assets/builds/foundation-scss.tmp.css': 'css/vendor/foundation/foundation.scss' } },
		};

		tasks.core_css.unshift('sass:foundation');

		config.watch.core_css.files.push('css/**/*.scss');
	}

	// --------------------------------
	// JSHTML
	// --------------------------------
	checklist('JSRender templates', jshtml);

	if (jshtml) {
		grunt.loadNpmTasks('grunt-template-client');

		config.templateclient = {
			core: {
				options: {
					variable: 'nwayo_jshtml',
					prefix: 'window.kafe.dependencies.jQuery.templates(',
					suffix: ')'
				},
				src: ['tmpl/**/*.jshtml'],
				dest: '../assets/builds/templateclient.tmp.js'
			}
		};

		tasks.core_js.unshift('templateclient:core');

		config.watch.core_js.files.push('tmpl/**/*.jshtml');
	}

	// --------------------------------
	// EDITOR
	// --------------------------------
	checklist('Editor styles', editor);

	if (editor) {
		config.less.editor   = { files: { '../assets/builds/editor-less.tmp.css': 'css/misc/editor.less' } };
		config.cssmin.editor = { files: { '../assets/builds/editor.css': getCssLibs('../assets/builds/editor-less.tmp.css') }, };

		grunt.registerTask('editor', [
			'less:editor',
			'cssmin:editor',
			'clean:builds_tmp'
		]);

		tasks.core_css.push('editor');

		config.watch.editor = {
			files: ['css/misc/editor.less'],
			tasks: 'editor'
		};
	}

	// --------------------------------
	// NEWSLETTER
	// --------------------------------
	checklist('Static newsletter', newsletter);

	if (newsletter) {
		grunt.loadNpmTasks('grunt-inline-css');

		config.less.newsletter = { files: { '../assets/builds/newsletter-less.tmp.css': 'css/misc/newsletter.less' } };
		config.inlinecss = { newsletter: {
			files: { '../assets/builds/newsletter.html': 'misc/newsletter.html' }
		}};

		tasks.newsletter = [
			'less:newsletter',
			'inlinecss:newsletter',
			'clean:builds_tmp'
		];

		tasks.core_css.push('newsletter');

		config.watch.newsletter = {
			files: ['css/misc/newsletter.less','misc/newsletter.html'],
			tasks: 'newsletter'
		};
	}

	// --------------------------------
	// GRUNT
	// --------------------------------
	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-watch');

	grunt.initConfig(config);

	// tasks
	for (var name in tasks) {
		grunt.registerTask(name, tasks[name]);
	}

	grunt.log.writeln('-----------------------\n');
};

<|endoftext|>


<commit_before>/**
 * Created by thobber on 13.02.17.
 */
/** @namespace item.categories[0].category */
/** @namespace item.categories.category */
/** @namespace item.categories */

const responseItems = "sources/json/response-items.json";
const responseCategories = "sources/json/response-categories.json";

function readTextFile(file, callback)
{
    let rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function ()
    {
        if (rawFile.readyState === 4 && rawFile.status == "200")
        {
            callback(rawFile.responseText);
        }
    };
    rawFile.send(null);
}

readTextFile(responseCategories, function (text)
{
    const ul_categoryList = document.getElementById("category-list");

    const data = JSON.parse(text);
    for (const item of Object.values(data))
    {
        const categories = item.category[language];

        const categories_a = document.createElement("a");
        const categories_li = document.createElement("li");

        categories_a.textContent = categories;
        categories_a.setAttribute("href", "#");

        categories_li.appendChild(categories_a);
        ul_categoryList.appendChild(categories_li);
    }
});

readTextFile(responseItems, function (text)
{

    const ul_itemList = document.getElementById("main-list");

    const data = JSON.parse(text);
    for (const item of Object.values(data))
    {
        const items_a = document.createElement("a");
        const items_li = document.createElement("li");
        items_a.textContent = item["item_name"];
        items_a.setAttribute("href", "#");

        items_li.appendChild(items_a);
        ul_itemList.appendChild(items_li);
    }
});<commit_msg>Added API support.<commit_after>/**
 * Created by thobber on 13.02.17.
 */
/** @namespace item.categories[0].category */
/** @namespace item.categories.category */
/** @namespace item.categories */

function readTextFile(file, callback)
{
    let rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function ()
    {
        if (rawFile.readyState === 4 && rawFile.status == "200")
        {
            callback(rawFile.responseText);
        }
    };
    rawFile.send(null);
}

const responseCategories = "http://158.39.162.161/api/categories";
readTextFile(responseCategories, function (text)
{
    const ul_categoryList = document.getElementById("category-list");

    const data = JSON.parse(text);
    for (const item of Object.values(data))
    {
        const categories = item.category[language];

        const categories_a = document.createElement("a");
        const categories_li = document.createElement("li");

        categories_a.textContent = categories;
        categories_a.setAttribute("href", "#");

        categories_li.appendChild(categories_a);
        ul_categoryList.appendChild(categories_li);
    }
});

const responseItems = "http://158.39.162.161/api/items";

readTextFile(responseItems, function (text)
{

    const ul_itemList = document.getElementById("main-list");

    const data = JSON.parse(text);
    for (const item of Object.values(data))
    {
        const items_a = document.createElement("a");
        const items_li = document.createElement("li");
        items_a.textContent = item["item_name"];
        items_a.setAttribute("href", "#");

        items_li.appendChild(items_a);
        ul_itemList.appendChild(items_li);
    }
});<|endoftext|>


<commit_before>define( [
    'osg/Utils',
    'osg/StateAttribute',
    'osg/Uniform',
    'osg/Matrix',
    'osg/Vec3',
    'osg/Vec4',
    'osg/Map'
], function ( MACROUTILS, StateAttribute, Uniform, Matrix, Vec3, Vec4, Map ) {
    'use strict';

    var Light = function ( lightNumber ) {
        StateAttribute.call( this );

        if ( lightNumber === undefined ) {
            lightNumber = 0;
        }

        this._ambient = [ 0.2, 0.2, 0.2, 1.0 ];
        this._diffuse = [ 0.8, 0.8, 0.8, 1.0 ];
        this._specular = [ 0.2, 0.2, 0.2, 1.0 ];

        this._position = [ 0.0, 0.0, 1.0, 0.0 ];
        this._direction = [ 0.0, 0.0, -1.0 ];

        this._spotCutoff = 1.0;
        this._spotBlend = 0.01;
        this._falloffType = 'INVERSE_LINEAR';
        this._distance = 25;
        this._attenuation = [ 25.0, 0.0, 1.0, 0.0 ];

        this._energy = 1.0;

        this._lightUnit = lightNumber;
        this._type = 'SPOT';

        this._useSphere = false;
        this._enable = true;
        this._invMatrix = new Matrix.create();
        this.dirty();
    };

    /** @lends Light.prototype */
    Light.uniforms = {};
    Light.prototype = MACROUTILS.objectLibraryClass( MACROUTILS.objectInherit( StateAttribute.prototype, {
        attributeType: 'Light',
        cloneType: function () {
            return new Light( this._lightUnit );
        },
        getType: function () {
            return this.attributeType;
        },
        getTypeMember: function () {
            return this.attributeType + this._lightUnit;
        },
        getUniformName: function ( name ) {
            return this.getPrefix() + '_uniform_' + name;
        },
        getHash: function () {
            return 'Light' + this._lightUnit + this._type + this._falloffType + this._useSphere.toString() + this._ambient.toString() + this._diffuse.toString() + this._specular.toString();
        },
        getOrCreateUniforms: function () {

            var obj = Light;
            var typeMember = this.getTypeMember();

            if ( obj.uniforms[ typeMember ] ) return obj.uniforms[ typeMember ];

            var uniformList = {
                'ambient': 'createFloat4',
                'diffuse': 'createFloat4',
                'specular': 'createFloat4',

                'attenuation': 'createFloat4',
                'position': 'createFloat4',
                'direction': 'createFloat3',

                'spotCutOff': 'createFloat1',
                'spotBlend': 'createFloat1',
                'distance': 'createFloat1'

            };

            var uniforms = {};

            Object.keys( uniformList ).forEach( function ( key ) {

                var type = uniformList[ key ];
                var func = Uniform[ type ];
                uniforms[ key ] = func( this.getUniformName( key ) );

            }.bind( this ) );

            obj.uniforms[ typeMember ] = new Map( uniforms );

            return obj.uniforms[ typeMember ];
        },

        isEnable: function () {
            return this._enable;
        },
        setEnable: function ( bool ) {
            this._enable = bool;
        },
        setPosition: function ( a ) {
            Vec4.copy( a, this._position );
        },
        setDirection: function ( a ) {
            Vec3.copy( a, this._direction );
        },

        setAmbient: function ( a ) {
            Vec3.copy( a, this._ambient );
            this.dirty();
        },
        getAmbient: function () {
            return this._ambient;
        },

        setDiffuse: function ( a ) {
            this._diffuse = a;
            this.dirty();
        },

        getDiffuse: function () {
            return this._diffuse;
        },

        setSpecular: function ( a ) {
            this._specular = a;
            this.dirty();
        },

        getSpecular: function () {
            return this._specular;
        },

        setEnergy: function ( a ) {
            this._energy = a;
            this.dirty();
        },
        getEnergy: function () {
            return this._energy;
        },

        setSpotCutoff: function ( a ) {
            this._spotCutoff = a;
            this.dirty();
        },
        setSpotBlend: function ( a ) {
            this._spotBlend = a;
            this.dirty();
        },

        setConstantAttenuation: function ( value ) {
            this._falloffType = 'INVERSE_CONSTANT';
            this._distance = value;
            this._attenuation[ 0 ] = value;
            this._attenuation[ 1 ] = 1.0;
            this._attenuation[ 2 ] = 0.0;
            this._attenuation[ 3 ] = 0.0;
            this.dirty();
        },

        setLinearAttenuation: function ( value ) {
            this._falloffType = 'INVERSE_LINEAR';
            this._distance = value;
            this._attenuation[ 0 ] = value;
            this._attenuation[ 1 ] = 0.0;
            this._attenuation[ 2 ] = 1.0;
            this._attenuation[ 3 ] = 0.0;

            this.dirty();
        },

        setQuadraticAttenuation: function ( value ) {
            this._falloffType = 'INVERSE_SQUARE';
            this._distance = value;
            this._attenuation[ 0 ] = value;
            this._attenuation[ 1 ] = 0.0;
            this._attenuation[ 2 ] = 0.0;
            this._attenuation[ 3 ] = 1.0;
            this.dirty();
        },

        setLightType: function ( a ) {
            if ( a === 'SUN' || a === 'HEMI' ) {
                this._position = [ 0, 0, -1 ];
            } else {
                this._position = [ 0, 0, 0 ];
            }
            this._type = a;
            this.dirty();
        },
        getLightType: function () {
            return this._type;
        },

        setFalloffType: function ( value ) {
            switch ( value ) {
            case 'INVERSE_LINEAR':
                this.setLinearAttenuation( this._distance );
                break;
            case 'INVERSE_CONSTANT':
                this.setConstantAttenuation( this._distance );
                break;
            case 'INVERSE_SQUARE':
                this.setQuadraticAttenuation( this._distance );
                break;
            default:
                return;
            }
        },
        getFalloffType: function () {
            return this._falloffType;
        },

        setUseSphere: function ( value ) {
            this._useSphere = value;
        },
        getUseSphere: function () {
            return this._useSphere;
        },

        setDistance: function ( value ) {
            this._distance = value;
            this.dirty();
        },
        getDistance: function () {
            return this._distance;
        },

        setLightNumber: function ( unit ) {
            this._lightUnit = unit;
            this.dirty();
        },
        getLightNumber: function () {
            return this._lightUnit;
        },

        getPrefix: function () {
            return this.getType() + this._lightUnit;
        },
        getParameterName: function ( name ) {
            return this.getPrefix() + '_' + name;
        },

        applyPositionedUniform: function ( matrix /*, state*/ ) {

            var uniformMap = this.getOrCreateUniforms();

            if ( this._type === 'SUN' || this._type === 'HEMI' ) {
                Matrix.copy( matrix, this._invMatrix );
                this._invMatrix[ 12 ] = 0.0;
                this._invMatrix[ 13 ] = 0.0;
                this._invMatrix[ 14 ] = 0.0;
                Matrix.inverse( this._invMatrix, this._invMatrix );
                Matrix.transpose( this._invMatrix, this._invMatrix );
                Matrix.transformVec3( this._invMatrix, this._position, uniformMap.position.get() );
            } else {
                Matrix.transformVec3( matrix, this._position, uniformMap.position.get() );
            }
            if ( this._type === 'SPOT' ) {
                Matrix.copy( matrix, this._invMatrix );
                this._invMatrix[ 12 ] = 0.0;
                this._invMatrix[ 13 ] = 0.0;
                this._invMatrix[ 14 ] = 0.0;
                Matrix.inverse( this._invMatrix, this._invMatrix );
                Matrix.transpose( this._invMatrix, this._invMatrix );
                Matrix.transformVec3( this._invMatrix, this._direction, uniformMap.direction.get() );
            }

            uniformMap.position.dirty();
            uniformMap.direction.dirty();
        },

        applyEnergy: function ( colorUniform, colorVar ) {
            var color = colorUniform.get();
            color[ 0 ] = colorVar[ 0 ] * this._energy;
            color[ 1 ] = colorVar[ 1 ] * this._energy;
            color[ 2 ] = colorVar[ 2 ] * this._energy;
            colorUniform.dirty();
        },

        apply: function ( /*state*/) {
            var uniformMap = this.getOrCreateUniforms();

            this.applyEnergy( uniformMap.ambient, this._ambient );
            this.applyEnergy( uniformMap.diffuse, this._diffuse );
            this.applyEnergy( uniformMap.specular, this._specular );

            Vec3.copy( this._position, uniformMap.position.get() );
            Vec3.copy( this._direction, uniformMap.direction.get() );
            uniformMap.position.dirty();
            uniformMap.direction.dirty();

            var spotsize = Math.cos( this._spotCutoff * 0.5 );
            uniformMap.spotCutOff.get()[ 0 ] = spotsize;
            uniformMap.spotCutOff.dirty();

            uniformMap.spotBlend.get()[ 0 ] = ( 1.0 - spotsize ) * this._spotBlend;
            uniformMap.spotBlend.dirty();

            uniformMap.distance.get()[ 0 ] = this._distance;
            uniformMap.distance.dirty();

            Vec4.copy( this._attenuation, uniformMap.attenuation.get() );
            uniformMap.attenuation.dirty();

            this.setDirty( false );
        }

    } ), 'osg', 'Light' );

    MACROUTILS.setTypeID( Light );

    return Light;
} );
<commit_msg>Removes light sphere<commit_after>define( [
    'osg/Utils',
    'osg/StateAttribute',
    'osg/Uniform',
    'osg/Matrix',
    'osg/Vec3',
    'osg/Vec4',
    'osg/Map'
], function ( MACROUTILS, StateAttribute, Uniform, Matrix, Vec3, Vec4, Map ) {
    'use strict';

    var Light = function ( lightNumber ) {
        StateAttribute.call( this );

        if ( lightNumber === undefined ) {
            lightNumber = 0;
        }

        this._ambient = [ 0.2, 0.2, 0.2, 1.0 ];
        this._diffuse = [ 0.8, 0.8, 0.8, 1.0 ];
        this._specular = [ 0.2, 0.2, 0.2, 1.0 ];

        this._position = [ 0.0, 0.0, 1.0, 0.0 ];
        this._direction = [ 0.0, 0.0, -1.0 ];

        this._spotCutoff = 1.0;
        this._spotBlend = 0.01;
        this._falloffType = 'INVERSE_LINEAR';
        this._distance = 25;
        this._attenuation = [ 25.0, 0.0, 1.0, 0.0 ];

        this._energy = 1.0;

        this._lightUnit = lightNumber;
        this._type = 'SPOT';

        this._enable = true;
        this._invMatrix = new Matrix.create();
        this.dirty();
    };

    /** @lends Light.prototype */
    Light.uniforms = {};
    Light.prototype = MACROUTILS.objectLibraryClass( MACROUTILS.objectInherit( StateAttribute.prototype, {
        attributeType: 'Light',
        cloneType: function () {
            return new Light( this._lightUnit );
        },
        getType: function () {
            return this.attributeType;
        },
        getTypeMember: function () {
            return this.attributeType + this._lightUnit;
        },
        getUniformName: function ( name ) {
            return this.getPrefix() + '_uniform_' + name;
        },
        getHash: function () {
            return 'Light' + this._lightUnit + this._type + this._falloffType + this._ambient.toString() + this._diffuse.toString() + this._specular.toString();
        },
        getOrCreateUniforms: function () {

            var obj = Light;
            var typeMember = this.getTypeMember();

            if ( obj.uniforms[ typeMember ] ) return obj.uniforms[ typeMember ];

            var uniformList = {
                'ambient': 'createFloat4',
                'diffuse': 'createFloat4',
                'specular': 'createFloat4',

                'attenuation': 'createFloat4',
                'position': 'createFloat4',
                'direction': 'createFloat3',

                'spotCutOff': 'createFloat1',
                'spotBlend': 'createFloat1',
                'distance': 'createFloat1'

            };

            var uniforms = {};

            Object.keys( uniformList ).forEach( function ( key ) {

                var type = uniformList[ key ];
                var func = Uniform[ type ];
                uniforms[ key ] = func( this.getUniformName( key ) );

            }.bind( this ) );

            obj.uniforms[ typeMember ] = new Map( uniforms );

            return obj.uniforms[ typeMember ];
        },

        isEnable: function () {
            return this._enable;
        },
        setEnable: function ( bool ) {
            this._enable = bool;
        },
        setPosition: function ( a ) {
            Vec4.copy( a, this._position );
        },
        setDirection: function ( a ) {
            Vec3.copy( a, this._direction );
        },

        setAmbient: function ( a ) {
            Vec3.copy( a, this._ambient );
            this.dirty();
        },
        getAmbient: function () {
            return this._ambient;
        },

        setDiffuse: function ( a ) {
            this._diffuse = a;
            this.dirty();
        },

        getDiffuse: function () {
            return this._diffuse;
        },

        setSpecular: function ( a ) {
            this._specular = a;
            this.dirty();
        },

        getSpecular: function () {
            return this._specular;
        },

        setEnergy: function ( a ) {
            this._energy = a;
            this.dirty();
        },
        getEnergy: function () {
            return this._energy;
        },

        setSpotCutoff: function ( a ) {
            this._spotCutoff = a;
            this.dirty();
        },
        setSpotBlend: function ( a ) {
            this._spotBlend = a;
            this.dirty();
        },

        setConstantAttenuation: function ( value ) {
            this._falloffType = 'INVERSE_CONSTANT';
            this._distance = value;
            this._attenuation[ 0 ] = value;
            this._attenuation[ 1 ] = 1.0;
            this._attenuation[ 2 ] = 0.0;
            this._attenuation[ 3 ] = 0.0;
            this.dirty();
        },

        setLinearAttenuation: function ( value ) {
            this._falloffType = 'INVERSE_LINEAR';
            this._distance = value;
            this._attenuation[ 0 ] = value;
            this._attenuation[ 1 ] = 0.0;
            this._attenuation[ 2 ] = 1.0;
            this._attenuation[ 3 ] = 0.0;

            this.dirty();
        },

        setQuadraticAttenuation: function ( value ) {
            this._falloffType = 'INVERSE_SQUARE';
            this._distance = value;
            this._attenuation[ 0 ] = value;
            this._attenuation[ 1 ] = 0.0;
            this._attenuation[ 2 ] = 0.0;
            this._attenuation[ 3 ] = 1.0;
            this.dirty();
        },

        setLightType: function ( a ) {
            if ( a === 'SUN' || a === 'HEMI' ) {
                this._position = [ 0, 0, -1 ];
            } else {
                this._position = [ 0, 0, 0 ];
            }
            this._type = a;
            this.dirty();
        },
        getLightType: function () {
            return this._type;
        },

        setFalloffType: function ( value ) {
            switch ( value ) {
            case 'INVERSE_LINEAR':
                this.setLinearAttenuation( this._distance );
                break;
            case 'INVERSE_CONSTANT':
                this.setConstantAttenuation( this._distance );
                break;
            case 'INVERSE_SQUARE':
                this.setQuadraticAttenuation( this._distance );
                break;
            default:
                return;
            }
        },
        getFalloffType: function () {
            return this._falloffType;
        },

        setDistance: function ( value ) {
            this._distance = value;
            this.dirty();
        },
        getDistance: function () {
            return this._distance;
        },

        setLightNumber: function ( unit ) {
            this._lightUnit = unit;
            this.dirty();
        },
        getLightNumber: function () {
            return this._lightUnit;
        },

        getPrefix: function () {
            return this.getType() + this._lightUnit;
        },
        getParameterName: function ( name ) {
            return this.getPrefix() + '_' + name;
        },

        applyPositionedUniform: function ( matrix /*, state*/ ) {

            var uniformMap = this.getOrCreateUniforms();

            if ( this._type === 'SUN' || this._type === 'HEMI' ) {
                Matrix.copy( matrix, this._invMatrix );
                this._invMatrix[ 12 ] = 0.0;
                this._invMatrix[ 13 ] = 0.0;
                this._invMatrix[ 14 ] = 0.0;
                Matrix.inverse( this._invMatrix, this._invMatrix );
                Matrix.transpose( this._invMatrix, this._invMatrix );
                Matrix.transformVec3( this._invMatrix, this._position, uniformMap.position.get() );
            } else {
                Matrix.transformVec3( matrix, this._position, uniformMap.position.get() );
            }
            if ( this._type === 'SPOT' ) {
                Matrix.copy( matrix, this._invMatrix );
                this._invMatrix[ 12 ] = 0.0;
                this._invMatrix[ 13 ] = 0.0;
                this._invMatrix[ 14 ] = 0.0;
                Matrix.inverse( this._invMatrix, this._invMatrix );
                Matrix.transpose( this._invMatrix, this._invMatrix );
                Matrix.transformVec3( this._invMatrix, this._direction, uniformMap.direction.get() );
            }

            uniformMap.position.dirty();
            uniformMap.direction.dirty();
        },

        applyEnergy: function ( colorUniform, colorVar ) {
            var color = colorUniform.get();
            color[ 0 ] = colorVar[ 0 ] * this._energy;
            color[ 1 ] = colorVar[ 1 ] * this._energy;
            color[ 2 ] = colorVar[ 2 ] * this._energy;
            colorUniform.dirty();
        },

        apply: function ( /*state*/) {
            var uniformMap = this.getOrCreateUniforms();

            this.applyEnergy( uniformMap.ambient, this._ambient );
            this.applyEnergy( uniformMap.diffuse, this._diffuse );
            this.applyEnergy( uniformMap.specular, this._specular );

            Vec3.copy( this._position, uniformMap.position.get() );
            Vec3.copy( this._direction, uniformMap.direction.get() );
            uniformMap.position.dirty();
            uniformMap.direction.dirty();

            var spotsize = Math.cos( this._spotCutoff * 0.5 );
            uniformMap.spotCutOff.get()[ 0 ] = spotsize;
            uniformMap.spotCutOff.dirty();

            uniformMap.spotBlend.get()[ 0 ] = ( 1.0 - spotsize ) * this._spotBlend;
            uniformMap.spotBlend.dirty();

            uniformMap.distance.get()[ 0 ] = this._distance;
            uniformMap.distance.dirty();

            Vec4.copy( this._attenuation, uniformMap.attenuation.get() );
            uniformMap.attenuation.dirty();

            this.setDirty( false );
        }

    } ), 'osg', 'Light' );

    MACROUTILS.setTypeID( Light );

    return Light;
} );
<|endoftext|>


<commit_before>import { Mongo } from 'meteor/mongo';

export const Rooms = new Meteor.Collection("rooms",
{
    transform:function(entry)
    {
        entry.getRightDirection = function(direction) {
          switch (direction) {
          case 'N':
            return('E');
          case 'E':
            return('S');
          case 'S':
            return('W');
          default:
            return('N');
          }
        };
        entry.goLeft = function(){ return(undefined);};
        entry.goRight = function(direction) {
          return(this.passages[this.getRightDirection(direction)]);
        };
        entry.goForward = function(direction) {
          return(this.passages[direction]);
        };
        entry.toString = function() {
          return(this.x.toString() + "," + this.y.toString());
        };
        return entry;
    }
});
<commit_msg>get left direction<commit_after>import { Mongo } from 'meteor/mongo';

export const Rooms = new Meteor.Collection("rooms",
{
    transform:function(entry)
    {
        entry.getLeftDirection = function(direction) {
          switch (direction) {
          case 'N':
            return('W');
          case 'E':
            return('N');
          case 'S':
            return('E');
          default:
            return('S');
          }
        };
        entry.getRightDirection = function(direction) {
          switch (direction) {
          case 'N':
            return('E');
          case 'E':
            return('S');
          case 'S':
            return('W');
          default:
            return('N');
          }
        };
        entry.goLeft = function(direction) {
          return(this.passages[this.getLeftDirection(direction)]);
        };
        entry.goRight = function(direction) {
          return(this.passages[this.getRightDirection(direction)]);
        };
        entry.goForward = function(direction) {
          return(this.passages[direction]);
        };
        entry.toString = function() {
          return(this.x.toString() + "," + this.y.toString());
        };
        return entry;
    }
});
<|endoftext|>


<commit_before>import string from 'string'

const slugify = s =>
  string(s).slugify().toString()

const position = {
  false: 'push',
  true: 'unshift'
}

const renderPermalink = (slug, opts, state, idx) => {
  const space = () =>
    Object.assign(new state.Token('text', '', 0), { content: ' ' })

  const linkTokens = [
    Object.assign(new state.Token('link_open', 'a', 1), {
      attrs: [
        ['class', opts.permalinkClass],
        ['href', `#${slug}`],
        ['aria-hidden', 'true']
      ]
    }),
    Object.assign(new state.Token('html_block', '', 0), { content: opts.permalinkSymbol }),
    new state.Token('link_close', 'a', -1)
  ]

  // `push` or `unshift` according to position option.
  // Space is at the opposite side.
  linkTokens[position[!opts.permalinkBefore]](space())
  state.tokens[idx + 1].children[position[opts.permalinkBefore]](...linkTokens)
}

const uniqueSlug = (slug, slugs) => {
  // Mark this slug as used in the environment.
  slugs[slug] = (slugs[slug] || 0) + 1

  // First slug, return as is.
  if (slugs[slug] === 1) {
    return slug
  }

  // Duplicate slug, add a `-2`, `-3`, etc. to keep ID unique.
  return slug + '-' + slugs[slug]
}

const anchor = (md, opts) => {
  opts = Object.assign({}, anchor.defaults, opts)

  md.core.ruler.push('anchor', state => {
    const slugs = {}
    const tokens = state.tokens

    tokens
      .filter(token => token.type === 'heading_open')
      .filter(token => token.tag.substr(1) >= opts.level)
      .forEach(token => {
        // Aggregate the next token children text.
        const title = tokens[tokens.indexOf(token) + 1].children
          .filter(token => token.type === 'text')
          .reduce((acc, t) => acc + t.content, '')

        const slug = uniqueSlug(opts.slugify(title), slugs)

        token.attrPush(['id', slug])

        if (opts.permalink) {
          opts.renderPermalink(slug, opts, state, tokens.indexOf(token))
        }

        if (opts.callback) {
          opts.callback(token, { slug, title })
        }
      })
  })
}

anchor.defaults = {
  level: 1,
  slugify,
  permalink: false,
  renderPermalink,
  permalinkClass: 'header-anchor',
  permalinkSymbol: '¶',
  permalinkBefore: false
}

export default anchor
<commit_msg>Update index.es6<commit_after>import string from 'string'

const slugify = s =>
  string(s).slugify().toString()

const position = {
  false: 'push',
  true: 'unshift'
}

const hasProp = ({}).hasOwnProperty;

const renderPermalink = (slug, opts, state, idx) => {
  const space = () =>
    Object.assign(new state.Token('text', '', 0), { content: ' ' })

  const linkTokens = [
    Object.assign(new state.Token('link_open', 'a', 1), {
      attrs: [
        ['class', opts.permalinkClass],
        ['href', `#${slug}`],
        ['aria-hidden', 'true']
      ]
    }),
    Object.assign(new state.Token('html_block', '', 0), { content: opts.permalinkSymbol }),
    new state.Token('link_close', 'a', -1)
  ]

  // `push` or `unshift` according to position option.
  // Space is at the opposite side.
  linkTokens[position[!opts.permalinkBefore]](space())
  state.tokens[idx + 1].children[position[opts.permalinkBefore]](...linkTokens)
}

const uniqueSlug = (slug, slugs) => {
  // Mark this slug as used in the environment.
  slugs[slug] = (hasProp.call(slugs, slug) ? slugs[slug] : 0) + 1

  // First slug, return as is.
  if (slugs[slug] === 1) {
    return slug
  }

  // Duplicate slug, add a `-2`, `-3`, etc. to keep ID unique.
  return slug + '-' + slugs[slug]
}

const anchor = (md, opts) => {
  opts = Object.assign({}, anchor.defaults, opts)

  md.core.ruler.push('anchor', state => {
    const slugs = {}
    const tokens = state.tokens

    tokens
      .filter(token => token.type === 'heading_open')
      .filter(token => token.tag.substr(1) >= opts.level)
      .forEach(token => {
        // Aggregate the next token children text.
        const title = tokens[tokens.indexOf(token) + 1].children
          .filter(token => token.type === 'text')
          .reduce((acc, t) => acc + t.content, '')

        const slug = uniqueSlug(opts.slugify(title), slugs)

        token.attrPush(['id', slug])

        if (opts.permalink) {
          opts.renderPermalink(slug, opts, state, tokens.indexOf(token))
        }

        if (opts.callback) {
          opts.callback(token, { slug, title })
        }
      })
  })
}

anchor.defaults = {
  level: 1,
  slugify,
  permalink: false,
  renderPermalink,
  permalinkClass: 'header-anchor',
  permalinkSymbol: '¶',
  permalinkBefore: false
}

export default anchor
<|endoftext|>


<commit_before>"use strict";

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  Navigator,
  TextInput,
  TouchableHighlight,
  ActivityIndicatorIOS,
  View
} from 'react-native';

import fetchWeather from "./App/Api/weatherapi"
import TrailList from "./App/Components/TrailList"
import weatherIcon from "./App/Utils/icons"
import Trail from './App/Components/Trail'
import Weather from './App/Components/Weather'
import Local from './App/Components/Local'
import Map from './App/Components/Map'
import Landmark from './App/Components/Landmark'
import LandmarkList from './App/Components/LandmarkList'

var Main = require('./App/Components/Main');

class CycleTheBay extends React.Component {

  renderScene(route,navigator) {
    if (route.name == 'Main') {
      return <Main navigator={navigator} />
    }
    if (route.name == 'Trails') {
      return <TrailList navigator={navigator} />
    }
    if (route.name == 'Trail') {
      return <Trail navigator={navigator} {...route.passProps} />
    }
    if (route.name == 'Weather') {
      return <Weather navigator={navigator} />
    }
    if (route.name == 'Local') {
      return <Local navigator={navigator} />
    }
    if (route.name == 'Map') {
      return <Map navigator={navigator} />
    }
    if (route.name == 'Landmarks') {
      return <LandmarkList navigator={navigator} {...route.passProps} />
    }
    if (route.name == 'Landmark') {
      return <Landmark navigator={navigator} {...route.passProps} />
    }
  }

  render() {
    return (
      <Navigator
        style={{ flex: 1 }}
        initialRoute={{ name: 'Main' }}
        renderScene={ this.renderScene }
      />
    );
  }
};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ffff'
  }
});

AppRegistry.registerComponent('CycleTheBay', () => CycleTheBay);
<commit_msg>Optimize navigator transitions<commit_after>"use strict";

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  Navigator,
  TextInput,
  TouchableHighlight,
  ActivityIndicatorIOS,
  View
} from 'react-native';

import fetchWeather from "./App/Api/weatherapi"
import TrailList from "./App/Components/TrailList"
import weatherIcon from "./App/Utils/icons"
import Trail from './App/Components/Trail'
import Weather from './App/Components/Weather'
import Local from './App/Components/Local'
import Map from './App/Components/Map'
import Landmark from './App/Components/Landmark'
import LandmarkList from './App/Components/LandmarkList'

var Main = require('./App/Components/Main');

const SCREEN_WIDTH = require('Dimensions').get('window').width;

/**
 * Overwrite the default navigator scene config.
 * to use a wider area for back swiping.
 */
const FloatFromRight = {
  ...Navigator.SceneConfigs.FloatFromRight,
  gestures: {
    pop: {
      ...Navigator.SceneConfigs.FloatFromRight.gestures.pop,
      edgeHitWidth: SCREEN_WIDTH / 2,
    },
  },
};

class CycleTheBay extends React.Component {

  renderScene(route,navigator) {
    if (route.name == 'Main') {
      return <Main navigator={navigator} />
    }
    if (route.name == 'Trails') {
      return <TrailList navigator={navigator} />
    }
    if (route.name == 'Trail') {
      return <Trail navigator={navigator} {...route.passProps} />
    }
    if (route.name == 'Weather') {
      return <Weather navigator={navigator} />
    }
    if (route.name == 'Local') {
      return <Local navigator={navigator} />
    }
    if (route.name == 'Map') {
      return <Map navigator={navigator} />
    }
    if (route.name == 'Landmarks') {
      return <LandmarkList navigator={navigator} {...route.passProps} />
    }
    if (route.name == 'Landmark') {
      return <Landmark navigator={navigator} {...route.passProps} />
    }
  }

  render() {
    return (
      <Navigator
        style={{ flex: 1 }}
        initialRoute={{ name: 'Main' }}
        renderScene={ this.renderScene }
        configureScene={ () => FloatFromRight }
      />
    );
  }
};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ffff'
  }
});

AppRegistry.registerComponent('CycleTheBay', () => CycleTheBay);
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { AppRegistry,
  Text,
  View,
  TouchableHighlight } from 'react-native';
import formatTime from 'minutes-seconds-milliseconds';

import { styles } from './src/styles';

class Stopwatch extends Component {
  constructor(props) {
    super(props);
    this.state = {
      timeElasped: null,
      timerRunning: false,
      startTime: null,
      laps: [],
    };
    this.onStartPress = this.onStartPress.bind(this);
    this.onLapPress = this.onLapPress.bind(this);
  }

  // pressing start/stop button
  onStartPress() {
    // check if clock is running, then stop
    if (this.state.timerRunning) {
      clearInterval(this.interval);
      this.setState({
        timerRunning: false,
      });
      return;
    }

    this.setState({
      startTime: new Date(),
    });

    this.interval = setInterval(() => {
      this.setState({
        timeElasped: new Date() - this.state.startTime,
        timerRunning: true,
      });
    }, 30);
  }

  // pressing lap/restart button
  onLapPress() {
    // Reset timer
    if (!this.state.timerRunning) {
      this.setState({
        timeElasped: new Date(),
        laps: [],
      });
      return;
    }

    const lap = this.state.timeElasped;

    this.setState({
      startTime: new Date(),
      laps: this.state.laps.concat(lap),
    });
  }

  // create laps list
  createLaps() {
    return this.state.laps.map((time, idx) => (
      <View key={idx} style={styles.lap}>
        <Text style={styles.lapText}>
          Lap #{idx + 1}: {formatTime(time)}
        </Text>
      </View>
    ));
  }

  // create start/stop buttons
  startStopButton() {
    const style = this.state.timerRunning ? styles.stopButton : styles.startButton;

    return (
      <TouchableHighlight
        onPress={this.onStartPress}
        underlayColor="#e6e6fa"
        style={[styles.button, style]}
      >
        <Text>
          {this.state.timerRunning ? 'Stop' : 'Start'}
        </Text>
      </TouchableHighlight>
    );
  }

  // create the lap button
  lapButton() {
    return (
      <TouchableHighlight
        onPress={this.onLapPress}
        underlayColor="#e6e6fa"
        style={styles.button}
      >
        <Text>
          {this.state.timerRunning ? 'Lap' : 'Reset'}
        </Text>
      </TouchableHighlight>
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <View style={styles.timerWrapper}>
            <Text style={styles.time}>{formatTime(this.state.timeElasped)}</Text>
          </View>

          <View style={styles.buttonWrapper}>
            {this.startStopButton()}
            {this.lapButton()}
          </View>
        </View>

        <View style={styles.footer}>
          {this.createLaps()}
        </View>
      </View>
    );
  }
}

AppRegistry.registerComponent('stopwatch', () => Stopwatch);
<commit_msg>Enable scroll for laps view<commit_after>import React, { Component } from 'react';
import { AppRegistry,
  Text,
  View,
  ScrollView,
  TouchableHighlight } from 'react-native';
import formatTime from 'minutes-seconds-milliseconds';

import { styles } from './src/styles';

class Stopwatch extends Component {
  constructor(props) {
    super(props);
    this.state = {
      timeElasped: null,
      timerRunning: false,
      startTime: null,
      laps: [],
    };
    this.onStartPress = this.onStartPress.bind(this);
    this.onLapPress = this.onLapPress.bind(this);
  }

  // pressing start/stop button
  onStartPress() {
    // check if clock is running, then stop
    if (this.state.timerRunning) {
      clearInterval(this.interval);
      this.setState({
        timerRunning: false,
      });
      return;
    }

    this.setState({
      startTime: new Date(),
    });

    this.interval = setInterval(() => {
      this.setState({
        timeElasped: new Date() - this.state.startTime,
        timerRunning: true,
      });
    }, 30);
  }

  // pressing lap/restart button
  onLapPress() {
    // Reset timer
    if (!this.state.timerRunning) {
      this.setState({
        timeElasped: new Date(),
        laps: [],
      });
      return;
    }

    const lap = this.state.timeElasped;

    this.setState({
      startTime: new Date(),
      laps: this.state.laps.concat(lap),
    });
  }

  // create laps list
  createLaps() {
    return this.state.laps.map((time, idx) => (
      <View key={idx} style={styles.lap}>
        <Text style={styles.lapText}>
          Lap #{idx + 1}: {formatTime(time)}
        </Text>
      </View>
    ));
  }

  // create start/stop buttons
  startStopButton() {
    const style = this.state.timerRunning ? styles.stopButton : styles.startButton;

    return (
      <TouchableHighlight
        onPress={this.onStartPress}
        underlayColor="#e6e6fa"
        style={[styles.button, style]}
      >
        <Text>
          {this.state.timerRunning ? 'Stop' : 'Start'}
        </Text>
      </TouchableHighlight>
    );
  }

  // create the lap button
  lapButton() {
    return (
      <TouchableHighlight
        onPress={this.onLapPress}
        underlayColor="#e6e6fa"
        style={styles.button}
      >
        <Text>
          {this.state.timerRunning ? 'Lap' : 'Reset'}
        </Text>
      </TouchableHighlight>
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <View style={styles.timerWrapper}>
            <Text style={styles.time}>{formatTime(this.state.timeElasped)}</Text>
          </View>

          <View style={styles.buttonWrapper}>
            {this.startStopButton()}
            {this.lapButton()}
          </View>
        </View>

        <ScrollView style={styles.footer}>
          {this.createLaps()}
        </ScrollView>
      </View>
    );
  }
}

AppRegistry.registerComponent('stopwatch', () => Stopwatch);
<|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

var PropertyFinder = React.createClass({
  render: function() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.ios.js
        </Text>
        <Text style={styles.instructions}>
          Press Cmd+R to reload,{'\n'}
          Cmd+D or shake for dev menu
        </Text>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('PropertyFinder', () => PropertyFinder);
<commit_msg>Hello React Native<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');

class PropertyFinderApp extends React.Component {
  render() {
    return React.createElement(React.Text, {style: styles.text}, "hello World");
  }
}

var styles = React.StyleSheet.create({
  text: {
    color: 'black',
    backgroundColor: 'white',
    fontSize: 30,
    margin: 80
  }
});

React.AppRegistry.registerComponent('PropertyFinder', function(){return PropertyFinderApp});
<|endoftext|>


<commit_before>// @flow

import { NativeModules } from 'react-native'
const PermissionsIOS = NativeModules.ReactNativePermissions

const permissionTypes = [
  'location',
  'camera',
  'microphone',
  'photo',
  'contacts',
  'event',
  'reminder',
  'bluetooth',
  'notification',
  'backgroundRefresh',
  'speechRecognition',
]

const DEFAULTS = {
  location: 'whenInUse',
  notification: ['alert', 'badge', 'sound'],
}

class ReactNativePermissions {
  canOpenSettings = () => PermissionsIOS.canOpenSettings()
  openSettings = () => PermissionsIOS.openSettings()
  getTypes = () => permissionTypes

  check = (permission, type) => {
    if (!permissionTypes.includes(permission)) {
      return Promise.reject(
        `ReactNativePermissions: ${
          permission
        } is not a valid permission type on iOS`,
      )
    }

    return PermissionsIOS.getPermissionStatus(
      permission,
      type || DEFAULTS[permission],
    )
  }

  request = (permission, options) => {
    let type = null;
    if (typeof options === 'string' || options instanceof Array) {
      console.warn('[react-native-permissions] : You are using a deprecated version of request(). You should use an object as second parameter. Please check the documentation for more information : https://github.com/yonahforst/react-native-permissions');
      type = options;
    } else if (options != null) {
      type = options.type;
    }

    if (!permissionTypes.includes(permission)) {
      return Promise.reject(
        `ReactNativePermissions: ${
          permission
        } is not a valid permission type on iOS`,
      )
    }

    if (permission == 'backgroundRefresh') {
      return Promise.reject(
        'ReactNativePermissions: You cannot request backgroundRefresh',
      )
    }

    return PermissionsIOS.requestPermission(
      permission,
      type || DEFAULTS[permission],
    )
  }

  checkMultiple = permissions =>
    Promise.all(permissions.map(permission => this.check(permission))).then(
      result =>
        result.reduce((acc, value, index) => {
          const name = permissions[index]
          acc[name] = value
          return acc
        }, {}),
    )
}

module.exports = new ReactNativePermissions()
<commit_msg>Remove blank line.<commit_after>// @flow

import { NativeModules } from 'react-native'
const PermissionsIOS = NativeModules.ReactNativePermissions

const permissionTypes = [
  'location',
  'camera',
  'microphone',
  'photo',
  'contacts',
  'event',
  'reminder',
  'bluetooth',
  'notification',
  'backgroundRefresh',
  'speechRecognition',
]

const DEFAULTS = {
  location: 'whenInUse',
  notification: ['alert', 'badge', 'sound'],
}

class ReactNativePermissions {
  canOpenSettings = () => PermissionsIOS.canOpenSettings()
  openSettings = () => PermissionsIOS.openSettings()
  getTypes = () => permissionTypes

  check = (permission, type) => {
    if (!permissionTypes.includes(permission)) {
      return Promise.reject(
        `ReactNativePermissions: ${
          permission
        } is not a valid permission type on iOS`,
      )
    }

    return PermissionsIOS.getPermissionStatus(
      permission,
      type || DEFAULTS[permission],
    )
  }

  request = (permission, options) => {
    let type = null
    if (typeof options === 'string' || options instanceof Array) {
      console.warn(
        '[react-native-permissions] : You are using a deprecated version of request(). You should use an object as second parameter. Please check the documentation for more information : https://github.com/yonahforst/react-native-permissions',
      )
      type = options
    } else if (options != null) {
      type = options.type
    }

    if (!permissionTypes.includes(permission)) {
      return Promise.reject(
        `ReactNativePermissions: ${
          permission
        } is not a valid permission type on iOS`,
      )
    }

    if (permission == 'backgroundRefresh') {
      return Promise.reject(
        'ReactNativePermissions: You cannot request backgroundRefresh',
      )
    }

    return PermissionsIOS.requestPermission(
      permission,
      type || DEFAULTS[permission],
    )
  }

  checkMultiple = permissions =>
    Promise.all(permissions.map(permission => this.check(permission))).then(
      result =>
        result.reduce((acc, value, index) => {
          const name = permissions[index]
          acc[name] = value
          return acc
        }, {}),
    )
}

module.exports = new ReactNativePermissions()
<|endoftext|>


<commit_before>var React = require('react-native');
var moment = require('moment');
var Dimensions = require('Dimensions');

var {
  AppRegistry,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  TouchableWithoutFeedback,
  View
} = React;

const DAYS = ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  MAX_COLUMNS = 7,
  MAX_ROWS = 7,
  DEVICE_WIDTH = Dimensions.get('window').width;

var _currentMonthIndex;

class CalendarSwiper extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      calendarDates: [moment().format()],
      selectedDate: null,
      currentMonth: moment().format()
    }
  }

  renderHeading() {
    return (
      <View style={styles.calendarHeading}>
        {DAYS.map((day) => { return (<Text style={styles.dayListDay}>{day}</Text>) })}
      </View>
    )
  }

  renderControls(date) {
    return (
      <View style={styles.calendarControls}>
        <TouchableOpacity style={styles.controlButton} onPress={this._onPrev.bind(this)}>
          <Text>Prev</Text>
        </TouchableOpacity>
        <Text style={styles.title}>
          {moment(this.state.currentMonth).format('MMMM YYYY')}
        </Text>
        <TouchableOpacity style={styles.controls} onPress={this._onNext.bind(this)}>
          <Text>Next</Text>
        </TouchableOpacity>
      </View>
    )
  }

  componentDidMount() {
    _currentMonthIndex = 1;
    this._prependMonth();
    this._appendMonth();
    this._scrollToItem(_currentMonthIndex);
  }

  renderMonthView(date) {

    var dayStart = moment(date).startOf('month').format(),
      daysInMonth = moment(dayStart).daysInMonth(),
      offset = moment(dayStart).get('day'),
      preFiller = 0,
      currentDay = 0,
      weekRows = [];

    for (var i = 0; i < MAX_COLUMNS; i++) {
      var days = [];
      for (var j = 0; j < MAX_ROWS; j++) {
        if (preFiller < offset) {
          days.push(<TouchableWithoutFeedback><Text style={styles.dayListDay}></Text></TouchableWithoutFeedback>);
        } else {
          if(currentDay < daysInMonth) {
            days.push((
              <TouchableOpacity
                onPress={this._selectDate.bind(this, moment(dayStart).set('date', currentDay + 1))}>
                <Text style={styles.dayListDay}>{currentDay+1}</Text>
              </TouchableOpacity>
            ));
            currentDay++;
          }
        }
        preFiller++;
      } // row

      if(days.length > 0 && days.length < 7) {
        for (var x = days.length; x < 7; x++) {
          days.push(<TouchableWithoutFeedback><Text style={styles.dayListDay}></Text></TouchableWithoutFeedback>);
        }
        weekRows.push(<View style={styles.dayList}>{days}</View>);
      } else {
        weekRows.push(<View style={styles.dayList}>{days}</View>);
      }
    } // column

    return (
      <View ref="InnerScrollView" style={styles.calendarContainer}>
      {weekRows}
      <Text>{moment(date).format('MMMM')}</Text>
      </View>
    );
  }

  _onPrev(){
    this._prependMonth();
    this._scrollToItem(_currentMonthIndex);

  }
  _onNext(){
    _currentMonthIndex++;
    this._appendMonth();
    this._scrollToItem(_currentMonthIndex);
  }

  _prependMonth() {
    console.log('prepending');
    var calendarDates = this.state.calendarDates;
    calendarDates.unshift(moment(calendarDates[0]).subtract(1, 'month').format());
    this.setState({
      calendarDates: calendarDates,
      currentMonth: calendarDates[_currentMonthIndex]
    });
  }

  _appendMonth(){
    console.log('appending');
    var calendarDates = this.state.calendarDates;
    calendarDates.push(moment(calendarDates[calendarDates.length - 1]).add(1, 'month').format());
    this.setState({
      calendarDates: calendarDates,
      currentMonth: calendarDates[_currentMonthIndex]
    });
  }

  _selectDate(date) {
    console.log(date.format());
  }

  _scrollToItem(itemIndex) {
      var scrollToX = itemIndex * DEVICE_WIDTH;
      this.refs.calendar.scrollWithoutAnimationTo(0, scrollToX);
  }

  _scrollEnded(event) {
    var position = event.nativeEvent.contentOffset.x;
    var currentPage = position / DEVICE_WIDTH;

    if (currentPage < _currentMonthIndex) {
      console.log('User Swiped Back');
      this._prependMonth();
      this._scrollToItem(_currentMonthIndex);

    } else if (currentPage > _currentMonthIndex) {
      console.log('User Swiped Forward');
      _currentMonthIndex++;
      this._appendMonth();
      this._scrollToItem(_currentMonthIndex);
    } else {
        console.log('Same Page - Returning false');
        return false;
    }
  }

  render() {
    console.log(this.refs.calendar);
    return (
      <View>
        {this.renderControls()}
        {this.renderHeading()}
        <ScrollView
          ref='calendar'
          horizontal={true}
          bounces={false}
          pagingEnabled={true}
          removeClippedSubviews={true}
          scrollEventThrottle={600}
          showsHorizontalScrollIndicator={false}
          onMomentumScrollEnd={(event) => this._scrollEnded(event)}>
          {this.state.calendarDates.map((date) => { return this.renderMonthView(date) })}
        </ScrollView>
      </View>
    )
  }
};
  var styles = StyleSheet.create({
    calendarContainer: {
      width: DEVICE_WIDTH
    },
    title: {
      textAlign: 'center',
      flex: 2,
    },
    calendarControls: {
      flexDirection: 'row',
      alignItems: 'center',
      margin: 10,
      marginTop: 30,
    },
    controlButton: {
      flex: 0.1
    },
    title: {
      flex: 0.8,
      textAlign: 'center'
    },
    calendarHeading: {
      flex: 1,
      flexDirection: 'row',
      alignItems: 'center',
      borderTopWidth: 2,
      borderBottomWidth: 2
    },
    dayList: {
      flex: 1,
      flexDirection: 'row',
      alignItems: 'center'
    },
    dayListDay: {
      padding: 5,
      flex: 1,
      textAlign: 'center',
      fontSize: 20,
      justifyContent: 'flex-start'
    },
    currentDay: {
      color: '#FF3333'
    }
  });

AppRegistry.registerComponent('CalendarSwiper', () => CalendarSwiper);<commit_msg>pop and shift as user navigates. eliminate array growing to large. smoother scrolling<commit_after>var React = require('react-native');
var Dimensions = require('Dimensions');
var moment = require('moment');

var {
  AppRegistry,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  TouchableWithoutFeedback,
  View
} = React;

const DAYS = ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  MAX_COLUMNS = 7,
  MAX_ROWS = 7,
  DEVICE_WIDTH = Dimensions.get('window').width;

var _currentMonthIndex = 1;

class CalendarSwiper extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      calendarDates: [moment().subtract(1, 'month').format(), moment().format(), moment().add(1, 'month').format()],
      selectedDate: null,
      currentMonth: moment().format()
    }
  }

  componentDidMount() {
    this._scrollToItem(_currentMonthIndex);
  }

  renderHeading() {
    return (
      <View style={styles.calendarHeading}>
        {DAYS.map((day) => { return (<Text style={styles.dayListDay}>{day}</Text>) })}
      </View>
    )
  }

  renderControls(date) {
    return (
      <View style={styles.calendarControls}>
        <TouchableOpacity style={styles.controlButton} onPress={this._onPrev.bind(this)}>
          <Text>Prev</Text>
        </TouchableOpacity>
        <Text style={styles.title}>
          {moment(this.state.currentMonth).format('MMMM YYYY')}
        </Text>
        <TouchableOpacity style={styles.controls} onPress={this._onNext.bind(this)}>
          <Text>Next</Text>
        </TouchableOpacity>
      </View>
    )
  }

  renderMonthView(date) {

    var dayStart = moment(date).startOf('month').format(),
      daysInMonth = moment(dayStart).daysInMonth(),
      offset = moment(dayStart).get('day'),
      preFiller = 0,
      currentDay = 0,
      weekRows = [];

    for (var i = 0; i < MAX_COLUMNS; i++) {
      var days = [];
      for (var j = 0; j < MAX_ROWS; j++) {
        if (preFiller < offset) {
          days.push(<TouchableWithoutFeedback><Text style={styles.dayListDay}></Text></TouchableWithoutFeedback>);
        } else {
          if(currentDay < daysInMonth) {
            days.push((
              <TouchableOpacity
                onPress={this._selectDate.bind(this, moment(dayStart).set('date', currentDay + 1))}>
                <Text style={styles.dayListDay}>{currentDay+1}</Text>
              </TouchableOpacity>
            ));
            currentDay++;
          }
        }
        preFiller++;
      } // row

      if(days.length > 0 && days.length < 7) {
        for (var x = days.length; x < 7; x++) {
          days.push(<TouchableWithoutFeedback><Text style={styles.dayListDay}></Text></TouchableWithoutFeedback>);
        }
        weekRows.push(<View style={styles.dayList}>{days}</View>);
      } else {
        weekRows.push(<View style={styles.dayList}>{days}</View>);
      }
    } // column
    return (<View style={styles.calendarContainer}>{weekRows}</View>);
  }

  _onPrev(){
    this._prependMonth();
    this._scrollToItem(_currentMonthIndex);
  }

  _onNext(){
    this._appendMonth();
    this._scrollToItem(_currentMonthIndex);
  }

  _prependMonth() {
    var calendarDates = this.state.calendarDates;

    calendarDates.unshift(moment(calendarDates[0]).subtract(1, 'month').format());
    calendarDates.pop();

    this.setState({
      calendarDates: calendarDates,
      currentMonth: calendarDates[_currentMonthIndex]
    });
  }

  _appendMonth(){
    var calendarDates = this.state.calendarDates;

    calendarDates.push(moment(calendarDates[calendarDates.length - 1]).add(1, 'month').format());
    calendarDates.shift();

    this.setState({
      calendarDates: calendarDates,
      currentMonth: calendarDates[_currentMonthIndex]
    });
  }

  _selectDate(date) {
    console.log(date.format());
  }

  _scrollToItem(itemIndex) {
      var scrollToX = itemIndex * DEVICE_WIDTH;
      this.refs.calendar.scrollWithoutAnimationTo(0, scrollToX);
  }

  _scrollEnded(event) {
    var position = event.nativeEvent.contentOffset.x;
    var currentPage = position / DEVICE_WIDTH;

    if (currentPage < _currentMonthIndex) {
      this._prependMonth();
      this._scrollToItem(_currentMonthIndex);
    } else if (currentPage > _currentMonthIndex) {
        this._appendMonth();
        this._scrollToItem(_currentMonthIndex);
    } else {
        return false;
    }
  }

  render() {
    return (
      <View>
        {this.renderControls()}
        {this.renderHeading()}
        <ScrollView
          ref='calendar'
          horizontal={true}
          bounces={false}
          pagingEnabled={true}
          removeClippedSubviews={true}
          scrollEventThrottle={600}
          showsHorizontalScrollIndicator={false}
          onMomentumScrollEnd={(event) => this._scrollEnded(event)}>
          {this.state.calendarDates.map((date) => { return this.renderMonthView(date) })}
        </ScrollView>
      </View>
    )
  }
};
  var styles = StyleSheet.create({
    calendarContainer: {
      width: DEVICE_WIDTH
    },
    title: {
      textAlign: 'center',
      flex: 2,
    },
    calendarControls: {
      flexDirection: 'row',
      alignItems: 'center',
      margin: 10,
      marginTop: 30,
    },
    controlButton: {
      flex: 0.1
    },
    title: {
      flex: 0.8,
      textAlign: 'center'
    },
    calendarHeading: {
      flex: 1,
      flexDirection: 'row',
      alignItems: 'center',
      borderTopWidth: 2,
      borderBottomWidth: 2
    },
    dayList: {
      flex: 1,
      flexDirection: 'row',
      alignItems: 'center'
    },
    dayListDay: {
      padding: 5,
      flex: 1,
      textAlign: 'center',
      fontSize: 20,
      justifyContent: 'flex-start'
    },
    currentDay: {
      color: '#FF3333'
    }
  });

AppRegistry.registerComponent('CalendarSwiper', () => CalendarSwiper);<|endoftext|>


<commit_before>"use strict";

(function(Nuvola) {

  // Create media player component
  var player = Nuvola.$object(Nuvola.MediaPlayer);

  // Handy aliases
  var PlaybackState = Nuvola.PlaybackState;
  var PlayerAction = Nuvola.PlayerAction;

  // Create new WebApp prototype
  var WebApp = Nuvola.$WebApp();

  // Initialization routines
  WebApp._onInitWebWorker = function(emitter) {
    Nuvola.WebApp._onInitWebWorker.call(this, emitter);

    var state = document.readyState;
    if (state === "interactive" || state === "complete")
      this._onPageReady();
    else
      document.addEventListener("DOMContentLoaded",
        this._onPageReady.bind(this));
  }

  // Page is ready for magic
  WebApp._onPageReady = function() {
    // Connect handler for signal ActionActivated
    Nuvola.actions.connect("ActionActivated", this);

    // Set default action states
    player.setCanPlay(true);
    player.setCanPause(true);
    //player.setCanStop(false);
    player.setCanGoPrev(false);
    player.setCanGoNext(false);

    // Configure API hooks
    this.startApi();
  }

  // Loads the KEXP flowplayer API
  WebApp.startApi = function() {

    if (typeof(window.API.getMedia()) !== 'undefined') {
      this.update();
    } else {
      setTimeout(this.startApi.bind(this), 100);
    }
  }

  // Extract data from the web page
  WebApp.update = function() {
    if (typeof(window.API.getMedia()) !== 'undefined') {
      // Scrape track info
      var track = window.API.getMedia().title;
      var artist = window.API.getMedia().author;
      var album = "";
      var art = "http:" + window.API.getMedia().image;
      var track = {
        title: track,
        artist: artist,
        album: album,
        artLocation: art
      };
      player.setTrack(track);
    } else {
      var track = {
        title: "",
        artist: "",
        album: "",
        artLocation: ""
      };
    }

    if (document.getElementById("playback-controls").classList.contains("snoozed")) {
      var state = PlaybackState.PAUSED;
    } else {
      var state = PlaybackState.PLAYING;
    }

    player.setPlaybackState(state);

    // Schedule the next update
    setTimeout(this.update.bind(this), 500);
  }

  // Handler of playback actions
  WebApp._onActionActivated = function(emitter, name, param) {

    switch (name) {
      case PlayerAction.TOGGLE_PLAY:
        if (document.getElementById("playback-controls").classList.contains("snoozed")) {
          document.getElementById("playback-controls").getElementsByClassName("refresh")[0].click();
        } else {
          document.getElementById("playback-controls").getElementsByClassName("snooze")[0].click();
        }

        console.log("toggle play");
        //button refresh
        break;
      case PlayerAction.PLAY:
        document.getElementById("playback-controls").getElementsByClassName("refresh")[0].click();
        console.log("play");
        break;
      case PlayerAction.PAUSE:
        document.getElementById("playback-controls").getElementsByClassName("snooze")[0].click();
        console.log("pause");
        break;
      case PlayerAction.STOP:
        document.getElementById("playback-controls").getElementsByClassName("snooze")[0].click();
        console.log("stop");
        break;
      case PlayerAction.PREV_SONG:
        //not supported
        break;
      case PlayerAction.NEXT_SONG:
        //not supported
        break;
      default:
        throw {
          "message": "Not supported."
        };
    }
  }

  WebApp.start();
})(this);
<commit_msg>Tweak ready state<commit_after>"use strict";

(function(Nuvola) {

  // Create media player component
  var player = Nuvola.$object(Nuvola.MediaPlayer);

  // Handy aliases
  var PlaybackState = Nuvola.PlaybackState;
  var PlayerAction = Nuvola.PlayerAction;

  // Create new WebApp prototype
  var WebApp = Nuvola.$WebApp();

  // Initialization routines
  WebApp._onInitWebWorker = function(emitter) {
    Nuvola.WebApp._onInitWebWorker.call(this, emitter);

    var state = document.readyState;
    if (state === "interactive" || state === "complete")
      this._onPageReady();
    else
      document.addEventListener("DOMContentLoaded",
        this._onPageReady.bind(this));
  }

  // Page is ready for magic
  WebApp._onPageReady = function() {
    // Connect handler for signal ActionActivated
    Nuvola.actions.connect("ActionActivated", this);

    // Set default action states
    player.setCanPlay(true);
    player.setCanPause(true);
    //player.setCanStop(false);
    player.setCanGoPrev(false);
    player.setCanGoNext(false);

    // Configure API hooks
    this.startApi();
  }

  // Loads the KEXP flowplayer API
  WebApp.startApi = function() {

    if (document.getElementById("yt-frame")) {
      this.update();
    } else {
      setTimeout(this.startApi.bind(this), 100);
    }
  }

  // Extract data from the web page
  WebApp.update = function() {
    if (document.getElementById("yt-frame")) {
      // Scrape track info
      var track = window.API.getMedia().title;
      var artist = window.API.getMedia().author;
      var album = "";
      var art = "http:" + window.API.getMedia().image;
      var track = {
        title: track,
        artist: artist,
        album: album,
        artLocation: art
      };
      player.setTrack(track);
    } else {
      var track = {
        title: null,
        artist: null,
        album: null,
        artLocation: null
      };
    }

    if (document.getElementById("playback-controls").classList.contains("snoozed")) {
      var state = PlaybackState.PAUSED;
    } else {
      var state = PlaybackState.PLAYING;
    }

    player.setPlaybackState(state);

    // Schedule the next update
    setTimeout(this.update.bind(this), 500);
  }

  // Handler of playback actions
  WebApp._onActionActivated = function(emitter, name, param) {

    switch (name) {
      case PlayerAction.TOGGLE_PLAY:
        if (document.getElementById("playback-controls").classList.contains("snoozed")) {
          document.getElementById("playback-controls").getElementsByClassName("refresh")[0].click();
        } else {
          document.getElementById("playback-controls").getElementsByClassName("snooze")[0].click();
        }

        console.log("toggle play");
        //button refresh
        break;
      case PlayerAction.PLAY:
        document.getElementById("playback-controls").getElementsByClassName("refresh")[0].click();
        console.log("play");
        break;
      case PlayerAction.PAUSE:
        document.getElementById("playback-controls").getElementsByClassName("snooze")[0].click();
        console.log("pause");
        break;
      case PlayerAction.STOP:
        document.getElementById("playback-controls").getElementsByClassName("snooze")[0].click();
        console.log("stop");
        break;
      case PlayerAction.PREV_SONG:
        //not supported
        break;
      case PlayerAction.NEXT_SONG:
        //not supported
        break;
      default:
        throw {
          "message": "Not supported."
        };
    }
  }

  WebApp.start();
})(this);
<|endoftext|>


<commit_before>describe("WizardStep", function() {

    var step, clock;

    beforeEach(function() {
        step = new WizardStep({url: '/foobar'});
        clock = sinon.useFakeTimers();
    });

    afterEach(function() {
        clock.restore();
    });

    it("should be initializable with url option", function() {
        expect(step.url).toEqual('/foobar');
    });

    it("should load the contents of given url via", function() {

        spyOn($, 'ajax').andCallFake(function (req) {
            var d = $.Deferred();
            d.resolve('
ffffuuuuuu
');
            return d.promise();
        });

        step.load();
        clock.tick(100);
        expect(step.content).toBe('
ffffuuuuuu
');
        expect($.ajax.mostRecentCall.args[0]["url"]).toEqual('/foobar');

    });
});

describe("Wizard", function() {

    var wizard, clock;

    beforeEach(function() {
        $('body').append('

');
        wizard = new Wizard('wizard');
        clock = sinon.useFakeTimers();
    });

    afterEach(function() {
        clock.restore();
    });

    it("should not have any steps by default", function() {
        expect(wizard.steps.length).toEqual(0);
    });

    it("should have default index of -1 before rendering", function() {
        expect(wizard.currentIndex).toEqual(-1);
    });

    it("should call finalize option function if provided", function() {
        var finalizeFn = jasmine.createSpy();
        finalizeFn(function() {
            return true;
        });
        var w = new Wizard('testEl', {
            finalize: finalizeFn
        });
        w.finalize();
        expect(finalizeFn).toHaveBeenCalled();
    });

    it("should be able to add steps", function() {
        var step = new WizardStep({url: '/foobar'});
        wizard.addStep(step);
        expect(step.wizard).toEqual(wizard);
        expect(wizard.steps.length).toEqual(1);
        expect(step.id).toEqual(1);
        var step2 = new WizardStep({url: '/foobar2'});
        wizard.addStep(step2);
        expect(step2.id).toEqual(2);
        expect(wizard.steps.length).toEqual(2);
    });

    it("should render its basic skeleton template with first step", function() {
        var step1 = new WizardStep({url: '/foobar'});

        spyOn(step1, 'load').andCallFake(function (req) {
            var d = $.Deferred();
            d.resolve();
            return d.promise();
        });

        wizard.addStep(step1);
        wizard.render();
        expect(wizard.currentStep).toEqual(step1);
        expect(wizard.$content.find('div.wizard-step').length).toEqual(1);
        expect(step1.load).toHaveBeenCalled();
    });

    it("should load next steps asynchronously by default and update current step", function() {
        var step1 = new WizardStep({url: '/foobar1'});
        var step2 = new WizardStep({url: '/foobar2'});
        var step3 = new WizardStep({url: '/foobar3'});
        wizard.addStep(step1);
        wizard.addStep(step2);
        wizard.addStep(step3);

        spyOn($, 'ajax').andCallFake(function (req) {
            var d = $.Deferred();
            d.resolve('
ffffuuuuuubar1
');
            return d.promise();
        });

        wizard.render();
        clock.tick(100);
        expect(wizard.currentStep).toEqual(step1);
        expect(wizard.isOnLastStep()).toEqual(false);

        wizard.nextStep();
        clock.tick(100);
        expect(wizard.currentStep).toEqual(step2);
        expect(wizard.isOnLastStep()).toEqual(false);

        wizard.nextStep();
        clock.tick(100);
        expect(wizard.currentStep).toEqual(step3);
        expect(wizard.isOnLastStep()).toEqual(true);

    });

    it("doesnt proceed to next step if validation failed", function() {
        spyOn($, 'ajax').andCallFake(function (req) {
            var d = $.Deferred();
            d.resolve('
ffffuuuuuu
');
            return d.promise();
        });

        var step1 = new WizardStep({
            url: '/foobar1',
            validate: function() {
                return $.Deferred().reject().promise();
            }
        });
        var step2 = new WizardStep({url: '/foobar2'});
        spyOn(step2, 'load');

        wizard.addStep(step1);
        wizard.render();
        clock.tick(100);
        expect(wizard.currentStep).toEqual(step1);
        wizard.nextStep();
        clock.tick(100);
        expect(wizard.currentStep).toEqual(step1);
        expect(step2.load).not.toHaveBeenCalled();
    });

});<commit_msg>Fixed spec<commit_after>describe("WizardStep", function() {

    var step, clock;

    beforeEach(function() {
        step = new WizardStep({url: '/foobar'});
        clock = sinon.useFakeTimers();
    });

    afterEach(function() {
        clock.restore();
    });

    it("should be initializable with url option", function() {
        expect(step.url).toEqual('/foobar');
    });

    it("should load the contents of given url via", function() {

        spyOn($, 'ajax').andCallFake(function (req) {
            var d = $.Deferred();
            d.resolve('
ffffuuuuuu
');
            return d.promise();
        });

        step.load();
        clock.tick(100);
        expect(step.content).toBe('
ffffuuuuuu
');
        expect($.ajax.mostRecentCall.args[0]["url"]).toEqual('/foobar');

    });
});

describe("Wizard", function() {

    var wizard, clock;

    beforeEach(function() {
        $('body').append('

');
        wizard = new Wizard('wizard');
        clock = sinon.useFakeTimers();
    });

    afterEach(function() {
        clock.restore();
    });

    it("should not have any steps by default", function() {
        expect(wizard.steps.length).toEqual(0);
    });

    it("should have default index of -1 before rendering", function() {
        expect(wizard.currentIndex).toEqual(-1);
    });

    it("should call finalize option function if provided", function() {
        var finalizeFn = jasmine.createSpy();
        var w = new Wizard('testEl', {
            finalize: finalizeFn
        });
        w.finalize();
        expect(finalizeFn).toHaveBeenCalled();
    });

    it("should be able to add steps", function() {
        var step = new WizardStep({url: '/foobar'});
        wizard.addStep(step);
        expect(step.wizard).toEqual(wizard);
        expect(wizard.steps.length).toEqual(1);
        expect(step.id).toEqual(1);
        var step2 = new WizardStep({url: '/foobar2'});
        wizard.addStep(step2);
        expect(step2.id).toEqual(2);
        expect(wizard.steps.length).toEqual(2);
    });

    it("should render its basic skeleton template with first step", function() {
        var step1 = new WizardStep({url: '/foobar'});

        spyOn(step1, 'load').andCallFake(function (req) {
            var d = $.Deferred();
            d.resolve();
            return d.promise();
        });

        wizard.addStep(step1);
        wizard.render();
        expect(wizard.currentStep).toEqual(step1);
        expect(wizard.$content.find('div.wizard-step').length).toEqual(1);
        expect(step1.load).toHaveBeenCalled();
    });

    it("should load next steps asynchronously by default and update current step", function() {
        var step1 = new WizardStep({url: '/foobar1'});
        var step2 = new WizardStep({url: '/foobar2'});
        var step3 = new WizardStep({url: '/foobar3'});
        wizard.addStep(step1);
        wizard.addStep(step2);
        wizard.addStep(step3);

        spyOn($, 'ajax').andCallFake(function (req) {
            var d = $.Deferred();
            d.resolve('
ffffuuuuuubar1
');
            return d.promise();
        });

        wizard.render();
        clock.tick(100);
        expect(wizard.currentStep).toEqual(step1);
        expect(wizard.isOnLastStep()).toEqual(false);

        wizard.nextStep();
        clock.tick(100);
        expect(wizard.currentStep).toEqual(step2);
        expect(wizard.isOnLastStep()).toEqual(false);

        wizard.nextStep();
        clock.tick(100);
        expect(wizard.currentStep).toEqual(step3);
        expect(wizard.isOnLastStep()).toEqual(true);

    });

    it("doesnt proceed to next step if validation failed", function() {
        spyOn($, 'ajax').andCallFake(function (req) {
            var d = $.Deferred();
            d.resolve('
ffffuuuuuu
');
            return d.promise();
        });

        var step1 = new WizardStep({
            url: '/foobar1',
            validate: function() {
                return $.Deferred().reject().promise();
            }
        });
        var step2 = new WizardStep({url: '/foobar2'});
        spyOn(step2, 'load');

        wizard.addStep(step1);
        wizard.render();
        clock.tick(100);
        expect(wizard.currentStep).toEqual(step1);
        wizard.nextStep();
        clock.tick(100);
        expect(wizard.currentStep).toEqual(step1);
        expect(step2.load).not.toHaveBeenCalled();
    });

});<|endoftext|>


<commit_before>import React from 'react';
import Head from 'next/head';
import paths from '../lib/paths';
import ThemeLayout from '../layouts/Theme';
import Contributors from '../components/Contributors';
import Updates from '../components/Updates';
import download from 'download';
import probe from 'probe-image-size';
import { convertMarkdownToReact } from '../lib/markdown';

export async function getStaticPaths() {
  return { paths, fallback: 'blocking' };
}

export async function getStaticProps({ params }) {
  const header = {
    headers: {
      'Authorization': `token ${process.env.GITHUB_PERSONAL_ACCESS_TOKEN}`
    }
  };

  const query = paths.find(path => path.params.theme === params.theme).params;

  const installReq = await fetch(`https://api.github.com/repos/dracula/${query.repo}/contents/INSTALL.md`, header);
  const installRes = await installReq.json();
  const installBuffer = Buffer.from(installRes.content, 'base64');
  query.install = installBuffer.toString('utf8');

  const contributorsReq = await fetch(`https://api.github.com/repos/dracula/${query.repo}/contributors`, header);
  const contributors = await contributorsReq.json();
  query.contributors = contributors;

  const image = `https://raw.githubusercontent.com/dracula/${query.repo}/master/screenshot.png`;
  await download(image, 'public/static/img/screenshots', { filename: `${query.theme}.png` });

  const metadata = await probe(image);
  query.imageWidth = metadata.width;
  query.imageHeight = metadata.height;

  return { props: { query }, revalidate: 7200 };
}

class Theme extends React.Component {
  state = {
    views: ''
  };

  componentDidMount() {
    this.getViews();
  }

  async getViews() {
    const viewsReq = await fetch(`/api/views/${this.props.query.theme}`);
    const viewsRes = await viewsReq.json();
    const views = new Intl.NumberFormat().format(viewsRes.views || 0);

    this.setState({ views });
  }

  renderViews() {
    if (this.state.views) {
      return
{this.state.views} views

    }

    return

  }

  render() {
    let title = `Dark theme for ${this.props.query.title} and ${paths.length}+ apps — Dracula`;

    if (this.props.query.title === 'Wallpaper') {
      title = `Dark wallpaper collection — Dracula`;
    }

    const description = `Dracula is a color scheme for code editors and terminal emulators, including ${this.props.query.title} and ${paths.length}+ other apps. Check the instructions to learn how to install it.`;
    const content = convertMarkdownToReact(this.props.query.install);

    return

        <title>{title}</title>
        <meta content={title} property="og:title" />
        <meta content={description} name="description" />
        <meta content={description} property="og:description" />
        <meta content={`https://draculatheme.com/${this.props.query.theme}`} property="og:url" />
        <meta content="https://draculatheme.com/static/img/facebook.png" property="og:image" />

        <img className="preview" src={`/static/img/screenshots/${this.props.query.theme}.png`} alt={`${this.props.query.title} Theme Preview`} width={this.props.query.imageWidth} height={this.props.query.imageHeight} />
        {this.renderViews()}

          {content}

        <Updates type="theme" />
        <Contributors repo={this.props.query.repo} data={this.props.query.contributors} />

  }
}

Theme.Layout = ThemeLayout;

export default Theme;
<commit_msg>Filter @ImgBotApp from list of collaborators<commit_after>import React from 'react';
import Head from 'next/head';
import paths from '../lib/paths';
import ThemeLayout from '../layouts/Theme';
import Contributors from '../components/Contributors';
import Updates from '../components/Updates';
import download from 'download';
import probe from 'probe-image-size';
import { convertMarkdownToReact } from '../lib/markdown';

export async function getStaticPaths() {
  return { paths, fallback: 'blocking' };
}

export async function getStaticProps({ params }) {
  const header = {
    headers: {
      'Authorization': `token ${process.env.GITHUB_PERSONAL_ACCESS_TOKEN}`
    }
  };

  const query = paths.find(path => path.params.theme === params.theme).params;

  const installReq = await fetch(`https://api.github.com/repos/dracula/${query.repo}/contents/INSTALL.md`, header);
  const installRes = await installReq.json();
  const installBuffer = Buffer.from(installRes.content, 'base64');
  query.install = installBuffer.toString('utf8');

  const contributorsReq = await fetch(`https://api.github.com/repos/dracula/${query.repo}/contributors`, header);
  const contributors = await contributorsReq.json();
  query.contributors = contributors.filter(contributor => {
    if (contributor.login === 'ImgBotApp') return;
    return contributor;
  });

  const image = `https://raw.githubusercontent.com/dracula/${query.repo}/master/screenshot.png`;
  await download(image, 'public/static/img/screenshots', { filename: `${query.theme}.png` });

  const metadata = await probe(image);
  query.imageWidth = metadata.width;
  query.imageHeight = metadata.height;

  return { props: { query }, revalidate: 7200 };
}

class Theme extends React.Component {
  state = {
    views: ''
  };

  componentDidMount() {
    this.getViews();
  }

  async getViews() {
    const viewsReq = await fetch(`/api/views/${this.props.query.theme}`);
    const viewsRes = await viewsReq.json();
    const views = new Intl.NumberFormat().format(viewsRes.views || 0);

    this.setState({ views });
  }

  renderViews() {
    if (this.state.views) {
      return
{this.state.views} views

    }

    return

  }

  render() {
    let title = `Dark theme for ${this.props.query.title} and ${paths.length}+ apps — Dracula`;

    if (this.props.query.title === 'Wallpaper') {
      title = `Dark wallpaper collection — Dracula`;
    }

    const description = `Dracula is a color scheme for code editors and terminal emulators, including ${this.props.query.title} and ${paths.length}+ other apps. Check the instructions to learn how to install it.`;
    const content = convertMarkdownToReact(this.props.query.install);

    return

        <title>{title}</title>
        <meta content={title} property="og:title" />
        <meta content={description} name="description" />
        <meta content={description} property="og:description" />
        <meta content={`https://draculatheme.com/${this.props.query.theme}`} property="og:url" />
        <meta content="https://draculatheme.com/static/img/facebook.png" property="og:image" />

        <img className="preview" src={`/static/img/screenshots/${this.props.query.theme}.png`} alt={`${this.props.query.title} Theme Preview`} width={this.props.query.imageWidth} height={this.props.query.imageHeight} />
        {this.renderViews()}

          {content}

        <Updates type="theme" />
        <Contributors repo={this.props.query.repo} data={this.props.query.contributors} />

  }
}

Theme.Layout = ThemeLayout;

export default Theme;
<|endoftext|>