<commit_before>define(['backbone'], function(Backbone) {

    var Model = Backbone.Model.extend({
    	idAttribute: 'FACILITYCODE',
        urlRoot: '/shipment/dewars/registry',
        _fcCache: {},

        defaults: {
            new: false,
        },

        validation: {
            FACILITYCODE: function(value, attr, state) {
                if (!Backbone.Validation.patterns.fcode.test(value)) {
                    return Backbone.Validation.messages.fcode
                }

                if (this.get('new')) {
                    if (!(value in this._fcCache)) {
                        var self = this
                        var tmp = new Model({ FACILITYCODE: value })
                        tmp.fetch({
                            data: { all: 1 },
                            async: false,
                            success: function() {
                                self._fcCache[value] = tmp.get('PROP')
                            },

                            failure: function() {
                                self._fcCache[value] = false
                            }
                        })
                    }

                    if (this._fcCache[value]) {
                        return 'That facility code is already registered to '+this._fcCache[value]
                    }
                }
            },

        	LABCONTACTID: {
        		required: true,
        		pattern: 'number',
        	},
        }
    })

    return Model
})<commit_msg>add new facility code field<commit_after>define(['backbone'], function(Backbone) {

    var Model = Backbone.Model.extend({
    	idAttribute: 'FACILITYCODE',
        urlRoot: '/shipment/dewars/registry',
        _fcCache: {},

        defaults: {
            new: false,
        },

        validation: {
            FACILITYCODE: function(value, attr, state) {
                if (!Backbone.Validation.patterns.fcode.test(value)) {
                    return Backbone.Validation.messages.fcode
                }

                if (this.get('new')) {
                    if (!(value in this._fcCache)) {
                        var self = this
                        var tmp = new Model({ FACILITYCODE: value })
                        tmp.fetch({
                            data: { all: 1 },
                            async: false,
                            success: function() {
                                self._fcCache[value] = tmp.get('PROP')
                            },

                            failure: function() {
                                self._fcCache[value] = false
                            }
                        })
                    }

                    if (this._fcCache[value]) {
                        return 'That facility code is already registered to '+this._fcCache[value]
                    }
                }
            },

        	LABCONTACTID: {
        		required: true,
        		pattern: 'number',
        	},
        }
    })

    Model.prototype.validation.NEWFACILITYCODE = Model.prototype.validation.FACILITYCODE

    return Model
})<|endoftext|>


<commit_before>var gridOptions = {
    columnDefs: [
        {headerName: "Athlete", field: "athlete",  minWidth: 150},
        {headerName: "Age", field: "age", minWidth: 50, filter: 'number'},
        {headerName: "Country", field: "country", width: 120},
        {headerName: "Year", field: "year", width: 90},
        {headerName: "Date", field: "date", width: 110},
        {headerName: "Sport", field: "sport", width: 110},
        {headerName: "Gold", field: "gold", width: 150, aggFunc: 'sum'},
        {headerName: "Silver", field: "silver", width: 150, aggFunc: 'sum'},
        {headerName: "Bronze", field: "bronze", width: 150, aggFunc: 'sum'}
    ],

    enableColResize: true,
    floatingFilter: true,
    pivotTotals: true, <!-- turns on pivot total columns when pivot mode is enabled -->

    onGridReady: function () {
        initialise();
    }
};

var pivotingOn = true;
var groupOn = true;

function initialise() {
    gridOptions.api.sizeColumnsToFit();
    gridOptions.columnApi.setPivotMode(true);
    gridOptions.columnApi.setRowGroupColumns(['country']);
    gridOptions.columnApi.setPivotColumns(['sport', 'year']);
}

function pivot() {
    var pivotBtn = document.getElementById('pivotBtn');

    if(pivotingOn) {
        pivotBtn.innerHTML = 'Pivot';
        gridOptions.columnApi.setPivotMode(false);
    } else {
        pivotBtn.innerHTML = 'Unpivot';
        gridOptions.columnApi.setPivotMode(true);
    }

    pivotBtn.blur();
    pivotingOn = !pivotingOn;
}

function group() {
    var groupBtn = document.getElementById('groupBtn');

    if(groupOn) {
        groupBtn.innerHTML = 'Group';
        gridOptions.columnApi.setRowGroupColumns([]);
    } else {
        groupBtn.innerHTML = 'Ungroup';
        gridOptions.columnApi.setRowGroupColumns(['country']);
    }

    groupBtn.blur();
    groupOn = !groupOn;
}

// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function () {
    var gridDiv = document.querySelector('#myGrid');
    new agGrid.Grid(gridDiv, gridOptions);

    // do http request to get our sample data - not using any framework to keep the example self contained.
    // you will probably use a framework like JQuery, Angular or something else to do your HTTP calls.
    var httpRequest = new XMLHttpRequest();
    httpRequest.open('GET', '../olympicWinners.json');
    httpRequest.send();
    httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState === 4 && httpRequest.status === 200) {
            var httpResult = JSON.parse(httpRequest.responseText);
            gridOptions.api.setRowData(httpResult);
        }
    };
});<commit_msg>AG-551 - simplified pivot total documentation example<commit_after>var gridOptions = {
    columnDefs: [
        {headerName: "Athlete", field: "athlete",  minWidth: 150},
        {headerName: "Age", field: "age", minWidth: 50, filter: 'number'},
        {headerName: "Country", field: "country", width: 120, rowGroup: true},
        {headerName: "Sport", field: "sport", width: 110, pivot: true},
        {headerName: "Year", field: "year", width: 90, pivot: true},
        {headerName: "Date", field: "date", width: 110},
        {headerName: "Gold", field: "gold", width: 150, aggFunc: 'sum'},
        {headerName: "Silver", field: "silver", width: 150, aggFunc: 'sum'},
        {headerName: "Bronze", field: "bronze", width: 150, aggFunc: 'sum'}
    ],

    enableColResize: true,
    pivotMode: true,
    pivotTotals: true,
    sizeColumnsToFit: true
};

// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function () {
    var gridDiv = document.querySelector('#myGrid');
    new agGrid.Grid(gridDiv, gridOptions);

    // do http request to get our sample data - not using any framework to keep the example self contained.
    // you will probably use a framework like JQuery, Angular or something else to do your HTTP calls.
    var httpRequest = new XMLHttpRequest();
    httpRequest.open('GET', '../olympicWinners.json');
    httpRequest.send();
    httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState === 4 && httpRequest.status === 200) {
            var httpResult = JSON.parse(httpRequest.responseText);
            gridOptions.api.setRowData(httpResult);
        }
    };
});<|endoftext|>


<commit_before>import HocSinh from '../models/hocsinh-model';
import { generateStudentID } from '../utilities/id_generates';

function create(req, res) {
    generateStudentID()
    .then((studentID) => {
        return HocSinh.create({
                maHocSinh: studentID,
                hoTen: req.body.name,
                ngaySinh: req.body.birthday,
                gioiTinh: req.body.gender,
                diaChi: req.body.address,
                email: req.body.email,
                namNhapHoc: 1
            });
    })
    .then((student) => {
        res.status(200).json({
            success: true,
            message: "Created student successfully"
        })
    })
    .catch((err) => {
        res.status(500).json({
            success: false,
            message: "Failed to create student"
        })
    });
}

export default { create };<commit_msg>Fix create student<commit_after>import HocSinh from '../models/hocsinh-model';
import { generateStudentID } from '../utilities/id_generates';

function create(req, res) {
    generateStudentID()
    .then((studentID) => {
        return HocSinh.create({
                maHocSinh: studentID,
                hoTen: req.body.name,
                ngaySinh: req.body.birthday,
                gioiTinh: req.body.gender,
                diaChi: req.body.address,
                email: req.body.email,
                namNhapHoc: req.body.schoolYearID
            });
    })
    .then((student) => {
        res.status(200).json({
            success: true,
            message: "Created student successfully"
        })
    })
    .catch((err) => {
        res.status(500).json({
            success: false,
            message: "Failed to create student"
        })
    });
}

export default { create };<|endoftext|>


<commit_before>/* The contents of this file are subject to the Mozilla Public
 * License Version 1.1 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
 *
 * The Original Code is the Bugzilla Bug Tracking System.
 *
 * The Initial Developer of the Original Code is Everything Solved, Inc.
 * Portions created by Everything Solved are Copyright (C) 2010 Everything
 * Solved, Inc. All Rights Reserved.
 *
 * Contributor(s): Max Kanat-Alexander <mkanat@bugzilla.org>
 */

/* This library assumes that the needed YUI libraries have been loaded
   already. */

YAHOO.bugzilla.dupTable = {
    counter: 0,
    dataSource: null,
    updateTable: function(dataTable, product_name, summary_field) {
        if (summary_field.value.length < 4) return;

        YAHOO.bugzilla.dupTable.counter = YAHOO.bugzilla.dupTable.counter + 1;
        YAHOO.util.Connect.setDefaultPostHeader('application/json', true);
        var json_object = {
            version : "1.1",
            method : "Bug.possible_duplicates",
            id : YAHOO.bugzilla.dupTable.counter,
            params : {
                product : product_name,
                summary : summary_field.value,
                limit : 7,
                include_fields : [ "id", "summary", "status", "resolution",
                                   "update_token" ]
            }
        };
        var post_data = YAHOO.lang.JSON.stringify(json_object);

        var callback = {
            success: dataTable.onDataReturnInitializeTable,
            failure: dataTable.onDataReturnInitializeTable,
            scope:   dataTable,
            argument: dataTable.getState()
        };
        dataTable.showTableMessage(dataTable.get("MSG_LOADING"),
                                   YAHOO.widget.DataTable.CLASS_LOADING);
        YAHOO.util.Dom.removeClass('possible_duplicates_container',
                                   'bz_default_hidden');
        dataTable.getDataSource().sendRequest(post_data, callback);
    },
    formatBugLink: function(el, oRecord, oColumn, oData) {
        el.innerHTML = ''
                       + oData + '';
    },
    formatStatus: function(el, oRecord, oColumn, oData) {
        var resolution = oRecord.getData('resolution');
        if (resolution) {
            el.innerHTML = oData + ' ' + resolution;
        }
        else {
            el.innerHTML = oData;
        }
    },
    formatCcButton: function(el, oRecord, oColumn, oData) {
        var url = 'process_bug.cgi?id=' + oRecord.getData('id')
                  + '&addselfcc=1&token=' + escape(oData);
        var button = document.createElement('button');
        button.setAttribute('type', 'button');
        button.innerHTML = YAHOO.bugzilla.dupTable.addCcMessage;
        button.onclick = function() { window.location = url; return false; };
        el.appendChild(button);
    },
    init_ds: function() {
        var new_ds = new YAHOO.util.XHRDataSource("jsonrpc.cgi");
        new_ds.connTimeout = 30000;
        new_ds.connMethodPost = true;
        new_ds.connXhrMode = "cancelStaleRequests";
        new_ds.maxCacheEntries = 3;
        new_ds.responseSchema = {
            resultsList : "result.bugs",
            metaFields : { error: "error", jsonRpcId: "id" },
        };
        // DataSource can't understand a JSON-RPC error response, so
        // we have to modify the result data if we get one.
        new_ds.doBeforeParseData =
            function(oRequest, oFullResponse, oCallback) {
                if (oFullResponse.error) {
                    oFullResponse.result = {};
                    oFullResponse.result.bugs = [];
                    if (console) {
                        console.log("JSON-RPC error:", oFullResponse.error);
                    }
                }
                return oFullResponse;
        }

        this.dataSource = new_ds;
    },
    init: function(data) {
        if (this.dataSource == null) this.init_ds();
        data.options.initialLoad = false;
        var dt = new YAHOO.widget.DataTable(data.container, data.columns,
            this.dataSource, data.options);
        YAHOO.util.Event.on(data.summary_field, 'blur',
            function(e) {
                YAHOO.bugzilla.dupTable.updateTable(dt, data.product_name,
                    YAHOO.util.Event.getTarget(e))
            }
        );
    },
};
<commit_msg>Bug 576912: Make the automatic duplicate detection table appear onkeyup instead of onblur, but give it a delay so that (a) we're not sending too many queries and (b) so that it doesn't appear at the exact same time as you click Submit Bug (making the "Submit Bug" click not work) r=timello, a=mkanat<commit_after>/* The contents of this file are subject to the Mozilla Public
 * License Version 1.1 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
 *
 * The Original Code is the Bugzilla Bug Tracking System.
 *
 * The Initial Developer of the Original Code is Everything Solved, Inc.
 * Portions created by Everything Solved are Copyright (C) 2010 Everything
 * Solved, Inc. All Rights Reserved.
 *
 * Contributor(s): Max Kanat-Alexander <mkanat@bugzilla.org>
 */

/* This library assumes that the needed YUI libraries have been loaded
   already. */

YAHOO.bugzilla.dupTable = {
    counter: 0,
    dataSource: null,
    updateTable: function(dataTable, product_name, summary_field) {
        if (summary_field.value.length < 4) return;

        YAHOO.bugzilla.dupTable.counter = YAHOO.bugzilla.dupTable.counter + 1;
        YAHOO.util.Connect.setDefaultPostHeader('application/json', true);
        var json_object = {
            version : "1.1",
            method : "Bug.possible_duplicates",
            id : YAHOO.bugzilla.dupTable.counter,
            params : {
                product : product_name,
                summary : summary_field.value,
                limit : 7,
                include_fields : [ "id", "summary", "status", "resolution",
                                   "update_token" ]
            }
        };
        var post_data = YAHOO.lang.JSON.stringify(json_object);

        var callback = {
            success: dataTable.onDataReturnInitializeTable,
            failure: dataTable.onDataReturnInitializeTable,
            scope:   dataTable,
            argument: dataTable.getState()
        };
        dataTable.showTableMessage(dataTable.get("MSG_LOADING"),
                                   YAHOO.widget.DataTable.CLASS_LOADING);
        YAHOO.util.Dom.removeClass('possible_duplicates_container',
                                   'bz_default_hidden');
        dataTable.getDataSource().sendRequest(post_data, callback);
    },
    // This is the keyup event handler. It calls updateTable with a relatively
    // long delay, to allow additional input. However, the delay is short
    // enough that nobody could get from the summary field to the Submit
    // Bug button before the table is shown (which is important, because
    // the showing of the table causes the Submit Bug button to move, and
    // if the table shows at the exact same time as the button is clicked,
    // the click on the button won't register.)
    doUpdateTable: function(e, args) {
        var dt = args[0];
        var product_name = args[1];
        var summary = YAHOO.util.Event.getTarget(e);
        clearTimeout(YAHOO.bugzilla.dupTable.lastTimeout);
        YAHOO.bugzilla.dupTable.lastTimeout = setTimeout(function() {
            YAHOO.bugzilla.dupTable.updateTable(dt, product_name, summary) },
            600);
    },
    formatBugLink: function(el, oRecord, oColumn, oData) {
        el.innerHTML = ''
                       + oData + '';
    },
    formatStatus: function(el, oRecord, oColumn, oData) {
        var resolution = oRecord.getData('resolution');
        if (resolution) {
            el.innerHTML = oData + ' ' + resolution;
        }
        else {
            el.innerHTML = oData;
        }
    },
    formatCcButton: function(el, oRecord, oColumn, oData) {
        var url = 'process_bug.cgi?id=' + oRecord.getData('id')
                  + '&addselfcc=1&token=' + escape(oData);
        var button = document.createElement('button');
        button.setAttribute('type', 'button');
        button.innerHTML = YAHOO.bugzilla.dupTable.addCcMessage;
        button.onclick = function() { window.location = url; return false; };
        el.appendChild(button);
    },
    init_ds: function() {
        var new_ds = new YAHOO.util.XHRDataSource("jsonrpc.cgi");
        new_ds.connTimeout = 30000;
        new_ds.connMethodPost = true;
        new_ds.connXhrMode = "cancelStaleRequests";
        new_ds.maxCacheEntries = 3;
        new_ds.responseSchema = {
            resultsList : "result.bugs",
            metaFields : { error: "error", jsonRpcId: "id" },
        };
        // DataSource can't understand a JSON-RPC error response, so
        // we have to modify the result data if we get one.
        new_ds.doBeforeParseData =
            function(oRequest, oFullResponse, oCallback) {
                if (oFullResponse.error) {
                    oFullResponse.result = {};
                    oFullResponse.result.bugs = [];
                    if (console) {
                        console.log("JSON-RPC error:", oFullResponse.error);
                    }
                }
                return oFullResponse;
        }

        this.dataSource = new_ds;
    },
    init: function(data) {
        if (this.dataSource == null) this.init_ds();
        data.options.initialLoad = false;
        var dt = new YAHOO.widget.DataTable(data.container, data.columns,
            this.dataSource, data.options);
        YAHOO.util.Event.on(data.summary_field, 'keyup', this.doUpdateTable,
                            [dt, data.product_name]);
    },
};
<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.getAllData = function() {
         $.getJSON('/api/project/getAllData/' + gvm.projectId, function(data) {
            console.log(data);
         });
    };

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    };

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    };
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getAllData();

    fetchProjectStructure();
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description);

            $.each(item.subcompetences, function(i, subcomp){
                var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description);
                competence.subcompetences.push(subcompetence);

                $.each(subcomp.indicators, function(i, indic){
                    subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
                });
            });
        })
    });
}

function Competence(viewmodel, id, code, name, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        subcompetences: ko.observableArray(subcompetences)
    };
}

function SubCompetence(parent, id, code, name, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        indicators: ko.observableArray(indicators)
    };
}

function Indicator(parent, id, name, description, score) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        description: ko.observable(description),
        points: ko.observable(points)
    };
}

ko.bindingHandlers.slider = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var options = allBindingsAccessor().sliderOptions || {};
        $(element).slider(options);
        ko.utils.registerEventHandler(element, "slidechange", function (event, ui) {
            var observable = valueAccessor();
            observable(ui.value);
        });
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).slider("destroy");
        });
        ko.utils.registerEventHandler(element, "slide", function (event, ui) {
            var observable = valueAccessor();
            observable(ui.value);
        });
    }
};

<commit_msg>assess score<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.getAllData = function() {
         $.getJSON('/api/project/getAllData/' + gvm.projectId, function(data) {
            console.log(data);
         });
    };

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    };

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    };
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getAllData();

    fetchProjectStructure();
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description);

            $.each(item.subcompetences, function(i, subcomp){
                var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description);
                competence.subcompetences.push(subcompetence);

                $.each(subcomp.indicators, function(i, indic){
                    subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
                });
            });
        })
    });
}

function Competence(viewmodel, id, code, name, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        subcompetences: ko.observableArray(subcompetences)
    };
}

function SubCompetence(parent, id, code, name, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        indicators: ko.observableArray(indicators)
    };
}

function Indicator(parent, id, name, description, points) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        description: ko.observable(description),
        points: ko.observable(points)
    };
}

ko.bindingHandlers.slider = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var options = allBindingsAccessor().sliderOptions || {};
        $(element).slider(options);
        ko.utils.registerEventHandler(element, "slidechange", function (event, ui) {
            var observable = valueAccessor();
            observable(ui.value);
        });
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).slider("destroy");
        });
        ko.utils.registerEventHandler(element, "slide", function (event, ui) {
            var observable = valueAccessor();
            observable(ui.value);
        });
    }
};

<|endoftext|>


<commit_before>'use strict';

var express = require('express'),
    bodyParser = require('body-parser'),
    cookieParser = require('cookie-parser'),
    session = require('express-session'),
    methodOverride = require('method-override'),
    serveStatic = require('serve-static'),
    compress = require('compression'),
    errorHandler = require('errorhandler'),
    morgan = require('morgan'),
    helmet = require('helmet'),
    path = require('path'),
    config = require('./config'),
    cred = require('./credentials/mongo'),
    passport = require('passport'),
    csrf = require('csurf'),
    fs = require('fs'),
    MongoStore = require('connect-mongo')(session);

module.exports = function(app) {

    /* Disable caching of scripts for easier testing
    =================================================================== */
    app.use(function noCache(req, res, next) {
        if (req.url.indexOf('/modules/') === 0) {
            res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
            res.header('Pragma', 'no-cache');
            res.header('Expires', 0);
        }
        next();
    });

    /* Log request (Development only)
    =================================================================== */
    if (config.env === 'development') {

        app.use(morgan('dev'));
        app.set('view cache', false);

    } else if (config.env === 'production') {
        app.locals.cache = 'memory';
    }

    /* Assets compression
    =================================================================== */
    app.use(compress({
        filter: function(req, res) {
            return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
        },
        level: 9
    }));

    /* Defaults
    =================================================================== */
    app.engine('html', require('ejs').renderFile);
    app.set('view engine', 'html');
    app.set('views', config.root + '/app');

    /* Request body parsing middleware
    =================================================================== */

    app.use(bodyParser.urlencoded());
    app.use(bodyParser.json());
    app.use(methodOverride());
    app.enable('jsonp callback');
    app.use(cookieParser());

    /* Persist session with MongoStore
    =================================================================== */
    app.use(session({
        secret: cred.mongo.secret,
        maxAge: new Date(Date.now() + 3600000),
        store: new MongoStore({
            url: config.mongo.uri,
            collection: cred.mongo.collection
        }, function() {
            console.log("Database connection open at: " + config.mongo.uri);
        })
    }));

    /* Init csrf protection
    =================================================================== */
    app.use(csrf());

    /* Passport Session
    =================================================================== */
    app.use(passport.initialize());
    app.use(passport.session());

    /* Use helmet to secure Express headers
    =================================================================== */
    app.use(helmet.xframe());
    app.use(helmet.iexss());
    app.use(helmet.contentTypeOptions());
    app.use(helmet.ienoopen());
    app.disable('x-powered-by');

    /* Send token
    =================================================================== */

    app.use(function(req, res, next) {
        res.cookie('_csrf', req.csrfToken());
        res.locals.csrftoken = req.csrfToken();
        next();
    });

    /* Static
    =================================================================== */
    app.use('/', serveStatic(config.root + '/app'));

    /* Error Handler
    =================================================================== */
        app.use(errorHandler());

    };
<commit_msg>fix linting issues<commit_after>'use strict';

var express = require('express'),
    bodyParser = require('body-parser'),
    cookieParser = require('cookie-parser'),
    session = require('express-session'),
    methodOverride = require('method-override'),
    serveStatic = require('serve-static'),
    compress = require('compression'),
    errorHandler = require('errorhandler'),
    morgan = require('morgan'),
    helmet = require('helmet'),
    path = require('path'),
    config = require('./config'),
    cred = require('./credentials/mongo'),
    passport = require('passport'),
    csrf = require('csurf'),
    fs = require('fs'),
    MongoStore = require('connect-mongo')(session);

module.exports = function(app) {

    /* Disable caching of scripts for easier testing
    =================================================================== */
    app.use(function noCache(req, res, next) {
        if (req.url.indexOf('/modules/') === 0) {
            res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
            res.header('Pragma', 'no-cache');
            res.header('Expires', 0);
        }
        next();
    });

    /* Log request (Development only)
    =================================================================== */
    if (config.env === 'development') {

        app.use(morgan('dev'));
        app.set('view cache', false);

    } else if (config.env === 'production') {
        app.locals.cache = 'memory';
    }

    /* Assets compression
    =================================================================== */
    app.use(compress({
        filter: function(req, res) {
            return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
        },
        level: 9
    }));

    /* Defaults
    =================================================================== */
    app.engine('html', require('ejs').renderFile);
    app.set('view engine', 'html');
    app.set('views', config.root + '/app');

    /* Request body parsing middleware
    =================================================================== */

    app.use(bodyParser.urlencoded());
    app.use(bodyParser.json());
    app.use(methodOverride());
    app.enable('jsonp callback');
    app.use(cookieParser());

    /* Persist session with MongoStore
    =================================================================== */
    app.use(session({
        secret: cred.mongo.secret,
        maxAge: new Date(Date.now() + 3600000),
        store: new MongoStore({
            url: config.mongo.uri,
            collection: cred.mongo.collection
        }, function() {
            console.log("Database connection open at: " + config.mongo.uri);
        })
    }));

    /* Init csrf protection
    =================================================================== */
    app.use(csrf());

    /* Passport Session
    =================================================================== */
    app.use(passport.initialize());
    app.use(passport.session());

    /* Use helmet to secure Express headers
    =================================================================== */
    app.use(helmet.xframe());
    app.use(helmet.iexss());
    app.use(helmet.contentTypeOptions());
    app.use(helmet.ienoopen());
    app.disable('x-powered-by');

    /* Send token
    =================================================================== */

    app.use(function(req, res, next) {
        res.cookie('_csrf', req.csrfToken());
        res.locals.csrftoken = req.csrfToken();
        next();
    });

    /* Static
    =================================================================== */
    app.use('/', serveStatic(config.root + '/app'));

    /* Error Handler
    =================================================================== */
    app.use(errorHandler());

};
<|endoftext|>


<commit_before>var app = angular.module('odin.categoryControllers', []);

app.factory('model', function ($resource) {
    return $resource();
});

function CategoryListController($scope, $location, rest, $rootScope, $routeParams, $httpParamSerializer, $log, usSpinnerService) {
    usSpinnerService.spin('spinner');
    $rootScope.countQuery++;
    $rootScope.countQuery++;

    var cache = false;
    var cacheFilt = false;

    if ($routeParams['categories.slug']) {
        sessionStorage.setItem('activeCategory', $routeParams['categories.slug']);
    }
    $scope.activeCategory = sessionStorage.getItem('activeCategory');
    $scope.url_api = $rootScope.url;
    $scope.activeCategory = $.isArray($scope.activeCategory) ? $scope.activeCategory[0] : sessionStorage.getItem('activeCategory');
    $scope.modelName = "Category";
    $scope.type = "categories";
    $scope.showCategories = true;
    $scope.statistics = {};
    $scope.porcentual = {};
    $scope.totalStatistics = 0;
    $scope.letterLimit = 4;
    $scope.hideCategoriesSidebar = function () {
        $rootScope.showBackdrop = false;
        $rootScope.showCategoriesSidebar = false;
    };

    var totalCategories = 0;
    var totalFiletypes = 0;

    $scope.$watch(function () {
        if (!!sessionStorage.getItem('categories')) {
            return sessionStorage.getItem('categories');
        }

    }, function (val) {
        if (!!val && !cache && val.length > 0) {
            var arrayCats = JSON.parse(val);
            if (arrayCats.length == totalCategories) {
                $rootScope.dataCategories = JSON.parse(val);
                $rootScope.countQuery--;
                if ($rootScope.countQuery == 0) {
                    usSpinnerService.stop('spinner');
                }
            }
        }
    });

    $scope.$watch(function () {
        if (!!sessionStorage.getItem('filetypes')) {
            return sessionStorage.getItem('filetypes');
        }

    }, function (val) {
        if (!!val && !cacheFilt && val.length > 0) {
            var arrayFilt = JSON.parse(val);
            if (arrayFilt.length == totalFiletypes) {
                $rootScope.dataFiletypes = JSON.parse(val);
                $rootScope.countQuery--;
                if ($rootScope.countQuery == 0) {
                    usSpinnerService.stop('spinner');
                }
            }
        }
    });

    $rootScope.showCategories = true;

    if (!!sessionStorage.getItem('categories')) {
        cache = true;
        $scope.categories = JSON.parse(sessionStorage.getItem('categories'));
        $rootScope.dataCategories = $scope.categories;
        $rootScope.showCategories = false;
        $rootScope.countQuery--;
        if ($rootScope.countQuery == 0) {
            usSpinnerService.stop('spinner');
        }
    } else {
        rest().get({
            type: $scope.type,
            params: "parent=null&orderBy=name&sort=ASC"
        }, function (categories) {
            totalCategories = categories.meta.count;
            //$scope.categories = categories.data;
            var cats = [];
            sessionStorage.setItem('categories', JSON.stringify(cats));
            angular.forEach(categories.data, function (element) {
                var info = {
                    id: element.id,
                    active: element.active,
                    color: element.color,
                    name: element.name,
                    slug: element.slug,
                    image: ''
                };

                rest().image({
                    type: 'categories',
                    id: element.id
                }, function (resp) {
                    info.image = resp.svg;
                    cats.push(info);
                    sessionStorage.setItem('categories', JSON.stringify(cats));
                }, function (error) {
                    cats.push(info);
                    sessionStorage.setItem('categories', JSON.stringify(cats));
                });

            });

            $scope.categories = cats;

            $rootScope.showCategories = false;
        }, function (error) {
            $rootScope.countQuery--;
            if ($rootScope.countQuery == 0) {
                usSpinnerService.stop('spinner');
            }
        });
    }
    ;

    if (!!sessionStorage.getItem('filetypes')) {
        $rootScope.dataFiletypes = JSON.parse(sessionStorage.getItem('filetypes'));
        cacheFilt = true;
        $rootScope.countQuery--;
        if ($rootScope.countQuery == 0) {
            usSpinnerService.stop('spinner');
        }
    } else {
        rest().get({
            type: 'filetypes'
        }, function (filetypes) {
            totalFiletypes = filetypes.meta.count;
            var fils = [];
            sessionStorage.setItem('filetypes', JSON.stringify(fils));
            angular.forEach(filetypes.data, function (element) {
                var info = {
                    id: element.id,
                    api: element.api,
                    mimetype: element.mimetype,
                    name: element.name,
                    slug: element.slug
                };

                fils.push(info);
                sessionStorage.setItem('filetypes', JSON.stringify(fils));

            });
        }, function (error) {
            $rootScope.countQuery--;
            if ($rootScope.countQuery == 0) {
                usSpinnerService.stop('spinner');
            }
        });
    }
    ;
}
<commit_msg>clears filters on category change<commit_after>var app = angular.module('odin.categoryControllers', []);

app.factory('model', function ($resource) {
    return $resource();
});

function CategoryListController($scope, $location, rest, $rootScope, $routeParams, $httpParamSerializer, $log, usSpinnerService) {

    usSpinnerService.spin('spinner');
    $rootScope.countQuery++;
    $rootScope.countQuery++;

    var cache = false;
    var cacheFilt = false;

    if ($routeParams['categories.slug']) {
        var activeCategory = $routeParams['categories.slug'];
        sessionStorage.setItem('activeCategory', activeCategory);
        checkFilters(activeCategory);
        sessionStorage.setItem('selectedCategory', $routeParams['categories.slug']);
    }

    $scope.activeCategory = sessionStorage.getItem('activeCategory');
    $scope.url_api = $rootScope.url;
    $scope.activeCategory = $.isArray($scope.activeCategory) ? $scope.activeCategory[0] : sessionStorage.getItem('activeCategory');

    $scope.modelName = "Category";
    $scope.type = "categories";
    $scope.showCategories = true;
    $scope.statistics = {};
    $scope.porcentual = {};
    $scope.totalStatistics = 0;
    $scope.letterLimit = 4;
    $scope.hideCategoriesSidebar = function () {
        $rootScope.showBackdrop = false;
        $rootScope.showCategoriesSidebar = false;
    };

    var totalCategories = 0;
    var totalFiletypes = 0;

    $scope.$watch(function () {
        if (!!sessionStorage.getItem('categories')) {
            return sessionStorage.getItem('categories');
        }

    }, function (val) {
        if (!!val && !cache && val.length > 0) {
            var arrayCats = JSON.parse(val);
            if (arrayCats.length == totalCategories) {
                $rootScope.dataCategories = JSON.parse(val);
                $rootScope.countQuery--;
                if ($rootScope.countQuery == 0) {
                    usSpinnerService.stop('spinner');
                }
            }
        }
    });

    $scope.$watch(function () {
        if (!!sessionStorage.getItem('filetypes')) {
            return sessionStorage.getItem('filetypes');
        }

    }, function (val) {
        if (!!val && !cacheFilt && val.length > 0) {
            var arrayFilt = JSON.parse(val);
            if (arrayFilt.length == totalFiletypes) {
                $rootScope.dataFiletypes = JSON.parse(val);
                $rootScope.countQuery--;
                if ($rootScope.countQuery == 0) {
                    usSpinnerService.stop('spinner');
                }
            }
        }
    });

    $rootScope.showCategories = true;

    if (!!sessionStorage.getItem('categories')) {
        cache = true;
        $scope.categories = JSON.parse(sessionStorage.getItem('categories'));
        $rootScope.dataCategories = $scope.categories;
        $rootScope.showCategories = false;
        $rootScope.countQuery--;
        if ($rootScope.countQuery == 0) {
            usSpinnerService.stop('spinner');
        }
    } else {
        rest().get({
            type: $scope.type,
            params: "parent=null&orderBy=name&sort=ASC"
        }, function (categories) {
            totalCategories = categories.meta.count;
            //$scope.categories = categories.data;
            var cats = [];
            sessionStorage.setItem('categories', JSON.stringify(cats));
            angular.forEach(categories.data, function (element) {
                var info = {
                    id: element.id,
                    active: element.active,
                    color: element.color,
                    name: element.name,
                    slug: element.slug,
                    image: ''
                };

                rest().image({
                    type: 'categories',
                    id: element.id
                }, function (resp) {
                    info.image = resp.svg;
                    cats.push(info);
                    sessionStorage.setItem('categories', JSON.stringify(cats));
                }, function (error) {
                    cats.push(info);
                    sessionStorage.setItem('categories', JSON.stringify(cats));
                });

            });

            $scope.categories = cats;

            $rootScope.showCategories = false;
        }, function (error) {
            $rootScope.countQuery--;
            if ($rootScope.countQuery == 0) {
                usSpinnerService.stop('spinner');
            }
        });
    }
    ;

    if (!!sessionStorage.getItem('filetypes')) {
        $rootScope.dataFiletypes = JSON.parse(sessionStorage.getItem('filetypes'));
        cacheFilt = true;
        $rootScope.countQuery--;
        if ($rootScope.countQuery == 0) {
            usSpinnerService.stop('spinner');
        }
    } else {
        rest().get({
            type: 'filetypes'
        }, function (filetypes) {
            totalFiletypes = filetypes.meta.count;
            var fils = [];
            sessionStorage.setItem('filetypes', JSON.stringify(fils));
            angular.forEach(filetypes.data, function (element) {
                var info = {
                    id: element.id,
                    api: element.api,
                    mimetype: element.mimetype,
                    name: element.name,
                    slug: element.slug
                };

                fils.push(info);
                sessionStorage.setItem('filetypes', JSON.stringify(fils));

            });
        }, function (error) {
            $rootScope.countQuery--;
            if ($rootScope.countQuery == 0) {
                usSpinnerService.stop('spinner');
            }
        });
    }
    ;
}

function checkFilters(activeCategory){
  activeCategory = $.isArray(activeCategory) ? activeCategory[0] : sessionStorage.getItem('activeCategory');
  var selected = sessionStorage.getItem('selectedCategory');
  if (selected && activeCategory != selected) {
    clearFilters();
  }
}
function clearFilters(){
  sessionStorage.removeItem('tagsAutocomplete');
  sessionStorage.removeItem('orgsAutocomplete');
  sessionStorage.removeItem('formatsAutocomplete');
  sessionStorage.removeItem('selectedTags');
  sessionStorage.removeItem('selectedOrgs');
  sessionStorage.removeItem('selectedFormats');
}
<|endoftext|>


<commit_before>(function (){

var parseTSV = function (text){
  var content;
  var rows;
  var header;

  if (text!=""){
    rows = _.escape(text).split("\n");
    header = rows.shift().split("\t");
    content = _.map(rows, function (rowstr) {
      return _.object(header, rowstr.split("\t"));
    });
  } else {
    content = [];
  }

  return content;
};

var parseTSV = function (text){
  var content;
  var rows;
  var header;

  if (text!=""){
    rows = _.escape(text).split("\n");
    header = rows.shift().split("\t");
    content = _.map(rows, function (rowstr) {
      return _.object(header, rowstr.split("\t"));
    });
  } else {
    content = [];
  }

  return content;
};

var loadSourceData = function (callback){
  var port = chrome.extension.connect();
  port.postMessage();
  port.onMessage.addListener(function (res){
    callback.call(this, res);
  });

  return port;
};

var convert_isbn13to10 = function(isbn13) {
  if(isbn13.length!=13){
    throw isbn13 + " is not ISBN13.";
  }

  var isbn10_ary = isbn13.substr(3,9).split("");
  var sum    = 0;
  var digit_number;
  var check_digit;
  var isbn10;

  for (var i=0, len=isbn10_ary.length; i<len;i++){
    sum+=isbn10_ary[i] * (10 - i);
  }

  digit_number = 11 - (sum % 11);
  switch(digit_number){
    case 10:
      check_digit = 'x';
      break;
    case 11:
      check_digit = '0';
      break;
    default:
      check_digit = digit_number;
      break;
  }

  isbn10_ary.push(check_digit);
  isbn10 = isbn10_ary.join("");
  return isbn10;
};

var convert_isbn10to13 = function(_isbn10) {
  var weights = [1,3,1,3,1,3,1,3,1,3,1,3];
  var isbn10 = _isbn10.replace(/-/g, "");
  var numbers;
  var check_digit;

  if(isbn10.length!=10){
    throw isbn10 + "is not ISBN10";
  }

  numbers = ("978"+isbn10).split("");
  numbers.pop();

  check_digit = 10 - ( _.chain(numbers)
                        .clone()
                        .zip(weights)
                        .reduce(function (memo, pair){ return memo+(parseInt(pair[0]) * pair[1]) }, 0)
                        .value() % 10 );

  numbers.push(check_digit);
  return numbers.join("");
};

var getYoutubeID = function (res, target_isbn){
  var youtube_id;
  var row = _.find(res, function (row){
    var isbn = row["book:isbn"].replace(/-/g,"");

    if (target_isbn.length==10){
      target_isbn = convert_isbn10to13(target_isbn)
    }
    if (isbn.length==10){
      isbn = convert_isbn10to13(isbn);
    }

    return isbn == target_isbn;
  });

  if (_.isObject(row)){
    youtube_id = row["movie:youtube_id"];
  }

  return youtube_id;
};

var extractPageContext = function (){
  var url = location.href;
  var isbn;
  var context;

  if (url.match(/http[s]{0,1}:\/\/www.amazon.co.jp\/.*$/)) {
    isbn    = url.match(/[0-9X]{10,13}/)[0];
    context = {service:"amazon", isbn:isbn};
  } else if (url.match(/^http[s]{0,1}:\/\/www.kinokuniya.co.jp\/.*$/)){
    isbn    = url.match(/[0-9X]{10,13}/)[0];
    context = {service:"kinokuniya", isbn:isbn};
  } else if (url.match(/^http[s]{0,1}:\/\/www.honyaclub.com\/.*$/)) {
    isbn    = /[0-9]{10,13}/.exec(document.querySelectorAll(".item-price")[0].innerHTML);
    context = {service:"honyaclub", isbn:isbn};
  } else if (url.match(/^http[s]{0,1}:\/\/honto.jp\/.*$/)) {
    isbn    = /ISBN：([0-9\-]+)/.exec(document.querySelectorAll(".stItemData")[0].innerHTML)[1].replace(/\-/g, "");
    context = {service:"honto", isbn:isbn};
  }else {
    context = null;
  }

  return context;
};

var insertMovieByService = function (service_name, youtube_id){
  var result;
  var template;

  switch(service_name){
    case "amazon":
      template = _.template('

ビブリオバトル動画
<iframe width="560" height="315" src="//www.youtube.com/embed/<%= youtube_id %>" frameborder="0" allowfullscreen>
');
      document.querySelectorAll(".bucketDivider")[0].insertAdjacentHTML("beforebegin", template({youtube_id: youtube_id}));
      result = true;
      break;
    case "kinokuniya":
      template = _.template('

ビブリオバトル動画
<iframe width="560" height="315" src="//www.youtube.com/embed/<%= youtube_id %>" frameborder="0" allowfullscreen>

');
      document.querySelectorAll(".career_box")[0].insertAdjacentHTML("beforebegin", template({youtube_id: youtube_id}));
      result = true;
      break;
    case "honyaclub":
      template = _.template('
ビブリオバトル動画
<iframe width="560" height="315" src="//www.youtube.com/embed/<%= youtube_id %>" frameborder="0" allowfullscreen>
');
      document.querySelectorAll(".detail-block01")[0].insertAdjacentHTML("beforeend", template({youtube_id: youtube_id}));
      result = true;
      break;
    case "honto":
      template = _.template('

ビブリオバトル動画

<iframe width="560" height="315" src="//www.youtube.com/embed/<%= youtube_id %>" frameborder="0" allowfullscreen>

');
      document.querySelectorAll("#mainArea #area0 .pbNested .pbNestedWrapper")[0].insertAdjacentHTML("afterend", template({youtube_id: youtube_id}));
      result = true;
      break
  }

  return result;
};

// main block
loadSourceData(function (res){
  var context     = extractPageContext();
  var database    = parseTSV(res);

  if(_.isObject(context)){
    var target_isbn = context.isbn;
    var youtube_id = getYoutubeID(database, target_isbn);

    if (_.isString(youtube_id)){
      insertMovieByService(context.service, youtube_id);
    }

  }

});

})();
<commit_msg>bug fix<commit_after>(function (){

var parseTSV = function (text){
  var content;
  var rows;
  var header;

  if (text!=""){
    rows = _.escape(text).split("\n");
    header = rows.shift().split("\t");
    content = _.map(rows, function (rowstr) {
      return _.object(header, rowstr.split("\t"));
    });
  } else {
    content = [];
  }

  return content;
};

var parseTSV = function (text){
  var content;
  var rows;
  var header;

  if (text!=""){
    rows = _.escape(text).split("\n");
    header = rows.shift().split("\t");
    content = _.map(rows, function (rowstr) {
      return _.object(header, rowstr.split("\t"));
    });
  } else {
    content = [];
  }

  return content;
};

var loadSourceData = function (callback){
  var port = chrome.extension.connect();
  port.postMessage();
  port.onMessage.addListener(function (res){
    callback.call(this, res);
  });

  return port;
};

var convert_isbn13to10 = function(isbn13) {
  if(isbn13.length!=13){
    throw isbn13 + " is not ISBN13.";
  }

  var isbn10_ary = isbn13.substr(3,9).split("");
  var sum    = 0;
  var digit_number;
  var check_digit;
  var isbn10;

  for (var i=0, len=isbn10_ary.length; i<len;i++){
    sum+=isbn10_ary[i] * (10 - i);
  }

  digit_number = 11 - (sum % 11);
  switch(digit_number){
    case 10:
      check_digit = 'x';
      break;
    case 11:
      check_digit = '0';
      break;
    default:
      check_digit = digit_number;
      break;
  }

  isbn10_ary.push(check_digit);
  isbn10 = isbn10_ary.join("");
  return isbn10;
};

var convert_isbn10to13 = function(_isbn10) {
  var weights = [1,3,1,3,1,3,1,3,1,3,1,3];
  var isbn10 = _isbn10.replace(/-/g, "");
  var numbers;
  var check_digit;

  if(isbn10.length!=10){
    throw isbn10 + "is not ISBN10";
  }

  numbers = ("978"+isbn10).split("");
  numbers.pop();

  check_digit = 10 - ( _.chain(numbers)
                        .clone()
                        .zip(weights)
                        .reduce(function (memo, pair){ return memo+(parseInt(pair[0]) * pair[1]) }, 0)
                        .value() % 10 );

  numbers.push(check_digit);
  return numbers.join("");
};

var getYoutubeID = function (res, target_isbn){
  var youtube_id;
  var row = _.find(res, function (row){
    if (!_.isString(row["book:isbn"])){
      return false;
    }

    var isbn = row["book:isbn"].replace(/-/g,"");

    if (target_isbn.length==10){
      target_isbn = convert_isbn10to13(target_isbn)
    }
    if (isbn.length==10){
      isbn = convert_isbn10to13(isbn);
    }

    return isbn == target_isbn;
  });

  if (_.isObject(row)){
    youtube_id = row["movie:youtube_id"];
  }

  return youtube_id;
};

var extractPageContext = function (){
  var url = location.href;
  var isbn;
  var context;

  if (url.match(/http[s]{0,1}:\/\/www.amazon.co.jp\/.*$/)) {
    isbn    = url.match(/[0-9X]{10,13}/)[0];
    context = {service:"amazon", isbn:isbn};
  } else if (url.match(/^http[s]{0,1}:\/\/www.kinokuniya.co.jp\/.*$/)){
    isbn    = url.match(/[0-9X]{10,13}/)[0];
    context = {service:"kinokuniya", isbn:isbn};
  } else if (url.match(/^http[s]{0,1}:\/\/www.honyaclub.com\/.*$/)) {
    isbn    = /[0-9]{10,13}/.exec(document.querySelectorAll(".item-price")[0].innerHTML);
    context = {service:"honyaclub", isbn:isbn};
  } else if (url.match(/^http[s]{0,1}:\/\/honto.jp\/.*$/)) {
    isbn    = /ISBN：([0-9\-]+)/.exec(document.querySelectorAll(".stItemData")[0].innerHTML)[1].replace(/\-/g, "");
    context = {service:"honto", isbn:isbn};
  }else {
    context = null;
  }

  return context;
};

var insertMovieByService = function (service_name, youtube_id){
  var result;
  var template;

  switch(service_name){
    case "amazon":
      template = _.template('

ビブリオバトル動画
<iframe width="560" height="315" src="//www.youtube.com/embed/<%= youtube_id %>" frameborder="0" allowfullscreen>
');
      document.querySelectorAll(".bucketDivider")[0].insertAdjacentHTML("beforebegin", template({youtube_id: youtube_id}));
      result = true;
      break;
    case "kinokuniya":
      template = _.template('

ビブリオバトル動画
<iframe width="560" height="315" src="//www.youtube.com/embed/<%= youtube_id %>" frameborder="0" allowfullscreen>

');
      document.querySelectorAll(".career_box")[0].insertAdjacentHTML("beforebegin", template({youtube_id: youtube_id}));
      result = true;
      break;
    case "honyaclub":
      template = _.template('
ビブリオバトル動画
<iframe width="560" height="315" src="//www.youtube.com/embed/<%= youtube_id %>" frameborder="0" allowfullscreen>
');
      document.querySelectorAll(".detail-block01")[0].insertAdjacentHTML("beforeend", template({youtube_id: youtube_id}));
      result = true;
      break;
    case "honto":
      template = _.template('

ビブリオバトル動画

<iframe width="560" height="315" src="//www.youtube.com/embed/<%= youtube_id %>" frameborder="0" allowfullscreen>

');
      document.querySelectorAll("#mainArea #area0 .pbNested .pbNestedWrapper")[0].insertAdjacentHTML("afterend", template({youtube_id: youtube_id}));
      result = true;
      break
  }

  return result;
};

// main block
loadSourceData(function (res){
  var context     = extractPageContext();
  var database    = parseTSV(res);

  if(_.isObject(context)){
    var target_isbn = context.isbn;
    var youtube_id = getYoutubeID(database, target_isbn);

    if (_.isString(youtube_id)){
      insertMovieByService(context.service, youtube_id);
    }

  }

});

})();
<|endoftext|>


<commit_before>'use strict';

var http = require('http');
var Request = require('request');
var Q = require('q');
var zlib = require('zlib');
var busywait = require('busywait').async;
var _ = require('underscore');

var debug = false;

module.exports = Codeine;

function Codeine(server,port,api_key) {
  this.server = server;
  this.api_key = api_key;
  this.port = port;
  this.request = Request.defaults({'headers': { 'api_token' : this.api_key} });
}

function getCodeinePath(self) {
  return 'http://' + self.server + ':' + self.port + '/api-with-token/';
}

Codeine.prototype.setDebug = function(val) {
  debug = val;
};

Codeine.prototype.getProjects = function() {
  var deferred = Q.defer();
  var uri = getCodeinePath(this) + 'projects';
  log('getProjects() - uri is ' + uri);
  this.request({ url : uri, encoding : null }, function (error, response, body) {
    if (!error && response && response.statusCode === 200) {
      var projects = JSON.parse(body);
      deferred.resolve(projects);
    }
    else {
      log('getProjects() - Error is', error);
      if (response && response.statusCode) {
        console.error('codeine:: getProjects() - Status Code =  ' + response.statusCode);
      }
      deferred.reject(error);
    }
  });
  return deferred.promise;
};

Codeine.prototype.createNewProject = function(projectName, selectedProject) {
  var deferred = Q.defer();
  var uri = getCodeinePath(this) + 'projects';
  log('createNewProject() - uri is ' + uri);
  this.request(createNewProjectCommand(uri,this.api_key,projectName,selectedProject), function (error, response, body) {
    if (!error && response && response.statusCode === 200) {
      deferred.resolve(body);
    }
    else {
      log('createNewProject() - Error is', error);
      if (response && response.statusCode) {
        console.error('codeine:: createNewProject() - Status Code =  ' + response.statusCode);
      }
      deferred.reject(error);
    }
  });
  return deferred.promise;
};

Codeine.prototype.runCommand = function(projectName, commandObject){
  var deferred = Q.defer();
  var runCommandOptions = createCodeineRunCommand(this.server,projectName,this.api_key, this.port);
  log('runCommand() - command object ', runCommandOptions);
  var post_data = JSON.stringify(commandObject);
  log('runCommand() - post data is ' + post_data);
  var commandReq = http.request(runCommandOptions, function(res) {
    res.setEncoding('utf8');

    if (res.statusCode === 200) {
      log('runCommand() - Command ran successfully');
    }
    else {
      console.error('codeine:: runCommand() - Status Code =  ' + res.statusCode);
      deferred.reject();
    }
    res.on('data', function (chunk) {
      log('Response: ', chunk);
      deferred.resolve(chunk);
    });
  });
  commandReq.write(post_data);
  commandReq.on('error', function(e) {
    console.error('codeine:: runCommand() - Error from server', e);
    deferred.reject(e);
  });
  commandReq.end();
  return deferred.promise;
};

Codeine.prototype.runCommandSync = function (projectName, commandObject, sleep, times) {
  var scope = this;
  log('runCommandSync() - Running command', commandObject.command_info.name);
  return this.runCommand(projectName, commandObject)
      .then(function (commandId) {
        log('runCommandSync() - Waiting for command', commandId, 'to finish');
        function check(iteration) {
          log('runCommandSync() - waiting for command', commandId, 'to finish.' +
              ' Iteration:', iteration);
          return scope.getCommandStatusJson(projectName, commandId, false)
              .then(function (res) {
                var skip_list = res.skip_list || [];
                var processedNodes = res.fail_list.length + res.success_list.length + skip_list.length;
                  if (res.finished && processedNodes === res.nodes_list.length) {
                      return _.map(res.fail_list.concat(skip_list), function (node) {
                          return node.name;
                      });
                  } else {
                      return Q.reject('not finished yet');
                  }
              });
        }
        return busywait(check, {sleepTime: sleep,maxChecks: times,
            failMsg: 'Command is not complete after timeout'})
            .then(function (result) {
              var failedNodes = result.result;
              if (failedNodes.length > 0) {
                return Q.reject("Failed running command on " + failedNodes);
              }
              log('runCommandSync() - Command', commandId, 'finished successfully');
            });
      });
};

Codeine.prototype.getProjectNodes = function(projectName, filter) {
  var deferred = Q.defer();
  var uri = getCodeinePath(this) + 'project-nodes?project='+ projectName;
  log('getProjectNodes() - uri is ' + uri);
  this.request({ url : uri, encoding : null }, function (error, response, body) {
    if (!error && response && response.statusCode === 200) {
      zlib.gunzip(body, function(err, decoded) {
        if (err) {
          console.error('codeine:: getProjectNodes() - Error during gzip', err);
          deferred.reject(err);
        }
        else {
          var projectNodes = JSON.parse(decoded);
          if (filter) {
            projectNodes = _.filter(projectNodes, function(node) { return filter(node);});
          }
          deferred.resolve(projectNodes);
        }
      });
    }
    else {
      log('getProjectNodes() - Error is', error);
      if (response && response.statusCode) {
        console.error('codeine:: getProjectNodes() - Status Code =  ' + response.statusCode);
      }
      deferred.reject(error);
    }
  });
  return deferred.promise;
};

Codeine.prototype.getProjectConfiguration = function(projectName) {
  var deferred = Q.defer();
  var uri = getCodeinePath(this) + 'project-configuration?project='+ projectName;
  log('getProjectConfiguration() - uri is ' + uri);
  this.request({ url : uri, encoding : null }, function (error, response, body) {
    if (!error && response && response.statusCode === 200) {
      var config = JSON.parse(body);
      deferred.resolve(config);
    }
    else {
      log('getProjectConfiguration() - Error is', error);
      if (response && response.statusCode) {
        console.error('codeine:: getProjectConfiguration() - Status Code =  ' + response.statusCode);
      }
      deferred.reject(error);
    }
  });
  return deferred.promise;
};

Codeine.prototype.getProjectCommandsConfiguration = function(projectName) {
  var deferred = Q.defer();
  var uri = getCodeinePath(this) + 'project-commands-configuration?project='+ projectName;
  log('getProjectCommandsConfiguration() - uri is ' + uri);
  this.request({ url : uri, encoding : null }, function (error, response, body) {
    if (!error && response && response.statusCode === 200) {
      var config = JSON.parse(body);
      deferred.resolve(config);
    }
    else {
      log('getProjectCommandsConfiguration() - Error is', error);
      if (response && response.statusCode) {
        console.error('codeine:: getProjectCommandsConfiguration() - Status Code =  ' + response.statusCode);
      }
      deferred.reject(error);
    }
  });
  return deferred.promise;
};

Codeine.prototype.getProjectStatus = function(projectName) {
  var deferred = Q.defer();
  var uri = getCodeinePath(this) + 'project-status2?project='+ projectName;
  log('getProjectStatus() - uri is ' + uri);
  this.request({ url : uri, encoding : null }, function (error, response, body) {
    if (!error && response && response.statusCode === 200) {
      var config = JSON.parse(body);
      deferred.resolve(config);
    }
    else {
      log('getProjectStatus() - Error is', error);
      if (response && response.statusCode) {
        console.error('codeine:: getProjectStatus() - Status Code =  ' + response.statusCode);
      }
      deferred.reject(error);
    }
  });
  return deferred.promise;
};

Codeine.prototype.saveProjectConfiguration = function(projectName, conf) {
  var deferred = Q.defer();
  var saveConfCommandOptions = createSaveConfCommand(this.server, projectName, this.api_key, this.port);
  var post_data = JSON.stringify(conf);
  log('saveProjectConfiguration() - post data is ', post_data);
  var commandReq = http.request(saveConfCommandOptions, function(res) {
    res.setEncoding('utf8');
    if (res.statusCode === 200) {
      log('saveProjectConfiguration() - Configuration was saved successfully');
    }
    else {
      console.error('coeine:: saveProjectConfiguration() - Status Code =  ' + res.statusCode);
      deferred.reject();
    }
    res.on('data', function (chunk) {
      log('Response: ', chunk);
      deferred.resolve(chunk);
    });
  });
  commandReq.write(post_data);
  commandReq.on('error', function(e) {
    console.error('codeine:: saveProjectConfiguration() - Error from server', e);
    deferred.reject(e);
  });
  commandReq.end();
  return deferred.promise;
};

Codeine.prototype.getCommandStatus = function(projectName, commandId, includeOutput) {
  var uri = getCodeinePath(this) + 'command-status?command=' + commandId + '&project='+ projectName;
  if (includeOutput !== undefined && includeOutput === false) {
    uri += '&output=false';
  }
  log('getCommandStatus() - uri is ' + uri);
  return this.request({ url : uri, encoding : null }).pipe(zlib.createGunzip());
};

Codeine.prototype.getCommandStatusJson = function(projectName, commandId, includeOutput) {
  var deferred = Q.defer();
  var stream = this.getCommandStatus(projectName,commandId,includeOutput);
  var chunks = [];
  stream.on("data", function (chunk) {
    chunks.push(chunk);
  });
  stream.on("end", function () {
    deferred.resolve(JSON.parse(Buffer.concat(chunks).toString()));
  });
  stream.on("error", function (err) {
    deferred.reject(err);
  });
  return deferred.promise;
};

Codeine.prototype.getCommandOutput = function(projectName, commandId) {
  var uri = getCodeinePath(this) + 'command-output?command-id=' + commandId + '&project='+ projectName;
  log('getCommandOutput() - uri is ' + uri);
  return this.request({ url : uri, encoding : null });
};

function createNewProjectCommand(url,api_token,projectName,selectedProject) {
  var requestData = {
    'project_name': projectName,
    'type': 'New'
  };
  if (selectedProject) {
    requestData.type = 'Copy';
    requestData.selected_project = selectedProject;
  }
  return {
    url: url,
    encoding: null,
    headers  : {
      'api_token' : api_token
    },
    method: 'POST',
    body: JSON.stringify(requestData)
  };
}

function createSaveConfCommand(server,project,api_token,port) {
  return {
    hostname: server,
    headers  : {'api_token' : api_token} ,
    port: port,
    path: '/api-with-token/project-configuration?project=' + project,
    method: 'PUT'
  };
}

function createCodeineRunCommand(server,project,api_token,port) {
  return {
    hostname: server,
    headers  : {'api_token' : api_token} ,
    port: port,
    path: '/api-with-token/command-nodes?project=' + project,
    method: 'POST'
  };
}

function log() {
  if (debug) {
    console.log.apply(undefined,arguments);
  }
}
<commit_msg>add ability to return output of sync command (#11)<commit_after>'use strict';

var http = require('http');
var Request = require('request');
var Q = require('q');
var zlib = require('zlib');
var busywait = require('busywait').async;
var _ = require('underscore');

var debug = false;

module.exports = Codeine;

function Codeine(server,port,api_key) {
  this.server = server;
  this.api_key = api_key;
  this.port = port;
  this.request = Request.defaults({'headers': { 'api_token' : this.api_key} });
}

function getCodeinePath(self) {
  return 'http://' + self.server + ':' + self.port + '/api-with-token/';
}

Codeine.prototype.setDebug = function(val) {
  debug = val;
};

Codeine.prototype.getProjects = function() {
  var deferred = Q.defer();
  var uri = getCodeinePath(this) + 'projects';
  log('getProjects() - uri is ' + uri);
  this.request({ url : uri, encoding : null }, function (error, response, body) {
    if (!error && response && response.statusCode === 200) {
      var projects = JSON.parse(body);
      deferred.resolve(projects);
    }
    else {
      log('getProjects() - Error is', error);
      if (response && response.statusCode) {
        console.error('codeine:: getProjects() - Status Code =  ' + response.statusCode);
      }
      deferred.reject(error);
    }
  });
  return deferred.promise;
};

Codeine.prototype.createNewProject = function(projectName, selectedProject) {
  var deferred = Q.defer();
  var uri = getCodeinePath(this) + 'projects';
  log('createNewProject() - uri is ' + uri);
  this.request(createNewProjectCommand(uri,this.api_key,projectName,selectedProject), function (error, response, body) {
    if (!error && response && response.statusCode === 200) {
      deferred.resolve(body);
    }
    else {
      log('createNewProject() - Error is', error);
      if (response && response.statusCode) {
        console.error('codeine:: createNewProject() - Status Code =  ' + response.statusCode);
      }
      deferred.reject(error);
    }
  });
  return deferred.promise;
};

Codeine.prototype.runCommand = function(projectName, commandObject){
  var deferred = Q.defer();
  var runCommandOptions = createCodeineRunCommand(this.server,projectName,this.api_key, this.port);
  log('runCommand() - command object ', runCommandOptions);
  var post_data = JSON.stringify(commandObject);
  log('runCommand() - post data is ' + post_data);
  var commandReq = http.request(runCommandOptions, function(res) {
    res.setEncoding('utf8');

    if (res.statusCode === 200) {
      log('runCommand() - Command ran successfully');
    }
    else {
      console.error('codeine:: runCommand() - Status Code =  ' + res.statusCode);
      deferred.reject();
    }
    res.on('data', function (chunk) {
      log('Response: ', chunk);
      deferred.resolve(chunk);
    });
  });
  commandReq.write(post_data);
  commandReq.on('error', function(e) {
    console.error('codeine:: runCommand() - Error from server', e);
    deferred.reject(e);
  });
  commandReq.end();
  return deferred.promise;
};

Codeine.prototype.runCommandSync = function (projectName, commandObject, sleep, times, disableOutput) {
  var scope = this;
  log('runCommandSync() - Running command', commandObject.command_info.name);
  return this.runCommand(projectName, commandObject)
      .then(function (commandId) {
        log('runCommandSync() - Waiting for command', commandId, 'to finish');
        function check(iteration) {
          log('runCommandSync() - waiting for command', commandId, 'to finish.' +
              ' Iteration:', iteration);
          return scope.getCommandStatusJson(projectName, commandId, !!disableOutput)
              .then(function (res) {
                var skip_list = res.skip_list || [];
                var processedNodes = res.fail_list.length + res.success_list.length + skip_list.length;
                  if (res.finished && processedNodes === res.nodes_list.length) {
                      var failedNodes = _.map(res.fail_list.concat(skip_list), function (node) {
                          return node.name;
                      });
                      return {
                          failedNodes: failedNodes,
                          output: res.output
                      }
                  } else {
                      return Q.reject('not finished yet');
                  }
              });
        }
        return busywait(check, {sleepTime: sleep,maxChecks: times,
            failMsg: 'Command is not complete after timeout'})
            .then(function (result) {
              var failedNodes = result.result.failedNodes;
              if (failedNodes.length > 0) {
                return Q.reject(result.result);
              }
              log('runCommandSync() - Command', commandId, 'finished successfully');
              return result.result.output;
            });
      });
};

Codeine.prototype.getProjectNodes = function(projectName, filter) {
  var deferred = Q.defer();
  var uri = getCodeinePath(this) + 'project-nodes?project='+ projectName;
  log('getProjectNodes() - uri is ' + uri);
  this.request({ url : uri, encoding : null }, function (error, response, body) {
    if (!error && response && response.statusCode === 200) {
      zlib.gunzip(body, function(err, decoded) {
        if (err) {
          console.error('codeine:: getProjectNodes() - Error during gzip', err);
          deferred.reject(err);
        }
        else {
          var projectNodes = JSON.parse(decoded);
          if (filter) {
            projectNodes = _.filter(projectNodes, function(node) { return filter(node);});
          }
          deferred.resolve(projectNodes);
        }
      });
    }
    else {
      log('getProjectNodes() - Error is', error);
      if (response && response.statusCode) {
        console.error('codeine:: getProjectNodes() - Status Code =  ' + response.statusCode);
      }
      deferred.reject(error);
    }
  });
  return deferred.promise;
};

Codeine.prototype.getProjectConfiguration = function(projectName) {
  var deferred = Q.defer();
  var uri = getCodeinePath(this) + 'project-configuration?project='+ projectName;
  log('getProjectConfiguration() - uri is ' + uri);
  this.request({ url : uri, encoding : null }, function (error, response, body) {
    if (!error && response && response.statusCode === 200) {
      var config = JSON.parse(body);
      deferred.resolve(config);
    }
    else {
      log('getProjectConfiguration() - Error is', error);
      if (response && response.statusCode) {
        console.error('codeine:: getProjectConfiguration() - Status Code =  ' + response.statusCode);
      }
      deferred.reject(error);
    }
  });
  return deferred.promise;
};

Codeine.prototype.getProjectCommandsConfiguration = function(projectName) {
  var deferred = Q.defer();
  var uri = getCodeinePath(this) + 'project-commands-configuration?project='+ projectName;
  log('getProjectCommandsConfiguration() - uri is ' + uri);
  this.request({ url : uri, encoding : null }, function (error, response, body) {
    if (!error && response && response.statusCode === 200) {
      var config = JSON.parse(body);
      deferred.resolve(config);
    }
    else {
      log('getProjectCommandsConfiguration() - Error is', error);
      if (response && response.statusCode) {
        console.error('codeine:: getProjectCommandsConfiguration() - Status Code =  ' + response.statusCode);
      }
      deferred.reject(error);
    }
  });
  return deferred.promise;
};

Codeine.prototype.getProjectStatus = function(projectName) {
  var deferred = Q.defer();
  var uri = getCodeinePath(this) + 'project-status2?project='+ projectName;
  log('getProjectStatus() - uri is ' + uri);
  this.request({ url : uri, encoding : null }, function (error, response, body) {
    if (!error && response && response.statusCode === 200) {
      var config = JSON.parse(body);
      deferred.resolve(config);
    }
    else {
      log('getProjectStatus() - Error is', error);
      if (response && response.statusCode) {
        console.error('codeine:: getProjectStatus() - Status Code =  ' + response.statusCode);
      }
      deferred.reject(error);
    }
  });
  return deferred.promise;
};

Codeine.prototype.saveProjectConfiguration = function(projectName, conf) {
  var deferred = Q.defer();
  var saveConfCommandOptions = createSaveConfCommand(this.server, projectName, this.api_key, this.port);
  var post_data = JSON.stringify(conf);
  log('saveProjectConfiguration() - post data is ', post_data);
  var commandReq = http.request(saveConfCommandOptions, function(res) {
    res.setEncoding('utf8');
    if (res.statusCode === 200) {
      log('saveProjectConfiguration() - Configuration was saved successfully');
    }
    else {
      console.error('coeine:: saveProjectConfiguration() - Status Code =  ' + res.statusCode);
      deferred.reject();
    }
    res.on('data', function (chunk) {
      log('Response: ', chunk);
      deferred.resolve(chunk);
    });
  });
  commandReq.write(post_data);
  commandReq.on('error', function(e) {
    console.error('codeine:: saveProjectConfiguration() - Error from server', e);
    deferred.reject(e);
  });
  commandReq.end();
  return deferred.promise;
};

Codeine.prototype.getCommandStatus = function(projectName, commandId, includeOutput) {
  var uri = getCodeinePath(this) + 'command-status?command=' + commandId + '&project='+ projectName;
  if (includeOutput !== undefined && includeOutput === false) {
    uri += '&output=false';
  }
  log('getCommandStatus() - uri is ' + uri);
  return this.request({ url : uri, encoding : null }).pipe(zlib.createGunzip());
};

Codeine.prototype.getCommandStatusJson = function(projectName, commandId, includeOutput) {
  var deferred = Q.defer();
  var stream = this.getCommandStatus(projectName,commandId,includeOutput);
  var chunks = [];
  stream.on("data", function (chunk) {
    chunks.push(chunk);
  });
  stream.on("end", function () {
    deferred.resolve(JSON.parse(Buffer.concat(chunks).toString()));
  });
  stream.on("error", function (err) {
    deferred.reject(err);
  });
  return deferred.promise;
};

Codeine.prototype.getCommandOutput = function(projectName, commandId) {
  var uri = getCodeinePath(this) + 'command-output?command-id=' + commandId + '&project='+ projectName;
  log('getCommandOutput() - uri is ' + uri);
  return this.request({ url : uri, encoding : null });
};

function createNewProjectCommand(url,api_token,projectName,selectedProject) {
  var requestData = {
    'project_name': projectName,
    'type': 'New'
  };
  if (selectedProject) {
    requestData.type = 'Copy';
    requestData.selected_project = selectedProject;
  }
  return {
    url: url,
    encoding: null,
    headers  : {
      'api_token' : api_token
    },
    method: 'POST',
    body: JSON.stringify(requestData)
  };
}

function createSaveConfCommand(server,project,api_token,port) {
  return {
    hostname: server,
    headers  : {'api_token' : api_token} ,
    port: port,
    path: '/api-with-token/project-configuration?project=' + project,
    method: 'PUT'
  };
}

function createCodeineRunCommand(server,project,api_token,port) {
  return {
    hostname: server,
    headers  : {'api_token' : api_token} ,
    port: port,
    path: '/api-with-token/command-nodes?project=' + project,
    method: 'POST'
  };
}

function log() {
  if (debug) {
    console.log.apply(undefined,arguments);
  }
}
<|endoftext|>


<commit_before>var ModuleTestWMJSZip = (function(global) {

var _runOnNode = "process" in global;
var _runOnWorker = "WorkerLocation" in global;
var _runOnBrowser = "document" in global;
var JSZip = WMJSZip;
return new Test("WMJSZip", {
        disable:    false,
        browser:    true,
        worker:     true,
        node:       false,
        button:     true,
        both:       true, // test the primary module and secondary module
    }).add([
        test_WMJSZip,
    ]).run().clone();

function test_WMJSZip(test, pass, miss) {
     var zipObj = new JSZip();
     var expected = "R0lGODdhBQAFAIACAAAAAP/eACwAAAAABQAFAAACCIwPkWerClIBADs="
     zipObj.file("smile.gif", expected, {base64: true});
     var base64 = zipObj.generate({DEFLATE: "DEFLATE"});
     var arraybuffer = zipObj.load(base64, {base64: true}).file("smile.gif").asArrayBuffer();
     var reader = new FileReader();
     reader.readAsDataURL(new Blob([arraybuffer], {mimeType:"image/gif"}));
     reader.onloadend = function(ev){
        var actuary = reader.result.replace(/data\:\;base64\,(.+)/, "$1");
        console.log(actuary, expected);
        if (actuary === expected) {
            test.done(pass());
        } else {
            test.done(miss());
        }
     }
}

})((this || 0).self || global);
<commit_msg>little fix<commit_after>var ModuleTestWMJSZip = (function(global) {

var _runOnNode = "process" in global;
var _runOnWorker = "WorkerLocation" in global;
var _runOnBrowser = "document" in global;

return new Test("WMJSZip", {
        disable:    false,
        browser:    true,
        worker:     true,
        node:       false,
        button:     true,
        both:       true, // test the primary module and secondary module
    }).add([
        test_WMJSZip,
    ]).run().clone();

function test_WMJSZip(test, pass, miss) {
     var zipObj = new WMJSZip();
     var expected = "R0lGODdhBQAFAIACAAAAAP/eACwAAAAABQAFAAACCIwPkWerClIBADs="
     zipObj.file("smile.gif", expected, {base64: true});
     var base64 = zipObj.generate({DEFLATE: "DEFLATE"});
     var arraybuffer = zipObj.load(base64, {base64: true}).file("smile.gif").asArrayBuffer();
     var reader = new FileReader();
     reader.readAsDataURL(new Blob([arraybuffer], {mimeType:"image/gif"}));
     reader.onloadend = function(ev){
        var actuary = reader.result.replace(/data\:\;base64\,(.+)/, "$1");
        console.log(actuary, expected);
        if (actuary === expected) {
            test.done(pass());
        } else {
            test.done(miss());
        }
     }
}

})((this || 0).self || global);
<|endoftext|>


<commit_before>var settings = require('../helpers/settings')

var fs = require('fs-extra')
var path = require('path')
var request = require('request')
var url = require('url')

var BING_ROOT = path.join(settings.getGlobalMapsDirectory(), 'Bing')

function prepare(req, res, next) {
  fs.access(BING_ROOT, fs.F_OK | fs.R_OK | fs.W_OK, function(err) {
    if (err && err.code == 'ENOENT') {
      fs.mkdir(BING_ROOT, function(err2) {
        next(err);
      });
    } else
      next(err);
  });
}

function handleProxy(req, res) {
  var tileUrl = decodeURIComponent(req.param('url'))
  var fileName = tileUrl.match(/\/([^\/]*.jpe?g)/)[1]
  var pathName = path.join(BING_ROOT, fileName)
  try {
    var stats = fs.statSync(pathName)
    if (stats.size < 100) {
      fs.unlinkSync(pathName)
      throw new Error('Found truncated file')
    }
    var stream = fs.createReadStream(pathName)
    console.log('cached: ' + pathName)
    stream.pipe(res)
  } catch (err) {
    console.log('downloading: ' + fileName)
    try{
      var r = request
        .get({
          timeout: 10000,
          uri: tileUrl
        })
        .on('error', function (fetch_err) {
          console.log(fetch_err)
          res.status(500)
        })
      try {
        cachefile = fs.createWriteStream(pathName)
        r.pipe(cachefile)
      } catch (err) {
        console.log('error saving tile, streaming it anyway')
        console.log(err)
      }
      r.pipe(res)
    } catch (err) {
      console.log('error saving or streaming tile')
      console.log(err)
    }
  }
}

function handleMetadata(req, res) {
  var metadataUrl = decodeURIComponent(req.param('url'))
  request
    .get(metadataUrl)
    .on('error', function (fetch_err) {
      console.log("Could not fetch metadata. Sending fake Bing metadata.")
      var parsedMetadataUrl = url.parse(metadataUrl, true)
      var cbid = parsedMetadataUrl.query.jsonp
      var metadata = fs.readFileSync(path.join(path.dirname(__dirname), 'application', 'offline-metadata.js'), 'utf8')
      res.send(metadata.replace('_bing_metadata_mapfilter',cbid))
    })
    .pipe(res)
}

module.exports = {
  prepare: prepare,
  proxy: handleProxy,
  metadata: handleMetadata
}
<commit_msg>Add stream error handlers to bing-proxy<commit_after>var settings = require('../helpers/settings')

var fs = require('fs-extra')
var path = require('path')
var request = require('request')
var url = require('url')

var BING_ROOT = path.join(settings.getGlobalMapsDirectory(), 'Bing')

function prepare (req, res, next) {
  fs.access(BING_ROOT, fs.F_OK | fs.R_OK | fs.W_OK, function (err) {
    if (err && err.code === 'ENOENT') {
      fs.mkdir(BING_ROOT, function (err2) {
        next(err)
      })
    } else {
      next(err)
    }
  })
}

function handleError (err) {
  console.log('Stream error')
  console.log(err)
}

function handleProxy (req, res) {
  var tileUrl = decodeURIComponent(req.param('url'))
  var fileName = tileUrl.match(/\/([^\/]*.jpe?g)/)[1]
  var pathName = path.join(BING_ROOT, fileName)
  try {
    var stats = fs.statSync(pathName)
    if (stats.size < 100) {
      fs.unlinkSync(pathName)
      throw new Error('Found truncated file')
    }
    var stream = fs.createReadStream(pathName)
    stream.on('error', handleError)
    console.log('cached: ' + pathName)
    stream.pipe(res)
  } catch (err) {
    console.log('downloading: ' + fileName)
    try {
      var r = request
        .get({
          timeout: 10000,
          uri: tileUrl
        })
        .on('error', function (fetch_err) {
          console.log(fetch_err)
          res.status(500)
        })
      try {
        var cachefile = fs.createWriteStream(pathName)
        cachefile.on('error', handleError)
        r.pipe(cachefile)
      } catch (err) {
        console.log('error saving tile, streaming it anyway')
        console.log(err)
      }
      r.pipe(res)
    } catch (err) {
      console.log('error saving or streaming tile')
      console.log(err)
    }
  }
}

function handleMetadata (req, res) {
  var metadataUrl = decodeURIComponent(req.param('url'))
  request
    .get(metadataUrl)
    .on('error', function (fetch_err) {
      console.log('Could not fetch metadata. Sending fake Bing metadata.')
      var parsedMetadataUrl = url.parse(metadataUrl, true)
      var cbid = parsedMetadataUrl.query.jsonp
      var metadata = fs.readFileSync(path.join(path.dirname(__dirname), 'application', 'offline-metadata.js'), 'utf8')
      res.send(metadata.replace('_bing_metadata_mapfilter', cbid))
    })
    .pipe(res)
}

module.exports = {
  prepare: prepare,
  proxy: handleProxy,
  metadata: handleMetadata
}
<|endoftext|>