<commit_before>(function() {
    'use strict';

    var request = require('supertest'),
        express = require('express'),
        should = require('chai').should,
        expect = require('chai').expect,
        assert = require('chai').assert;

    var app = require('../').app;

    var exp_id = null,
        model_id = null;

    describe('REST API:', function() {
        describe('Create Experiment: POST /experiment', function() {
            it('should create an experiment with a randomly generated name', function(done) {
                request(app)
                    .post('/api/v1/experiment')
                    .expect(201)
                    .send({
                        'description': 'test'
                    })
                    .end(function(err, res) {
                        exp_id = res.body._id;
                        expect(res.body._id).to.be.ok;
                        expect(res.body.name).to.be.ok;
                        expect(res.body.description).to.equal('test');

                        done(err);
                    });
            });

            it('should get experiment with correct field values', function(done) {
                request(app)
                    .get('/api/v1/experiment/' + exp_id)
                    .expect(200)
                    .end(function(err, res) {
                        expect(res.body._id).to.be.ok;
                        expect(res.body.name).to.be.ok;
                        expect(res.body.description).to.equal('test');

                        done(err);
                    });
            });

            it('should create an experiment with a given generated name', function(done) {
                request(app)
                    .post('/api/v1/experiment')
                    .expect(201)
                    .send({
                        'description': 'test',
                        'name': 'ImageNet 2012'
                    })
                    .end(function(err, res) {
                        expect(res.body._id).to.be.ok;
                        expect(res.body.name).to.be.ok;
                        expect(res.body.description).to.equal('test');
                        expect(res.body.name).to.equal('ImageNet 2012');

                        done(err);
                    });
            });
        });

        describe('Change Experiment: PUT /experiment/:id', function() {
            it('should update the name and description', function(done) {
                request(app)
                    .put('/api/v1/experiment/' + exp_id)
                    .expect(200)
                    .send({
                        'description': 'just testing put',
                        'name': 'ImageNet 2011'
                    })
                    .end(function(err, res) {
                        expect(res.body._id).to.be.ok;
                        expect(res.body.name).to.be.ok;
                        expect(res.body.description).to.equal('just testing put');
                        expect(res.body.name).to.equal('ImageNet 2011');

                        done(err);
                    });
            });
        });

        describe('Create Model: POST /experiment/:id/model', function() {
            var dummyHyperparams = 'distribution: gaußian, n-grams: 2-grams, stopwords: removed',
                dummyName = 'bow naïve bayes',
                dummyDescr = 'some description';

            it('should create model for given experiment', function(done) {
                request(app)
                    .post('/api/v1/experiment/' + exp_id + '/model')
                    .expect(201)
                    .send({
                        'name': dummyName,
                        'description': dummyDescr,
                        'hyperparameter': dummyHyperparams
                    })
                    .end(function(err, res) {
                        model_id = res.body._id;

                        expect(res.body._id).to.be.ok;
                        expect(res.body.name).to.equal(dummyName);
                        expect(res.body.hyperparameter).to.equal(dummyHyperparams);
                        expect(res.body.description).to.equal(dummyDescr);

                        done(err);
                    });
            });

            it('should get the model with correct field values', function(done) {
                request(app)
                    .get('/api/v1/experiment/' + exp_id + '/model/' + model_id)
                    .expect(200)
                    .end(function(err, res) {
                        expect(res.body._id).to.be.ok;
                        expect(res.body.name).to.equal(dummyName);
                        expect(res.body.hyperparameter).to.equal(dummyHyperparams);
                        expect(res.body.description).to.equal(dummyDescr);

                        done(err);
                    });
            });
        });

        describe('Change Model: PUT /experiment/:id/model', function() {
            it('should change the model data', function(done) {
                request(app)
                    .put('/api/v1/experiment/' + exp_id + '/model/' + model_id)
                    .expect(200)
                    .send({
                        'name': 'foo',
                        'description': 'bar',
                        'hyperparameter': 'baz'
                    })
                    .end(function(err, res) {
                        console.log(res.body);

                        expect(res.body._id).to.be.ok;
                        expect(res.body.name).to.equal('foo');
                        expect(res.body.description).to.equal('bar');
                        expect(res.body.hyperparameter).to.equal('baz');

                        done(err);
                    });
            });
        });

        describe('Change Model: DELETE /experiment/:id/model/:id', function() {
            it('should remove the document', function(done) {
                request(app)
                    .del('/api/v1/experiment/' + exp_id + '/model/' + model_id)
                    .expect(200)
                    .end(function(err) {
                        done(err);
                    });
            });

            it('should not get the document', function(done) {
                request(app)
                    .get('/api/v1/experiment/' + exp_id + '/model/' + model_id)
                    .expect(404)
                    .end(function(err, doc) {
                        done(err);
                    });
            });
        });
    });
})();
<commit_msg>improved PUT test<commit_after>(function() {
    'use strict';

    var request = require('supertest'),
        express = require('express'),
        should = require('chai').should,
        expect = require('chai').expect,
        assert = require('chai').assert;

    var app = require('../').app;

    var exp_id = null,
        model_id = null;

    describe('REST API:', function() {
        describe('Create Experiment: POST /experiment', function() {
            it('should create an experiment with a randomly generated name', function(done) {
                request(app)
                    .post('/api/v1/experiment')
                    .expect(201)
                    .send({
                        'description': 'test'
                    })
                    .end(function(err, res) {
                        exp_id = res.body._id;
                        expect(res.body._id).to.be.ok;
                        expect(res.body.name).to.be.ok;
                        expect(res.body.description).to.equal('test');

                        done(err);
                    });
            });

            it('should get experiment with correct field values', function(done) {
                request(app)
                    .get('/api/v1/experiment/' + exp_id)
                    .expect(200)
                    .end(function(err, res) {
                        expect(res.body._id).to.be.ok;
                        expect(res.body.name).to.be.ok;
                        expect(res.body.description).to.equal('test');

                        done(err);
                    });
            });

            it('should create an experiment with a given generated name', function(done) {
                request(app)
                    .post('/api/v1/experiment')
                    .expect(201)
                    .send({
                        'description': 'test',
                        'name': 'ImageNet 2012'
                    })
                    .end(function(err, res) {
                        expect(res.body._id).to.be.ok;
                        expect(res.body.name).to.be.ok;
                        expect(res.body.description).to.equal('test');
                        expect(res.body.name).to.equal('ImageNet 2012');

                        done(err);
                    });
            });
        });

        describe('Change Experiment: PUT /experiment/:id', function() {
            it('should update the name and description', function(done) {
                request(app)
                    .put('/api/v1/experiment/' + exp_id)
                    .expect(200)
                    .send({
                        'description': 'just testing put',
                        'name': 'ImageNet 2011'
                    })
                    .end(function(err, res) {
                        expect(res.body._id).to.be.ok;
                        expect(res.body.name).to.be.ok;
                        expect(res.body.description).to.equal('just testing put');
                        expect(res.body.name).to.equal('ImageNet 2011');

                        done(err);
                    });
            });
        });

        describe('Create Model: POST /experiment/:id/model', function() {
            var dummyHyperparams = 'distribution: gaußian, n-grams: 2-grams, stopwords: removed',
                dummyName = 'bow naïve bayes',
                dummyDescr = 'some description';

            it('should create model for given experiment', function(done) {
                request(app)
                    .post('/api/v1/experiment/' + exp_id + '/model')
                    .expect(201)
                    .send({
                        'name': dummyName,
                        'description': dummyDescr,
                        'hyperparameter': dummyHyperparams
                    })
                    .end(function(err, res) {
                        model_id = res.body._id;

                        expect(res.body._id).to.be.ok;
                        expect(res.body.name).to.equal(dummyName);
                        expect(res.body.hyperparameter).to.equal(dummyHyperparams);
                        expect(res.body.description).to.equal(dummyDescr);

                        done(err);
                    });
            });

            it('should get the model with correct field values', function(done) {
                request(app)
                    .get('/api/v1/experiment/' + exp_id + '/model/' + model_id)
                    .expect(200)
                    .end(function(err, res) {
                        expect(res.body._id).to.be.ok;
                        expect(res.body.name).to.equal(dummyName);
                        expect(res.body.hyperparameter).to.equal(dummyHyperparams);
                        expect(res.body.description).to.equal(dummyDescr);

                        done(err);
                    });
            });
        });

        describe('Change Model: PUT /experiment/:id/model/:id', function() {
            it('should change the model data', function(done) {
                request(app)
                    .put('/api/v1/experiment/' + exp_id + '/model/' + model_id)
                    .expect(200)
                    .send({
                        'name': 'foo',
                        'description': 'bar',
                        'hyperparameter': 'baz'
                    })
                    .end(function(err, res) {
                        expect(res.body._id).to.be.ok;
                        expect(res.body.name).to.equal('foo');
                        expect(res.body.description).to.equal('bar');
                        expect(res.body.hyperparameter).to.equal('baz');

                        done(err);
                    });
            });
        });

        describe('Change Model: DELETE /experiment/:id/model/:id', function() {
            it('should remove the document', function(done) {
                request(app)
                    .del('/api/v1/experiment/' + exp_id + '/model/' + model_id)
                    .expect(200)
                    .end(function(err) {
                        done(err);
                    });
            });

            it('should not get the document', function(done) {
                request(app)
                    .get('/api/v1/experiment/' + exp_id + '/model/' + model_id)
                    .expect(404)
                    .end(function(err, doc) {
                        done(err);
                    });
            });
        });
    });
})();
<|endoftext|>


<commit_before>module.exports = function antenna(id) {
  var map = {
    'adapter': './adapter',
    'app': './app',
    'boot/connection': './boot/connection'
  };

  var mid = map[id];
  if (mid) {
    return require(mid);
  }
};
<commit_msg>Expose create functions.<commit_after>exports = module.exports = function antenna(id) {
  var map = {
    'adapter': './adapter',
    'app': './app',
    'boot/connection': './boot/connection'
  };

  var mid = map[id];
  if (mid) {
    return require(mid);
  }
};

exports.createAdapter = require('./adapter');
exports.createConnectionBootPhase = require('./boot/connection');
<|endoftext|>


<commit_before>/**
 * Created by alexisvincent on 2016/09/02.
 */
import chokidar from 'chokidar'
import path from 'path'
import fs from 'fs'
import jspm from 'jspm'
import io from 'socket.io'
import spdy from 'spdy'

import {
    handler,
} from './handlers'

const setupHMR = (tools) => {
    if (tools.hmr) {

        let cssFiles = new Set();

        tools.entries.forEach(entry =>
            tools._thenBuild(
                tools.builder.trace(entry).then((m) => {
                    Object.keys(m)
                        .filter(file => file.endsWith('.pcss'))
                        .forEach(f => cssFiles.add(f))
                })
            )
        )

        let socket = tools.socket

        /**
         * When a new client connects add it to a list and handle it disconnecting
         */
        socket.on('connect', soc => {
            soc.on('identification', (name) => {
                console.log('connected client: ', name)
            })
        })

        tools.watcher.on('all', (event, changePath) => {
            console.log('File ', changePath, ' emitted: ', event)
            let absolutePath = path.join(process.cwd(), changePath)

            /**
             * Deal with the special case when the changed file is a scss file
             * due to the face that we compile it as a whole.
             */
            if (changePath.endsWith('.pcss')) {
                console.log(Object.keys(tools.builder.cache.trace).filter(f => f.endsWith('.pcss')))
                cssFiles.add(changePath)
                console.log(tools.builder.invalidate(changePath))
                cssFiles.forEach(file => {
                    socket.emit(event, {path: file, file})
                })

            } else {
                socket.emit(event, {path: changePath, absolutePath})
            }
        })
    }
}

const optionsValid = (options = {}) => {

    let valid = true
    const error = msg => {
        console.error(msg)
        valid = false
    }

    if (options.packagePath)
        try {
            fs.statSync(options.packagePath);
        } catch (e) {
            if (options.packagePath == '')
                error(`
JSPM Devtools:

        You did not provide a valid packagePath

`)
        }

    return valid
}

const make = (options) => {

    // Validate options
    if (!optionsValid(options))
        throw new Error()

    const optionDefaults = {
        entries: [],
        packagePath: process.cwd(),
        hmr: false, // Since hmr needs socket.io default to it off
        resolveHandler: ({resolvers, initiatedBySystemJS}) => (
            initiatedBySystemJS
                ? resolvers.bundle()
                : resolvers.next()
        ),
        port: 1337
    }

    const buildOptionDefaults = {
        sourceMaps: 'inline'
    }

    // Construct tools object from defaults and provided options
    const tools = Object.assign({}, optionDefaults, options)

    // Construct builder config from defaults and provided options
    tools.builderConfig = Object.assign({}, buildOptionDefaults, tools.builderConfig)

    // If no jspm instance was specified, set the default
    if (!tools.jspm) {
        jspm.setPackagePath(tools.packagePath)
        tools.jspm = jspm
    }

    // Construct for pipelining build operations (parallel is slower)
    tools._buildPromise = Promise.resolve();
    tools._thenBuild = f => {
        tools._buildPromise = tools._buildPromise.then(f)
    }

    // Builder instance (so we can share the cache)
    tools.builder = new tools.jspm.Builder();

    tools._loaderConfig = tools.builder.loader.getConfig()

    const baseURL = path.relative(tools.packagePath, tools._loaderConfig.baseURL.substr(7))

    // Watch for changes (used to invalidate builder and hmr)
    tools.watcher = chokidar.watch("./"+baseURL, {
        ignored: ["**/jspm_packages", "**/node_modules", "**/icons"],
        ignoreInitial: true
    })

    // Invalidate builder when anything happens to a file (imprecise)
    tools.watcher.on('all', (event, changePath) => {
        tools.builder.invalidate(changePath)
    })

    // Preemptively trace the entry and bundle (populate trace/compile cache)
    tools.entries.forEach(entry =>
        tools._thenBuild(
            tools.builder.bundle(entry, tools.builderConfig).then(() => {
                console.log(":: Preemptively Cached ", entry)
            })
        )
    )

    // Express handler
    tools.handler = handler(tools)

    tools.server = spdy.createServer(require('spdy-keys'), () => "Nothing to see here")
    tools.socket = io(tools.server)

    tools.server.listen(tools.port || 1337)

    // Setup HMR
    setupHMR(tools)

    return tools
}

export {make};

<commit_msg>Fixed hopefullt<commit_after>/**
 * Created by alexisvincent on 2016/09/02.
 */
import chokidar from 'chokidar'
import path from 'path'
import fs from 'fs'
import jspm from 'jspm'
import io from 'socket.io'
import spdy from 'spdy'

import {
    handler,
} from './handlers'

const setupHMR = (tools) => {
    if (tools.hmr) {

        let cssFiles = new Set();

        tools.entries.forEach(entry =>
            tools._thenBuild(
                tools.builder.trace(entry).then((m) => {
                    Object.keys(m)
                        .filter(file => file.endsWith('.pcss'))
                        .forEach(f => cssFiles.add(f))
                })
            )
        )

        let socket = tools.socket

        /**
         * When a new client connects add it to a list and handle it disconnecting
         */
        socket.on('connect', soc => {
            soc.on('identification', (name) => {
                console.log('connected client: ', name)
            })
        })

        tools.watcher.on('all', (event, changePath) => {
            changePath = path.relative(tools._baseURL, changePath)
            console.log('File ', changePath, ' emitted: ', event)
            let absolutePath = path.join(process.cwd(), changePath)

            /**
             * Deal with the special case when the changed file is a scss file
             * due to the face that we compile it as a whole.
             */
            if (changePath.endsWith('.pcss')) {
                console.log(Object.keys(tools.builder.cache.trace).filter(f => f.endsWith('.pcss')))
                cssFiles.add(changePath)
                console.log(tools.builder.invalidate(changePath))
                cssFiles.forEach(file => {
                    socket.emit(event, {path: file, file})
                })

            } else {
                socket.emit(event, {path: changePath, absolutePath})
            }
        })
    }
}

const optionsValid = (options = {}) => {

    let valid = true
    const error = msg => {
        console.error(msg)
        valid = false
    }

    if (options.packagePath)
        try {
            fs.statSync(options.packagePath);
        } catch (e) {
            if (options.packagePath == '')
                error(`
JSPM Devtools:

        You did not provide a valid packagePath

`)
        }

    return valid
}

const make = (options) => {

    // Validate options
    if (!optionsValid(options))
        throw new Error()

    const optionDefaults = {
        entries: [],
        packagePath: process.cwd(),
        hmr: false, // Since hmr needs socket.io default to it off
        resolveHandler: ({resolvers, initiatedBySystemJS}) => (
            initiatedBySystemJS
                ? resolvers.bundle()
                : resolvers.next()
        ),
        port: 1337
    }

    const buildOptionDefaults = {
        sourceMaps: 'inline'
    }

    // Construct tools object from defaults and provided options
    const tools = Object.assign({}, optionDefaults, options)

    // Construct builder config from defaults and provided options
    tools.builderConfig = Object.assign({}, buildOptionDefaults, tools.builderConfig)

    // If no jspm instance was specified, set the default
    if (!tools.jspm) {
        jspm.setPackagePath(tools.packagePath)
        tools.jspm = jspm
    }

    // Construct for pipelining build operations (parallel is slower)
    tools._buildPromise = Promise.resolve();
    tools._thenBuild = f => {
        tools._buildPromise = tools._buildPromise.then(f)
    }

    // Builder instance (so we can share the cache)
    tools.builder = new tools.jspm.Builder();

    tools._loaderConfig = tools.builder.loader.getConfig()

    tools._baseURL = tools.packagePath + path.relative(tools.packagePath, tools._loaderConfig.baseURL.substr(7))

    // Watch for changes (used to invalidate builder and hmr)
    tools.watcher = chokidar.watch("./"+baseURL, {
        ignored: ["**/jspm_packages", "**/node_modules", "**/icons"],
        ignoreInitial: true
    })

    // Invalidate builder when anything happens to a file (imprecise)
    tools.watcher.on('all', (event, changePath) => {
        tools.builder.invalidate(changePath)
    })

    // Preemptively trace the entry and bundle (populate trace/compile cache)
    tools.entries.forEach(entry =>
        tools._thenBuild(
            tools.builder.bundle(entry, tools.builderConfig).then(() => {
                console.log(":: Preemptively Cached ", entry)
            })
        )
    )

    // Express handler
    tools.handler = handler(tools)

    tools.server = spdy.createServer(require('spdy-keys'), () => "Nothing to see here")
    tools.socket = io(tools.server)

    tools.server.listen(tools.port || 1337)

    // Setup HMR
    setupHMR(tools)

    return tools
}

export {make};

<|endoftext|>


<commit_before>zeus.simpleModule('apps.projects', function (projects, region) {

    controller = {
        showProject: function () {
            console.log(" => show project");
            var view = new projects.views.ProjectDetails({
                model: new projects.models.Project(zeus.project)
            });
            region.show(view);
        },

        showBuildset: function (name, number) {
            console.log(" => show buildset " + number);
            var buildset = new projects.models.Buildset({number: number});
            var view = new projects.views.BuildsetDetails({model: buildset});
            buildset.fetch({
                success: function () {
                    region.show(view);
                    zeus.navigate(buildset.get('url'));
                }
            });
        }
    };

    zeus.on('show:project', controller.showProject);
    zeus.on('show:buildset', controller.showBuildset);

}, zeus.mainRegion);
<commit_msg>Breadcrumbs should work on "Back" action<commit_after>zeus.simpleModule('apps.projects', function (projects, region) {

    controller = {
        showProject: function () {
            console.log(" => show project");
            var view = new projects.views.ProjectDetails({
                model: new projects.models.Project(zeus.project)
            });
            region.show(view);
            zeus.navigate(zeus.project.url);
        },

        showBuildset: function (name, number) {
            console.log(" => show buildset " + number);
            var buildset = new projects.models.Buildset({number: number});
            var view = new projects.views.BuildsetDetails({model: buildset});
            buildset.fetch({
                success: function () {
                    region.show(view);
                    zeus.navigate(buildset.get('url'));
                }
            });
        }
    };

    zeus.on('show:project', controller.showProject);
    zeus.on('show:buildset', controller.showBuildset);

}, zeus.mainRegion);
<|endoftext|>


<commit_before>pc.extend(pc, function () {
    'use strict';

    var JSON_ADDRESS_MODE = {
        "repeat": pc.ADDRESS_REPEAT,
        "clamp":  pc.ADDRESS_CLAMP_TO_EDGE,
        "mirror": pc.ADDRESS_MIRRORED_REPEAT
    };

    var JSON_FILTER_MODE = {
        "nearest":             pc.FILTER_NEAREST,
        "linear":              pc.FILTER_LINEAR,
        "nearest_mip_nearest": pc.FILTER_NEAREST_MIPMAP_NEAREST,
        "linear_mip_nearest":  pc.FILTER_LINEAR_MIPMAP_NEAREST,
        "nearest_mip_linear":  pc.FILTER_NEAREST_MIPMAP_LINEAR,
        "linear_mip_linear":   pc.FILTER_LINEAR_MIPMAP_LINEAR
    };

    function arrayBufferCopy(src, dst, dstByteOffset, numBytes) {
        var i;
        var dst32Offset = dstByteOffset / 4;
        var tail = (numBytes % 4);
        var src32 = new Uint32Array(src.buffer, 0, (numBytes - tail) / 4);
        var dst32 = new Uint32Array(dst.buffer);
        for (i = 0; i < src32.length; i++) {
            dst32[dst32Offset + i] = src32[i];
        }
        for (i = numBytes - tail; i < numBytes; i++) {
            dst[dstByteOffset + i] = src[i];
        }
    }

    var TextureHandler = function (device, assets, loader) {
        this._device = device;
        this._assets = assets;
        this._loader = loader;

        // by default don't try cross-origin, because some browsers send different cookes (e.g. safari) if this is set.
        this.crossOrigin = undefined;
        if (assets.prefix) {
            // ensure we send cookies if we load images.
            this.crossOrigin = 'use-credentials';
        }
    };

    TextureHandler.prototype = {
        load: function (url, callback) {
            var self = this;

            var urlWithoutParams = url.indexOf('?') >= 0 ? url.split('?')[0] : url;

            var ext = pc.path.getExtension(urlWithoutParams).toLowerCase();
            if ((ext === '.dds') || (ext === '.crn')) {
                var options = {
                    cache: true,
                    responseType: "arraybuffer"
                };

                pc.http.get(url, options, function (err, response) {
                    if (!err) {
                        callback(null, response);
                    } else {
                        callback(err)
                    }
                });
            } else if ((ext === '.jpg') || (ext === '.jpeg') || (ext === '.gif') || (ext === '.png')) {
                var image = new Image();
                if (self.crossOrigin !== undefined) {
                    image.crossOrigin = self.crossOrigin;
                }

                // Call success callback after opening Texture
                image.onload = function () {
                    callback(null, image);
                };

                // Call error callback with details.
                image.onerror = function (event) {
                    callback(pc.string.format("Error loading Texture from: '{0}'", url));
                };

                image.src = url;
            } else {
                // Unsupported texture extension
                // Use timeout because asset events can be hooked up after load gets called in some
                // cases. For example, material loads a texture on 'add' event.
                setTimeout(function () {
                    callback(pc.string.format("Error loading Texture: format not supported: '{0}'", ext));
                }, 0);
            }
        },

        open: function (url, data) {
            if (! url)
                return;

            var self = this;
            var texture;
            var ext = pc.path.getExtension(url).toLowerCase();
            var format = null;

            // Every browser seems to pass data as an Image type. For some reason, the XDK
            // passes an HTMLImageElement. TODO: figure out why!
            // DDS textures are ArrayBuffers
            if ((data instanceof Image) || (data instanceof HTMLImageElement)) { // PNG, JPG or GIF
                var img = data;

                format = (ext === ".jpg" || ext === ".jpeg") ? pc.PIXELFORMAT_R8_G8_B8 : pc.PIXELFORMAT_R8_G8_B8_A8;
                texture = new pc.Texture(this._device, {
                    width: img.width,
                    height: img.height,
                    format: format
                });
                texture.setSource(img);

            } else if (data instanceof ArrayBuffer) { // DDS or CRN
                if (ext === ".crn") {
                    // Copy loaded file into Emscripten-managed memory
                    var srcSize = data.byteLength;
                    var bytes = new Uint8Array(data);
                    var src = Module._malloc(srcSize);
                    arrayBufferCopy(bytes, Module.HEAPU8, src, srcSize);

                    // Decompress CRN to DDS (minus the header)
                    var dst = Module._crn_decompress_get_data(src, srcSize);
                    var dstSize = Module._crn_decompress_get_size(src, srcSize);

                    data = Module.HEAPU8.buffer.slice(dst, dst + dstSize);
                }

                // DDS loading
                var header = new Uint32Array(data, 0, 128 / 4);

                var width = header[4];
                var height = header[3];
                var mips = Math.max(header[7], 1);
                var isFourCc = header[20] === 4;
                var fcc = header[21];
                var bpp = header[22];
                var isCubemap = header[28] === 65024; // TODO: check by bitflag

                var FCC_DXT1 = 827611204; // DXT1
                var FCC_DXT5 = 894720068; // DXT5
                var FCC_FP32 = 116; // RGBA32f

                // non standard
                var FCC_ETC1 = 826496069;
                var FCC_PVRTC_2BPP_RGB_1 = 825438800;
                var FCC_PVRTC_2BPP_RGBA_1 = 825504336;
                var FCC_PVRTC_4BPP_RGB_1 = 825439312;
                var FCC_PVRTC_4BPP_RGBA_1 = 825504848;

                var compressed = false;
                var floating = false;
                var etc1 = false;
                var pvrtc2 = false;
                var pvrtc4 = false;
                if (isFourCc) {
                    if (fcc===FCC_DXT1) {
                        format = pc.PIXELFORMAT_DXT1;
                        compressed = true;
                    } else if (fcc===FCC_DXT5) {
                        format = pc.PIXELFORMAT_DXT5;
                        compressed = true;
                    } else if (fcc===FCC_FP32) {
                        format = pc.PIXELFORMAT_RGBA32F;
                        floating = true;
                    } else if (fcc===FCC_ETC1) {
                        format = pc.PIXELFORMAT_ETC1;
                        compressed = true;
                        etc1 = true;
                    } else if (fcc===FCC_PVRTC_2BPP_RGB_1 || fcc===FCC_PVRTC_2BPP_RGBA_1) {
                        format = fcc===FCC_PVRTC_2BPP_RGB_1? pc.PIXELFORMAT_PVRTC_2BPP_RGB_1 : pc.PIXELFORMAT_PVRTC_2BPP_RGBA_1;
                        compressed = true;
                        pvrtc2 = true;
                    } else if (fcc===FCC_PVRTC_4BPP_RGB_1 || fcc===FCC_PVRTC_4BPP_RGBA_1) {
                        format = fcc===FCC_PVRTC_4BPP_RGB_1? pc.PIXELFORMAT_PVRTC_4BPP_RGB_1 : pc.PIXELFORMAT_PVRTC_4BPP_RGBA_1;
                        compressed = true;
                        pvrtc4 = true;
                    }
                } else {
                    if (bpp===32) {
                        format = pc.PIXELFORMAT_R8_G8_B8_A8;
                    }
                }

                var requiredMips = Math.round(Math.log2(Math.max(width, height)) + 1);
                var cantLoad = !format || (mips !== requiredMips && compressed);
                if (cantLoad) {
                    var errEnd = ". Empty texture will be created instead.";
                    if (!format) {
                        console.error("This DDS pixel format is currently unsupported" + errEnd);
                    } else {
                        console.error("DDS has " + mips + " mips, but engine requires " + requiredMips + " for DXT format. " + errEnd);
                    }
                    texture = new pc.Texture(this._device, {
                        width: 4,
                        height: 4,
                        format: pc.PIXELFORMAT_R8_G8_B8
                    });
                    return texture;
                }

                var texOptions = {
                    width: width,
                    height: height,
                    format: format,
                    cubemap: isCubemap
                };
                texture = new pc.Texture(this._device, texOptions);
                if (isCubemap) {
                    texture.addressU = pc.ADDRESS_CLAMP_TO_EDGE;
                    texture.addressV = pc.ADDRESS_CLAMP_TO_EDGE;
                }

                var offset = 128;
                var faces = isCubemap? 6 : 1;
                var mipSize;
                var DXT_BLOCK_WIDTH = 4;
                var DXT_BLOCK_HEIGHT = 4;
                var blockSize = fcc===FCC_DXT1? 8 : 16;
                var numBlocksAcross, numBlocksDown, numBlocks;
                for(var face=0; face<faces; face++) {
                    var mipWidth = width;
                    var mipHeight = height;
                    for(var i=0; i<mips; i++) {
                        if (compressed) {
                            if (etc1) {
                                mipSize = Math.floor((mipWidth + 3) / 4) * Math.floor((mipHeight + 3) / 4) * 8;
                            } else if (pvrtc2) {
                                mipSize = Math.max(mipWidth, 16) * Math.max(mipHeight, 8) / 4;
                            } else if (pvrtc4) {
                                mipSize = Math.max(mipWidth, 8) * Math.max(mipHeight, 8) / 2;
                            } else {
                                numBlocksAcross = Math.floor((mipWidth + DXT_BLOCK_WIDTH - 1) / DXT_BLOCK_WIDTH);
                                numBlocksDown = Math.floor((mipHeight + DXT_BLOCK_HEIGHT - 1) / DXT_BLOCK_HEIGHT);
                                numBlocks = numBlocksAcross * numBlocksDown;
                                mipSize = numBlocks * blockSize;
                            }
                        } else {
                            mipSize = mipWidth * mipHeight * 4;
                        }

                        var mipBuff = floating? new Float32Array(data, offset, mipSize) : new Uint8Array(data, offset, mipSize);
                        if (!isCubemap) {
                            texture._levels[i] = mipBuff;
                        } else {
                            if (!texture._levels[i]) texture._levels[i] = [];
                            texture._levels[i][face] = mipBuff;
                        }
                        offset += floating? mipSize * 4 : mipSize;
                        mipWidth = Math.max(mipWidth * 0.5, 1);
                        mipHeight = Math.max(mipHeight * 0.5, 1);
                    }
                }

                texture.upload();
            }
            return texture;
        },

        patch: function (asset, assets) {
            var texture = asset.resource;

            if (! texture)
                return;

            if (texture.name !== asset.name)
                texture.name = asset.name;

            if (asset.data.hasOwnProperty('minfilter') && texture.minFilter !== JSON_FILTER_MODE[asset.data.minfilter])
                texture.minFilter = JSON_FILTER_MODE[asset.data.minfilter];

            if (asset.data.hasOwnProperty('magfilter') && texture.magFilter !== JSON_FILTER_MODE[asset.data.magfilter])
                texture.magFilter = JSON_FILTER_MODE[asset.data.magfilter];

            if (asset.data.hasOwnProperty('addressu') && texture.addressU !== JSON_ADDRESS_MODE[asset.data.addressu])
                texture.addressU = JSON_ADDRESS_MODE[asset.data.addressu];

            if (asset.data.hasOwnProperty('addressv') && texture.addressV !== JSON_ADDRESS_MODE[asset.data.addressv])
                texture.addressV = JSON_ADDRESS_MODE[asset.data.addressv];

            if (asset.data.hasOwnProperty('anisotropy') && texture.anisotropy !== asset.data.anisotropy)
                texture.anisotropy = asset.data.anisotropy;

            if (asset.data.hasOwnProperty('rgbm') && texture.rgbm !== !! asset.data.rgbm)
                texture.rgbm = !! asset.data.rgbm;
        }
    };

    return {
        TextureHandler: TextureHandler,
    };
}());
<commit_msg>Use crossOrigin 'anonymous' by default in texture handler if asset prefix is set (this prevents failing to load when server uses wildcard origin)<commit_after>pc.extend(pc, function () {
    'use strict';

    var JSON_ADDRESS_MODE = {
        "repeat": pc.ADDRESS_REPEAT,
        "clamp":  pc.ADDRESS_CLAMP_TO_EDGE,
        "mirror": pc.ADDRESS_MIRRORED_REPEAT
    };

    var JSON_FILTER_MODE = {
        "nearest":             pc.FILTER_NEAREST,
        "linear":              pc.FILTER_LINEAR,
        "nearest_mip_nearest": pc.FILTER_NEAREST_MIPMAP_NEAREST,
        "linear_mip_nearest":  pc.FILTER_LINEAR_MIPMAP_NEAREST,
        "nearest_mip_linear":  pc.FILTER_NEAREST_MIPMAP_LINEAR,
        "linear_mip_linear":   pc.FILTER_LINEAR_MIPMAP_LINEAR
    };

    function arrayBufferCopy(src, dst, dstByteOffset, numBytes) {
        var i;
        var dst32Offset = dstByteOffset / 4;
        var tail = (numBytes % 4);
        var src32 = new Uint32Array(src.buffer, 0, (numBytes - tail) / 4);
        var dst32 = new Uint32Array(dst.buffer);
        for (i = 0; i < src32.length; i++) {
            dst32[dst32Offset + i] = src32[i];
        }
        for (i = numBytes - tail; i < numBytes; i++) {
            dst[dstByteOffset + i] = src[i];
        }
    }

    var TextureHandler = function (device, assets, loader) {
        this._device = device;
        this._assets = assets;
        this._loader = loader;

        // by default don't try cross-origin, because some browsers send different cookes (e.g. safari) if this is set.
        this.crossOrigin = undefined;
        if (assets.prefix) {
            // ensure we send cookies if we load images.
            this.crossOrigin = 'anonymous';
        }
    };

    TextureHandler.prototype = {
        load: function (url, callback) {
            var self = this;

            var urlWithoutParams = url.indexOf('?') >= 0 ? url.split('?')[0] : url;

            var ext = pc.path.getExtension(urlWithoutParams).toLowerCase();
            if ((ext === '.dds') || (ext === '.crn')) {
                var options = {
                    cache: true,
                    responseType: "arraybuffer"
                };

                pc.http.get(url, options, function (err, response) {
                    if (!err) {
                        callback(null, response);
                    } else {
                        callback(err)
                    }
                });
            } else if ((ext === '.jpg') || (ext === '.jpeg') || (ext === '.gif') || (ext === '.png')) {
                var image = new Image();
                if (self.crossOrigin !== undefined) {
                    image.crossOrigin = self.crossOrigin;
                }

                // Call success callback after opening Texture
                image.onload = function () {
                    callback(null, image);
                };

                // Call error callback with details.
                image.onerror = function (event) {
                    callback(pc.string.format("Error loading Texture from: '{0}'", url));
                };

                image.src = url;
            } else {
                // Unsupported texture extension
                // Use timeout because asset events can be hooked up after load gets called in some
                // cases. For example, material loads a texture on 'add' event.
                setTimeout(function () {
                    callback(pc.string.format("Error loading Texture: format not supported: '{0}'", ext));
                }, 0);
            }
        },

        open: function (url, data) {
            if (! url)
                return;

            var self = this;
            var texture;
            var ext = pc.path.getExtension(url).toLowerCase();
            var format = null;

            // Every browser seems to pass data as an Image type. For some reason, the XDK
            // passes an HTMLImageElement. TODO: figure out why!
            // DDS textures are ArrayBuffers
            if ((data instanceof Image) || (data instanceof HTMLImageElement)) { // PNG, JPG or GIF
                var img = data;

                format = (ext === ".jpg" || ext === ".jpeg") ? pc.PIXELFORMAT_R8_G8_B8 : pc.PIXELFORMAT_R8_G8_B8_A8;
                texture = new pc.Texture(this._device, {
                    width: img.width,
                    height: img.height,
                    format: format
                });
                texture.setSource(img);

            } else if (data instanceof ArrayBuffer) { // DDS or CRN
                if (ext === ".crn") {
                    // Copy loaded file into Emscripten-managed memory
                    var srcSize = data.byteLength;
                    var bytes = new Uint8Array(data);
                    var src = Module._malloc(srcSize);
                    arrayBufferCopy(bytes, Module.HEAPU8, src, srcSize);

                    // Decompress CRN to DDS (minus the header)
                    var dst = Module._crn_decompress_get_data(src, srcSize);
                    var dstSize = Module._crn_decompress_get_size(src, srcSize);

                    data = Module.HEAPU8.buffer.slice(dst, dst + dstSize);
                }

                // DDS loading
                var header = new Uint32Array(data, 0, 128 / 4);

                var width = header[4];
                var height = header[3];
                var mips = Math.max(header[7], 1);
                var isFourCc = header[20] === 4;
                var fcc = header[21];
                var bpp = header[22];
                var isCubemap = header[28] === 65024; // TODO: check by bitflag

                var FCC_DXT1 = 827611204; // DXT1
                var FCC_DXT5 = 894720068; // DXT5
                var FCC_FP32 = 116; // RGBA32f

                // non standard
                var FCC_ETC1 = 826496069;
                var FCC_PVRTC_2BPP_RGB_1 = 825438800;
                var FCC_PVRTC_2BPP_RGBA_1 = 825504336;
                var FCC_PVRTC_4BPP_RGB_1 = 825439312;
                var FCC_PVRTC_4BPP_RGBA_1 = 825504848;

                var compressed = false;
                var floating = false;
                var etc1 = false;
                var pvrtc2 = false;
                var pvrtc4 = false;
                if (isFourCc) {
                    if (fcc===FCC_DXT1) {
                        format = pc.PIXELFORMAT_DXT1;
                        compressed = true;
                    } else if (fcc===FCC_DXT5) {
                        format = pc.PIXELFORMAT_DXT5;
                        compressed = true;
                    } else if (fcc===FCC_FP32) {
                        format = pc.PIXELFORMAT_RGBA32F;
                        floating = true;
                    } else if (fcc===FCC_ETC1) {
                        format = pc.PIXELFORMAT_ETC1;
                        compressed = true;
                        etc1 = true;
                    } else if (fcc===FCC_PVRTC_2BPP_RGB_1 || fcc===FCC_PVRTC_2BPP_RGBA_1) {
                        format = fcc===FCC_PVRTC_2BPP_RGB_1? pc.PIXELFORMAT_PVRTC_2BPP_RGB_1 : pc.PIXELFORMAT_PVRTC_2BPP_RGBA_1;
                        compressed = true;
                        pvrtc2 = true;
                    } else if (fcc===FCC_PVRTC_4BPP_RGB_1 || fcc===FCC_PVRTC_4BPP_RGBA_1) {
                        format = fcc===FCC_PVRTC_4BPP_RGB_1? pc.PIXELFORMAT_PVRTC_4BPP_RGB_1 : pc.PIXELFORMAT_PVRTC_4BPP_RGBA_1;
                        compressed = true;
                        pvrtc4 = true;
                    }
                } else {
                    if (bpp===32) {
                        format = pc.PIXELFORMAT_R8_G8_B8_A8;
                    }
                }

                var requiredMips = Math.round(Math.log2(Math.max(width, height)) + 1);
                var cantLoad = !format || (mips !== requiredMips && compressed);
                if (cantLoad) {
                    var errEnd = ". Empty texture will be created instead.";
                    if (!format) {
                        console.error("This DDS pixel format is currently unsupported" + errEnd);
                    } else {
                        console.error("DDS has " + mips + " mips, but engine requires " + requiredMips + " for DXT format. " + errEnd);
                    }
                    texture = new pc.Texture(this._device, {
                        width: 4,
                        height: 4,
                        format: pc.PIXELFORMAT_R8_G8_B8
                    });
                    return texture;
                }

                var texOptions = {
                    width: width,
                    height: height,
                    format: format,
                    cubemap: isCubemap
                };
                texture = new pc.Texture(this._device, texOptions);
                if (isCubemap) {
                    texture.addressU = pc.ADDRESS_CLAMP_TO_EDGE;
                    texture.addressV = pc.ADDRESS_CLAMP_TO_EDGE;
                }

                var offset = 128;
                var faces = isCubemap? 6 : 1;
                var mipSize;
                var DXT_BLOCK_WIDTH = 4;
                var DXT_BLOCK_HEIGHT = 4;
                var blockSize = fcc===FCC_DXT1? 8 : 16;
                var numBlocksAcross, numBlocksDown, numBlocks;
                for(var face=0; face<faces; face++) {
                    var mipWidth = width;
                    var mipHeight = height;
                    for(var i=0; i<mips; i++) {
                        if (compressed) {
                            if (etc1) {
                                mipSize = Math.floor((mipWidth + 3) / 4) * Math.floor((mipHeight + 3) / 4) * 8;
                            } else if (pvrtc2) {
                                mipSize = Math.max(mipWidth, 16) * Math.max(mipHeight, 8) / 4;
                            } else if (pvrtc4) {
                                mipSize = Math.max(mipWidth, 8) * Math.max(mipHeight, 8) / 2;
                            } else {
                                numBlocksAcross = Math.floor((mipWidth + DXT_BLOCK_WIDTH - 1) / DXT_BLOCK_WIDTH);
                                numBlocksDown = Math.floor((mipHeight + DXT_BLOCK_HEIGHT - 1) / DXT_BLOCK_HEIGHT);
                                numBlocks = numBlocksAcross * numBlocksDown;
                                mipSize = numBlocks * blockSize;
                            }
                        } else {
                            mipSize = mipWidth * mipHeight * 4;
                        }

                        var mipBuff = floating? new Float32Array(data, offset, mipSize) : new Uint8Array(data, offset, mipSize);
                        if (!isCubemap) {
                            texture._levels[i] = mipBuff;
                        } else {
                            if (!texture._levels[i]) texture._levels[i] = [];
                            texture._levels[i][face] = mipBuff;
                        }
                        offset += floating? mipSize * 4 : mipSize;
                        mipWidth = Math.max(mipWidth * 0.5, 1);
                        mipHeight = Math.max(mipHeight * 0.5, 1);
                    }
                }

                texture.upload();
            }
            return texture;
        },

        patch: function (asset, assets) {
            var texture = asset.resource;

            if (! texture)
                return;

            if (texture.name !== asset.name)
                texture.name = asset.name;

            if (asset.data.hasOwnProperty('minfilter') && texture.minFilter !== JSON_FILTER_MODE[asset.data.minfilter])
                texture.minFilter = JSON_FILTER_MODE[asset.data.minfilter];

            if (asset.data.hasOwnProperty('magfilter') && texture.magFilter !== JSON_FILTER_MODE[asset.data.magfilter])
                texture.magFilter = JSON_FILTER_MODE[asset.data.magfilter];

            if (asset.data.hasOwnProperty('addressu') && texture.addressU !== JSON_ADDRESS_MODE[asset.data.addressu])
                texture.addressU = JSON_ADDRESS_MODE[asset.data.addressu];

            if (asset.data.hasOwnProperty('addressv') && texture.addressV !== JSON_ADDRESS_MODE[asset.data.addressv])
                texture.addressV = JSON_ADDRESS_MODE[asset.data.addressv];

            if (asset.data.hasOwnProperty('anisotropy') && texture.anisotropy !== asset.data.anisotropy)
                texture.anisotropy = asset.data.anisotropy;

            if (asset.data.hasOwnProperty('rgbm') && texture.rgbm !== !! asset.data.rgbm)
                texture.rgbm = !! asset.data.rgbm;
        }
    };

    return {
        TextureHandler: TextureHandler,
    };
}());
<|endoftext|>


<commit_before>module.exports = {
  plugins: [
    'jsx-a11y',
    'react'
  ],

  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
  },

  rules: {
    // Enforce that anchors have content
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/anchor-has-content.md
    'jsx-a11y/anchor-has-content': ['error', { components: [] }],

    // Require ARIA roles to be valid and non-abstract
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-role.md
    'jsx-a11y/aria-role': ['error', { ignoreNonDOM: false }],

    // Enforce all aria-* props are valid.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-props.md
    'jsx-a11y/aria-props': 'error',

    // Enforce ARIA state and property values are valid.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-proptypes.md
    'jsx-a11y/aria-proptypes': 'error',

    // Enforce that elements that do not support ARIA roles, states, and
    // properties do not have those attributes.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-unsupported-elements.md
    'jsx-a11y/aria-unsupported-elements': 'error',

    // Enforce that all elements that require alternative text have meaningful information
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/alt-text.md
    'jsx-a11y/alt-text': ['error', {
      elements: ['img', 'object', 'area', 'input[type="image"]'],
      img: [],
      object: [],
      area: [],
      'input[type="image"]': [],
    }],

    // Prevent img alt text from containing redundant words like "image", "picture", or "photo"
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/img-redundant-alt.md
    'jsx-a11y/img-redundant-alt': 'error',

    // require that JSX labels use "htmlFor"
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/label-has-for.md
    // deprecated: replaced by `label-has-associated-control` rule
    'jsx-a11y/label-has-for': ['off', {
      components: [],
      required: {
        every: ['nesting', 'id'],
      },
      allowChildren: false,
    }],

    // Enforce that a label tag has a text label and an associated control.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/b800f40a2a69ad48015ae9226fbe879f946757ed/docs/rules/label-has-associated-control.md
    'jsx-a11y/label-has-associated-control': ['error', {
      labelComponents: [],
      labelAttributes: [],
      controlComponents: [],
      assert: 'both',
      depth: 25
    }],

    // Enforce that a control (an interactive element) has a text label.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/control-has-associated-label.md
    'jsx-a11y/control-has-associated-label': ['error', {
      labelAttributes: ['label'],
      controlComponents: [],
      ignoreElements: [
        'audio',
        'canvas',
        'embed',
        'input',
        'textarea',
        'tr',
        'video',
      ],
      ignoreRoles: [
        'grid',
        'listbox',
        'menu',
        'menubar',
        'radiogroup',
        'row',
        'tablist',
        'toolbar',
        'tree',
        'treegrid',
      ],
      depth: 5,
    }],

    // require that mouseover/out come with focus/blur, for keyboard-only users
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/mouse-events-have-key-events.md
    'jsx-a11y/mouse-events-have-key-events': 'error',

    // Prevent use of `accessKey`
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-access-key.md
    'jsx-a11y/no-access-key': 'error',

    // require onBlur instead of onChange
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-onchange.md
    'jsx-a11y/no-onchange': 'off',

    // Elements with an interactive role and interaction handlers must be focusable
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/interactive-supports-focus.md
    'jsx-a11y/interactive-supports-focus': 'error',

    // Enforce that elements with ARIA roles must have all required attributes
    // for that role.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/role-has-required-aria-props.md
    'jsx-a11y/role-has-required-aria-props': 'error',

    // Enforce that elements with explicit or implicit roles defined contain
    // only aria-* properties supported by that role.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/role-supports-aria-props.md
    'jsx-a11y/role-supports-aria-props': 'error',

    // Enforce tabIndex value is not greater than zero.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/tabindex-no-positive.md
    'jsx-a11y/tabindex-no-positive': 'error',

    // ensure <hX> tags have content and are not aria-hidden
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/heading-has-content.md
    'jsx-a11y/heading-has-content': ['error', { components: [''] }],

    // require HTML elements to have a "lang" prop
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/html-has-lang.md
    'jsx-a11y/html-has-lang': 'error',

    // require HTML element's lang prop to be valid
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/lang.md
    'jsx-a11y/lang': 'error',

    // prevent distracting elements, like <marquee> and <blink>
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-distracting-elements.md
    'jsx-a11y/no-distracting-elements': ['error', {
      elements: ['marquee', 'blink'],
    }],

    // only allow <th> to have the "scope" attr
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/scope.md
    'jsx-a11y/scope': 'error',

    // require onClick be accompanied by onKeyUp/onKeyDown/onKeyPress
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/click-events-have-key-events.md
    'jsx-a11y/click-events-have-key-events': 'error',

    // Enforce that DOM elements without semantic behavior not have interaction handlers
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-static-element-interactions.md
    'jsx-a11y/no-static-element-interactions': ['error', {
      handlers: [
        'onClick',
        'onMouseDown',
        'onMouseUp',
        'onKeyPress',
        'onKeyDown',
        'onKeyUp',
      ]
    }],

    // A non-interactive element does not support event handlers (mouse and key handlers)
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-noninteractive-element-interactions.md
    'jsx-a11y/no-noninteractive-element-interactions': ['error', {
      handlers: [
        'onClick',
        'onMouseDown',
        'onMouseUp',
        'onKeyPress',
        'onKeyDown',
        'onKeyUp',
      ]
    }],

    // elements with aria-activedescendant must be tabbable
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-activedescendant-has-tabindex.md
    'jsx-a11y/aria-activedescendant-has-tabindex': 'error',

    // ensure iframe elements have a unique title
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/iframe-has-title.md
    'jsx-a11y/iframe-has-title': 'error',

    // prohibit autoFocus prop
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-autofocus.md
    'jsx-a11y/no-autofocus': ['error', { ignoreNonDOM: true }],

    // ensure HTML elements do not specify redundant ARIA roles
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-redundant-roles.md
    'jsx-a11y/no-redundant-roles': 'error',

    // media elements must have captions
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/media-has-caption.md
    'jsx-a11y/media-has-caption': ['error', {
      audio: [],
      video: [],
      track: [],
    }],

    // WAI-ARIA roles should not be used to convert an interactive element to non-interactive
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-interactive-element-to-noninteractive-role.md
    'jsx-a11y/no-interactive-element-to-noninteractive-role': ['error', {
      tr: ['none', 'presentation'],
    }],

    // WAI-ARIA roles should not be used to convert a non-interactive element to interactive
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-noninteractive-element-to-interactive-role.md
    'jsx-a11y/no-noninteractive-element-to-interactive-role': ['error', {
      ul: ['listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid'],
      ol: ['listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid'],
      li: ['menuitem', 'option', 'row', 'tab', 'treeitem'],
      table: ['grid'],
      td: ['gridcell'],
    }],

    // Tab key navigation should be limited to elements on the page that can be interacted with.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-noninteractive-tabindex.md
    'jsx-a11y/no-noninteractive-tabindex': ['error', {
      tags: [],
      roles: ['tabpanel'],
    }],

    // ensure <a> tags are valid
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/0745af376cdc8686d85a361ce36952b1fb1ccf6e/docs/rules/anchor-is-valid.md
    'jsx-a11y/anchor-is-valid': ['error', {
      components: ['Link'],
      specialLink: ['to'],
      aspects: ['noHref', 'invalidHref', 'preferButton'],
    }],

    // Ensure the autocomplete attribute is correct and suitable for the form field it is used with
    // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/29c68596b15c4ff0a40daae6d4a2670e36e37d35/docs/rules/autocomplete-valid.md
    'jsx-a11y/autocomplete-valid': ['off', {
      inputComponents: [],
    }],
  },
};
<commit_msg>[eslint config] [patch] re-add `jsx-a11y/accessible-emoji`, but disabled<commit_after>module.exports = {
  plugins: [
    'jsx-a11y',
    'react'
  ],

  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
  },

  rules: {
    // Enforce that anchors have content
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/anchor-has-content.md
    'jsx-a11y/anchor-has-content': ['error', { components: [] }],

    // Require ARIA roles to be valid and non-abstract
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-role.md
    'jsx-a11y/aria-role': ['error', { ignoreNonDOM: false }],

    // Enforce all aria-* props are valid.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-props.md
    'jsx-a11y/aria-props': 'error',

    // Enforce ARIA state and property values are valid.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-proptypes.md
    'jsx-a11y/aria-proptypes': 'error',

    // Enforce that elements that do not support ARIA roles, states, and
    // properties do not have those attributes.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-unsupported-elements.md
    'jsx-a11y/aria-unsupported-elements': 'error',

    // Enforce that all elements that require alternative text have meaningful information
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/alt-text.md
    'jsx-a11y/alt-text': ['error', {
      elements: ['img', 'object', 'area', 'input[type="image"]'],
      img: [],
      object: [],
      area: [],
      'input[type="image"]': [],
    }],

    // Prevent img alt text from containing redundant words like "image", "picture", or "photo"
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/img-redundant-alt.md
    'jsx-a11y/img-redundant-alt': 'error',

    // require that JSX labels use "htmlFor"
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/label-has-for.md
    // deprecated: replaced by `label-has-associated-control` rule
    'jsx-a11y/label-has-for': ['off', {
      components: [],
      required: {
        every: ['nesting', 'id'],
      },
      allowChildren: false,
    }],

    // Enforce that a label tag has a text label and an associated control.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/b800f40a2a69ad48015ae9226fbe879f946757ed/docs/rules/label-has-associated-control.md
    'jsx-a11y/label-has-associated-control': ['error', {
      labelComponents: [],
      labelAttributes: [],
      controlComponents: [],
      assert: 'both',
      depth: 25
    }],

    // Enforce that a control (an interactive element) has a text label.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/control-has-associated-label.md
    'jsx-a11y/control-has-associated-label': ['error', {
      labelAttributes: ['label'],
      controlComponents: [],
      ignoreElements: [
        'audio',
        'canvas',
        'embed',
        'input',
        'textarea',
        'tr',
        'video',
      ],
      ignoreRoles: [
        'grid',
        'listbox',
        'menu',
        'menubar',
        'radiogroup',
        'row',
        'tablist',
        'toolbar',
        'tree',
        'treegrid',
      ],
      depth: 5,
    }],

    // require that mouseover/out come with focus/blur, for keyboard-only users
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/mouse-events-have-key-events.md
    'jsx-a11y/mouse-events-have-key-events': 'error',

    // Prevent use of `accessKey`
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-access-key.md
    'jsx-a11y/no-access-key': 'error',

    // require onBlur instead of onChange
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-onchange.md
    'jsx-a11y/no-onchange': 'off',

    // Elements with an interactive role and interaction handlers must be focusable
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/interactive-supports-focus.md
    'jsx-a11y/interactive-supports-focus': 'error',

    // Enforce that elements with ARIA roles must have all required attributes
    // for that role.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/role-has-required-aria-props.md
    'jsx-a11y/role-has-required-aria-props': 'error',

    // Enforce that elements with explicit or implicit roles defined contain
    // only aria-* properties supported by that role.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/role-supports-aria-props.md
    'jsx-a11y/role-supports-aria-props': 'error',

    // Enforce tabIndex value is not greater than zero.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/tabindex-no-positive.md
    'jsx-a11y/tabindex-no-positive': 'error',

    // ensure <hX> tags have content and are not aria-hidden
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/heading-has-content.md
    'jsx-a11y/heading-has-content': ['error', { components: [''] }],

    // require HTML elements to have a "lang" prop
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/html-has-lang.md
    'jsx-a11y/html-has-lang': 'error',

    // require HTML element's lang prop to be valid
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/lang.md
    'jsx-a11y/lang': 'error',

    // prevent distracting elements, like <marquee> and <blink>
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-distracting-elements.md
    'jsx-a11y/no-distracting-elements': ['error', {
      elements: ['marquee', 'blink'],
    }],

    // only allow <th> to have the "scope" attr
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/scope.md
    'jsx-a11y/scope': 'error',

    // require onClick be accompanied by onKeyUp/onKeyDown/onKeyPress
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/click-events-have-key-events.md
    'jsx-a11y/click-events-have-key-events': 'error',

    // Enforce that DOM elements without semantic behavior not have interaction handlers
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-static-element-interactions.md
    'jsx-a11y/no-static-element-interactions': ['error', {
      handlers: [
        'onClick',
        'onMouseDown',
        'onMouseUp',
        'onKeyPress',
        'onKeyDown',
        'onKeyUp',
      ]
    }],

    // A non-interactive element does not support event handlers (mouse and key handlers)
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-noninteractive-element-interactions.md
    'jsx-a11y/no-noninteractive-element-interactions': ['error', {
      handlers: [
        'onClick',
        'onMouseDown',
        'onMouseUp',
        'onKeyPress',
        'onKeyDown',
        'onKeyUp',
      ]
    }],

    // ensure emoji are accessible
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/accessible-emoji.md
    // disabled; rule is deprecated
    'jsx-a11y/accessible-emoji': 'off',

    // elements with aria-activedescendant must be tabbable
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-activedescendant-has-tabindex.md
    'jsx-a11y/aria-activedescendant-has-tabindex': 'error',

    // ensure iframe elements have a unique title
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/iframe-has-title.md
    'jsx-a11y/iframe-has-title': 'error',

    // prohibit autoFocus prop
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-autofocus.md
    'jsx-a11y/no-autofocus': ['error', { ignoreNonDOM: true }],

    // ensure HTML elements do not specify redundant ARIA roles
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-redundant-roles.md
    'jsx-a11y/no-redundant-roles': 'error',

    // media elements must have captions
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/media-has-caption.md
    'jsx-a11y/media-has-caption': ['error', {
      audio: [],
      video: [],
      track: [],
    }],

    // WAI-ARIA roles should not be used to convert an interactive element to non-interactive
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-interactive-element-to-noninteractive-role.md
    'jsx-a11y/no-interactive-element-to-noninteractive-role': ['error', {
      tr: ['none', 'presentation'],
    }],

    // WAI-ARIA roles should not be used to convert a non-interactive element to interactive
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-noninteractive-element-to-interactive-role.md
    'jsx-a11y/no-noninteractive-element-to-interactive-role': ['error', {
      ul: ['listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid'],
      ol: ['listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid'],
      li: ['menuitem', 'option', 'row', 'tab', 'treeitem'],
      table: ['grid'],
      td: ['gridcell'],
    }],

    // Tab key navigation should be limited to elements on the page that can be interacted with.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-noninteractive-tabindex.md
    'jsx-a11y/no-noninteractive-tabindex': ['error', {
      tags: [],
      roles: ['tabpanel'],
    }],

    // ensure <a> tags are valid
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/0745af376cdc8686d85a361ce36952b1fb1ccf6e/docs/rules/anchor-is-valid.md
    'jsx-a11y/anchor-is-valid': ['error', {
      components: ['Link'],
      specialLink: ['to'],
      aspects: ['noHref', 'invalidHref', 'preferButton'],
    }],

    // Ensure the autocomplete attribute is correct and suitable for the form field it is used with
    // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/29c68596b15c4ff0a40daae6d4a2670e36e37d35/docs/rules/autocomplete-valid.md
    'jsx-a11y/autocomplete-valid': ['off', {
      inputComponents: [],
    }],
  },
};
<|endoftext|>


<commit_before>const noLaunch = process.argv.includes('--no-launch')
const testMinified = process.argv.includes('--minified')
const isSauce = process.argv.includes('--sauce')
const isNetlify = process.argv.includes('--netlify')

if (isNetlify) {
  process.env.CHROME_BIN = require('puppeteer').executablePath()
}

const webpackConfig = {
  devtool: 'inline-source-map',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|dist)/,
        use: {
          loader: 'babel-loader',
          options: {/* babel options */}
        }
      }
    ]
  }
}

const karmaPlugins = [
  'karma-coverage',
  'karma-webpack',
  'karma-qunit',
  'karma-spec-reporter',
  'karma-sourcemap-loader',
  'karma-chrome-launcher',
  'karma-firefox-launcher',
  'karma-ie-launcher',
  'karma-sauce-launcher'
]

const preprocessors = {
  'test/qunit/**/*.js': [
    'webpack',
    'sourcemap'
  ],
  'dist/*.js': [
    'coverage'
  ]
}

const coverageReporter = {
  dir: 'coverage',
  reporters: [
    { type: 'html', subdir: '.' },
    { type: 'lcov', subdir: '.' }
  ]
}

const sauceLabsLaunchers = {
  safari: {
    base: 'SauceLabs',
    browserName: 'Safari',
    version: 'latest',
    // TODO(@limonte): remove this line, the current latest 10.14 doesn't work (#1349)
    platform: 'macOS 10.13'
  },
  // TODO(@limonte): doesn't work, revisit
  // edge: {
  //   base: 'SauceLabs',
  //   browserName: 'MicrosoftEdge',
  //   version: 'latest'
  // },
  ie: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    platformVersion: '11.0',
    platform: 'Windows 7'
  },
  iphone: {
    base: 'SauceLabs',
    browserName: 'Safari',
    deviceName: 'iPhone Simulator',
    platformName: 'iOS',
    platformVersion: 'latest'
  },
  android: {
    base: 'SauceLabs',
    deviceName: 'Android Emulator',
    browserName: 'Chrome',
    platformName: 'Android',
    platformVersion: 'latest'
  }
}

function checkSauceCredentials () {
  if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    console.error('SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables must be set')
    process.exit(1)
  }
}

function getFiles () {
  let files
  if (testMinified) {
    files = [
      'dist/sweetalert2.all.min.js'
    ]
  } else {
    files = [
      'dist/sweetalert2.css',
      'dist/sweetalert2.js'
    ]
  }
  return files.concat([
    'node_modules/promise-polyfill/dist/polyfill.min.js',
    'test/qunit/**/*.js'
  ])
}

function getBrowsers () {
  if (noLaunch) {
    return []
  }

  let browsers = ['ChromeHeadless']

  // Cron on GitHub Actions or check:qunit --sauce
  if (isSauce) {
    checkSauceCredentials()
    browsers = Object.keys(sauceLabsLaunchers)

  // GitHub Actions
  } else if (process.env.GITHUB_ACTION) {
    browsers = ['ChromeHeadless', 'FirefoxHeadless']
  }

  return browsers
}

function getReporters () {
  const reporters = ['spec', 'saucelabs']

  // GitHub Actions
  if (process.env.GITHUB_ACTION && !testMinified) {
    reporters.push('coverage')
  }

  return reporters
}

module.exports = function (config) {
  config.set({
    port: 3000,
    plugins: karmaPlugins,

    frameworks: ['qunit'],
    qunit: { reorder: false },

    customLaunchers: sauceLabsLaunchers,

    files: getFiles(),
    browsers: getBrowsers(),
    reporters: getReporters(),
    preprocessors,
    coverageReporter,

    webpack: webpackConfig,
    webpackMiddleware: {
      stats: 'errors-only'
    },

    captureTimeout: 360000,
    browserNoActivityTimeout: 360000
  })
}
<commit_msg>chore: drop tests in Android Emulator<commit_after>const noLaunch = process.argv.includes('--no-launch')
const testMinified = process.argv.includes('--minified')
const isSauce = process.argv.includes('--sauce')
const isNetlify = process.argv.includes('--netlify')

if (isNetlify) {
  process.env.CHROME_BIN = require('puppeteer').executablePath()
}

const webpackConfig = {
  devtool: 'inline-source-map',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|dist)/,
        use: {
          loader: 'babel-loader',
          options: {/* babel options */}
        }
      }
    ]
  }
}

const karmaPlugins = [
  'karma-coverage',
  'karma-webpack',
  'karma-qunit',
  'karma-spec-reporter',
  'karma-sourcemap-loader',
  'karma-chrome-launcher',
  'karma-firefox-launcher',
  'karma-ie-launcher',
  'karma-sauce-launcher'
]

const preprocessors = {
  'test/qunit/**/*.js': [
    'webpack',
    'sourcemap'
  ],
  'dist/*.js': [
    'coverage'
  ]
}

const coverageReporter = {
  dir: 'coverage',
  reporters: [
    { type: 'html', subdir: '.' },
    { type: 'lcov', subdir: '.' }
  ]
}

const sauceLabsLaunchers = {
  safari: {
    base: 'SauceLabs',
    browserName: 'Safari',
    version: 'latest',
    // TODO(@limonte): remove this line, the current latest 10.14 doesn't work (#1349)
    platform: 'macOS 10.13'
  },
  // TODO(@limonte): doesn't work, revisit
  // edge: {
  //   base: 'SauceLabs',
  //   browserName: 'MicrosoftEdge',
  //   version: 'latest'
  // },
  ie: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    platformVersion: '11.0',
    platform: 'Windows 7'
  },
  iphone: {
    base: 'SauceLabs',
    browserName: 'Safari',
    deviceName: 'iPhone Simulator',
    platformName: 'iOS',
    platformVersion: 'latest'
  },
}

function checkSauceCredentials () {
  if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    console.error('SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables must be set')
    process.exit(1)
  }
}

function getFiles () {
  let files
  if (testMinified) {
    files = [
      'dist/sweetalert2.all.min.js'
    ]
  } else {
    files = [
      'dist/sweetalert2.css',
      'dist/sweetalert2.js'
    ]
  }
  return files.concat([
    'node_modules/promise-polyfill/dist/polyfill.min.js',
    'test/qunit/**/*.js'
  ])
}

function getBrowsers () {
  if (noLaunch) {
    return []
  }

  let browsers = ['ChromeHeadless']

  // Cron on GitHub Actions or check:qunit --sauce
  if (isSauce) {
    checkSauceCredentials()
    browsers = Object.keys(sauceLabsLaunchers)

  // GitHub Actions
  } else if (process.env.GITHUB_ACTION) {
    browsers = ['ChromeHeadless', 'FirefoxHeadless']
  }

  return browsers
}

function getReporters () {
  const reporters = ['spec', 'saucelabs']

  // GitHub Actions
  if (process.env.GITHUB_ACTION && !testMinified) {
    reporters.push('coverage')
  }

  return reporters
}

module.exports = function (config) {
  config.set({
    port: 3000,
    plugins: karmaPlugins,

    frameworks: ['qunit'],
    qunit: { reorder: false },

    customLaunchers: sauceLabsLaunchers,

    files: getFiles(),
    browsers: getBrowsers(),
    reporters: getReporters(),
    preprocessors,
    coverageReporter,

    webpack: webpackConfig,
    webpackMiddleware: {
      stats: 'errors-only'
    },

    captureTimeout: 360000,
    browserNoActivityTimeout: 360000
  })
}
<|endoftext|>


<commit_before>var addressGPS = require('address-gps');
var request = require('request');
var artTemplate = require('art-template');
var template = require('template-cache');
var path = require('path');

var PRODUCTS = ['astro', 'civil', 'civillight', 'meteo', 'two'];

template.load(path.join(__dirname, './tpl'), {
  engine: artTemplate.compile
});

var base = function (lon, lat, product, callback) {
  if (typeof callback === 'undefined') {
    callback = product;
    product = '';
  }
  product = (product = PRODUCTS.indexOf(product.toLowerCase())) > -1 ? PRODUCTS[product] : 'astro';
  var url = 'http://www.7timer.com/v4/bin/api.pl?' + [
    'lon=' + lon, 'lat=' + lat, 'product=' + product, 'output=' + 'json'
    ].join('&');
  request.get(url, callback);
};

var byAddress = function (address, product, callback) {
  addressGPS.getGPS(address, function (location) {
    console.log('Address:' + location.prettyAddress);
    base(location.longitude, location.latitude, product, callback);
  });
};

byAddress('shenzhen', function (err, res, body) {
  if (err) {
    return console.error(err);
  }
  console.log(template.require('astro')(JSON.parse(body).dataseries[0]));
});
<commit_msg>add myip server<commit_after>var addressGPS = require('address-gps');
var request = require('request');
var artTemplate = require('art-template');
var template = require('template-cache');
var path = require('path');

var PRODUCTS = ['astro', 'civil', 'civillight', 'meteo', 'two'];

template.load(path.join(__dirname, './tpl'), {
  engine: artTemplate.compile
});

var base = function (lon, lat, product, callback) {
  if (typeof callback === 'undefined') {
    callback = product;
    product = '';
  }
  product = (product = PRODUCTS.indexOf(product.toLowerCase())) > -1 ? PRODUCTS[product] : 'astro';
  var url = 'http://www.7timer.com/v4/bin/api.pl?' + [
    'lon=' + lon, 'lat=' + lat, 'product=' + product, 'output=' + 'json'
    ].join('&');
  request.get(url, function (err, res, body) {
    callback(err, JSON.parse(body));
  });
};

var byAddress = function (address, product, callback) {
  addressGPS.getGPS(address, function (location) {
    console.log('Address: ' + location.prettyAddress);
    base(location.longitude, location.latitude, product, callback);
  });
};

var byMyIP = function (product, callback) {
  var url = 'http://ip-api.com/json';
  request.get(url, function (err, res, body) {
    var result;
    if (err) {
      return callback(err);
    }
    if (!body || !(result = JSON.parse(body))) {
      return callback(new Error('cannot get my ip'));
    }
    console.log('Address: ' + result.city + ', ' + result.regionName + ', ' + result.country);
    base(result.lon, result.lat, product, callback);
  });
};

// byAddress('shenzhen', function (err, data) {
//   if (err) {
//     return console.error(err);
//   }
//   console.log(template.require('astro')(data.dataseries[0]));
// });

byMyIP(function (err, data) {
  if (err) {
    return console.error(err);
  }
  console.log(template.require('astro')(data.dataseries[0]));
});<|endoftext|>


<commit_before>
window.AudioContext = window.AudioContext || window.webkitAudioContext;

var audioContext = new AudioContext();
var audioInput = null,
    realAudioInput = null,
    inputPoint = null,
    audioRecorder = null;
var rafID = null;
var analyserContext = null;
var canvasWidth, canvasHeight;

//~ function saveAudio() {
    //~ audioRecorder.exportWAV( doneEncoding );
//~ }

//~ function gotBuffers( buffers ) {
    //~ var canvas = document.getElementById( "wavedisplay" );

    //~ drawBuffer( canvas.width, canvas.height, canvas.getContext('2d'), buffers[0] );
    //~ audioRecorder.exportWAV( doneEncoding );
//~ }

//~ function doneEncoding( blob ) {
    //~ Recorder.setupDownload( blob, "myRecording" + ((recIndex<10)?"0":"") + recIndex + ".wav" );
    //~ recIndex++;
//~ }

//~ function toggleRecording( e ) {
    //~ if (e.classList.contains("recording")) {
        //~ // stop recording
        //~ audioRecorder.stop();
        //~ e.classList.remove("recording");
        //~ audioRecorder.getBuffers( gotBuffers );
    //~ } else {
        //~ // start recording
        //~ if (!audioRecorder)
            //~ return;
        //~ e.classList.add("recording");
        //~ audioRecorder.clear();
        //~ audioRecorder.record();
    //~ }
//~ }

//~ function convertToMono( input ) {
    //~ var splitter = audioContext.createChannelSplitter(2);
    //~ var merger = audioContext.createChannelMerger(2);

    //~ input.connect( splitter );
    //~ splitter.connect( merger, 0, 0 );
    //~ splitter.connect( merger, 0, 1 );
    //~ return merger;
//~ }

function cancelAnalyserUpdates() {
    window.cancelAnimationFrame( rafID );
    rafID = null;
}
if (document.getElementById('ajaxCheck').checked === "false"){
	cancelAnalyserUpdates();
}
function updateAnalysers(time) {
    if (!analyserContext) {
        var canvas = document.getElementById("analyser");
        canvasWidth = canvas.width*2;
        canvasHeight = (canvas.height)*1;
        analyserContext = canvas.getContext('2d');
    }

    // analyzer draw code here
    {
        var SPACING = 2;
        var BAR_WIDTH = 23;
        var numBars = Math.round(canvasWidth / SPACING);
        var freqByteData = new Uint8Array(analyserNode.frequencyBinCount);

        analyserNode.getByteFrequencyData(freqByteData);

        analyserContext.clearRect(0, 0, canvasWidth, canvasHeight);
        analyserContext.fillStyle = '#232323';
        analyserContext.lineCap = 'round';
        var multiplier = analyserNode.frequencyBinCount / numBars;

// We are Lions

analyserNode.minDecibels = -54;
analyserNode.maxDecibels = -48;

analyserNode.fftSize = 1024;
var bufferLength = analyserNode.frequencyBinCount;
//~ console.log(bufferLength);

		 //~ console.log(freqByteData);
		 		 //~ console.log(multiplier);
		var pwnyFreq = freqByteData.filter(elem >= 72);
		//~ var pwnyFreq = pwnyFreq.filter(function(n){return n !== undefined});

		var pwnyFreqbars = pwnyFreq.length;
		//~ console.log(pwnyFreq);

		//~ function pwnyEQ() {
		  //~ var xhttp = new XMLHttpRequest();
		  //~ xhttp.onreadystatechange = function() {
		    //~ if (this.readyState == 4 && this.status == 200) {
		      //~ document.getElementById("pwnyStatus").innerHTML = pwnyFreq;
		      //~ this.responseText;
		    //~ }
		  //~ };
		  //~ xhttp.open("GET", "/", true);
		  //~ xhttp.send();
		//~ }pwnyEQ()

if (document.getElementById('ajaxCheck').checked === "false"){
		  var xhttp = new XMLHttpRequest();

		  xhttp.onreadystatechange = function() {
		    if (this.readyState == 4 && this.status == 200) {
		  var eqBcol = document.getElementById('bcolorDiv').innerHTML;
		  var eqHcol = document.getElementById('hcolorDiv').innerHTML;
		  var eqOcol = document.getElementById('ocolorDiv').innerHTML;
		  var pwnyUrl = "daemon.php?eqdata="+pwnyFreqbars+"&eq1="+pwnyFreq[2]+"&eq2="+pwnyFreq[6]+"&eq3="+pwnyFreq[12]+"&eq4="+pwnyFreq[16]+"&eq5="+pwnyFreq[19]+"&eq6="+pwnyFreq[24]+"&eq7="+pwnyFreq[28]+"&eq8="+pwnyFreq[32]+"&eqbColor="+eqBcol+"&eqhColor="+eqHcol+"&eqoColor="+eqOcol;
		  //~ console.log(pwnyFreq[8]);
		    }
		  };

		  xhttp.open("GET", pwnyUrl, true);
		  xhttp.send();

	}

// Yes we scan

        // Draw rectangle for each frequency bin.
        for (var i = 0; i < numBars; ++i) {
            var magnitude = -3;
            var offset = Math.floor( i * multiplier );
            // gotta sum/average the block, or we miss narrow-bandwidth spikes
            for (var j = 0; j< multiplier; j++)
                magnitude += freqByteData[offset + j];
            magnitude = magnitude / multiplier;
            var magnitude2 = freqByteData[i * multiplier];

            analyserContext.fillStyle = "hsl( " + Math.round((i*360)/numBars) + ", 100%, 50%)";
            analyserContext.fillRect(i * SPACING, canvasHeight, BAR_WIDTH, -magnitude);
        }
    }

    rafID = window.requestAnimationFrame( updateAnalysers );
}

//~ function toggleMono() {
    //~ if (audioInput != realAudioInput) {
        //~ audioInput.disconnect();
        //~ realAudioInput.disconnect();
        //~ audioInput = realAudioInput;
    //~ } else {
        //~ realAudioInput.disconnect();
        //~ audioInput = convertToMono( realAudioInput );
    //~ }

    //~ audioInput.connect(inputPoint);
//~ }

function gotStream(stream) {
    inputPoint = audioContext.createGain();

    // Create an AudioNode from the stream.
    realAudioInput = audioContext.createMediaStreamSource(stream);
    audioInput = realAudioInput;
    audioInput.connect(inputPoint);

//    audioInput = convertToMono( input );

    analyserNode = audioContext.createAnalyser();
    analyserNode.fftSize = 2048;
    inputPoint.connect( analyserNode );

    zeroGain = audioContext.createGain();
    zeroGain.gain.value = 0.0;
    inputPoint.connect( zeroGain );
    zeroGain.connect( audioContext.destination );
    updateAnalysers();
}

function initAudio() {
        if (!navigator.getUserMedia)
            navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
        if (!navigator.cancelAnimationFrame)
            navigator.cancelAnimationFrame = navigator.webkitCancelAnimationFrame || navigator.mozCancelAnimationFrame;
        if (!navigator.requestAnimationFrame)
            navigator.requestAnimationFrame = navigator.webkitRequestAnimationFrame || navigator.mozRequestAnimationFrame;

    navigator.getUserMedia(
        {
            "audio": {
                "mandatory": {
                    "googEchoCancellation": "false",
                    "googAutoGainControl": "false",
                    "googNoiseSuppression": "false",
                    "googHighpassFilter": "false"
                },
                "optional": []
            },
        }, gotStream, function(e) {
            alert('Error getting audio');
            console.log(e);
        });
}

window.addEventListener('load', initAudio );
<commit_msg>Delete main_.js<commit_after><|endoftext|>