<commit_before>/*jslint browser: true, nomen: true */

(function (flow, _, Backbone, d3, girder) {
    "use strict";

    // The main app view
    flow.App = Backbone.View.extend({
        el: 'body',

        types: ['table', 'tree', 'string', 'image', 'r'],

        visualizationDescriptors: [
            {
                name: "table",
                inputs: [{name: "data", type: "table", format: "rows"}]
            },
            {
                name: "timeline",
                inputs: [
                    {name: "data", type: "table", format: "rows"},
                    {name: "date", type: "json", "default": {format: "inline", data: {"field": "Date"}}},
                    {name: "y", type: "json", "default": {format: "inline", data: [{"field": "y"}]}}
                ]
            },
            {
                name: "dendrogram",
                inputs: [
                    {name: "data", type: "tree", format: "nested"},
                    {name: "distance", type: "json", "default": {format: "inline", data: {"field": "edge_data.weight"}}},
                    {name: "lineStyle", type: "string", domain: ["axisAligned", "curved"]},
                    {name: "orientation", type: "string", domain: ["horizontal", "vertical"]}
                ]
            },
            {
                name: "image",
                inputs: [
                    {name: "data", type: "image", format: "png.base64"}
                ]
            },
            {
                name: "treeHeatmap",
                inputs: [
                    {
                        name: "tree",
                        type: "tree",
                        format: "vtktree.serialized",
                        dataIsURI: true
                    },
                    {
                        name: "table",
                        type: "table",
                        format: "vtktable.serialized",
                        dataIsURI: true
                    }
                ]
            }
        ],

        events: {
            'click #login': function () {
                girder.events.trigger('g:loginUi');
            },

            'click #logout': function () {
                girder.restRequest({
                    path: 'user/authentication',
                    type: 'DELETE'
                }).done(_.bind(function () {
                    girder.currentUser = null;
                    girder.events.trigger('g:login');
                }, this));
            },

            'click #register': function () {
                girder.events.trigger('g:registerUi');
            }
        },

        initialize: function () {
            girder.restRequest({
                path: 'user/authentication',
                error: null
            }).done(_.bind(function (resp) {
                resp.user.token = resp.authToken.token;
                girder.currentUser = new girder.models.UserModel(resp.user);
                this.render();
            }, this)).error(_.bind(function () {
                this.render();
            }, this));

            this.$("#control-panel").controlPanel();

            this.collection = new girder.collections.CollectionCollection();
            this.collection.append = false;
            this.collection.pageLimit = 100;
            this.collection.fetch();

            this.view = new flow.CollectionsView({el: this.$('#collections'), itemView: flow.CollectionView, collection: this.collection});
            this.view.on('flow:change-active', this.collectionVisibilityChange, this);
            this.view.render();

            this.datasets = new flow.DatasetCollection();
            this.datasets.append = true;
            this.datasets.pageLimit = 100;
            this.datasetsView = new flow.DatasetManagementView({el: this.$('#dataset-management'), datasets: this.datasets});
            this.datasetsView.render();

            this.analyses = new girder.collections.ItemCollection();
            this.analyses.append = true;
            this.analyses.pageLimit = 100;
            this.analysesView = new flow.AnalysisManagementView({el: this.$('#analysis-management'), analyses: this.analyses, datasets: this.datasets});
            this.analysesView.render();

            this.visualizations = new Backbone.Collection(this.visualizationDescriptors);
            this.visualizationsView = new flow.VisualizationManagementView({el: this.$('#visualization-management'), visualizations: this.visualizations, datasets: this.datasets});
            this.visualizationsView.render();

            girder.events.on('g:loginUi', this.loginDialog, this);
            girder.events.on('g:registerUi', this.registerDialog, this);
            girder.events.on('g:login', this.login, this);
        },

        render: function () {
            if (girder.currentUser) {
                this.$("#logged-in").removeClass("hidden");
                this.$("#logged-out").addClass("hidden");
                this.$("#name").text("Logged in as " + girder.currentUser.get('firstName') + " " + girder.currentUser.get('lastName'));
            } else {
                this.$("#logged-in").addClass("hidden");
                this.$("#logged-out").removeClass("hidden");
            }
        },

        /**
         * Show a dialog allowing a user to login or register.
         */
        loginDialog: function () {
            if (!this.loginView) {
                this.loginView = new girder.views.LoginView({
                    el: this.$('#g-dialog-container')
                });
            }
            this.loginView.render();
        },

        registerDialog: function () {
            if (!this.registerView) {
                this.registerView = new girder.views.RegisterView({
                    el: this.$('#g-dialog-container')
                });
            }
            this.registerView.render();
        },

        collectionVisibilityChange: function (collection) {
            if (collection.get('active')) {
                d3.json(girder.apiRoot + '/folder?parentType=collection&parentId=' + collection.id, _.bind(function (error, folders) {
                    folders.forEach(function (f) {
                        if (f.name === "Analyses") {
                            collection.set({analysisFolder: f._id});
                        } else if (f.name === "Data") {
                            collection.set({dataFolder: f._id});
                        }
                    });

                    if (collection.get('analysisFolder')) {
                        this.analyses.offset = 0;
                        this.analyses.off('add', null, this).on('add', function (analysis) {
                            analysis.set({collection: collection});
                        }, this).fetch({
                            folderId: collection.get('analysisFolder')
                        });
                    }

                    if (collection.get('dataFolder')) {
                        this.datasets.offset = 0;
                        this.datasets.off('add', null, this).on('add', function (dataset) {
                            dataset.set({collection: collection});
                        }, this).fetch({
                            folderId: collection.get('dataFolder')
                        });
                    }
                }, this));
            } else {
                this.analyses.remove(this.analyses.where({collection: collection}));
                this.datasets.remove(this.datasets.where({collection: collection}));
            }
        },

        login: function () {
            this.render();
            this.collection.fetch({}, true);
        }
    });

}(window.flow, window._, window.Backbone, window.d3, window.girder));
<commit_msg>Set context for adding datasets<commit_after>/*jslint browser: true, nomen: true */

(function (flow, _, Backbone, d3, girder) {
    "use strict";

    // The main app view
    flow.App = Backbone.View.extend({
        el: 'body',

        types: ['table', 'tree', 'string', 'image', 'r'],

        visualizationDescriptors: [
            {
                name: "table",
                inputs: [{name: "data", type: "table", format: "rows"}]
            },
            {
                name: "timeline",
                inputs: [
                    {name: "data", type: "table", format: "rows"},
                    {name: "date", type: "json", "default": {format: "inline", data: {"field": "Date"}}},
                    {name: "y", type: "json", "default": {format: "inline", data: [{"field": "y"}]}}
                ]
            },
            {
                name: "dendrogram",
                inputs: [
                    {name: "data", type: "tree", format: "nested"},
                    {name: "distance", type: "json", "default": {format: "inline", data: {"field": "edge_data.weight"}}},
                    {name: "lineStyle", type: "string", domain: ["axisAligned", "curved"]},
                    {name: "orientation", type: "string", domain: ["horizontal", "vertical"]}
                ]
            },
            {
                name: "image",
                inputs: [
                    {name: "data", type: "image", format: "png.base64"}
                ]
            },
            {
                name: "treeHeatmap",
                inputs: [
                    {
                        name: "tree",
                        type: "tree",
                        format: "vtktree.serialized",
                        dataIsURI: true
                    },
                    {
                        name: "table",
                        type: "table",
                        format: "vtktable.serialized",
                        dataIsURI: true
                    }
                ]
            }
        ],

        events: {
            'click #login': function () {
                girder.events.trigger('g:loginUi');
            },

            'click #logout': function () {
                girder.restRequest({
                    path: 'user/authentication',
                    type: 'DELETE'
                }).done(_.bind(function () {
                    girder.currentUser = null;
                    girder.events.trigger('g:login');
                }, this));
            },

            'click #register': function () {
                girder.events.trigger('g:registerUi');
            }
        },

        initialize: function () {
            girder.restRequest({
                path: 'user/authentication',
                error: null
            }).done(_.bind(function (resp) {
                resp.user.token = resp.authToken.token;
                girder.currentUser = new girder.models.UserModel(resp.user);
                this.render();
            }, this)).error(_.bind(function () {
                this.render();
            }, this));

            this.$("#control-panel").controlPanel();

            this.collection = new girder.collections.CollectionCollection();
            this.collection.append = false;
            this.collection.pageLimit = 100;
            this.collection.fetch();

            this.view = new flow.CollectionsView({el: this.$('#collections'), itemView: flow.CollectionView, collection: this.collection});
            this.view.on('flow:change-active', this.collectionVisibilityChange, this);
            this.view.render();

            this.datasets = new flow.DatasetCollection();
            this.datasets.append = true;
            this.datasets.pageLimit = 100;
            this.datasetsView = new flow.DatasetManagementView({el: this.$('#dataset-management'), datasets: this.datasets});
            this.datasetsView.render();

            this.analyses = new girder.collections.ItemCollection();
            this.analyses.append = true;
            this.analyses.pageLimit = 100;
            this.analysesView = new flow.AnalysisManagementView({el: this.$('#analysis-management'), analyses: this.analyses, datasets: this.datasets});
            this.analysesView.render();

            this.visualizations = new Backbone.Collection(this.visualizationDescriptors);
            this.visualizationsView = new flow.VisualizationManagementView({el: this.$('#visualization-management'), visualizations: this.visualizations, datasets: this.datasets});
            this.visualizationsView.render();

            girder.events.on('g:loginUi', this.loginDialog, this);
            girder.events.on('g:registerUi', this.registerDialog, this);
            girder.events.on('g:login', this.login, this);
        },

        render: function () {
            if (girder.currentUser) {
                this.$("#logged-in").removeClass("hidden");
                this.$("#logged-out").addClass("hidden");
                this.$("#name").text("Logged in as " + girder.currentUser.get('firstName') + " " + girder.currentUser.get('lastName'));
            } else {
                this.$("#logged-in").addClass("hidden");
                this.$("#logged-out").removeClass("hidden");
            }
        },

        /**
         * Show a dialog allowing a user to login or register.
         */
        loginDialog: function () {
            if (!this.loginView) {
                this.loginView = new girder.views.LoginView({
                    el: this.$('#g-dialog-container')
                });
            }
            this.loginView.render();
        },

        registerDialog: function () {
            if (!this.registerView) {
                this.registerView = new girder.views.RegisterView({
                    el: this.$('#g-dialog-container')
                });
            }
            this.registerView.render();
        },

        collectionVisibilityChange: function (collection) {
            if (collection.get('active')) {
                d3.json(girder.apiRoot + '/folder?parentType=collection&parentId=' + collection.id, _.bind(function (error, folders) {
                    folders.forEach(function (f) {
                        if (f.name === "Analyses") {
                            collection.set({analysisFolder: f._id});
                        } else if (f.name === "Data") {
                            collection.set({dataFolder: f._id});
                        }
                    });

                    if (collection.get('analysisFolder')) {
                        this.analyses.offset = 0;
                        this.analyses.off('add', null, this).on('add', function (analysis) {
                            analysis.set({collection: collection});
                        }, this).fetch({
                            folderId: collection.get('analysisFolder')
                        });
                    }

                    if (collection.get('dataFolder')) {
                        this.datasets.offset = 0;
                        this.datasets.off('add', null, 'set-collection').on('add', function (dataset) {
                            dataset.set({collection: collection});
                        }, 'set-collection').fetch({
                            folderId: collection.get('dataFolder')
                        });
                    }
                }, this));
            } else {
                this.analyses.remove(this.analyses.where({collection: collection}));
                this.datasets.remove(this.datasets.where({collection: collection}));
            }
        },

        login: function () {
            this.render();
            this.collection.fetch({}, true);
        }
    });

}(window.flow, window._, window.Backbone, window.d3, window.girder));
<|endoftext|>


<commit_before>/*
 * Validator for AST nodes
 * @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com)
 * @lastmodifiedDate 2015-08-03
 */
function ASTValidator() {
}

/**
 * Check for the node is a valid AST node or not
 * @param   {Object}  node      AST node
 * @param   {Object}  [options] Option object
 * @returns {boolean} True if it's valid, false otherwise
 */
ASTValidator.prototype.check = function (node, options) {
    'use strict';
    if (!!options) {
        return (!!node.type) && ((!options.range)? true : node.range) && ((!options.loc)? true : node.loc);
    }
    return (!!node.type);
};

/**
 * Validate for the object is an AST node or not
 * @param {Object} node    AST node
 * @param {Object} options Option object
 * @param {string} msg     Custom error message
 * @throws "Not an AST node"
 */
ASTValidator.prototype.validate = function (node, options, msg) {
    'use strict';
    if (!this.check(node, options)) {
        throw new Error(msg || 'Not an AST node');
    }
};

var validator = new ASTValidator();
module.exports = validator;
<commit_msg>Add a checker method for the AST of a page<commit_after>/*
 * Validator for AST nodes
 * @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com)
 * @lastmodifiedDate 2015-08-03
 */
function ASTValidator() {
}

/**
 * Check for the node is a valid AST node or not
 * @param   {Object}  node      AST node
 * @param   {Object}  [options] Option object
 * @returns {boolean} True if it's valid, false otherwise
 */
ASTValidator.prototype.check = function (node, options) {
    'use strict';
    if (!!options) {
        return (!!node.type) && ((!options.range)? true : node.range) && ((!options.loc)? true : node.loc);
    }
    return (!!node.type);
};

/**
 * Validate for the object is an AST node or not
 * @param {Object} node    AST node
 * @param {Object} options Option object
 * @param {string} msg     Custom error message
 * @throws "Not an AST node"
 */
ASTValidator.prototype.validate = function (node, options, msg) {
    'use strict';
    if (!this.check(node, options)) {
        throw new Error(msg || 'Not an AST node');
    }
};

/**
 * Check for the AST node is a root of a page
 * @param   {Object}    node   AST node
 * @returns {boolean}   True, if it's, false otherwise
 */
ASTValidator.prototype.isPageAST = function (node) {
	"use strict";
	return this.check(node) && node.type === 'Program';
};

var validator = new ASTValidator();
module.exports = validator;
<|endoftext|>


<commit_before>/*
 Author:     Maxime Hadjinlian
             maxime.hadjinlian@gmail.com
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
 3. The name of the author may not be used to endorse or promote products
    derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

var tab_array = [];
var forbidden_url = ["chrome://", "chrome-extension://", "chrome-devtools://"];
var TIMEOUT_TIMER = 15;
if (localStorage.getItem("timer") !== null)
    TIMEOUT_TIMER = localStorage["timer"];

if (localStorage.getItem("exclude_list") !== null)
    forbidden_url = forbidden_url.concat(localStorage["exclude_list"].split('\n'));

window.addEventListener("storage", update_storage, false);
chrome.alarms.create({periodInMinutes: 1.0});

// When users changes the options, update the timer value
function update_storage(event_storage) {
    if (event_storage.key !== "timer") return;
    TIMEOUT_TIMER = event_storage.new_value;
}

// Returns true if a url is forbidden, false otherwise
function is_forbidden(url) {
    var found = false;
    forbidden_url.forEach(function(f_url) {
        if (url.indexOf(f_url) !== -1)
            found = true;
    });
    return found;
}

function findById(source, id) {
    return source.filter(function( obj ) {
        // coerce both obj.id and id to numbers
        // for val & type comparison
        return +obj.id === +id;
    })[ 0 ];
}

// On startup, get all tabs already created
chrome.windows.getAll({populate: true}, function (windows){
    windows.forEach(function(cwindow) {
        cwindow.tabs.forEach(function(tab) {
            if (is_forbidden(tab.url) == true) return;
            tab_array.push({id: tab.id, timer: 0, killed: false });
        });
    });
});

// When a tab gets a suitable URL and is not already in our array, add it.
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    var new_tab = findById(tab_array, tabId);
    if (is_forbidden(tab.url) == true){
        // Tab does not exists
        if ( typeof new_tab === "undefined") return;
        // If the tab exists, we should remove it.
        var idx_removed = tab_array.indexOf(new_tab);
        tab_array.splice(idx_removed, 1);
        return;
    }
    // If the tab is not already in our array, add it.
    if ( typeof new_tab !== "undefined") return;
    tab_array.push({id: tabId, timer: 0, killed: false });
});

// Every time a tab is activated, its timer must be reset.
chrome.tabs.onActivated.addListener(function(activeInfo) {
    var activated_tab = findById(tab_array, activeInfo.tabId);
    if ( typeof activated_tab === "undefined") return;
    activated_tab.timer = 0;
    if (activated_tab.killed){
        // Reload the killed tab, since its activated
        chrome.tabs.reload(activated_tab.id);
        activated_tab.killed = false;
    }
});

// Remove the tab from tab_array
chrome.tabs.onRemoved.addListener(function(tabId, removeInfo) {
    var removed = findById(tab_array, tabId);
    var idx_removed = tab_array.indexOf(removed);
    if(idx_removed != -1) {
        tab_array.splice(idx_removed, 1);
    }
});

chrome.alarms.onAlarm.addListener(function() {
    // Loop through each tab, to increment its timer
    tab_array.forEach( function(tab) {
        chrome.tabs.get(tab.id, function(ctab) {
            // Do not update the timer of the active tab
            // or if the tab is already marked as killed.
            if (ctab.active || tab.killed) return;
            tab.timer += 1;
            // If the tab's timer has gone out, kill it.
            if (tab.timer >= TIMEOUT_TIMER) {
                chrome.experimental.processes.getProcessIdForTab(tab.id, function(processId) {
                    chrome.experimental.processes.terminate(processId);
                });
                tab.killed = true;
            }
        });
    });
});

<commit_msg>Reload forbidden_url array on save<commit_after>/*
 Author:     Maxime Hadjinlian
             maxime.hadjinlian@gmail.com
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
 3. The name of the author may not be used to endorse or promote products
    derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

var tab_array = [];
var FORBIDDEN_URL_ORIG = ["chrome://", "chrome-extension://", "chrome-devtools://"];
var FORBIDDEN_URL = FORBIDDEN_URL_ORIG;
var TIMEOUT_TIMER = 15;
if (localStorage.getItem("timer") !== null)
    TIMEOUT_TIMER = localStorage["timer"];

if (localStorage.getItem("exclude_list") !== null)
    FORBIDDEN_URL = FORBIDDEN_URL_ORIG.concat(localStorage["exclude_list"].split('\n'));

window.addEventListener("storage", update_storage, false);
chrome.alarms.create({periodInMinutes: 1.0});

// When users changes the options, update the timer value
function update_storage(event_storage) {
    if (event_storage.key === "timer") {
        TIMEOUT_TIMER = event_storage.newValue;
    } else if (event_storage.key === "exclude_list") {
        if (event_storage.newValue === "") {
            FORBIDDEN_URL = FORBIDDEN_URL_ORIG;
            return;
        }
        FORBIDDEN_URL = FORBIDDEN_URL_ORIG.concat(event_storage.newValue.split('\n'));
    }
}

// Returns true if a url is forbidden, false otherwise
function is_forbidden(url) {
    var found = false;
    FORBIDDEN_URL.forEach(function(f_url) {
        if (url.indexOf(f_url) !== -1) found = true;
    });
    return found;
}

function findById(source, id) {
    return source.filter(function( obj ) {
        // coerce both obj.id and id to numbers
        // for val & type comparison
        return +obj.id === +id;
    })[ 0 ];
}

// On startup, get all tabs already created
chrome.windows.getAll({populate: true}, function (windows){
    windows.forEach(function(cwindow) {
        cwindow.tabs.forEach(function(tab) {
            if (is_forbidden(tab.url) == true) return;
            tab_array.push({id: tab.id, timer: 0, killed: false });
        });
    });
});

// When a tab gets a suitable URL and is not already in our array, add it.
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    var new_tab = findById(tab_array, tabId);
    if (is_forbidden(tab.url) == true){
        // Tab does not exists
        if ( typeof new_tab === "undefined") return;
        // If the tab exists, we should remove it.
        var idx_removed = tab_array.indexOf(new_tab);
        tab_array.splice(idx_removed, 1);
        return;
    }
    // If the tab is not already in our array, add it.
    if ( typeof new_tab !== "undefined") return;
    tab_array.push({id: tabId, timer: 0, killed: false });
});

// Every time a tab is activated, its timer must be reset.
chrome.tabs.onActivated.addListener(function(activeInfo) {
    var activated_tab = findById(tab_array, activeInfo.tabId);
    if ( typeof activated_tab === "undefined") return;
    activated_tab.timer = 0;
    if (activated_tab.killed){
        // Reload the killed tab, since its activated
        chrome.tabs.reload(activated_tab.id);
        activated_tab.killed = false;
    }
});

// Remove the tab from tab_array
chrome.tabs.onRemoved.addListener(function(tabId, removeInfo) {
    var removed = findById(tab_array, tabId);
    var idx_removed = tab_array.indexOf(removed);
    if(idx_removed != -1) {
        tab_array.splice(idx_removed, 1);
    }
});

chrome.alarms.onAlarm.addListener(function() {
    // Loop through each tab, to increment its timer
    tab_array.forEach( function(tab) {
        chrome.tabs.get(tab.id, function(ctab) {
            // Do not update the timer of the active tab
            // or if the tab is already marked as killed.
            if (ctab.active || tab.killed) return;
            tab.timer += 1;
            // If the tab's timer has gone out, kill it.
            if (tab.timer >= TIMEOUT_TIMER) {
                chrome.experimental.processes.getProcessIdForTab(tab.id, function(processId) {
                    chrome.experimental.processes.terminate(processId);
                });
                tab.killed = true;
            }
        });
    });
});

<|endoftext|>


<commit_before>// extend Entity with an element that can hold children entities
var Entity = require('./entity.js')
var GroupedEntity = require('./entity-grouped.js')

class AppendableEntity extends Entity{
  constructor (command,...args){
    super(command,...args)
    //add a place to put children items
    this.children = new GroupedEntity()
  }
  // append a child
  append(child){
    // check that child is actually a Entity
    if(typeof child === 'undefined' || !child instanceof Entity) {
      throw new Error('Invalid child element.')
    }
    // it's all gravy - append the child
    this.children.append(child)
    return child
  }
  render (indent = '',depth = 0){
    // render the children element
    let children = this.children.render(indent, depth+1)
    // render this entity
    if(children !== ''){
      // calcultate brace indent
      let braceIndent = indent.repeat(depth)
      children = '\n' + braceIndent + '{\n' + children + '\n'+ braceIndent + '}'
    }
    return super.render(indent,depth) + children
  }
}

module.exports = AppendableEntity
<commit_msg>Expanded functionality (include, comment, direct append)<commit_after>// extend Entity with an element that can hold children entities
var Entity = require('./entity.js')
var GroupedEntity = require('./entity-grouped.js')
var CommentEntity = require('./entity-comment.js')
var IncludeEntity = require('./entity-include.js')

class AppendableEntity extends Entity{
  constructor (command,...args){
    super(command,...args)
    //add a place to put children items
    this.children = new GroupedEntity()
  }
  // append a child
  append(child,...args){
    // support the creation of an AppendableEntity directly
    if( typeof child == 'string'){
      child = new AppendableEntity(child,...args)
    }
    // check that child is actually a Entity
    if(typeof child === 'undefined' || !child instanceof Entity) {
      throw new Error('Invalid child element.')
    }
    // it's all gravy - append the child
    this.children.append(child)
    return child
  }
  // add in a shortcut to add a comment
  comment(text){
    this.children.append(new CommentEntity(text))
    return this
  }
  // add in a shortcut to add an include file
  include(file){
    this.children.append(new IncludeEntity(file))
    return this
  }
  // define how the entity renders
  render (indent = '',depth = 0){
    // render the children element
    let children = this.children.render(indent, depth+1)
    // render this entity
    if(children !== ''){
      // calcultate brace indent
      let braceIndent = indent.repeat(depth)
      children = '\n' + braceIndent + '{\n' + children + '\n'+ braceIndent + '}'
    }
    return super.render(indent,depth) + children
  }
}

module.exports = AppendableEntity
<|endoftext|>


<commit_before>"use strict";

var Camera = require("./camera");

function EntityBoxCamera(entity, width, height, screenCenterX, screenCenterY) {
	this.entity = entity;
	this.screenCenterX = screenCenterX;
	this.screenCenterY = screenCenterY;

	var x = keepPositionInBox(entity.x, entity.width, 0, width, screenCenterX);
	var y = keepPositionInBox(entity.y, entity.height, 0, height, screenCenterY);
	Camera.call(this, x, y, width, height);
}
EntityBoxCamera.prototype = Object.create(Camera.prototype);
EntityBoxCamera.prototype.move = function() {
	this.x = keepPositionInBox(this.entity.x, this.entity.width, this.x, this.width, this.screenCenterX);
	this.y = keepPositionInBox(this.entity.y, this.entity.height, this.y, this.height, this.screenCenterY);
};

function keepPositionInBox(entityPos, entitySize, thisPos, thisSize, offset) {
	var boundsFromCenter = thisSize / 2;
	if (entityPos < thisPos + offset - boundsFromCenter) {
		thisPos = entityPos - offset + boundsFromCenter;
	}
	if (entityPos + entitySize > thisPos + offset + boundsFromCenter) {
		thisPos = entityPos + entitySize - offset - boundsFromCenter;
	}
	return thisPos;
}

module.exports = EntityBoxCamera;
<commit_msg>Add EntityBoxCamera docs.<commit_after>"use strict";

var Camera = require("./camera");

/**
 * A {@link Camera} that tracks an {@link Entity} to keep it onscreen within an invisible box. If the entity moves outside of the invisible box, the camera is adjusted the minimal amount so that the entity is back inside the box.
 * @constructor
 * @param {Entity} entity The entity for the camera to track.
 * @param {number} width The width of the invisible box to keep the {@link Entity} within.
 * @param {number} height The height of the invisible box to keep the {@link Entity} within.
 * @param {number} screenCenterX The center of the invisible box on the screen along the x axis.
 * @param {number} screenCenterY The center of the invisible box on the screen along the y axis.
 * @example
var scene = new Splat.Scene(canvas, function() {
	// initialization
	this.player = new Splat.Entity(200, 200, 50, 50);
	// make a camera that won't let the player closer than 100 pixels to the left and right sides, or 50 pixels from the top or bottom
	this.camera = new Splat.EntityBoxCamera(this.player, canvas.width - 200, canvas.height - 100, canvas.width / 2, canvas.height / 2);
}, function(elapsedMillis) {
	// simulation
}, function(context) {
	// draw
});
 */
function EntityBoxCamera(entity, width, height, screenCenterX, screenCenterY) {
	/**
	 * The {@link Entity} for the camera to track.
	 * @member {Entity}
	 */
	this.entity = entity;
	/**
	 * The center of the invisible box on the screen along the x axis.
	 * @member {number}
	 */
	this.screenCenterX = screenCenterX;
	/**
	 * The center of the invisible box on the screen along the y axis.
	 * @member {number}
	 */
	this.screenCenterY = screenCenterY;

	var x = keepPositionInBox(entity.x, entity.width, 0, width, screenCenterX);
	var y = keepPositionInBox(entity.y, entity.height, 0, height, screenCenterY);
	Camera.call(this, x, y, width, height);
}
EntityBoxCamera.prototype = Object.create(Camera.prototype);
/**
 * Adjust the camera so that it keeps {@link EntityBoxCamera#entity} within the invisible box.
 */
EntityBoxCamera.prototype.move = function() {
	this.x = keepPositionInBox(this.entity.x, this.entity.width, this.x, this.width, this.screenCenterX);
	this.y = keepPositionInBox(this.entity.y, this.entity.height, this.y, this.height, this.screenCenterY);
};

function keepPositionInBox(entityPos, entitySize, thisPos, thisSize, offset) {
	var boundsFromCenter = thisSize / 2;
	if (entityPos < thisPos + offset - boundsFromCenter) {
		thisPos = entityPos - offset + boundsFromCenter;
	}
	if (entityPos + entitySize > thisPos + offset + boundsFromCenter) {
		thisPos = entityPos + entitySize - offset - boundsFromCenter;
	}
	return thisPos;
}

module.exports = EntityBoxCamera;
<|endoftext|>


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

var _ = require('underscore'),
	util = require('util'),
	utils = require('keystone-utils'),
	super_ = require('../field');

/**
 * Select FieldType Constructor
 * @extends Field
 * @api public
 */

function select(list, path, options) {

	this._nativeType = (options.numeric) ? Number : String;
	this._underscoreMethods = ['format'];

	this.ui = options.ui || 'select';

	if (typeof options.options == 'string')
		options.options = options.options.split(',');

	if (!Array.isArray(options.options))
		throw new Error("Select fields require an options array.");

	this.ops = options.options.map(function(i) {
		return ('string' == typeof i) ? { value: i.trim(), label: utils.keyToLabel(i) } : i;
	});

	// if it's a numeric field, ensure all provided values are numbers
	if (options.numeric) {
		for (var i in this.ops) {
			i.value = Number(i.value);
		}
	}

	// undefined options.emptyOption defaults to true
	if (options.emptyOption === undefined) {
		options.emptyOption = true;
	}

	// ensure this.emptyOption is a boolean
	this.emptyOption = options.emptyOption ? true : false;

	// cached maps for options, labels and values
	this.map = utils.optionsMap(this.ops);
	this.labels = utils.optionsMap(this.ops, 'label');
	this.values = _.pluck(this.ops, 'value');

	select.super_.call(this, list, path, options);
}

/*!
 * Inherit from Field
 */

util.inherits(select, super_);

/**
 * Registers the field on the List's Mongoose Schema.
 *
 * Adds a virtual for accessing the label of the selected value,
 * and statics to the Schema for converting a value to a label,
 * and retrieving all of the defined options.
 *
 * @api public
 */

select.prototype.addToSchema = function() {

	var field = this,
		schema = this.list.schema;

	this.paths = {
		data: this.options.dataPath || this._path.append('Data'),
		label: this.options.labelPath || this._path.append('Label'),
		options: this.options.optionsPath || this._path.append('Options'),
		map: this.options.optionsMapPath || this._path.append('OptionsMap')
	};

	schema.path(this.path, _.defaults({
		type: this._nativeType,
		enum: this.values,
		set: function(val) {
			if (val === '')
				return undefined;
			return val;
		}
	}, this.options));

	schema.virtual(this.paths.data).get(function () {
		return field.map[this.get(field.path)];
	});

	schema.virtual(this.paths.label).get(function () {
		return field.labels[this.get(field.path)];
	});

	schema.virtual(this.paths.options).get(function() {
		return field.ops;
	});

	schema.virtual(this.paths.map).get(function() {
		return field.map;
	});

	this.underscoreMethod('pluck', function(property, d) {
		var option = this.get(field.paths.data);
		return (option) ? option[property] : d;
	});

	this.bindUnderscoreMethods();

};

/**
 * Retrieves a shallow clone of the options array
 *
 * @api public
 */

select.prototype.cloneOps = function() {
	return _.map(this.ops, _.clone);
};

/**
 * Retrieves a shallow clone of the options map
 *
 * @api public
 */

select.prototype.cloneMap = function() {
	return utils.optionsMap(this.ops, true);
};

/**
 * Validates that a valid option has been provided in a data object
 *
 * @api public
 */

select.prototype.validateInput = function(data, required, item) {

	if (data[this.path]) {
		return (data[this.path] in this.map) ? true : false;
	} else {
		return (!required || (!(this.path in data) && item && item.get(this.path))) ? true : false;
	}

};

/**
 * Formats the field value
 *
 * @api public
 */

select.prototype.format = function(item) {
	return this.labels[item.get(this.path)];
};

/*!
 * Export class
 */

exports = module.exports = select;
<commit_msg>Cleaning up select.js, inc. linter and other minor issues<commit_after>/*!
 * Module dependencies.
 */

var _ = require('underscore'),
	util = require('util'),
	utils = require('keystone-utils'),
	super_ = require('../field');

/**
 * Select FieldType Constructor
 * @extends Field
 * @api public
 */

function select(list, path, options) {

	this._nativeType = (options.numeric) ? Number : String;
	this._underscoreMethods = ['format'];

	this.ui = options.ui || 'select';

	if (typeof options.options === 'string') {
		options.options = options.options.split(',');
	}

	if (!Array.isArray(options.options)) {
		throw new Error('Select fields require an options array.');
	}

	this.ops = options.options.map(function(i) {
		var op = _.isString(i) ? { value: i.trim(), label: utils.keyToLabel(i) } : i;
		if (!_.isObject(op)) {
			op = { label: ''+i, value: ''+i };
		}
		if (options.numeric && !_.isNumber(op.value)) {
			op.value = Number(op.value);
		}
		return op;
	});

	// undefined options.emptyOption defaults to true
	if (options.emptyOption === undefined) {
		options.emptyOption = true;
	}

	// ensure this.emptyOption is a boolean
	this.emptyOption = options.emptyOption ? true : false;

	// cached maps for options, labels and values
	this.map = utils.optionsMap(this.ops);
	this.labels = utils.optionsMap(this.ops, 'label');
	this.values = _.pluck(this.ops, 'value');

	select.super_.call(this, list, path, options);
}

/*!
 * Inherit from Field
 */

util.inherits(select, super_);

/**
 * Registers the field on the List's Mongoose Schema.
 *
 * Adds a virtual for accessing the label of the selected value,
 * and statics to the Schema for converting a value to a label,
 * and retrieving all of the defined options.
 *
 * @api public
 */

select.prototype.addToSchema = function() {

	var field = this,
		schema = this.list.schema;

	this.paths = {
		data: this.options.dataPath || this._path.append('Data'),
		label: this.options.labelPath || this._path.append('Label'),
		options: this.options.optionsPath || this._path.append('Options'),
		map: this.options.optionsMapPath || this._path.append('OptionsMap')
	};

	schema.path(this.path, _.defaults({
		type: this._nativeType,
		enum: this.values,
		set: function(val) {
			return (val === '') ? undefined : val;
		}
	}, this.options));

	schema.virtual(this.paths.data).get(function () {
		return field.map[this.get(field.path)];
	});

	schema.virtual(this.paths.label).get(function () {
		return field.labels[this.get(field.path)];
	});

	schema.virtual(this.paths.options).get(function() {
		return field.ops;
	});

	schema.virtual(this.paths.map).get(function() {
		return field.map;
	});

	this.underscoreMethod('pluck', function(property, d) {
		var option = this.get(field.paths.data);
		return (option) ? option[property] : d;
	});

	this.bindUnderscoreMethods();

};

/**
 * Retrieves a shallow clone of the options array
 *
 * @api public
 */

select.prototype.cloneOps = function() {
	return _.map(this.ops, _.clone);
};

/**
 * Retrieves a shallow clone of the options map
 *
 * @api public
 */

select.prototype.cloneMap = function() {
	return utils.optionsMap(this.ops, true);
};

/**
 * Validates that a valid option has been provided in a data object
 *
 * @api public
 */

select.prototype.validateInput = function(data, required, item) {

	if (data[this.path]) {
		return (data[this.path] in this.map) ? true : false;
	} else {
		return (!required || (!(this.path in data) && item && item.get(this.path))) ? true : false;
	}

};

/**
 * Formats the field value
 *
 * @api public
 */

select.prototype.format = function(item) {
	return this.labels[item.get(this.path)];
};

/*!
 * Export class
 */

exports = module.exports = select;
<|endoftext|>


<commit_before>/* jshint node: true */

var Promise = require('bluebird');
var orm = require('../../util/orm');
var errors = require('../../errors');

module.exports = {

  // Doit retourner le délai en tours avant l'exécution de l'action
  cooldown:  60 * 1000, // 60s de cooldown

  // Exécute l'action
  execute: Promise.method(function(bot, params) {

    var Sector = orm.model('Sector');

    // On effectue toutes les opérations dans une transaction
    return orm.transaction(function(trx) {

      var opts = {transacting: trx};

      // On récupère le secteur courant du Bot
      return bot.related('sector')
        .fetch(opts)
        .then(function(currentSector) {

          var dir = params.dir;
          var coords = {x: currentSector.get('x'), y: currentSector.get('y')};

          switch (dir) {
            case "S" :
              coords.y -= 1;
              break;
            case "N" :
              coords.y += 1;
              break;
            case "W" :
              coords.x -= 1;
              break;
            case "E" :
              coords.x += 1;
              break;
            case "NE" :
              coords.x += 1;
              coords.y -= 1;
              break;
            case "SE" :
              coords.x += 1;
              coords.y += 1;
              break;
            case "SW" :
              coords.x -= 1;
              coords.y += 1;
              break;
            case "NW" :
              coords.x -= 1;
              coords.y -= 1;
              break;
            default:
              throw new errors.UnknownDirectionError(dir);
          }

          return coords;

        })
        .then(function(coords) {
          return Sector
            .where(coords)
            .fetch(opts)
            .then(function(existing) {
              if(existing) {
                return existing;
              } else {
                return new Sector(coords).save(null, opts);
              }
            });
        })
        .then(function(destination) {
          bot.set('sector_id', destination.id);
          return bot.save(null, opts);
        })
        .then(function() {
          delete bot.relations.sector;
          return bot.related('sector').fetch(opts);
        });

    });

  })

};<commit_msg>fix erreur move<commit_after>/* jshint node: true */

var Promise = require('bluebird');
var orm = require('../../util/orm');
var errors = require('../../errors');

module.exports = {

  // Doit retourner le délai en tours avant l'exécution de l'action
  cooldown:  60 * 1000, // 60s de cooldown

  // Exécute l'action
  execute: Promise.method(function(bot, params) {

    var Sector = orm.model('Sector');

    // On effectue toutes les opérations dans une transaction
    return orm.transaction(function(trx) {

      var opts = {transacting: trx};

      // On récupère le secteur courant du Bot
      return bot.related('sector')
        .fetch(opts)
        .then(function(currentSector) {

          var dir = params.dir;
          var coords = {x: currentSector.get('x'), y: currentSector.get('y')};

          switch (dir) {
            case "S" :
              coords.y -= 1;
              break;
            case "N" :
              coords.y += 1;
              break;
            case "W" :
              coords.x -= 1;
              break;
            case "E" :
              coords.x += 1;
              break;
            case "NE" :
              coords.x += 1;
              coords.y += 1;
              break;
            case "SE" :
              coords.x += 1;
              coords.y -= 1;
              break;
            case "SW" :
              coords.x -= 1;
              coords.y -= 1;
              break;
            case "NW" :
              coords.x -= 1;
              coords.y += 1;
              break;
            default:
              throw new errors.UnknownDirectionError(dir);
          }

          return coords;

        })
        .then(function(coords) {
          return Sector
            .where(coords)
            .fetch(opts)
            .then(function(existing) {
              if(existing) {
                return existing;
              } else {
                return new Sector(coords).save(null, opts);
              }
            });
        })
        .then(function(destination) {
          bot.set('sector_id', destination.id);
          return bot.save(null, opts);
        })
        .then(function() {
          delete bot.relations.sector;
          return bot.related('sector').fetch(opts);
        });

    });

  })

};<|endoftext|>


<commit_before>/*
 * Copyright 2012, Mozilla Foundation and contributors
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

require('../test/recurse');
<commit_msg>refactor-864370: Remove unused test file<commit_after><|endoftext|>


<commit_before>/**
 * Boundary constructor
 *
 * @class Roguelike.Boundary
 * @classdesc A rectangle that represents the whole map or the viewport of the camera
 *
 * @param {Number} left - The left position of this boundary, in pixels
 * @param {Number} top - The top position of this boundary, in pixels
 * @param {Number} width - The width of this boundary, in pixels
 * @param {Number} height - The height of this boundary, in pixels
 */
Roguelike.Boundary = function(left, top, width, height) {

	/**
	 * @property {Number} left - The left position of this boundary, in pixels
	 */
	this.left = left || 0;

	/**
	 * @property {Number} top - The top position of this boundary, in pixels
	 */
	this.top = top || 0;

	/**
	 * @property {Number} width - The width of this boundary, in pixels
	 */
	this.width = width || 0;

	/**
	 * @property {Number} height - The height of this boundary, in pixels
	 */
	this.height = height || 0;

	/**
	 * @property {Number} right - The right position of this boundary, in pixels
	 */
	this.right = (this.left + this.width);

	/**
	 * @property {Number} bottom - The bottom position of this boundary, in pixels
	 */
	this.bottom = (this.top + this.height);

};

Roguelike.Boundary.prototype = {

	/**
	 * Function that allows the user to set new values for the boundary
	 * @protected
	 *
	 * @param {Number} left - The left position of this boundary, in pixels
	 * @param {Number} top - The top position of this boundary, in pixels
	 * @param {Number} width - Optional: The width of this boundary, in pixels
	 * @param {Number} height - Optional: The height of this boundary, in pixels
	 */
	set: function(left, top, width, height) {

		this.left = left;
		this.top = top;
		this.width = width || this.width;
		this.height = height || this.height;
		this.right = (this.left + this.width);
		this.bottom = (this.top + this.height);

	},

	/**
	 * Function to check if one boundary is still inside another boundary
	 * @protected
	 *
	 * @param {Roguelike.Boundary} boundary - The boundary to check against
	 *
	 * @return {Boolean} Returns true if the boundary is within this boundary, returns false if it isn't
	 */
	isWithin: function(boundary) {

		return(
			boundary.left <= this.left &&
				boundary.right >= this.right &&
				boundary.top <= this.top &&
				boundary.bottom >= this.bottom
			);

	},

	/**
	 * Function to check if one boundary overlaps another boundary
	 * @protected
	 *
	 * @param {Roguelike.Boundary} boundary - The boundary to check against
	 *
	 * @return {Number} Returns true if the boundary is overlapping this boundary, returns false if it isn't
	 */
	isOverlapping: function(boundary) {

		return(
			this.left < boundary.right &&
				boundary.left < this.right &&
				this.top < boundary.bottom &&
				boundary.top < this.bottom
			);

	}

};
<commit_msg>Code formatting in Boundary object.<commit_after>/**
 * Boundary constructor
 *
 * @class Roguelike.Boundary
 * @classdesc A rectangle that represents the whole map or the viewport of the camera
 *
 * @param {Number} left - The left position of this boundary, in pixels
 * @param {Number} top - The top position of this boundary, in pixels
 * @param {Number} width - The width of this boundary, in pixels
 * @param {Number} height - The height of this boundary, in pixels
 */
Roguelike.Boundary = function(left, top, width, height) {

	/**
	 * @property {Number} left - The left position of this boundary, in pixels
	 */
	this.left = left || 0;

	/**
	 * @property {Number} top - The top position of this boundary, in pixels
	 */
	this.top = top || 0;

	/**
	 * @property {Number} width - The width of this boundary, in pixels
	 */
	this.width = width || 0;

	/**
	 * @property {Number} height - The height of this boundary, in pixels
	 */
	this.height = height || 0;

	/**
	 * @property {Number} right - The right position of this boundary, in pixels
	 */
	this.right = (this.left + this.width);

	/**
	 * @property {Number} bottom - The bottom position of this boundary, in pixels
	 */
	this.bottom = (this.top + this.height);

};

Roguelike.Boundary.prototype = {

	/**
	 * Function that allows the user to set new values for the boundary
	 * @protected
	 *
	 * @param {Number} left - The left position of this boundary, in pixels
	 * @param {Number} top - The top position of this boundary, in pixels
	 * @param {Number} width - Optional: The width of this boundary, in pixels
	 * @param {Number} height - Optional: The height of this boundary, in pixels
	 */
	set: function(left, top, width, height) {

		this.left = left;
		this.top = top;
		this.width = width || this.width;
		this.height = height || this.height;
		this.right = (this.left + this.width);
		this.bottom = (this.top + this.height);

	},

	/**
	 * Function to check if one boundary is still inside another boundary
	 * @protected
	 *
	 * @param {Roguelike.Boundary} boundary - The boundary to check against
	 *
	 * @return {Boolean} Returns true if the boundary is within this boundary, returns false if it isn't
	 */
	isWithin: function(boundary) {

		return(
			boundary.left <= this.left &&
			boundary.right >= this.right &&
			boundary.top <= this.top &&
			boundary.bottom >= this.bottom
		);

	},

	/**
	 * Function to check if one boundary overlaps another boundary
	 * @protected
	 *
	 * @param {Roguelike.Boundary} boundary - The boundary to check against
	 *
	 * @return {Number} Returns true if the boundary is overlapping this boundary, returns false if it isn't
	 */
	isOverlapping: function(boundary) {

		return(
			this.left < boundary.right &&
				boundary.left < this.right &&
				this.top < boundary.bottom &&
				boundary.top < this.bottom
			);

	}

};
<|endoftext|>


<commit_before>// TODO 변경필요
const blogName = '애드투페이퍼';
const rootUrl = 'http://add2paper.github.io/';
const headerSrc = rootUrl + '/images/blog-cover.png';

// Module
const cheerio = require('cheerio');
const requestPromise = require('request-promise');

const rootPath = process.cwd();
const resultItem = require(rootPath + '/data/parser/result_item');

exports.getData = function (rootCallback) {
    requestPromise(rootUrl)
        .then(function (htmlString) {
            let $ = cheerio.load(htmlString);

            let articleItem = $('section.index').eq(0).children('div').eq(0);

            // Title
            let titleItem = articleItem.children('h2.title').eq(0);
            let parseTitle = titleItem.children('a').text();
            let parseLink = titleItem.children('a').attr('href');

            // Date
            let parseDate = articleItem.children('div.meta').eq(0).children('time').eq(0).attr('datetime'); // 메인화면에 표시되지 않음

            // Summary
            let parseSummary = articleItem.children('p').eq(0).text();

            let data = resultItem.getResultItem();
            data.blog_name = blogName;
            data.blog_favicon_src = 'https://www.google.com/s2/favicons?domain=' + rootUrl;
            data.blog_header_src = headerSrc;
            data.article_title = parseTitle;
            data.article_date = parseDate;
            data.article_link = parseLink;
            data.article_summary = parseSummary;

            rootCallback(data);
        })
        .catch(function (err) {
            console.log(err);
        });
}<commit_msg>주석 추가<commit_after>// TODO 변경필요
const blogName = '애드투페이퍼';
const rootUrl = 'http://add2paper.github.io/';
const headerSrc = rootUrl + '/images/blog-cover.png'; // 게시글 표시 이미지 없음

// Module
const cheerio = require('cheerio');
const requestPromise = require('request-promise');

const rootPath = process.cwd();
const resultItem = require(rootPath + '/data/parser/result_item');

exports.getData = function (rootCallback) {
    requestPromise(rootUrl)
        .then(function (htmlString) {
            let $ = cheerio.load(htmlString);

            // Article
            let articleItem = $('section.index').eq(0).children('div').eq(0);

            // Title
            let titleItem = articleItem.children('h2.title').eq(0);
            let parseTitle = titleItem.children('a').text();
            let parseLink = titleItem.children('a').attr('href');

            // Date
            let parseDate = articleItem.children('div.meta').eq(0).children('time').eq(0).attr('datetime'); // 메인화면에 표시되지 않음

            // Summary
            let parseSummary = articleItem.children('p').eq(0).text();

            let data = resultItem.getResultItem();
            data.blog_name = blogName;
            data.blog_favicon_src = 'https://www.google.com/s2/favicons?domain=' + rootUrl;
            data.blog_header_src = headerSrc;
            data.article_title = parseTitle;
            data.article_date = parseDate;
            data.article_link = parseLink;
            data.article_summary = parseSummary;

            rootCallback(data);
        })
        .catch(function (err) {
            console.log(err);
        });
}<|endoftext|>


<commit_before>/**
 * Created by tonycastronova on 10/12/15.
 */

$(document).ready(function () {

    // check to see if the view is in edit mode
    if(document.getElementById("id-mpmetadata") != null)
        // load jquery generated elements
        loadWidgets();

        // initialize datepicker
        //$(function() {
        $( "#modelReleaseDate_picker" ).datepicker({
            // bind a table view to the on close event
            onSelect: function (event) {
                onChange_releaseDate(event);
            }
        });

          //});

});

/**
 * Sets the hidden date field base on the datepicker.  The hidden field is what is submitted.
 */
function onChange_releaseDate(event){
    var date = document.getElementById('id_modelReleaseDate');
    var date_picker = document.getElementById("modelReleaseDate_picker");
    date.value = date_picker.value;

    // activate the save button
    $("#resourceSpecificTab").find('.btn-primary').show();
}

/**
 * Builds jQuery multiselect listboxes
 */
function loadWidgets(){

        // initialize help text popover
    $('[data-toggle="popover"]').popover({
        container: 'body'
    });

    // get the resource id from its url
    var url = document.URL;
    var url_array = url.split('/');
    var shortid = url_array[url_array.length - 2];

    // call django view to get model program metadata files
    $.ajax({
        type: "GET",
        url: '/hsapi/_internal/get-model-metadata/',
        data: {resource_id: shortid},
        success: function (data) {
            // get the fieldset items
            var fs = document.getElementById("id-mpmetadata").getElementsByTagName('fieldset')[0];

            // get the multiselect items
            var multiselect = fs.getElementsByClassName('div-multi-select');

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

                // get the metadata term associated with this multiselect field
                var term = multiselect[i].getAttribute('parent_metadata');

                // get the selected items that are saved to the resource
                var selected_terms = data[term];

                // loop through the options in the select list
                var options = $(multiselect[i]).find('option');
                for (var j = 0; j < options.length; j++) {

                    // set the selected attribute
                    if ($.inArray(options[j].value, selected_terms) >= 0) {
                        $(options[j]).attr("selected", 1);
                    }
                }
            }

            // set the initial value for the date picker
            $('#modelReleaseDate_picker').datepicker('setDate', new Date(data['date_released']));

        },
        error: function (data) {
            console.log('There was an error with model instance GET.')
        },
        complete: function (data) {
            // once the selected fields (html) have been updated, build the jQuery multiselect boxes

            // destroy any existing multiselect widgets
            $('.multi-select').multiselect('destroy');

            // get the size of the parent div
            var width = $('.div-multi-select').css('max-width');

            // rebuild the multiselect elements
            $('.multi-select').multiselect({

                buttonWidth: width,
                maxHeight: 200,
                numberDisplayed: 1,

                // bind a table view to the on close event
                onDropdownHide: function (event, checked) {
                    set_metadata_terms(event);
                }
            });

            // add pull-right to the dropdown-menu
            var dd = document.getElementsByClassName('multiselect-container dropdown-menu');
            for (var i = 0; i < dd.length; i++) {
                var classname = dd[i].className;
                if (classname.indexOf(' pull-right ') == -1) {
                    dd[i].className += ' pull-right';
                }
            }
        }
    });
}

/**
 * reloads the jQuery multi-select widgets on form submission
 */
$(document).bind("submit-success", function(event){
    // reload dynamically generated widgets
    loadWidgets();
});

/**
 * reloads the jQuery multi-select widgets on form submission failure
 */
$(document).bind("submit-error", function(event){
    // reload dynamically generated widgets
    loadWidgets();
});

/**
 * Sets multi-select selections to hidden field values that are submitted with the form
 * @param e
 */
function set_metadata_terms(e){

    // get parent div
    var parent = $(e.currentTarget.parentElement);

    // get selected items from select list
    var selected = parent.find('#multi-select').find("option:selected");

    // objects to store names and values in hidden metadata fields
    var values = [];

    // grab all of the selected values
    for(var i=0; i<selected.length; i++){
        values.push(selected[i].value);
    }

    // get parent metadata term
    var parent_meta_term = parent.get(0).getAttribute('parent_metadata');

    // get the metadata element based on this parent term
    var meta = document.getElementById("id_"+parent_meta_term);

    // set the value for this hidden field
    meta.value = values.join(';');

    // activate the save button
    $("#resourceSpecificTab").find('.btn-primary').show();
}<commit_msg>added check for valid date time [#632]<commit_after>/**
 * Created by tonycastronova on 10/12/15.
 */

$(document).ready(function () {

    // check to see if the view is in edit mode
    if(document.getElementById("id-mpmetadata") != null)
        // load jquery generated elements
        loadWidgets();

        // initialize datepicker
        //$(function() {
        $( "#modelReleaseDate_picker" ).datepicker({
            // bind a table view to the on close event
            onSelect: function (event) {
                onChange_releaseDate(event);
            }
        });

          //});

});

/**
 * Sets the hidden date field base on the datepicker.  The hidden field is what is submitted.
 */
function onChange_releaseDate(event){
    var date = document.getElementById('id_modelReleaseDate');
    var date_picker = document.getElementById("modelReleaseDate_picker");
    date.value = date_picker.value;

    // activate the save button
    $("#resourceSpecificTab").find('.btn-primary').show();
}

/**
 * Builds jQuery multiselect listboxes
 */
function loadWidgets(){

        // initialize help text popover
    $('[data-toggle="popover"]').popover({
        container: 'body'
    });

    // get the resource id from its url
    var url = document.URL;
    var url_array = url.split('/');
    var shortid = url_array[url_array.length - 2];

    // call django view to get model program metadata files
    $.ajax({
        type: "GET",
        url: '/hsapi/_internal/get-model-metadata/',
        data: {resource_id: shortid},
        success: function (data) {
            // get the fieldset items
            var fs = document.getElementById("id-mpmetadata").getElementsByTagName('fieldset')[0];

            // get the multiselect items
            var multiselect = fs.getElementsByClassName('div-multi-select');

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

                // get the metadata term associated with this multiselect field
                var term = multiselect[i].getAttribute('parent_metadata');

                // get the selected items that are saved to the resource
                var selected_terms = data[term];

                // loop through the options in the select list
                var options = $(multiselect[i]).find('option');
                for (var j = 0; j < options.length; j++) {

                    // set the selected attribute
                    if ($.inArray(options[j].value, selected_terms) >= 0) {
                        $(options[j]).attr("selected", 1);
                    }
                }
            }

            // set the initial value for the date picker
            var date = new Date(data['date_released']);
            if (isNaN(date) == false)
                $('#modelReleaseDate_picker').datepicker('setDate', date);

        },
        error: function (data) {
            console.log('There was an error with model instance GET.')
        },
        complete: function (data) {
            // once the selected fields (html) have been updated, build the jQuery multiselect boxes

            // destroy any existing multiselect widgets
            $('.multi-select').multiselect('destroy');

            // get the size of the parent div
            var width = $('.div-multi-select').css('max-width');

            // rebuild the multiselect elements
            $('.multi-select').multiselect({

                buttonWidth: width,
                maxHeight: 200,
                numberDisplayed: 1,

                // bind a table view to the on close event
                onDropdownHide: function (event, checked) {
                    set_metadata_terms(event);
                }
            });

            // add pull-right to the dropdown-menu
            var dd = document.getElementsByClassName('multiselect-container dropdown-menu');
            for (var i = 0; i < dd.length; i++) {
                var classname = dd[i].className;
                if (classname.indexOf(' pull-right ') == -1) {
                    dd[i].className += ' pull-right';
                }
            }
        }
    });
}

/**
 * reloads the jQuery multi-select widgets on form submission
 */
$(document).bind("submit-success", function(event){
    // reload dynamically generated widgets
    loadWidgets();
});

/**
 * reloads the jQuery multi-select widgets on form submission failure
 */
$(document).bind("submit-error", function(event){
    // reload dynamically generated widgets
    loadWidgets();
});

/**
 * Sets multi-select selections to hidden field values that are submitted with the form
 * @param e
 */
function set_metadata_terms(e){

    // get parent div
    var parent = $(e.currentTarget.parentElement);

    // get selected items from select list
    var selected = parent.find('#multi-select').find("option:selected");

    // objects to store names and values in hidden metadata fields
    var values = [];

    // grab all of the selected values
    for(var i=0; i<selected.length; i++){
        values.push(selected[i].value);
    }

    // get parent metadata term
    var parent_meta_term = parent.get(0).getAttribute('parent_metadata');

    // get the metadata element based on this parent term
    var meta = document.getElementById("id_"+parent_meta_term);

    // set the value for this hidden field
    meta.value = values.join(';');

    // activate the save button
    $("#resourceSpecificTab").find('.btn-primary').show();
}<|endoftext|>


<commit_before>import React, { Fragment } from 'react'
import styled from 'styled-components'
import tw from 'tailwind.macro'
import { Parallax } from 'react-spring/addons.cjs'

// Components
import Layout from '../components/Layout'
import ProjectCard from '../components/ProjectCard'

// Elements
import Inner from '../elements/Inner'
import { Title, BigTitle, Subtitle } from '../elements/Titles'

// Views
import Hero from '../views/Hero'
import Projects from '../views/Projects'
import About from '../views/About'
import Contact from '../views/Contact'

import avatar from '../images/avatar.jpg'

const ProjectsWrapper = styled.div`
  ${tw`flex flex-wrap justify-between mt-8`};
  display: grid;
  grid-gap: 4rem;
  grid-template-columns: repeat(2, 1fr);
  @media (max-width: 1200px) {
    grid-gap: 3rem;
  }
  @media (max-width: 900px) {
    grid-template-columns: 1fr;
    grid-gap: 2rem;
  }
`

const AboutHero = styled.div`
  ${tw`flex flex-col lg:flex-row items-center mt-8`};
`

const Avatar = styled.img`
  ${tw`rounded-full w-32 xl:w-48 shadow-lg h-auto`};
`

const AboutSub = styled.span`
  ${tw`text-white pt-12 lg:pt-0 lg:pl-12 text-2xl lg:text-3xl xl:text-4xl`};
`

const AboutDesc = styled.p`
  ${tw`text-grey-light text-lg md:text-xl lg:text-2xl font-sans pt-6 md:pt-12 text-justify`};
`

const ContactText = styled.p`
  ${tw`text-grey-light font-sans text-xl md:text-2xl lg:text-3xl`};
`

const Footer = styled.footer`
  ${tw`text-center text-grey absolute pin-b p-6 font-sans text-md lg:text-lg`};
`

const Index = () => (
  <Fragment>
    <Layout />
    <Parallax pages={5}>
      <Hero offset={0}>
        <BigTitle>
          Hello,
 I'm John Doe.
        </BigTitle>
        <Subtitle>I'm creating noice web experiences for the next generation of consumer-facing companies.</Subtitle>
      </Hero>
      <Projects offset={1}>
        <Title>Projects</Title>
        <ProjectsWrapper>
          <ProjectCard
            title="Freiheit"
            link="https://www.behance.net/gallery/58937147/Freiheit"
            bg="linear-gradient(to right, #D4145A 0%, #FBB03B 100%)"
          >
            This project is my entry to Adobe's #ChallengeYourPerspective contest.
          </ProjectCard>
          <ProjectCard
            title="Harry Potter"
            link="https://www.behance.net/gallery/52915793/Harry-Potter"
            bg="linear-gradient(to right, #662D8C 0%, #ED1E79 100%)"
          >
            I entered the DOCMA 2017 award with this Harry Potter inspired image.
          </ProjectCard>
          <ProjectCard
            title="Tomb Raider"
            link="https://www.behance.net/gallery/43907099/Tomb-Raider"
            bg="linear-gradient(to right, #009245 0%, #FCEE21 100%)"
          >
            Recreation of a Tomb Raider Wallpaper (Fan Art)
          </ProjectCard>
          <ProjectCard
            title="Eagle"
            link="https://www.behance.net/gallery/38068151/Eagle"
            bg="linear-gradient(to right, #D585FF 0%, #00FFEE 100%)"
          >
            A fantasy image manipulation relocating the habitat of wild animals.
          </ProjectCard>
        </ProjectsWrapper>
      </Projects>
      <About offset={3}>
        <Title>About</Title>
        <AboutHero>
          <Avatar src={avatar} alt="John Doe" />
          <AboutSub>
            The English language can not fully capture the depth and complexity of my thoughts. So I'm incorporating
            Emoji into my speech to better express myself. Winky face.
          </AboutSub>
        </AboutHero>
        <AboutDesc>
          You know the way you feel when you see a picture of two otters holding hands? That's how you're gonna feel
          every day. My mother cried the day I was born because she knew she’d never be prettier than me. You should
          make me your campaign manager. I was born for politics. I have great hair and I love lying. Captain? The kids
          want to know where Paulie the Pigeon is. I told them he got sucked up into an airplane engine, is that all
          right?
        </AboutDesc>
      </About>
      <Contact offset={4}>
        <Inner>
          <Title>Get in touch</Title>
          <ContactText>
            Say Hi or find me on other platforms:{' '}
            Dribbble &{' '}
            Instagram
          </ContactText>
        </Inner>

          © 2019 by Gatsby Starter Portfolio Cara.{' '}
          Github Repository. Made by{' '}
          LekoArts.

      </Contact>
    </Parallax>
  </Fragment>
)

export default Index
<commit_msg>fix adjustment hero section<commit_after>import React, { Fragment } from 'react'
import styled from 'styled-components'
import tw from 'tailwind.macro'
import { Parallax } from 'react-spring/addons.cjs'

// Components
import Layout from '../components/Layout'
import ProjectCard from '../components/ProjectCard'

// Elements
import Inner from '../elements/Inner'
import { Title, BigTitle, Subtitle } from '../elements/Titles'

// Views
import Hero from '../views/Hero'
import Projects from '../views/Projects'
import About from '../views/About'
import Contact from '../views/Contact'

import avatar from '../images/avatar.jpg'

const ProjectsWrapper = styled.div`
  ${tw`flex flex-wrap justify-between mt-8`};
  display: grid;
  grid-gap: 4rem;
  grid-template-columns: repeat(2, 1fr);
  @media (max-width: 1200px) {
    grid-gap: 3rem;
  }
  @media (max-width: 900px) {
    grid-template-columns: 1fr;
    grid-gap: 2rem;
  }
`

const AboutHero = styled.div`
  ${tw`flex flex-col lg:flex-row items-center mt-8`};
`

const Avatar = styled.img`
  ${tw`rounded-full w-32 xl:w-48 shadow-lg h-auto`};
`

const AboutSub = styled.span`
  ${tw`text-white pt-12 lg:pt-0 lg:pl-12 text-2xl lg:text-3xl xl:text-4xl`};
`

const AboutDesc = styled.p`
  ${tw`text-grey-light text-lg md:text-xl lg:text-2xl font-sans pt-6 md:pt-12 text-justify`};
`

const ContactText = styled.p`
  ${tw`text-grey-light font-sans text-xl md:text-2xl lg:text-3xl`};
`

const Footer = styled.footer`
  ${tw`text-center text-grey absolute pin-b p-6 font-sans text-md lg:text-lg`};
`

const Index = () => (
  <Fragment>
    <Layout />
    <Parallax pages={5}>
      <Hero offset={0}>
        <BigTitle>
          nosql:ba</BigTitle>
        <Subtitle>Conferência baiana sobre NoSQL Databases!</Subtitle>
      </Hero>
      <Projects offset={1}>
        <Title>Projects</Title>
        <ProjectsWrapper>
          <ProjectCard
            title="Freiheit"
            link="https://www.behance.net/gallery/58937147/Freiheit"
            bg="linear-gradient(to right, #D4145A 0%, #FBB03B 100%)"
          >
            This project is my entry to Adobe's #ChallengeYourPerspective contest.
          </ProjectCard>
          <ProjectCard
            title="Harry Potter"
            link="https://www.behance.net/gallery/52915793/Harry-Potter"
            bg="linear-gradient(to right, #662D8C 0%, #ED1E79 100%)"
          >
            I entered the DOCMA 2017 award with this Harry Potter inspired image.
          </ProjectCard>
          <ProjectCard
            title="Tomb Raider"
            link="https://www.behance.net/gallery/43907099/Tomb-Raider"
            bg="linear-gradient(to right, #009245 0%, #FCEE21 100%)"
          >
            Recreation of a Tomb Raider Wallpaper (Fan Art)
          </ProjectCard>
          <ProjectCard
            title="Eagle"
            link="https://www.behance.net/gallery/38068151/Eagle"
            bg="linear-gradient(to right, #D585FF 0%, #00FFEE 100%)"
          >
            A fantasy image manipulation relocating the habitat of wild animals.
          </ProjectCard>
        </ProjectsWrapper>
      </Projects>
      <About offset={3}>
        <Title>About</Title>
        <AboutHero>
          <Avatar src={avatar} alt="John Doe" />
          <AboutSub>
            The English language can not fully capture the depth and complexity of my thoughts. So I'm incorporating
            Emoji into my speech to better express myself. Winky face.
          </AboutSub>
        </AboutHero>
        <AboutDesc>
          You know the way you feel when you see a picture of two otters holding hands? That's how you're gonna feel
          every day. My mother cried the day I was born because she knew she’d never be prettier than me. You should
          make me your campaign manager. I was born for politics. I have great hair and I love lying. Captain? The kids
          want to know where Paulie the Pigeon is. I told them he got sucked up into an airplane engine, is that all
          right?
        </AboutDesc>
      </About>
      <Contact offset={4}>
        <Inner>
          <Title>Get in touch</Title>
          <ContactText>
            Say Hi or find me on other platforms:{' '}
            Dribbble &{' '}
            Instagram
          </ContactText>
        </Inner>

          © 2019 by Gatsby Starter Portfolio Cara.{' '}
          Github Repository. Made by{' '}
          LekoArts.

      </Contact>
    </Parallax>
  </Fragment>
)

export default Index
<|endoftext|>


<commit_before>var page = require('webpage').create(),
    async = require('../node_modules/async/lib/async.js'),
    downloadLink;

// Run a check function every 100 ms
function waitFor(checkFn, cb) {
  if (checkFn()) {
    cb();
  } else {
    setTimeout(function waitForFn () {
      waitFor(checkFn, cb);
    }, 100);
  }
}

// In series
async.series([
  function openIcoMoon (cb) {
    // Open IcoMoon
    page.open('http://icomoon.io/app', function (status) {
      cb();
    });
  },
  function waitForLoading (cb) {
    // Wait for loading to complete
    waitFor(function () {
      return page.evaluate(function () {
        return !document.getElementById('loading');
      });
    }, cb);
  },
  function uploadImages (cb) {
    // Submit many images (need a file path for all our images)
    var fs = require('fs'),
        filesPath = phantom.args[0],
        filesJSON = fs.read(filesPath),
        files = JSON.parse(filesJSON);

    // TODO: We might need to submit this many times per file
    page.uploadFile('#files', files);

    // Continue
    cb();
  },
  function moveToDownloadScreen (cb) {
    // Move to the downlod screen
    page.evaluate(function () {
      // Select our images
      $('#imported').find('.checkbox-icon').click();

      // "Click" the 'Next' link
      window.location.hash = 'font';
    });

    // Wait for the next screen to load
    waitFor(function () {
      return page.evaluate(function () {
        return $('#saveFont').length;
      });
    }, cb);
  },
  function exportFont (cb) {
    // Save any zip redirect requests
    page.onNavigationRequested = function (url) {
      if (url.indexOf('.zip') > -1) {
        downloadLink = url;
      }
    };

    // Click the download link
    page.evaluate(function () {
      $('#saveFont').click();
    });

    // Wait for the redirect request to our zip
    waitFor(function () {
      return downloadLink;
    }, cb);
  }
], function output (err) {
  // // DEV: Take a screenshot for progress
  // page.render('app.png');

  // If there was an error, log it
  if (err) {
    console.error(err);
    phantom.exit(1);
  } else {
  // Otherwise, output the download link for the next module
    console.log(downloadLink);
    phantom.exit(0);
  }
});<commit_msg>Seem to be over-uploading files o_O<commit_after>var page = require('webpage').create(),
    async = require('../node_modules/async/lib/async.js'),
    downloadLink;

// Run a check function every 100 ms
function waitFor(checkFn, cb) {
  if (checkFn()) {
    cb();
  } else {
    setTimeout(function waitForFn () {
      waitFor(checkFn, cb);
    }, 100);
  }
}

// In series
async.series([
  function openIcoMoon (cb) {
    // Open IcoMoon
    page.open('http://icomoon.io/app', function (status) {
      cb();
    });
  },
  function waitForLoading (cb) {
    // Wait for loading to complete
    waitFor(function () {
      return page.evaluate(function () {
        return !document.getElementById('loading');
      });
    }, cb);
  },
  function uploadImages (cb) {
    // Submit many images (need a file path for all our images)
    var fs = require('fs'),
        filesPath = phantom.args[0],
        filesJSON = fs.read(filesPath),
        files = JSON.parse(filesJSON);

    // TODO: We might need to submit this many times per file
    files.forEach(function (file) {
      page.uploadFile('#files', file);
    });

    // Continue
    cb();
  },
  function moveToDownloadScreen (cb) {
    // Move to the downlod screen
    page.evaluate(function () {
      // Select our images
      $('#imported').find('.checkbox-icon').click();

      // "Click" the 'Next' link
      window.location.hash = 'font';
    });

    // Wait for the next screen to load
    waitFor(function () {
      return page.evaluate(function () {
        return $('#saveFont').length;
      });
    }, cb);
  },
  function exportFont (cb) {
    // Save any zip redirect requests
    page.onNavigationRequested = function (url) {
      if (url.indexOf('.zip') > -1) {
        downloadLink = url;
      }
    };

    // Click the download link
    page.evaluate(function () {
      $('#saveFont').click();
    });

    // Wait for the redirect request to our zip
    waitFor(function () {
      return downloadLink;
    }, cb);
  }
], function output (err) {
  // // DEV: Take a screenshot for progress
  // page.render('app.png');

  // If there was an error, log it
  if (err) {
    console.error(err);
    phantom.exit(1);
  } else {
  // Otherwise, output the download link for the next module
    console.log(downloadLink);
    phantom.exit(0);
  }
});<|endoftext|>


<commit_before>const fs = require('fs')
const mkdirp = require('mkdirp')
const path = require('path')
const nm = require('../utils/nm')
const bin = require('./installer/bin')
const dat = require('./installer/dat')
const git = require('./installer/git')
const local = require('./installer/local')
const remote = require('./installer/remote')
const registry = require('./installer/registry')
const runner = require('../run/runner')
const isRoot = require('is-root')

const installer = (dep, deps, base, resolve, reject) => {
  mkdirp.sync(nm)
  mkdirp.sync(path.join(nm, '.bin'))

  const target = (base.length === 0)
    ? path.join(nm, dep)
    : path.join(nm, base.join('/'), 'node_modules', dep)
  mkdirp.sync(target)

  const pkg = deps[dep]
  var fetch

  switch (pkg.type) {
    case 'dat':
      fetch = dat(pkg, target)
      break
    case 'git':
      fetch = git(pkg, target)
      break
    case 'remote':
      fetch = remote(pkg, target)
      break
    case 'local':
      fetch = local(pkg, target)
      break
    case 'registry':
      fetch = registry(pkg, target)
      break
  }

  fetch.then(() => {
    return new Promise((resolve, reject) => {
      if (isRoot()) {
        process.stdout.write(
          'dep does not allow root users to run the install lifecycle scripts'
        )
        return resolve()
      }
      const args = ['install']
      const pkg = require(path.join(target, 'package.json'))
      if (!pkg.scripts || (
        pkg.scripts.preinstall &&
        pkg.scripts.install &&
        pkg.scripts.postinstall
      )) return resolve()
      runner(args, pkg).then(resolve).catch(reject)
    })
  }).then(() => {
    global.dependenciesCount += 1
    bin(dep, target)
    if (fs.existsSync(path.join(target, 'binding.gyp'))) {
      global.nativeBuildQueue.push(target)
    }
    if (!pkg.dependencies) return resolve()
    const tasks = Object.keys(pkg.dependencies).map((item) => {
      const list = pkg.dependencies
      var keys = [].concat(base, dep)
      if (keys.length > 1) keys.splice(-1, 0, 'node_modules')
      return new Promise((resolve, reject) => {
        installer(item, list, keys, resolve, reject)
      })
    })
    Promise.all(tasks).then(() => {
      resolve()
    })
  })
}

module.exports = (deps) => {
  return Object.keys(deps).map((dep) => {
    return new Promise((resolve, reject) => installer(dep, deps, [], resolve, reject))
  })
}
<commit_msg>fix(install): add error handling to installer<commit_after>const fs = require('fs')
const mkdirp = require('mkdirp')
const path = require('path')
const nm = require('../utils/nm')
const bin = require('./installer/bin')
const dat = require('./installer/dat')
const git = require('./installer/git')
const local = require('./installer/local')
const remote = require('./installer/remote')
const registry = require('./installer/registry')
const runner = require('../run/runner')
const isRoot = require('is-root')

const installer = (dep, deps, base, resolve, reject) => {
  mkdirp.sync(nm)
  mkdirp.sync(path.join(nm, '.bin'))

  const target = (base.length === 0)
    ? path.join(nm, dep)
    : path.join(nm, base.join('/'), 'node_modules', dep)
  mkdirp.sync(target)

  const pkg = deps[dep]
  var fetch

  switch (pkg.type) {
    case 'dat':
      fetch = dat(pkg, target)
      break
    case 'git':
      fetch = git(pkg, target)
      break
    case 'remote':
      fetch = remote(pkg, target)
      break
    case 'local':
      fetch = local(pkg, target)
      break
    case 'registry':
      fetch = registry(pkg, target)
      break
  }

  fetch.then(() => {
    return new Promise((resolve, reject) => {
      if (isRoot()) {
        process.stdout.write(
          'dep does not allow root users to run the install lifecycle scripts'
        )
        return resolve()
      }
      const args = ['install']
      const pkg = require(path.join(target, 'package.json'))
      if (!pkg.scripts || (
        pkg.scripts.preinstall &&
        pkg.scripts.install &&
        pkg.scripts.postinstall
      )) return resolve()
      runner(args, pkg).then(resolve).catch(reject)
    })
  }).then(() => {
    global.dependenciesCount += 1
    bin(dep, target)
    if (fs.existsSync(path.join(target, 'binding.gyp'))) {
      global.nativeBuildQueue.push(target)
    }
    if (!pkg.dependencies) return resolve()
    const tasks = Object.keys(pkg.dependencies).map((item) => {
      const list = pkg.dependencies
      var keys = [].concat(base, dep)
      if (keys.length > 1) keys.splice(-1, 0, 'node_modules')
      return new Promise((resolve, reject) => {
        installer(item, list, keys, resolve, reject)
      })
    })
    Promise.all(tasks).then(() => {
      resolve()
    }).catch(reject)
  }).catch(reject)
}

module.exports = (deps) => {
  return Object.keys(deps).map((dep) => {
    return new Promise((resolve, reject) => installer(dep, deps, [], resolve, reject))
  })
}
<|endoftext|>


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

    GeneratorApp.directive('questions', ['$compile', '$http', function($compile, $http) {
        return {
            restrict: 'E',
            link: function(scope, element, attrs) {

                scope.$watchCollection('questionsList', function(questionsList, old) {
                    if (angular.isObject(questionsList)) {
                        $http.get(__BASEPATH__ + 'assets/js/App/Template/Question.html').success(function(template) {
                            element.html(template);
                            $compile(element.contents())(scope);
                        });
                    } else if(null === questionsList) {
                        angular.element(element).hide();
                    }
                });
            }
        };
    }]);
}());<commit_msg>Better use of directive<commit_after>(function () {
    "use strict";

    GeneratorApp.directive('questions', ['$compile', '$http', function($compile, $http) {
        return {
            restrict: 'E',
            templateUrl: __BASEPATH__ + 'assets/js/App/Template/Question.html'
        };
    }]);
}());<|endoftext|>