<commit_before>var mapnik = require('../');
var assert = require('assert');
var path = require('path');
var fs = require('fs');

var stylesheet = './test/stylesheet.xml';
var reference = './test/support/grid2.json';
var reference_view = './test/support/grid_view.json';
var reference__id__ = './test/support/grid__id__.json';
var reference__id__2 = './test/support/grid__id__2.json';
var reference__id__3 = './test/support/grid__id__3.json';

mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'shape.input'));

describe('mapnik grid rendering ', function() {

    it('should match expected output (sync rendering)', function(done) {
        var map = new mapnik.Map(256, 256);
        map.loadSync(stylesheet, {strict: true});
        map.zoomAll();
        var grid = new mapnik.Grid(map.width, map.height, {key: '__id__'});
        var options = {'layer': 0,
                       'fields': ['NAME']
                      };
        map.render(grid, options, function(err, grid) {
            if (err) throw err;
            var grid_utf = grid.encodeSync('utf', {resolution: 4});
            // pull an identical view and compare it to original grid
            var gv = grid.view(0, 0, 256, 256);
            var gv_utf = gv.encodeSync('utf', {resolution: 4});
            if (process.env.UPDATE) {
                fs.writeFileSync(reference,JSON.stringify(grid_utf,null,1))
            } else {
                var expected = fs.readFileSync(reference,'utf8');
                assert.equal(JSON.stringify(grid_utf,null,1), expected);
                assert.equal(JSON.stringify(gv_utf,null,1), expected);
            }
            // pull a subsetted view (greenland basically)
            var gv2 = grid.view(64, 64, 64, 64);
            assert.equal(gv2.width(), 64);
            assert.equal(gv2.height(), 64);
            var gv_utf2 = gv2.encodeSync('utf', {resolution: 4});
            var expected_view = fs.readFileSync(reference_view,'utf8');
            if (process.env.UPDATE) {
                fs.writeFileSync(reference_view,JSON.stringify(gv_utf2,null,1))
            } else {
                assert.equal(JSON.stringify(gv_utf2,null,1), expected_view);
            }
            done();
        });
    });

    it('should match expected output (async rendering)', function(done) {
        var map = new mapnik.Map(256, 256);
        map.load(stylesheet, {strict: true}, function(err,map) {
            if (err) throw err;
            map.zoomAll();
            var grid = new mapnik.Grid(map.width, map.height, {key: '__id__'});

            var options = {'layer': 0,
                           'fields': ['NAME']
                          };
            map.render(grid, options, function(err, grid) {
                if (err) throw err;
                grid.encode('utf', {resolution: 4}, function(err,utf) {
                    assert.equal(JSON.stringify(utf,null,1), fs.readFileSync(reference,'utf8'));
                    done();
                });
            });
        });
    });

    it('should match expected output (async rendering view)', function(done) {
        var map = new mapnik.Map(256, 256);
        map.load(stylesheet, {strict: true}, function(err,map) {
            if (err) throw err;
            map.zoomAll();
            var grid = new mapnik.Grid(map.width, map.height, {key: '__id__'});

            var options = {'layer': 0,
                           'fields': ['NAME']
                          };
            map.render(grid, options, function(err, grid) {
                assert.ok(!err);
                var gv = grid.view(0, 0, 256, 256);
                gv.encode('utf', {resolution: 4}, function(err,gv_utf1) {
                    assert.equal(JSON.stringify(gv_utf1,null,1), fs.readFileSync(reference,'utf8'));
                    done();
                });
            });
        });
    });

    it('should match expected output (async rendering view subsetted)', function(done) {
        var map = new mapnik.Map(256, 256);
        map.load(stylesheet, {strict: true}, function(err,map) {
            if (err) throw err;
            map.zoomAll();
            var grid = new mapnik.Grid(map.width, map.height, {key: '__id__'});

            var options = {'layer': 0,
                           'fields': ['NAME']
                          };
            map.render(grid, options, function(err, grid) {
                assert.ok(!err);
                // pull a subsetted view (greenland basically)
                var gv2 = grid.view(64, 64, 64, 64);
                assert.equal(gv2.width(), 64);
                assert.equal(gv2.height(), 64);
                gv2.encode('utf', {resolution: 4}, function(err,gv_utf2) {
                    if (process.env.UPDATE) {
                        fs.writeFileSync(reference_view,JSON.stringify(gv_utf2,null,1))
                    } else {
                        assert.equal(JSON.stringify(gv_utf2,null,1), fs.readFileSync(reference_view,'utf8'));
                    }
                    done();
                });
            });
        });
    });

    it('should match expected output if __id__ is not the grid key', function(done) {
        var map = new mapnik.Map(256, 256);
        map.loadSync(stylesheet, {strict: true});
        map.zoomAll();
        var grid = new mapnik.Grid(map.width, map.height, {key: 'NAME'});
        var options = {'layer': 0,
                       'fields': ['FIPS','__id__']
                      };
        map.render(grid, options, function(err, grid) {
            if (err) throw err;
            var grid_utf = grid.encodeSync('utf', {resolution: 4});
            if (process.env.UPDATE) {
                fs.writeFileSync(reference__id__,JSON.stringify(grid_utf,null,1))
            } else {
                assert.equal(JSON.stringify(grid_utf,null,1), fs.readFileSync(reference__id__,'utf8'));
            }
            done();
        });
    });

    it('should match expected output if __id__ both the grid key and in the attributes with others', function(done) {
        var map = new mapnik.Map(256, 256);
        map.loadSync(stylesheet, {strict: true});
        map.zoomAll();
        var grid = new mapnik.Grid(map.width, map.height, {key: '__id__'});
        var options = {'layer': 0,
                       'fields': ['__id__','NAME']
                      };
        map.render(grid, options, function(err, grid) {
            if (err) throw err;
            var grid_utf = grid.encodeSync('utf', {resolution: 4});
            if (process.env.UPDATE) {
                fs.writeFileSync(reference__id__2,JSON.stringify(grid_utf,null,1))
            } else {
                assert.equal(JSON.stringify(grid_utf,null,1), fs.readFileSync(reference__id__2,'utf8'));
            }
            done();
        });
    });

    it('should match expected output if __id__ the grid key and the only attributes', function(done) {
        var map = new mapnik.Map(256, 256);
        map.loadSync(stylesheet, {strict: true});
        map.zoomAll();
        var grid = new mapnik.Grid(map.width, map.height, {key: '__id__'});
        var options = {'layer': 0,
                       'fields': ['__id__']
                      };
        map.render(grid, options, function(err, grid) {
            if (err) throw err;
            var grid_utf = grid.encodeSync('utf', {resolution: 4});
            if (process.env.UPDATE) {
                fs.writeFileSync(reference__id__3,JSON.stringify(grid_utf,null,1))
            } else {
                assert.equal(JSON.stringify(grid_utf,null,1), fs.readFileSync(reference__id__3,'utf8'));
            }
            done();
        });
    });

});
<commit_msg>avoid mocha diffs<commit_after>var mapnik = require('../');
var assert = require('assert');
var path = require('path');
var fs = require('fs');

var stylesheet = './test/stylesheet.xml';
var reference = './test/support/grid2.json';
var reference_view = './test/support/grid_view.json';
var reference__id__ = './test/support/grid__id__.json';
var reference__id__2 = './test/support/grid__id__2.json';
var reference__id__3 = './test/support/grid__id__3.json';

mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'shape.input'));

describe('mapnik grid rendering ', function() {

    it('should match expected output (sync rendering)', function(done) {
        var map = new mapnik.Map(256, 256);
        map.loadSync(stylesheet, {strict: true});
        map.zoomAll();
        var grid = new mapnik.Grid(map.width, map.height, {key: '__id__'});
        var options = {'layer': 0,
                       'fields': ['NAME']
                      };
        map.render(grid, options, function(err, grid) {
            if (err) throw err;
            var grid_utf = grid.encodeSync('utf', {resolution: 4});
            // pull an identical view and compare it to original grid
            var gv = grid.view(0, 0, 256, 256);
            var gv_utf = gv.encodeSync('utf', {resolution: 4});
            if (process.env.UPDATE) {
                fs.writeFileSync(reference,JSON.stringify(grid_utf,null,1))
            } else {
                var expected = fs.readFileSync(reference,'utf8');
                var equal =JSON.stringify(grid_utf,null,1) == expected;
                assert.ok(equal);
                equal = JSON.stringify(gv_utf,null,1) == expected;
                assert.ok(equal);
            }
            // pull a subsetted view (greenland basically)
            var gv2 = grid.view(64, 64, 64, 64);
            assert.equal(gv2.width(), 64);
            assert.equal(gv2.height(), 64);
            var gv_utf2 = gv2.encodeSync('utf', {resolution: 4});
            var expected_view = fs.readFileSync(reference_view,'utf8');
            if (process.env.UPDATE) {
                fs.writeFileSync(reference_view,JSON.stringify(gv_utf2,null,1))
            } else {
                var equal = JSON.stringify(gv_utf2,null,1) == expected_view;
                assert.ok(equal);
            }
            done();
        });
    });

    it('should match expected output (async rendering)', function(done) {
        var map = new mapnik.Map(256, 256);
        map.load(stylesheet, {strict: true}, function(err,map) {
            if (err) throw err;
            map.zoomAll();
            var grid = new mapnik.Grid(map.width, map.height, {key: '__id__'});

            var options = {'layer': 0,
                           'fields': ['NAME']
                          };
            map.render(grid, options, function(err, grid) {
                if (err) throw err;
                grid.encode('utf', {resolution: 4}, function(err,utf) {
                    var equal = JSON.stringify(utf,null,1) == fs.readFileSync(reference,'utf8');
                    assert.ok(equal);
                    done();
                });
            });
        });
    });

    it('should match expected output (async rendering view)', function(done) {
        var map = new mapnik.Map(256, 256);
        map.load(stylesheet, {strict: true}, function(err,map) {
            if (err) throw err;
            map.zoomAll();
            var grid = new mapnik.Grid(map.width, map.height, {key: '__id__'});

            var options = {'layer': 0,
                           'fields': ['NAME']
                          };
            map.render(grid, options, function(err, grid) {
                assert.ok(!err);
                var gv = grid.view(0, 0, 256, 256);
                gv.encode('utf', {resolution: 4}, function(err,gv_utf1) {
                    var equal = JSON.stringify(gv_utf1,null,1) == fs.readFileSync(reference,'utf8');
                    assert.ok(equal);
                    done();
                });
            });
        });
    });

    it('should match expected output (async rendering view subsetted)', function(done) {
        var map = new mapnik.Map(256, 256);
        map.load(stylesheet, {strict: true}, function(err,map) {
            if (err) throw err;
            map.zoomAll();
            var grid = new mapnik.Grid(map.width, map.height, {key: '__id__'});

            var options = {'layer': 0,
                           'fields': ['NAME']
                          };
            map.render(grid, options, function(err, grid) {
                assert.ok(!err);
                // pull a subsetted view (greenland basically)
                var gv2 = grid.view(64, 64, 64, 64);
                assert.equal(gv2.width(), 64);
                assert.equal(gv2.height(), 64);
                gv2.encode('utf', {resolution: 4}, function(err,gv_utf2) {
                    if (process.env.UPDATE) {
                        fs.writeFileSync(reference_view,JSON.stringify(gv_utf2,null,1))
                    } else {
                        var equal = JSON.stringify(gv_utf2,null,1) == fs.readFileSync(reference_view,'utf8');
                        assert.ok(equal);
                    }
                    done();
                });
            });
        });
    });

    it('should match expected output if __id__ is not the grid key', function(done) {
        var map = new mapnik.Map(256, 256);
        map.loadSync(stylesheet, {strict: true});
        map.zoomAll();
        var grid = new mapnik.Grid(map.width, map.height, {key: 'NAME'});
        var options = {'layer': 0,
                       'fields': ['FIPS','__id__']
                      };
        map.render(grid, options, function(err, grid) {
            if (err) throw err;
            var grid_utf = grid.encodeSync('utf', {resolution: 4});
            if (process.env.UPDATE) {
                fs.writeFileSync(reference__id__,JSON.stringify(grid_utf,null,1))
            } else {
                var equal =JSON.stringify(grid_utf,null,1) == fs.readFileSync(reference__id__,'utf8');
                assert.ok(equal);
            }
            done();
        });
    });

    it('should match expected output if __id__ both the grid key and in the attributes with others', function(done) {
        var map = new mapnik.Map(256, 256);
        map.loadSync(stylesheet, {strict: true});
        map.zoomAll();
        var grid = new mapnik.Grid(map.width, map.height, {key: '__id__'});
        var options = {'layer': 0,
                       'fields': ['__id__','NAME']
                      };
        map.render(grid, options, function(err, grid) {
            if (err) throw err;
            var grid_utf = grid.encodeSync('utf', {resolution: 4});
            if (process.env.UPDATE) {
                fs.writeFileSync(reference__id__2,JSON.stringify(grid_utf,null,1))
            } else {
                var equal = JSON.stringify(grid_utf,null,1) == fs.readFileSync(reference__id__2,'utf8');
                assert.ok(equal);
            }
            done();
        });
    });

    it('should match expected output if __id__ the grid key and the only attributes', function(done) {
        var map = new mapnik.Map(256, 256);
        map.loadSync(stylesheet, {strict: true});
        map.zoomAll();
        var grid = new mapnik.Grid(map.width, map.height, {key: '__id__'});
        var options = {'layer': 0,
                       'fields': ['__id__']
                      };
        map.render(grid, options, function(err, grid) {
            if (err) throw err;
            var grid_utf = grid.encodeSync('utf', {resolution: 4});
            if (process.env.UPDATE) {
                fs.writeFileSync(reference__id__3,JSON.stringify(grid_utf,null,1))
            } else {
                var equal = JSON.stringify(grid_utf,null,1) == fs.readFileSync(reference__id__3,'utf8');
                assert.ok(equal);
            }
            done();
        });
    });

});
<|endoftext|>


<commit_before>'use strict';

/*
 * RESTBase proxy layer
 *
 * Dispatches a request to
 * - A matching proxy handler, or
 * - A back-end handler iff
 *   - there is no front-end match
 *   - the request would map to the proxy handler making the request.
 */

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

function RESTBase (routers, options) {
    this.options = options;
    this.log = options.log; // logging method
    this._routers = routers.filter(function(r) {
        return r.routes && r.routes.length;
    });
    if (options.conf.monitoring && options.conf.monitoring.statdsHost) {
        this.timer = new util.Timer(options.conf.monitoring.statdsHost);
    }
    //console.log(JSON.stringify(this._routers, null, 2));
}

RESTBase.prototype.request = function request (req) {
    var self = this;

    if (req.__depth > this.options.maxDepth) {
        return Promise.resolve({
            status: 500,
            body: {
                type: 'proxy_recursion_depth_exceeded',
                title: 'RESTBase handler recursion depth exceeded.',
                uri: req.uri,
                method: req.method,
                depth: req.__depth
            }
        });
    }

    // COW for the request
    // jshint proto: true
    var childReq = { __proto__: req };
    if (!childReq.query) {
        req.query = {};
    }

    var i = 0;
    // jshint proto: true
    var parentReq = this.__parentReq;
    if (parentReq && req.uri === parentReq.uri) {
        // URL didn't change, jump to the next layer
        if (this.storageHandler) {
            // Normally used to call from a bucket straight to the storage
            // router.
            // XXX: match signature in storage.js
            return this.storageHandler(this, childReq);
        }
        i = (this.__layer || 0) + 1;
    }

    for (; i < this._routers.length; i++) {
        var match = this._routers[i].match(req.uri);
        if (match) {

            // start timer
            if (this.timer) {
                var statName = match.sortKey + "." + req.method;
                this.timer.start(statName);
            }

            //console.log(req.uri, match);
            // console.log('recursive', req.uri, req.method, match.methods);
            var handler = match.methods[req.method] || match.methods.all;
            if (handler && handler.request_handler) {
                // Found a matching proxy handler. Prepare to call it.
                // Still using __proto__, as it's quite a bit faster than
                // Object.create.
                // jshint proto: true
                var childRESTBase = {
                    __proto__: self,
                    __parentReq: req,
                    __layer: i,
                    __depth:  (self.__depth || 0) + 1
                };
                childReq.params = match.params;
                return handler.request_handler(childRESTBase, childReq)
                .then(function(item){
                    if (self.timer) {
                        if (item.status >= 500) {
                            self.timer.count(statName);
                        }
                        self.timer.stop(statName);
                    }
                    return item;
                })
                .catch(function(err){
                    if (self.timer) {
                        self.timer.stop(statName);
                    }
                    throw err;
                });
            }
        }
    }

    // No handler found.
    return Promise.resolve({
        status: 404,
        body: {
            type: 'not_found#proxy_handler',
            title: 'Not found.',
            uri: req.uri,
            method: req.method,
            level: i
        }
    });
};

// Generic parameter massaging:
// * If last parameter is an object, it is expected to be the request object.
// * If the first parameter is a string, it's expected to be the URL.
// * If the second parameter is a String or Buffer, it's expected to be a
//   resource body.
function makeRequest (args, method) {
    var argPos = args.length - 1,
        lastArg = args[argPos],
        req = {};
    if (lastArg && lastArg.constructor === Object) {
        req = lastArg;
        argPos--;
    }
    switch (argPos) {
    case 1: req.body = args[argPos]; argPos--;
            /* falls through */
    case 0: req.uri = args[argPos]; break;
    case -1: break;
    default: throw new Error('Invalid arguments supplied to Verb');
    }
    req.method = method;
    return req;
}

RESTBase.prototype.get = function get (uri, req) {
    return this.request(makeRequest(arguments, 'get'));
};

RESTBase.prototype.post = function post (uri, req) {
    return this.request(makeRequest(arguments, 'post'));
};

RESTBase.prototype.put = function put (uri, req) {
    return this.request(makeRequest(arguments, 'put'));
};

RESTBase.prototype.delete = function (uri, req) {
    return this.request(makeRequest(arguments, 'delete'));
};

RESTBase.prototype.head = function head (uri, req) {
    return this.request(makeRequest(arguments, 'head'));
};

RESTBase.prototype.options = function options (uri, req) {
    return this.request(makeRequest(arguments, 'options'));
};

RESTBase.prototype.trace = function trace (uri, req) {
    return this.request(makeRequest(arguments, 'trace'));
};

RESTBase.prototype.connect = function connect (uri, req) {
    return this.request(makeRequest(arguments, 'connect'));
};

RESTBase.prototype.copy = function copy (uri, req) {
    return this.request(makeRequest(arguments, 'copy'));
};

RESTBase.prototype.move = function move (uri, req) {
    return this.request(makeRequest(arguments, 'move'));
};

RESTBase.prototype.purge = function purge (uri, req) {
    return this.request(makeRequest(arguments, 'purge'));
};

module.exports = RESTBase;
<commit_msg>Use this instead of req for __depth lookup<commit_after>'use strict';

/*
 * RESTBase proxy layer
 *
 * Dispatches a request to
 * - A matching proxy handler, or
 * - A back-end handler iff
 *   - there is no front-end match
 *   - the request would map to the proxy handler making the request.
 */

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

function RESTBase (routers, options) {
    this.options = options;
    this.log = options.log; // logging method
    this._routers = routers.filter(function(r) {
        return r.routes && r.routes.length;
    });
    if (options.conf.monitoring && options.conf.monitoring.statdsHost) {
        this.timer = new util.Timer(options.conf.monitoring.statdsHost);
    }
    //console.log(JSON.stringify(this._routers, null, 2));
}

RESTBase.prototype.request = function request (req) {
    var self = this;

    if (this.__depth > this.options.maxDepth) {
        return Promise.resolve({
            status: 500,
            body: {
                type: 'proxy_recursion_depth_exceeded',
                title: 'RESTBase handler recursion depth exceeded.',
                uri: req.uri,
                method: req.method,
                depth: this.__depth
            }
        });
    }

    // COW for the request
    // jshint proto: true
    var childReq = { __proto__: req };
    if (!childReq.query) {
        req.query = {};
    }

    var i = 0;
    // jshint proto: true
    var parentReq = this.__parentReq;
    if (parentReq && req.uri === parentReq.uri) {
        // URL didn't change, jump to the next layer
        if (this.storageHandler) {
            // Normally used to call from a bucket straight to the storage
            // router.
            // XXX: match signature in storage.js
            return this.storageHandler(this, childReq);
        }
        i = (this.__layer || 0) + 1;
    }

    for (; i < this._routers.length; i++) {
        var match = this._routers[i].match(req.uri);
        if (match) {

            // start timer
            if (this.timer) {
                var statName = match.sortKey + "." + req.method;
                this.timer.start(statName);
            }

            //console.log(req.uri, match);
            // console.log('recursive', req.uri, req.method, match.methods);
            var handler = match.methods[req.method] || match.methods.all;
            if (handler && handler.request_handler) {
                // Found a matching proxy handler. Prepare to call it.
                // Still using __proto__, as it's quite a bit faster than
                // Object.create.
                // jshint proto: true
                var childRESTBase = {
                    __proto__: self,
                    __parentReq: req,
                    __layer: i,
                    __depth:  (this.__depth || 0) + 1
                };
                childReq.params = match.params;
                return handler.request_handler(childRESTBase, childReq)
                .then(function(item){
                    if (self.timer) {
                        if (item.status >= 500) {
                            self.timer.count(statName);
                        }
                        self.timer.stop(statName);
                    }
                    return item;
                })
                .catch(function(err){
                    if (self.timer) {
                        self.timer.stop(statName);
                    }
                    throw err;
                });
            }
        }
    }

    // No handler found.
    return Promise.resolve({
        status: 404,
        body: {
            type: 'not_found#proxy_handler',
            title: 'Not found.',
            uri: req.uri,
            method: req.method,
            level: i
        }
    });
};

// Generic parameter massaging:
// * If last parameter is an object, it is expected to be the request object.
// * If the first parameter is a string, it's expected to be the URL.
// * If the second parameter is a String or Buffer, it's expected to be a
//   resource body.
function makeRequest (args, method) {
    var argPos = args.length - 1,
        lastArg = args[argPos],
        req = {};
    if (lastArg && lastArg.constructor === Object) {
        req = lastArg;
        argPos--;
    }
    switch (argPos) {
    case 1: req.body = args[argPos]; argPos--;
            /* falls through */
    case 0: req.uri = args[argPos]; break;
    case -1: break;
    default: throw new Error('Invalid arguments supplied to Verb');
    }
    req.method = method;
    return req;
}

RESTBase.prototype.get = function get (uri, req) {
    return this.request(makeRequest(arguments, 'get'));
};

RESTBase.prototype.post = function post (uri, req) {
    return this.request(makeRequest(arguments, 'post'));
};

RESTBase.prototype.put = function put (uri, req) {
    return this.request(makeRequest(arguments, 'put'));
};

RESTBase.prototype.delete = function (uri, req) {
    return this.request(makeRequest(arguments, 'delete'));
};

RESTBase.prototype.head = function head (uri, req) {
    return this.request(makeRequest(arguments, 'head'));
};

RESTBase.prototype.options = function options (uri, req) {
    return this.request(makeRequest(arguments, 'options'));
};

RESTBase.prototype.trace = function trace (uri, req) {
    return this.request(makeRequest(arguments, 'trace'));
};

RESTBase.prototype.connect = function connect (uri, req) {
    return this.request(makeRequest(arguments, 'connect'));
};

RESTBase.prototype.copy = function copy (uri, req) {
    return this.request(makeRequest(arguments, 'copy'));
};

RESTBase.prototype.move = function move (uri, req) {
    return this.request(makeRequest(arguments, 'move'));
};

RESTBase.prototype.purge = function purge (uri, req) {
    return this.request(makeRequest(arguments, 'purge'));
};

module.exports = RESTBase;
<|endoftext|>


<commit_before>/**
 * The main class of the API Browser
 *
 * #asset(apibrowser/*)
 */
core.Class('api.Browser', {

	construct: function(base) {

		// Store data path
		if (!base) {
			base = "data";
		}

		this.__base = base;

		// Load initial data
		core.io.Queue.load([
			base + "/$index.jsonp",
			base + "/$template.jsonp",
			base + "/$search.jsonp"
		], this.__onLoad, this, false, "js");

		// Initialize data processor
		this.__processor = new api.Processor({
			showPrivate: true
		});

		this.__index = {};

	},

	members: {

		__onLoad : function() {

			var that = this;

			$('h3').live('click', function(event) {
				$(this).parent('li').toggleClass('unfold');
			});

			$('a').live('click', function(event) {

				var link = $(this).attr('href');
				if (link.charAt(0) == '#') {
					that.open(link.slice(1));
					return false;
				}

			});

			// Open opener URL
			this.open(location.hash.slice(1));

		},

		callback: function(data, id) {

			if (id == "$index") {

				console.debug("Loaded Index");

				document.getElementById('menu-tree').innerHTML = this.__treeWalker(data, "");
				this.open(location.hash);

			} else if (id == "$template") {

				console.debug("Loaded Template");
				this.__template = core.template.Compiler.compile(data.template);

			} else if (id == "$search") {

				console.debug("Loaded Search Index");

			} else {

				console.debug("Loaded Class: " + id);

			}

		},

		__treeWalker: function(node, base) {

			var html = '';

			var filter = function(value) {
				return value.charAt(0) != "$";
			};

			var comparator = function(a, b) {

				if (node[a].$type == node[b].$type) {

					return a > b ? 1 : -1;

				} else if (node[a].$type == "Package") {

					return -1;

				} else if (node[b].$type == "Package") {

					return 1;

				} else {

					return 0;

				}

			}

			var keys = Object.keys(node).filter(filter).sort(comparator);

			for (var i=0, l=keys.length; i<l; i++) {

				var key = keys[i];
				var entry = node[key];
				var name = base ? base + "." + key : key;

				if (entry.$type == "Package") {

					html += '
' + key + '
' + this.__treeWalker(entry, name) + '

';

				} else {

					html += '
' + key + '
';

				}

			}

			return html;

		},

		open: function(hash) {

			console.debug("Open: " + hash);

			if (hash.match(/!/)) {
				hash = hash.substr(1);
			}

			var data, params = [];

			if (hash.match(/\./)) {

				data = hash.substr(1, hash.length - 1).split('.');

				// namespace
				params.push(data[0]);

				if (data[1].match(/:/)) {
					data = data[1].split(/:/);
					params.push(data[0]); // class (id)
					params.push(data[1]); // method
				} else {
					params.push(data[1]); // class (id)
				}

			} else if (hash.match(/:/)) {

				params.push(this.__current.namespace);
				params.push(this.__current.id);
				params.push(hash.substr(1));

				hash = this.__current.namespace + '.' + this.__current.id + ':' + hash.substr(1);

			}

			var success = this.show.apply(this, params);
			if (success) {
				location.hash = hash;
			}

		},

		show: function(namespace, id, method) {

			namespace = typeof namespace == 'string' ? namespace : null;
			id = typeof id == 'string' ? id : null;
			method = typeof method == 'string' ? method : null;

			if (namespace == null || id == null) {
				return false;
			}

			var entry = this.__index[namespace + '.' + id];

			if (entry === undefined) {
				entry = this.__index[namespace + '.' + id] = {
					namespace: namespace,
					id: id
				};
			}

			if (
				entry.data === undefined
			) {

				var file = this.__base + '/' + namespace + '.' + id + '.json';
				this.load(file, function(status, json) {

					entry.data = this.__processor.processJSON(json);
					this.__current = entry;
					this.__render(entry);

				}, this);

			} else {
				this.__current = entry;
				this.__render(entry);
			}

			return true;

		},

		__render: function(entry) {

			var html = this.__template.render(entry.data);

			$('#content').html(html);

		}

	}

});

<commit_msg>Cleanup<commit_after>/**
 * The main class of the API Browser
 *
 * #asset(apibrowser/*)
 */
core.Class('api.Browser', {

	construct: function(base) {

		// Store data path
		if (!base) {
			base = "data";
		}

		this.__base = base;

		// Load initial data
		core.io.Queue.load([
			base + "/$index.jsonp",
			base + "/$template.jsonp",
			base + "/$search.jsonp"
		], this.__onLoad, this, false, "js");

		// Initialize data processor
		this.__processor = new api.Processor({
			showPrivate: true
		});

		this.__index = {};

	},

	members: {

		__onLoad : function() {

			var that = this;

			$('h3').live('click', function(event) {
				$(this).parent('li').toggleClass('unfold');
			});

			$('a').live('click', function(event) {

				var link = $(this).attr('href');
				if (link.charAt(0) == '#') {
					that.open(link.slice(1));
					return false;
				}

			});

			// Open opener URL
			this.open(location.hash.slice(1));

		},

		callback: function(data, id) {

			if (id == "$index") {

				console.debug("Loaded Index");

				document.getElementById('menu-tree').innerHTML = this.__treeWalker(data, "");

			} else if (id == "$template") {

				console.debug("Loaded Template");
				this.__template = core.template.Compiler.compile(data.template);

			} else if (id == "$search") {

				console.debug("Loaded Search Index");

			} else {

				console.debug("Loaded Class: " + id);

			}

		},

		__treeWalker: function(node, base) {

			var html = '';

			var filter = function(value) {
				return value.charAt(0) != "$";
			};

			var comparator = function(a, b) {

				if (node[a].$type == node[b].$type) {

					return a > b ? 1 : -1;

				} else if (node[a].$type == "Package") {

					return -1;

				} else if (node[b].$type == "Package") {

					return 1;

				} else {

					return 0;

				}

			}

			var keys = Object.keys(node).filter(filter).sort(comparator);

			for (var i=0, l=keys.length; i<l; i++) {

				var key = keys[i];
				var entry = node[key];
				var name = base ? base + "." + key : key;

				if (entry.$type == "Package") {

					html += '
' + key + '
' + this.__treeWalker(entry, name) + '

';

				} else {

					html += '
' + key + '
';

				}

			}

			return html;

		},

		open: function(hash) {

			console.debug("Open: " + hash);

			if (hash.match(/!/)) {
				hash = hash.substr(1);
			}

			var data, params = [];

			if (hash.match(/\./)) {

				data = hash.substr(1, hash.length - 1).split('.');

				// namespace
				params.push(data[0]);

				if (data[1].match(/:/)) {
					data = data[1].split(/:/);
					params.push(data[0]); // class (id)
					params.push(data[1]); // method
				} else {
					params.push(data[1]); // class (id)
				}

			} else if (hash.match(/:/)) {

				params.push(this.__current.namespace);
				params.push(this.__current.id);
				params.push(hash.substr(1));

				hash = this.__current.namespace + '.' + this.__current.id + ':' + hash.substr(1);

			}

			var success = this.show.apply(this, params);
			if (success) {
				location.hash = hash;
			}

		},

		show: function(namespace, id, method) {

			namespace = typeof namespace == 'string' ? namespace : null;
			id = typeof id == 'string' ? id : null;
			method = typeof method == 'string' ? method : null;

			if (namespace == null || id == null) {
				return false;
			}

			var entry = this.__index[namespace + '.' + id];

			if (entry === undefined) {
				entry = this.__index[namespace + '.' + id] = {
					namespace: namespace,
					id: id
				};
			}

			if (
				entry.data === undefined
			) {

				var file = this.__base + '/' + namespace + '.' + id + '.json';
				this.load(file, function(status, json) {

					entry.data = this.__processor.processJSON(json);
					this.__current = entry;
					this.__render(entry);

				}, this);

			} else {
				this.__current = entry;
				this.__render(entry);
			}

			return true;

		},

		__render: function(entry) {

			var html = this.__template.render(entry.data);

			$('#content').html(html);

		}

	}

});

<|endoftext|>


<commit_before>import remove from 'lodash/remove';
import logger from './logger';
import fetchData from './fetch';
import parseData from './parse';
import { getLatestTimestamp, saveDataPoints } from './database';

exports.handler = async function(event, context, callback) {
  logger.info('jenergia-scrape started');

  const latest = await getLatestTimestamp();
  const data = fetchData().then((data) => {
  	const consumption = parseData(data);

    logger.info(consumption.length, 'data points fetched');
    logger.debug('last saved data point is', latest.toISOString());

    remove(consumption, (dataPoint) => (dataPoint.timestamp <= latest));

    logger.debug(consumption.length, 'data points left');

    if(consumption.length > 0) {
      const save = saveDataPoints(consumption);

      save.then(() => {
        logger.info(consumption.length, 'data points saved');
        callback(null, { saved: consumption.length });
      });
    } else {
      callback(null, { saved: 0 });
    }
  });
}
<commit_msg>Add error handling<commit_after>import remove from 'lodash/remove';
import logger from './logger';
import fetchData from './fetch';
import parseData from './parse';
import { getLatestTimestamp, saveDataPoints } from './database';

exports.handler = async function(event, context, callback) {
  logger.info('jenergia-scrape started');

  const data = fetchData();

  data.then(async (data) => {
  	const consumption = parseData(data);
    const latest = await getLatestTimestamp();

    logger.info(consumption.length, 'data points fetched');
    logger.debug('last saved data point is', latest.toISOString());

    remove(consumption, (dataPoint) => (dataPoint.timestamp <= latest));

    logger.debug(consumption.length, 'data points left');

    if(consumption.length > 0) {
      const save = saveDataPoints(consumption);

      save.then(() => {
        logger.info(consumption.length, 'data points saved');
        callback(null, { saved: consumption.length });
      });

      save.catch((error) => {
        logger.error('Save failed:', error);
        callback(error, null);
      });
    } else {
      callback(null, { saved: 0 });
    }
  });

  data.catch((error) => {
    logger.error('Data fetching failed:', error);
    callback(error, null);
  });
}
<|endoftext|>


<commit_before>module.exports = {
  staticFileGlobs: [
    'index.html',
    'ce-fix.html',
    'manifest.json',
    'favicon.ico',
    'data/**/*',
    'images-optimized/**/*',
    'scripts/**/*',
    'bower_components/webcomponentsjs/webcomponents-loader.js'
  ],
  runtimeCaching: [
    {
      urlPattern: /\/data\/.*.(json|md)/,
      handler: 'fastest',
      options: {
        cache: {
          name: 'data-cache'
        }
      }
    },
    {
      urlPattern: /api\.areafiftylan.nl/,
      handler: 'fastest',
      options: {
        cache: {
          name: 'api-cache'
        }
      }
    },
    {
      urlPattern: /fonts\.(gstatic|googleapis)\.com/,
      handler: 'cacheFirst',
      options: {
        cache: {
          name: 'api-cache'
        }
      }
    },
  ],
  navigateFallback: 'index.html',
  navigateFallbackWhitelist: [/^(?!.*\.html$|\/data\/).*/],
};
<commit_msg>Only cache api data from `/web/` (#605)<commit_after>module.exports = {
  staticFileGlobs: [
    'index.html',
    'ce-fix.html',
    'manifest.json',
    'favicon.ico',
    'data/**/*',
    'images-optimized/**/*',
    'scripts/**/*',
    'bower_components/webcomponentsjs/webcomponents-loader.js'
  ],
  runtimeCaching: [
    {
      urlPattern: /\/data\/.*.(json|md)/,
      handler: 'fastest',
      options: {
        cache: {
          name: 'data-cache'
        }
      }
    },
    {
      urlPattern: /api\.areafiftylan.nl\/api\/v1\/web/,
      handler: 'fastest',
      options: {
        cache: {
          name: 'api-cache'
        }
      }
    },
    {
      urlPattern: /fonts\.(gstatic|googleapis)\.com/,
      handler: 'cacheFirst',
      options: {
        cache: {
          name: 'api-cache'
        }
      }
    },
  ],
  navigateFallback: 'index.html',
  navigateFallbackWhitelist: [/^(?!.*\.html$|\/data\/).*/],
};
<|endoftext|>


<commit_before>define('spec/checkpoints', ['lyria/checkpoints'], function(Checkpoints) {

  describe('lyria/checkpoints', function() {

    var checkpoints = new Checkpoints();

    it('is a function', function() {
      expect(Checkpoints).to.be.a('function');
    });

    describe('constructor', function() {
      it('can be instantiated', function() {
        expect(checkpoints).to.be.a('object');
        expect(checkpoints).to.be.an.instanceOf(Checkpoints);
      });

      it('has default values', function() {
        expect(checkpoints.startTime).to.be.a('number');
        expect(checkpoints.checkpointList).to.be.a('array');
      });
    });

    describe('Checkpoints functionality', function() {
      beforeEach(function() {
        checkpoints.reset();
      });

      describe('#pass', function() {
        it('pass a checkpoint', function() {
          checkpoints.pass('test');

          expect(checkpoints.checkpointsList).to.be.a('array');
          expect(checkpoints.checkpointsList.indexOf('test')).to.equal(0);
        });
      });
    });

  });

});
<commit_msg>Typo fix<commit_after>define('spec/checkpoints', ['lyria/checkpoints'], function(Checkpoints) {

  describe('lyria/checkpoints', function() {

    var checkpoints = new Checkpoints();

    it('is a function', function() {
      expect(Checkpoints).to.be.a('function');
    });

    describe('constructor', function() {
      it('can be instantiated', function() {
        expect(checkpoints).to.be.a('object');
        expect(checkpoints).to.be.an.instanceOf(Checkpoints);
      });

      it('has default values', function() {
        expect(checkpoints.startTime).to.be.a('number');
        expect(checkpoints.checkpointList).to.be.a('array');
      });
    });

    describe('Checkpoints functionality', function() {
      beforeEach(function() {
        checkpoints.reset();
      });

      describe('#pass', function() {

        it('pass a checkpoint', function() {
          checkpoints.pass('test');

          expect(checkpoints.checkpointList).to.be.a('array');
          expect(checkpoints.checkpointList.indexOf('test')).to.equal(0);
        });
      });
    });

  });

});
<|endoftext|>


<commit_before>"use strict";

// I don't think the stack order matters
// ReaderT r (WriterT w (StateT s Id)) a
//
// r -> s -> (s, (w, a))
function RWS(f) {
    if ( typeof f !== 'function' ) {
        throw new Error('RWS needs a function');
    }
    this.f = f;
}

function result(state, log, value) {
    return {
        'state': state,
        'log': log,
        'value': value
    };
}

RWS.pure = function(x) {
    function f(env, state) {
        return result(state, [], x);
    }
    return new RWS(f);
};

RWS.fmap = function(f, rws) {
    function g(env, state) {
        var out1 = rws.f(env, state);
        return result(out1.state, out1.log, f(out1.value));
    }
    return new RWS(g);
};

RWS.seq = function() {
    var rwss = Array.prototype.slice.call(arguments),
        log = [],
        vals = [],
        r;
    function f(env, state) {
        for (var i = 0; i < rwss.length; i++) {
            r = rwss[i].f(env, state);
            state = r.state;
            log = log.concat(r.log);
            vals.push(r.value);
        }
        return result(state, log, vals);
    }
    return new RWS(f);
};

// (r -> s -> (s, (w, a)) -> (a -> r -> s -> (s, (w, b))) -> (r -> s -> (s, (w, b)))
RWS.bind = function(rws, f) {
    function g(env, state) {
        var out1 = rws.f(env, state),
            out2 = f(out1.value)(env, out1.state);
        return result(out2.state, out1.log.concat(out2.log), out2. value);
    }
    return new RWS(g);
};

RWS.write = function(x) {
    function f(env, state) {
        return result(state, [x], null);
    }
    return new RWS(f);
};

RWS.local = function(f_r, rws) {
    function g(env, state) {
        return rws.f(f_r(env), state);
    }
    return new RWS(g);
};

RWS.ask = new RWS(function(env, state) {
    return result(state, [], env);
});

RWS.get = new RWS(function(env, state) {
    return result(state, [], state);
});

RWS.put = function(s) {
    return RWS.update(function(_old_state) {
        return s;
    });
};

RWS.update = function(f) {
    function g(env, state) {
        return result(f(state), [], null);
    }
    return new RWS(g);
};

module.exports = RWS;

/* these two probably belong in a different module */
RWS.warning = function(x) {
    function f(env, state) {
        return result(state, [{'warning': x}], null);
    }
    return new RWS(f);
}

// log an error -- not an error effect
RWS.error = function(x) {
    function f(env, state) {
        return result(state, [{'error': x}], null);
    }
    return new RWS(f);
}

<commit_msg>remove functions that belong in a different module<commit_after>"use strict";

// I don't think the stack order matters
// ReaderT r (WriterT w (StateT s Id)) a
//
// r -> s -> (s, (w, a))
function RWS(f) {
    if ( typeof f !== 'function' ) {
        throw new Error('RWS needs a function');
    }
    this.f = f;
}

function result(state, log, value) {
    return {
        'state': state,
        'log': log,
        'value': value
    };
}

RWS.pure = function(x) {
    function f(env, state) {
        return result(state, [], x);
    }
    return new RWS(f);
};

RWS.fmap = function(f, rws) {
    function g(env, state) {
        var out1 = rws.f(env, state);
        return result(out1.state, out1.log, f(out1.value));
    }
    return new RWS(g);
};

RWS.seq = function() {
    var rwss = Array.prototype.slice.call(arguments),
        log = [],
        vals = [],
        r;
    function f(env, state) {
        for (var i = 0; i < rwss.length; i++) {
            r = rwss[i].f(env, state);
            state = r.state;
            log = log.concat(r.log);
            vals.push(r.value);
        }
        return result(state, log, vals);
    }
    return new RWS(f);
};

// (r -> s -> (s, (w, a)) -> (a -> r -> s -> (s, (w, b))) -> (r -> s -> (s, (w, b)))
RWS.bind = function(rws, f) {
    function g(env, state) {
        var out1 = rws.f(env, state),
            out2 = f(out1.value)(env, out1.state);
        return result(out2.state, out1.log.concat(out2.log), out2. value);
    }
    return new RWS(g);
};

RWS.write = function(x) {
    function f(env, state) {
        return result(state, [x], null);
    }
    return new RWS(f);
};

RWS.local = function(f_r, rws) {
    function g(env, state) {
        return rws.f(f_r(env), state);
    }
    return new RWS(g);
};

RWS.ask = new RWS(function(env, state) {
    return result(state, [], env);
});

RWS.get = new RWS(function(env, state) {
    return result(state, [], state);
});

RWS.put = function(s) {
    return RWS.update(function(_old_state) {
        return s;
    });
};

RWS.update = function(f) {
    function g(env, state) {
        return result(f(state), [], null);
    }
    return new RWS(g);
};

module.exports = RWS;

<|endoftext|>


<commit_before>const fs = require('fs');
const gm = require('gm').subClass({imageMagick: true});

// Fake data to test (2 face_data currently)
var data = {
    "id": "87ecbaa3ec25f0eb0782b3a4",
    "media_info": {
        "length": 0,
        "width": 720,
        "height": 960,
        "type": "image",
        "file": "87ecbaa3ec25f0eb0782b3a4.jpg",
        "mime_type": "image/jpg"
    },
    "frames": [
        {
            "time": 0,
            "people": [
                {
                    "person_id": "0",
                    "demographics": {
                        "age_group": "Young Adult",
                        "gender": "Male"
                    },
                    "appearance": {
                        "glasses": "Yes"
                    },
                    "emotions": {
                        "anger": 0,
                        "disgust": 0,
                        "fear": 0,
                        "joy": 0,
                        "sadness": 0,
                        "surprise": 0
                    },
                    "tracking": {
                        "glances": 1,
                        "dwell": 0,
                        "attention": 100,
                        "blink": "No"
                    },
                    "landmarks": [
                        {
                            "leftEyeBrowOuterLeft": {
                                "x": 285,
                                "y": 369
                            }
                        },
                        {
                            "leftEyeBrowInnerLeft": {
                                "x": 295,
                                "y": 368
                            }
                        },
                        {
                            "leftEyeBrowInnerRight": {
                                "x": 305,
                                "y": 369
                            }
                        },
                        {
                            "leftEyeBrowOuterRight": {
                                "x": 314,
                                "y": 374
                            }
                        },
                        {
                            "righteEyeBrowOuterLeft": {
                                "x": 323,
                                "y": 373
                            }
                        },
                        {
                            "rightEyeBrowInnerLeft": {
                                "x": 330,
                                "y": 372
                            }
                        },
                        {
                            "rightEyeBrowInnerRight": {
                                "x": 338,
                                "y": 372
                            }
                        },
                        {
                            "rightEyeBrowOuterRight": {
                                "x": 345,
                                "y": 375
                            }
                        },
                        {
                            "noseBetweenEyes": {
                                "x": 317,
                                "y": 379
                            }
                        },
                        {
                            "noseBridge": {
                                "x": 316,
                                "y": 385
                            }
                        },
                        {
                            "noseBody": {
                                "x": 314,
                                "y": 392
                            }
                        },
                        {
                            "noseTipTop": {
                                "x": 313,
                                "y": 399
                            }
                        },
                        {
                            "leftNostrilOuterLeft": {
                                "x": 304,
                                "y": 409
                            }
                        },
                        {
                            "leftNostrilOuterRight": {
                                "x": 308,
                                "y": 411
                            }
                        },
                        {
                            "noseTipBottom": {
                                "x": 312,
                                "y": 411
                            }
                        },
                        {
                            "rightNostrilInnerLeft": {
                                "x": 315,
                                "y": 411
                            }
                        },
                        {
                            "rightNostrilOuterRight": {
                                "x": 320,
                                "y": 411
                            }
                        },
                        {
                            "leftEyeCornerLeft": {
                                "x": 288,
                                "y": 378
                            }
                        },
                        {
                            "leftEyeTopInnerLeft": {
                                "x": 294,
                                "y": 375
                            }
                        },
                        {
                            "leftEyeTopInnerRight": {
                                "x": 301,
                                "y": 376
                            }
                        },
                        {
                            "leftEyeCornerRight": {
                                "x": 305,
                                "y": 382
                            }
                        },
                        {
                            "leftEyeBottomInnerRight": {
                                "x": 300,
                                "y": 382
                            }
                        },
                        {
                            "leftEyeBottomInnerLeft": {
                                "x": 294,
                                "y": 382
                            }
                        },
                        {
                            "rightEyeCornerLeft": {
                                "x": 326,
                                "y": 385
                            }
                        },
                        {
                            "rightEyeTopInnerLeft": {
                                "x": 331,
                                "y": 379
                            }
                        },
                        {
                            "rightEyeTopInnerRight": {
                                "x": 337,
                                "y": 380
                            }
                        },
                        {
                            "rightEyeCornerRight": {
                                "x": 341,
                                "y": 384
                            }
                        },
                        {
                            "rightEyeBottomInnerRight": {
                                "x": 337,
                                "y": 387
                            }
                        },
                        {
                            "rightEyeBottomInnerLeft": {
                                "x": 331,
                                "y": 386
                            }
                        },
                        {
                            "upperLipTopCornerLeft": {
                                "x": 295,
                                "y": 433
                            }
                        },
                        {
                            "upperLipTopOuterLeft": {
                                "x": 302,
                                "y": 428
                            }
                        },
                        {
                            "upperLipTopInnerLeft": {
                                "x": 309,
                                "y": 424
                            }
                        },
                        {
                            "upperLipTopCenter": {
                                "x": 312,
                                "y": 426
                            }
                        },
                        {
                            "upperLipTopInnerRight": {
                                "x": 315,
                                "y": 425
                            }
                        },
                        {
                            "upperLipTopOuterRight": {
                                "x": 319,
                                "y": 429
                            }
                        },
                        {
                            "upperLipTopCornerRight": {
                                "x": 322,
                                "y": 436
                            }
                        },
                        {
                            "lowerLipBottomCornerRight": {
                                "x": 317,
                                "y": 439
                            }
                        },
                        {
                            "lowerLipBottomInnerRight": {
                                "x": 313,
                                "y": 441
                            }
                        },
                        {
                            "lowerLipBottomCenter": {
                                "x": 310,
                                "y": 440
                            }
                        },
                        {
                            "lowerLipBottomInnerLeft": {
                                "x": 307,
                                "y": 440
                            }
                        },
                        {
                            "lowerLipBottomCornerLeft": {
                                "x": 301,
                                "y": 437
                            }
                        },
                        {
                            "upperLipBottomOuterLeft": {
                                "x": 299,
                                "y": 433
                            }
                        },
                        {
                            "upperLipBottomInnerLeft": {
                                "x": 308,
                                "y": 430
                            }
                        },
                        {
                            "upperLipBottomCenter": {
                                "x": 311,
                                "y": 430
                            }
                        },
                        {
                            "uppeLipMBottomInnerRight": {
                                "x": 314,
                                "y": 430
                            }
                        },
                        {
                            "upperLipBottomOuterRight": {
                                "x": 319,
                                "y": 435
                            }
                        },
                        {
                            "lowerLipInnerRight": {
                                "x": 314,
                                "y": 434
                            }
                        },
                        {
                            "lowerLipTopInnerLeft": {
                                "x": 308,
                                "y": 434
                            }
                        }
                    ],
                    "pose": {
                        "yaw": 26.7608,
                        "pitch": -14.2665,
                        "roll": -2.03929
                    },
                    "face": {
                        "x": 244,
                        "y": 313,
                        "width": 130,
                        "height": 164
                    },
                    "distance": 43.7379
                }
            ]
        }
    ],
    "status_code": 4,
    "status_message": "Complete",
    "length": 0
};

// ***** Testing with fake buffer *****
// Create a fake buffer and put them into the fake data
// var fake_buffer_work_dir = __dirname.substr(0, __dirname.lastIndexOf("/"));
// gm(fake_buffer_work_dir + '/test.png')
// 	.toBuffer('PNG' ,function (err, buffer) {
// 		if (err) return console.log("Error to make a fake buffer");
// 		var arr = data.frames[0].people;
// 		arr.forEach(function(face_data) {
// 			face_data.buffer = buffer;
// 		});

// 		overlay(data, 'nick.jpg');
// 	})

function overlay(analysis_result, orig_photo_name, callback)
{
	var arr = analysis_result.people;
    var work_dir = __dirname.substr(0, __dirname.lastIndexOf("/"));
	var emoji_dir  = work_dir + '/uploads/emoji_dir';
	var input_dir  = work_dir + '/uploads';
	var output_dir = work_dir + '/uploads/output_photo';

	function delete_middlewares(index, photo_name)
	{
        callback();
        index--;
		for (; index >= 0; index--) {
			// Delete middlewares in output_photo directory
			if (index > 0) {
				fs.unlinkSync(output_dir + '/' + index + '_' + photo_name, function(err) {
					if (err) console.log("Error to delete a middleware in output_photo for index : " + index);
				});
			}
			fs.unlinkSync(emoji_dir + '/' + index + '_' + photo_name, function(err) {
				if (err) console.log("Error to delete a middleware in output_photo for index : " + index);
			});
		}
	};

	function calculate_slope(left_eye, right_eye) {
		return (Math.atan((right_eye.y - left_eye.y) / (right_eye.x - left_eye.x)) * 180 / Math.PI);
	};

	function insert_emoji(index, photo_name)
	{
		var geom = "+" + arr[index].face.x + "+" + arr[index].face.y;
		var photo_dir = ((index == 0) ? input_dir + '/' : output_dir + '/' + index + '_');
		var photo_path  = photo_dir + photo_name;
		var output_path = output_dir;
		var indexed_photo_name = index + '_' + photo_name;

		// Index is now for the next index
		index += 1;

        // Setting the output_path (For the last index, export the final photo to /uploads)
		if (index === arr.length) {
            output_path = input_dir + '/' + photo_name;
		} else {
			output_path += ('/' + index + '_' + photo_name);
		}

		// #IGNORE for rotating the emoji
		// var face_data = arr[index];
		// var left_eye = face_data.landmarks[18].leftEyeTopInnerLeft;
		// var right_eye = face_data.landmarks[25].rightEyeTopInnerRight;
		// var angle = calculate_slope(left_eye, right_eye);
		// var emoji_buffer = face_data.buffer;

		// // For non zero angle, the emoji needs to be rotated
		// if (angle != 0) {
		// 	// Read the emoji and rotate it by the angle
		// 	gm(destination + "emoji.png")
		// 		.rotate
		// }

		gm(photo_path)
			.composite(emoji_dir + '/' + indexed_photo_name)
			.geometry(geom)
			.write(output_path, function(err) {
				if (err) {
					console.log("Fail to write an image to the output_photo directory " + index);
					console.log(err);
				}
				if (index < arr.length) {
					emoji_buffer_to_emoji_photo(index, photo_name);
				} else {
					delete_middlewares(index, photo_name);
				}
			});
	};

	function emoji_buffer_to_emoji_photo(index, photo_name)
	{
		var emoji_buffer = arr[index].emojiBuffer;
		var emoji_path   = emoji_dir + '/' + index + '_' + photo_name;

		if (emoji_buffer) {
			// Convert the emoji_buff to a photo file to the destination
			fs.writeFile(emoji_path, emoji_buffer, "binary", function(err) {
				if (err) console.log("Failed to write buffer to a file with index : " + index);
				if (!err) insert_emoji(index, photo_name)
			});
		} else {
			console.log("Emoji buffer does not exist for index : " + index);
		}
	};

	function run()
	{
		if (arr.length == 0) console.log("Given data seems curropted");
		emoji_buffer_to_emoji_photo(0, orig_photo_name);
	};

	run();
};

module.exports = overlay;
<commit_msg>return empty image<commit_after>const fs = require('fs');
const gm = require('gm').subClass({imageMagick: true});

// Fake data to test (2 face_data currently)
var data = {
    "id": "87ecbaa3ec25f0eb0782b3a4",
    "media_info": {
        "length": 0,
        "width": 720,
        "height": 960,
        "type": "image",
        "file": "87ecbaa3ec25f0eb0782b3a4.jpg",
        "mime_type": "image/jpg"
    },
    "frames": [
        {
            "time": 0,
            "people": [
                {
                    "person_id": "0",
                    "demographics": {
                        "age_group": "Young Adult",
                        "gender": "Male"
                    },
                    "appearance": {
                        "glasses": "Yes"
                    },
                    "emotions": {
                        "anger": 0,
                        "disgust": 0,
                        "fear": 0,
                        "joy": 0,
                        "sadness": 0,
                        "surprise": 0
                    },
                    "tracking": {
                        "glances": 1,
                        "dwell": 0,
                        "attention": 100,
                        "blink": "No"
                    },
                    "landmarks": [
                        {
                            "leftEyeBrowOuterLeft": {
                                "x": 285,
                                "y": 369
                            }
                        },
                        {
                            "leftEyeBrowInnerLeft": {
                                "x": 295,
                                "y": 368
                            }
                        },
                        {
                            "leftEyeBrowInnerRight": {
                                "x": 305,
                                "y": 369
                            }
                        },
                        {
                            "leftEyeBrowOuterRight": {
                                "x": 314,
                                "y": 374
                            }
                        },
                        {
                            "righteEyeBrowOuterLeft": {
                                "x": 323,
                                "y": 373
                            }
                        },
                        {
                            "rightEyeBrowInnerLeft": {
                                "x": 330,
                                "y": 372
                            }
                        },
                        {
                            "rightEyeBrowInnerRight": {
                                "x": 338,
                                "y": 372
                            }
                        },
                        {
                            "rightEyeBrowOuterRight": {
                                "x": 345,
                                "y": 375
                            }
                        },
                        {
                            "noseBetweenEyes": {
                                "x": 317,
                                "y": 379
                            }
                        },
                        {
                            "noseBridge": {
                                "x": 316,
                                "y": 385
                            }
                        },
                        {
                            "noseBody": {
                                "x": 314,
                                "y": 392
                            }
                        },
                        {
                            "noseTipTop": {
                                "x": 313,
                                "y": 399
                            }
                        },
                        {
                            "leftNostrilOuterLeft": {
                                "x": 304,
                                "y": 409
                            }
                        },
                        {
                            "leftNostrilOuterRight": {
                                "x": 308,
                                "y": 411
                            }
                        },
                        {
                            "noseTipBottom": {
                                "x": 312,
                                "y": 411
                            }
                        },
                        {
                            "rightNostrilInnerLeft": {
                                "x": 315,
                                "y": 411
                            }
                        },
                        {
                            "rightNostrilOuterRight": {
                                "x": 320,
                                "y": 411
                            }
                        },
                        {
                            "leftEyeCornerLeft": {
                                "x": 288,
                                "y": 378
                            }
                        },
                        {
                            "leftEyeTopInnerLeft": {
                                "x": 294,
                                "y": 375
                            }
                        },
                        {
                            "leftEyeTopInnerRight": {
                                "x": 301,
                                "y": 376
                            }
                        },
                        {
                            "leftEyeCornerRight": {
                                "x": 305,
                                "y": 382
                            }
                        },
                        {
                            "leftEyeBottomInnerRight": {
                                "x": 300,
                                "y": 382
                            }
                        },
                        {
                            "leftEyeBottomInnerLeft": {
                                "x": 294,
                                "y": 382
                            }
                        },
                        {
                            "rightEyeCornerLeft": {
                                "x": 326,
                                "y": 385
                            }
                        },
                        {
                            "rightEyeTopInnerLeft": {
                                "x": 331,
                                "y": 379
                            }
                        },
                        {
                            "rightEyeTopInnerRight": {
                                "x": 337,
                                "y": 380
                            }
                        },
                        {
                            "rightEyeCornerRight": {
                                "x": 341,
                                "y": 384
                            }
                        },
                        {
                            "rightEyeBottomInnerRight": {
                                "x": 337,
                                "y": 387
                            }
                        },
                        {
                            "rightEyeBottomInnerLeft": {
                                "x": 331,
                                "y": 386
                            }
                        },
                        {
                            "upperLipTopCornerLeft": {
                                "x": 295,
                                "y": 433
                            }
                        },
                        {
                            "upperLipTopOuterLeft": {
                                "x": 302,
                                "y": 428
                            }
                        },
                        {
                            "upperLipTopInnerLeft": {
                                "x": 309,
                                "y": 424
                            }
                        },
                        {
                            "upperLipTopCenter": {
                                "x": 312,
                                "y": 426
                            }
                        },
                        {
                            "upperLipTopInnerRight": {
                                "x": 315,
                                "y": 425
                            }
                        },
                        {
                            "upperLipTopOuterRight": {
                                "x": 319,
                                "y": 429
                            }
                        },
                        {
                            "upperLipTopCornerRight": {
                                "x": 322,
                                "y": 436
                            }
                        },
                        {
                            "lowerLipBottomCornerRight": {
                                "x": 317,
                                "y": 439
                            }
                        },
                        {
                            "lowerLipBottomInnerRight": {
                                "x": 313,
                                "y": 441
                            }
                        },
                        {
                            "lowerLipBottomCenter": {
                                "x": 310,
                                "y": 440
                            }
                        },
                        {
                            "lowerLipBottomInnerLeft": {
                                "x": 307,
                                "y": 440
                            }
                        },
                        {
                            "lowerLipBottomCornerLeft": {
                                "x": 301,
                                "y": 437
                            }
                        },
                        {
                            "upperLipBottomOuterLeft": {
                                "x": 299,
                                "y": 433
                            }
                        },
                        {
                            "upperLipBottomInnerLeft": {
                                "x": 308,
                                "y": 430
                            }
                        },
                        {
                            "upperLipBottomCenter": {
                                "x": 311,
                                "y": 430
                            }
                        },
                        {
                            "uppeLipMBottomInnerRight": {
                                "x": 314,
                                "y": 430
                            }
                        },
                        {
                            "upperLipBottomOuterRight": {
                                "x": 319,
                                "y": 435
                            }
                        },
                        {
                            "lowerLipInnerRight": {
                                "x": 314,
                                "y": 434
                            }
                        },
                        {
                            "lowerLipTopInnerLeft": {
                                "x": 308,
                                "y": 434
                            }
                        }
                    ],
                    "pose": {
                        "yaw": 26.7608,
                        "pitch": -14.2665,
                        "roll": -2.03929
                    },
                    "face": {
                        "x": 244,
                        "y": 313,
                        "width": 130,
                        "height": 164
                    },
                    "distance": 43.7379
                }
            ]
        }
    ],
    "status_code": 4,
    "status_message": "Complete",
    "length": 0
};

// ***** Testing with fake buffer *****
// Create a fake buffer and put them into the fake data
// var fake_buffer_work_dir = __dirname.substr(0, __dirname.lastIndexOf("/"));
// gm(fake_buffer_work_dir + '/test.png')
// 	.toBuffer('PNG' ,function (err, buffer) {
// 		if (err) return console.log("Error to make a fake buffer");
// 		var arr = data.frames[0].people;
// 		arr.forEach(function(face_data) {
// 			face_data.buffer = buffer;
// 		});

// 		overlay(data, 'nick.jpg');
// 	})

function overlay(analysis_result, orig_photo_name, callback)
{
	var arr = analysis_result.people;
    var work_dir = __dirname.substr(0, __dirname.lastIndexOf("/"));
	var emoji_dir  = work_dir + '/uploads/emoji_dir';
	var input_dir  = work_dir + '/uploads';
	var output_dir = work_dir + '/uploads/output_photo';

	function delete_middlewares(index, photo_name)
	{
        callback();
        index--;
		for (; index >= 0; index--) {
			// Delete middlewares in output_photo directory
			if (index > 0) {
				fs.unlinkSync(output_dir + '/' + index + '_' + photo_name, function(err) {
					if (err) console.log("Error to delete a middleware in output_photo for index : " + index);
				});
			}
			fs.unlinkSync(emoji_dir + '/' + index + '_' + photo_name, function(err) {
				if (err) console.log("Error to delete a middleware in output_photo for index : " + index);
			});
		}
	};

	function calculate_slope(left_eye, right_eye) {
		return (Math.atan((right_eye.y - left_eye.y) / (right_eye.x - left_eye.x)) * 180 / Math.PI);
	};

	function insert_emoji(index, photo_name)
	{
		var geom = "+" + arr[index].face.x + "+" + arr[index].face.y;
		var photo_dir = ((index == 0) ? input_dir + '/' : output_dir + '/' + index + '_');
		var photo_path  = photo_dir + photo_name;
		var output_path = output_dir;
		var indexed_photo_name = index + '_' + photo_name;

		// Index is now for the next index
		index += 1;

        // Setting the output_path (For the last index, export the final photo to /uploads)
		if (index === arr.length) {
            output_path = input_dir + '/' + photo_name;
		} else {
			output_path += ('/' + index + '_' + photo_name);
		}

		// #IGNORE for rotating the emoji
		// var face_data = arr[index];
		// var left_eye = face_data.landmarks[18].leftEyeTopInnerLeft;
		// var right_eye = face_data.landmarks[25].rightEyeTopInnerRight;
		// var angle = calculate_slope(left_eye, right_eye);
		// var emoji_buffer = face_data.buffer;

		// // For non zero angle, the emoji needs to be rotated
		// if (angle != 0) {
		// 	// Read the emoji and rotate it by the angle
		// 	gm(destination + "emoji.png")
		// 		.rotate
		// }

		gm(photo_path)
			.composite(emoji_dir + '/' + indexed_photo_name)
			.geometry(geom)
			.write(output_path, function(err) {
				if (err) {
					console.log("Fail to write an image to the output_photo directory " + index);
					console.log(err);
				}
				if (index < arr.length) {
					emoji_buffer_to_emoji_photo(index, photo_name);
				} else {
					delete_middlewares(index, photo_name);
				}
			});
	};

	function emoji_buffer_to_emoji_photo(index, photo_name)
	{
		var emoji_buffer = arr[index].emojiBuffer;
		var emoji_path   = emoji_dir + '/' + index + '_' + photo_name;

		if (emoji_buffer) {
			// Convert the emoji_buff to a photo file to the destination
			fs.writeFile(emoji_path, emoji_buffer, "binary", function(err) {
				if (err) console.log("Failed to write buffer to a file with index : " + index);
				if (!err) insert_emoji(index, photo_name)
			});
		} else {
			console.log("Emoji buffer does not exist for index : " + index);
		}
	};

	function run()
	{
		if (arr.length == 0) {
            console.log("Given data seems curropted");
            callback();
            return;
        }
		emoji_buffer_to_emoji_photo(0, orig_photo_name);
	};

	run();
};

module.exports = overlay;
<|endoftext|>


<commit_before>import React from 'react'
import R from 'ramda'
import pluralize from 'pluralize'
import SidebarMenu from './sidebar_menu'
import AccountMenu from './account_menu'
import {ORG_ROLES} from 'constants'
import {orgRoleGroupLabel} from 'lib/ui'
import RegisterPrompt from '../demo/register_prompt'

const defaultAccountMenuExpanded = props => props.location.pathname.includes("/my_org/") || props.location.pathname.includes("/my_account/")

const menuSelected = props => {
  for (let type of ["apps", "services", "users"]){
    ; // fix Sublime highlights
    if(props.location.pathname.indexOf(`/${type}/`) != -1)return type
  }

  return "apps"
}

const defaultState = props => {
  return {
    accountMenuOpen: defaultAccountMenuExpanded(props),
    scrollX: 0,
    showRegisterPrompt: false
  }
}

const isDemo = process.env.NODE_ENV == "demo",
      demoPromptDelay = 45

export default class Sidebar extends React.Component {
  constructor(props){
    super(props)
    this.state = defaultState(props)
  }

  componentDidMount() {
    // if(window)window.addEventListener("scroll",::this._onWindowScroll)

    if (isDemo){
      setTimeout(()=> { this.setState({showRegisterPrompt: true}) }, demoPromptDelay * 1000)
    }
  }

  // componentWillUnmount() {
  //   if(window)window.removeEventListener("scroll",::this._onWindowScroll)
  // }

  componentWillReceiveProps(nextProps) {
    if (this.props.location.pathname != nextProps.location.pathname || !R.equals(this.props.params, nextProps.params)){
      this._reset(nextProps)
    }
  }

  _reset(props){
    this.setState(defaultState(props))
  }

  _onTabClick(type, e){
    this.setState({selected: type, accountMenuOpen: false})
  }

  _onWindowScroll(){
    const scrollX = window.scrollX
    if (scrollX > 0 && this.state.scrollX != scrollX){
      this.setState({scrollX: -scrollX})
    }
  }

  render(){
    return (

          <AccountMenu {...this.props}
                       isOpen={this.state.accountMenuOpen}
                       onToggle={()=> this.setState(state => ({accountMenuOpen: !state.accountMenuOpen}))} />

          {this._renderMenuSections()}

          {this._renderDemoRegisterPrompt()}

    )
  }

  _renderMenuSections(){
    const selected = menuSelected(this.props)
    return

      {this._renderMenuListSection("apps",
                                   "Apps",
                                   this.props.apps,
                                   "menu-lightning-white.svg",
                                   {selected: selected == "apps",
                                    pathFn: (item => `/${this.props.currentOrg.slug}/apps/${item.slug}`),
                                    newBtnLabel: "New App"})}

      {this._renderMenuListSection("users",
                                   "Users",
                                   this.props.users,
                                   "menu-user-white.svg",
                                   {selected: selected == "users",
                                    pathFn: (item => `/${this.props.currentOrg.slug}/users/${item.slug}/apps`),
                                    labelFn: (item => [{item.firstName + " "},
                                                       {item.lastName}]),
                                    // newBtnLabel: "Invite User",
                                    groups: R.reverse(ORG_ROLES),
                                    groupLabelFn: orgRoleGroupLabel})}

  }

  // {this._renderMenuListSection("services",
  //                                        "Mixin",
  //                                        this.props.services,
  //                                        {pathFn: (item => `/${this.props.currentOrg.slug}/services/${item.slug}`),
  //                                         newBtnLabel: "New Mixin" })}

  _renderMenuListSection(type, label, items, icon, componentParams){
    if (this.props.permissions.read[pluralize.singular(type)]){
      return <SidebarMenu {...this.props}
                          {...componentParams}
                          {...{type, items, label, icon}} />
    }
  }

  _renderDemoRegisterPrompt(){
    if (isDemo){
      return <RegisterPrompt show={this.state.showRegisterPrompt} />
    }
  }

}<commit_msg>fix for demo check in sidebar cta popup<commit_after>import React from 'react'
import R from 'ramda'
import pluralize from 'pluralize'
import SidebarMenu from './sidebar_menu'
import AccountMenu from './account_menu'
import {ORG_ROLES} from 'constants'
import {orgRoleGroupLabel} from 'lib/ui'
import RegisterPrompt from '../demo/register_prompt'

const defaultAccountMenuExpanded = props => props.location.pathname.includes("/my_org/") || props.location.pathname.includes("/my_account/")

const menuSelected = props => {
  for (let type of ["apps", "services", "users"]){
    ; // fix Sublime highlights
    if(props.location.pathname.indexOf(`/${type}/`) != -1)return type
  }

  return "apps"
}

const defaultState = props => {
  return {
    accountMenuOpen: defaultAccountMenuExpanded(props),
    scrollX: 0,
    showRegisterPrompt: false
  }
}

const isDemo = process.env.BUILD_ENV == "demo",
      demoPromptDelay = 45

export default class Sidebar extends React.Component {
  constructor(props){
    super(props)
    this.state = defaultState(props)
  }

  componentDidMount() {
    // if(window)window.addEventListener("scroll",::this._onWindowScroll)

    if (isDemo){
      setTimeout(()=> { this.setState({showRegisterPrompt: true}) }, demoPromptDelay * 1000)
    }
  }

  // componentWillUnmount() {
  //   if(window)window.removeEventListener("scroll",::this._onWindowScroll)
  // }

  componentWillReceiveProps(nextProps) {
    if (this.props.location.pathname != nextProps.location.pathname || !R.equals(this.props.params, nextProps.params)){
      this._reset(nextProps)
    }
  }

  _reset(props){
    this.setState(defaultState(props))
  }

  _onTabClick(type, e){
    this.setState({selected: type, accountMenuOpen: false})
  }

  _onWindowScroll(){
    const scrollX = window.scrollX
    if (scrollX > 0 && this.state.scrollX != scrollX){
      this.setState({scrollX: -scrollX})
    }
  }

  render(){
    return (

          <AccountMenu {...this.props}
                       isOpen={this.state.accountMenuOpen}
                       onToggle={()=> this.setState(state => ({accountMenuOpen: !state.accountMenuOpen}))} />

          {this._renderMenuSections()}

          {this._renderDemoRegisterPrompt()}

    )
  }

  _renderMenuSections(){
    const selected = menuSelected(this.props)
    return

      {this._renderMenuListSection("apps",
                                   "Apps",
                                   this.props.apps,
                                   "menu-lightning-white.svg",
                                   {selected: selected == "apps",
                                    pathFn: (item => `/${this.props.currentOrg.slug}/apps/${item.slug}`),
                                    newBtnLabel: "New App"})}

      {this._renderMenuListSection("users",
                                   "Users",
                                   this.props.users,
                                   "menu-user-white.svg",
                                   {selected: selected == "users",
                                    pathFn: (item => `/${this.props.currentOrg.slug}/users/${item.slug}/apps`),
                                    labelFn: (item => [{item.firstName + " "},
                                                       {item.lastName}]),
                                    // newBtnLabel: "Invite User",
                                    groups: R.reverse(ORG_ROLES),
                                    groupLabelFn: orgRoleGroupLabel})}

  }

  // {this._renderMenuListSection("services",
  //                                        "Mixin",
  //                                        this.props.services,
  //                                        {pathFn: (item => `/${this.props.currentOrg.slug}/services/${item.slug}`),
  //                                         newBtnLabel: "New Mixin" })}

  _renderMenuListSection(type, label, items, icon, componentParams){
    if (this.props.permissions.read[pluralize.singular(type)]){
      return <SidebarMenu {...this.props}
                          {...componentParams}
                          {...{type, items, label, icon}} />
    }
  }

  _renderDemoRegisterPrompt(){
    if (isDemo){
      return <RegisterPrompt show={this.state.showRegisterPrompt} />
    }
  }

}<|endoftext|>


<commit_before>/**
 * Summmary
 *
 * Takes a full file list and returns a object of summary data.
 */
module.exports = function bval (fileList) {
    var summary = {
        sessions: [],
        subjects: [],
        runs:     [],
        tasks:    [],
        modalities: []
    };

    for (var fileKey in fileList) {
        var file = fileList[fileKey];
        var path = file.relativePath;

        var checks = {
            'ses':  'sessions',
            'sub':  'subjects',
            'run':  'runs',
            'task': 'tasks'
        };

        for (var checkKey in checks) {
            // var check = checks[i];
            if (path.indexOf(checkKey + '-') > -1) {
                var task = path.slice(path.indexOf(checkKey + '-'));
                    task = task.slice(0, task.indexOf('/'));
                    if (task.indexOf('_') > -1) {task = task.slice(0, task.indexOf('_'));}
                    task = task.slice(checkKey.length + 1);
                if (summary[checks[checkKey]].indexOf(task) === -1) {summary[checks[checkKey]].push(task);}
            }
        }

        if (path.endsWith('.nii') || path.endsWith('.nii.gz')) {
            var pathParts = path.split('_');
            var suffix    = pathParts[pathParts.length -1];
                suffix    = suffix.slice(0, suffix.indexOf('.'));
            if (summary.modalities.indexOf(suffix) === -1) {summary.modalities.push(suffix);}
        }

    }

    // console.log(summary);
    return summary;
};
<commit_msg>Updated conditions to work with browser data<commit_after>/**
 * Summmary
 *
 * Takes a full file list and returns a object of summary data.
 */
module.exports = function bval (fileList) {
    var summary = {
        sessions: [],
        subjects: [],
        runs:     [],
        tasks:    [],
        modalities: []
    };

    for (var fileKey in fileList) {
        var file = fileList[fileKey];
        var path = file.relativePath;

        var checks = {
            'ses':  'sessions',
            'sub':  'subjects',
            'run':  'runs',
            'task': 'tasks'
        };

        for (var checkKey in checks) {
            if (path && path.indexOf(checkKey + '-') > -1) {
                var task = path.slice(path.indexOf(checkKey + '-'));
                    task = task.slice(0, task.indexOf('/'));
                    if (task.indexOf('_') > -1) {task = task.slice(0, task.indexOf('_'));}
                    task = task.slice(checkKey.length + 1);
                if (summary[checks[checkKey]].indexOf(task) === -1) {summary[checks[checkKey]].push(task);}
            }
        }

        if (path && (path.endsWith('.nii') || path.endsWith('.nii.gz'))) {
            var pathParts = path.split('_');
            var suffix    = pathParts[pathParts.length -1];
                suffix    = suffix.slice(0, suffix.indexOf('.'));
            if (summary.modalities.indexOf(suffix) === -1) {summary.modalities.push(suffix);}
        }

    }

    return summary;
};
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var parse = require('mootools-slick-parser').Slick.parse

/**
 * Module exports.
 */

module.exports = exports = Selector;

/**
 * CSS selector constructor.
 *
 * @param {String} selector text
 * @param {Array} optionally, precalculated specificity
 * @api public
 */

function Selector (text, spec) {
  this.text = text;
  this.spec = spec;
}

/**
 * Lazy specificity getter
 *
 * @api public
 */

Selector.prototype.specificity = function () {
  if (!this.spec) return specificity(this.text);
  return this.spec;

  function specificity (text) {
    var parsed = parse(text)
      , expressions = parsed.expressions[0]
      , spec = [0, 0, 0, 0]
      , nots = []

    for (var i = 0; i < expressions.length; i++) {
      var expression = expressions[i]
        , pseudos = expression.pseudos

      // id awards a point in the second column
      if (expression.id) spec[1]++;

      // classes and attributes award a point each in the third column
      if (expression.attributes) spec[2] += expression.attributes.length;
      if (expression.classes) spec[2] += expression.classes.length;

      // tag awards a point in the fourth column
      if (expression.tag && expression.tag != '*') spec[3]++;

      // pseudos award a point each in the fourth column
      if (pseudos) {
        spec[3] += pseudos.length;

        for (var p = 0; p < pseudos.length; p++) {
         if (pseudos[p].key == 'not'){
            nots.push(pseudos[p].value);
            spec[3]--;
          }
        }
      }
    }

    for (var ii = nots.length; ii--;) {
      var not = specificity(nots[ii]);
      for (var jj = 4; jj--;) spec[jj] += not[jj];
    }

    return spec;
  }
}
<commit_msg>Improved parsing caching.<commit_after>
/**
 * Module dependencies.
 */

var parser = require('mootools-slick-parser').Slick.parse

/**
 * Module exports.
 */

module.exports = exports = Selector;

/**
 * CSS selector constructor.
 *
 * @param {String} selector text
 * @param {Array} optionally, precalculated specificity
 * @api public
 */

function Selector (text, spec) {
  this.text = text;
  this.spec = spec;
}

/**
 * Get parsed selector.
 *
 * @api public
 */

Selector.prototype.parsed = function () {
  if (!this.tokens) this.tokens = parse(this.text);
  return this.tokens;
};

/**
 * Lazy specificity getter
 *
 * @api public
 */

Selector.prototype.specificity = function () {
  if (!this.spec) this.spec = specificity(this.text, this.parsed());
  return this.spec;

  function specificity (text, parsed) {
    var expressions = parsed || parse(text)
      , spec = [0, 0, 0, 0]
      , nots = []

    for (var i = 0; i < expressions.length; i++) {
      var expression = expressions[i]
        , pseudos = expression.pseudos

      // id awards a point in the second column
      if (expression.id) spec[1]++;

      // classes and attributes award a point each in the third column
      if (expression.attributes) spec[2] += expression.attributes.length;
      if (expression.classes) spec[2] += expression.classes.length;

      // tag awards a point in the fourth column
      if (expression.tag && expression.tag != '*') spec[3]++;

      // pseudos award a point each in the fourth column
      if (pseudos) {
        spec[3] += pseudos.length;

        for (var p = 0; p < pseudos.length; p++) {
         if (pseudos[p].key == 'not'){
            nots.push(pseudos[p].value);
            spec[3]--;
          }
        }
      }
    }

    for (var ii = nots.length; ii--;) {
      var not = specificity(nots[ii]);
      for (var jj = 4; jj--;) spec[jj] += not[jj];
    }

    return spec;
  }
}

/**
 * Parses a selector and returns the tokens.
 *
 * @param {String} selector
 * @api private.
 */

function parse (text) {
  try {
    return parser(text).expressions[0];
  } catch (e) {
    return [];
  }
}
<|endoftext|>