<commit_before>'use strict';

/**
 * This class manages App Generator prompts.
 */
module.exports = class Prompt {

  /**
   * Ask the user to answer some questions.
   */
  static questions (generator) {
    return generator.prompt([{
      type: 'input',
      name: 'appName',
      message: 'What\'s the name of your application package?',
      store: true
    },{
      type: 'checkbox',
      name: 'ngModules',
      message: 'What Angular modules do you want?',
      store: true,
      choices: [
        {
          name: 'ngAnimate',
          value: 'ngAnimate'
        },
        {
          name: 'ngCookies',
          value: 'ngCookies'
        },
        {
          name: 'ngTouch',
          value: 'ngTouch'
        },
        {
          name: 'ngSanitize',
          value: 'ngSanitize'
        },
        {
          name: 'ngMessages',
          value: 'ngMessages'
        }
      ]
    }, {
      type: 'list',
      name: 'resource',
      message: 'Would you like to use a REST resource library?',
      default: 'restangular',
      store: true,
      choices: [
        {
          name: 'Restangular, an alternative service to handles RESTful requests',
          value: 'restangular'
        },
        {
          name: 'ngResource, the official support for RESTful services',
          value: 'ngResource'
        },
        {
          name: 'None, $http is enough!',
          value: '$http'
        }
      ]
    }, {
      type: 'list',
      name: 'uiFramework',
      message: 'Which UI framework do you want?',
      default: 'ngMaterial',
      store: true,
      choices: [
        {
          name: 'Angular Material, the reference implementation of the Google\'s Material Design specification',
          value: 'ngMaterial'
        },
        {
          name: 'Bootstrap, the most popular HTML, CSS, and JS framework',
          value: 'bootstrap'
        },
        {
          name: 'None',
          value: 'none'
        }
      ]
    }, {
      type: 'list',
      name: 'cssPreprocessor',
      message: 'Which CSS preprocessor do you want?',
      default: 'sass',
      store: true,
      choices: [
        {
          name: 'Sass (with Node-sass)',
          value: 'sass'
        },
        {
          name: 'Less',
          value: 'less'
        },
        {
          name: 'Plain CSS',
          value: 'css'
        }
      ]
    }, {
      type: 'checkbox',
      name: 'otherModules',
      message: 'Here are some modules you might be interested in',
      store: true,
      choices: [
        {
          name: 'angular-translate (18n for your Angular app, made easy!)',
          value: 'angular-translate'
        },
        {
          name: 'sonar-web-frontend-reporters, generate linters reporters for the SonarQube plugin',
          value: 'sonar-web-frontend-reporters'
        },
        {
          name: 'json-server, a full fake REST API with zero coding in less than 30 seconds',
          value: 'json-server'
        }
      ]
    }, {
      type: 'list',
      name: 'packageManager',
      message: 'What package manager should i use to install your dependencies ?',
      default: 'npm',
      store: true,
      choices: [
        {
          name: 'npm, a package manager for javascript',
          value: 'npm'
        },
        {
          name: 'Yarn, Fast, reliable, and secure dependency management',
          value: 'yarn'
        }
      ]
    }]).then(answers => {

      //app name
      generator.props.appName = answers.appName;

      // Angular modules
      generator.props.ngAnimate = answers.ngModules && answers.ngModules.includes('ngAnimate');
      generator.props.ngCookies = answers.ngModules && answers.ngModules.includes('ngCookies');
      generator.props.ngTouch = answers.ngModules && answers.ngModules.includes('ngTouch');
      generator.props.ngSanitize = answers.ngModules && answers.ngModules.includes('ngSanitize');
      generator.props.ngMessages = answers.ngModules && answers.ngModules.includes('ngMessages');

      // Resource
      generator.props.resource = answers.resource;

      // UI Framework
      generator.props.uiFramework = answers.uiFramework;

      // CSS preprocessor
      generator.props.cssPreprocessor = answers.cssPreprocessor;

      // Other modules
      generator.props.angularTranslate = answers.otherModules && answers.otherModules.includes('angular-translate');
      generator.props.sonarWebFrontendReporters = answers.otherModules && answers.otherModules.includes('sonar-web-frontend-reporters');
      generator.props.jsonServer = answers.otherModules && answers.otherModules.includes('json-server');

      // Package manager
      generator.props.packageManager = answers.packageManager;

    });
  }
};
<commit_msg>fix(app): do not store the application name for future uses<commit_after>'use strict';

/**
 * This class manages App Generator prompts.
 */
module.exports = class Prompt {

  /**
   * Ask the user to answer some questions.
   */
  static questions (generator) {
    return generator.prompt([{
      type: 'input',
      name: 'appName',
      message: 'What\'s the name of your application package?'
    }, {
      type: 'checkbox',
      name: 'ngModules',
      message: 'What Angular modules do you want?',
      store: true,
      choices: [
        {
          name: 'ngAnimate',
          value: 'ngAnimate'
        },
        {
          name: 'ngCookies',
          value: 'ngCookies'
        },
        {
          name: 'ngTouch',
          value: 'ngTouch'
        },
        {
          name: 'ngSanitize',
          value: 'ngSanitize'
        },
        {
          name: 'ngMessages',
          value: 'ngMessages'
        }
      ]
    }, {
      type: 'list',
      name: 'resource',
      message: 'Would you like to use a REST resource library?',
      default: 'restangular',
      store: true,
      choices: [
        {
          name: 'Restangular, an alternative service to handles RESTful requests',
          value: 'restangular'
        },
        {
          name: 'ngResource, the official support for RESTful services',
          value: 'ngResource'
        },
        {
          name: 'None, $http is enough!',
          value: '$http'
        }
      ]
    }, {
      type: 'list',
      name: 'uiFramework',
      message: 'Which UI framework do you want?',
      default: 'ngMaterial',
      store: true,
      choices: [
        {
          name: 'Angular Material, the reference implementation of the Google\'s Material Design specification',
          value: 'ngMaterial'
        },
        {
          name: 'Bootstrap, the most popular HTML, CSS, and JS framework',
          value: 'bootstrap'
        },
        {
          name: 'None',
          value: 'none'
        }
      ]
    }, {
      type: 'list',
      name: 'cssPreprocessor',
      message: 'Which CSS preprocessor do you want?',
      default: 'sass',
      store: true,
      choices: [
        {
          name: 'Sass (with Node-sass)',
          value: 'sass'
        },
        {
          name: 'Less',
          value: 'less'
        },
        {
          name: 'Plain CSS',
          value: 'css'
        }
      ]
    }, {
      type: 'checkbox',
      name: 'otherModules',
      message: 'Here are some modules you might be interested in',
      store: true,
      choices: [
        {
          name: 'angular-translate (18n for your Angular app, made easy!)',
          value: 'angular-translate'
        },
        {
          name: 'sonar-web-frontend-reporters, generate linters reporters for the SonarQube plugin',
          value: 'sonar-web-frontend-reporters'
        },
        {
          name: 'json-server, a full fake REST API with zero coding in less than 30 seconds',
          value: 'json-server'
        }
      ]
    }, {
      type: 'list',
      name: 'packageManager',
      message: 'What package manager should i use to install your dependencies ?',
      default: 'npm',
      store: true,
      choices: [
        {
          name: 'npm, a package manager for javascript',
          value: 'npm'
        },
        {
          name: 'Yarn, Fast, reliable, and secure dependency management',
          value: 'yarn'
        }
      ]
    }]).then(answers => {

      // App name
      generator.props.appName = answers.appName;

      // Angular modules
      generator.props.ngAnimate = answers.ngModules && answers.ngModules.includes('ngAnimate');
      generator.props.ngCookies = answers.ngModules && answers.ngModules.includes('ngCookies');
      generator.props.ngTouch = answers.ngModules && answers.ngModules.includes('ngTouch');
      generator.props.ngSanitize = answers.ngModules && answers.ngModules.includes('ngSanitize');
      generator.props.ngMessages = answers.ngModules && answers.ngModules.includes('ngMessages');

      // Resource
      generator.props.resource = answers.resource;

      // UI Framework
      generator.props.uiFramework = answers.uiFramework;

      // CSS preprocessor
      generator.props.cssPreprocessor = answers.cssPreprocessor;

      // Other modules
      generator.props.angularTranslate = answers.otherModules && answers.otherModules.includes('angular-translate');
      generator.props.sonarWebFrontendReporters = answers.otherModules && answers.otherModules.includes('sonar-web-frontend-reporters');
      generator.props.jsonServer = answers.otherModules && answers.otherModules.includes('json-server');

      // Package manager
      generator.props.packageManager = answers.packageManager;

    });
  }
};
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

define([
    "httpmonitor/lib/trace",
    "httpmonitor/lib/object",
    "httpmonitor/lib/options",
    "httpmonitor/lib/string",
    "httpmonitor/net/httpActivityObserver",
    "httpmonitor/net/httpRequestObserver",
    "httpmonitor/net/netProgress",          //xxxHonza:is this dep correct?.
    "httpmonitor/net/netUtils",
    "httpmonitor/lib/events",
    "httpmonitor/net/netCacheListener",
    "httpmonitor/base/module",
    "httpmonitor/chrome/chrome",
    "httpmonitor/lib/window",
    "httpmonitor/chrome/defaultPrefs",
    "httpmonitor/net/documentLoadObserver",
    "httpmonitor/net/windowEventObserver",
],
function(FBTrace, Obj, Options, Str, HttpActivityObserver, HttpRequestObserver,
    NetProgress, NetUtils, Events, NetCacheListener, Module, Chrome, Win, DefaultPrefs,
    DocumentLoadObserver, WindowEventObserver) {

// ********************************************************************************************* //
// Constants

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;

var panelName = "net";

var windowPaint = NetProgress.prototype.windowPaint;
var timeStamp = NetProgress.prototype.timeStamp;
var windowLoad = NetProgress.prototype.windowLoad;
var contentLoad = NetProgress.prototype.contentLoad;

// ********************************************************************************************* //

/**
 * @module Represents a module object for the Net panel. This object is derived
 * from Module in order to support activation (enable/disable).
 * This allows to avoid (performance) expensive features if the functionality is not necessary
 * for the user.
 */
var NetMonitor = Obj.extend(Module,
{
    dispatchName: "netMonitor",
    maxQueueRequests: 500,

    // Observes document load.
    loadObserver: new DocumentLoadObserver(),

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Module

    initialize: function()
    {
        Module.initialize.apply(this, arguments);

        // Initialize options and pass in the pref domain for this application.
        Options.initialize("extensions.httpmonitor");
        Options.registerDefaultPrefs(DefaultPrefs);

        // Register document load observer to get notification about new top document
        // being requested to load.
        this.loadObserver.register(this);
    },

    initializeUI: function()
    {
        Module.initializeUI.apply(this, arguments);

        // Initialize max limit for logged requests.
        NetMonitor.updateMaxLimit();

        // Synchronize buttons with the current filter.
        this.syncFilterButtons();
    },

    shutdown: function()
    {
        Module.shutdown.apply(this, arguments);

        this.loadObserver.unregister();
    },

    initContext: function(context, persistedState)
    {
        Module.initContext.apply(this, arguments);

        if (FBTrace.DBG_NET)
            FBTrace.sysout("net.initContext for: " + context.getName());

        this.initNetContext(context);
        this.attachObservers(context);

        //xxxHonza: needed by NetExport, should be probably somewhere else.
        // Set Page title and id into all document objects.
        var netProgress = context.netProgress;
        for (var i=0; i<netProgress.documents.length; i++)
        {
            var doc = netProgress.documents[i];
            doc.id = context.uid;
            doc.title = NetUtils.getPageTitle(context);
        }
    },

    destroyContext: function(context, persistedState)
    {
        Module.destroyContext.apply(this, arguments);

        if (FBTrace.DBG_NET)
            FBTrace.sysout("net.destroyContext for: " +
                (context ? context.getName() : "No context"));

        this.destroyNetContext(context);
        this.detachObservers(context);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Document Load Observer

    onLoadDocument: function(request, win)
    {
        var context = Chrome.currentContext;
        if (!context || context.window != Win.getRootWindow(win))
        {
            FBTrace.sysout("This request doesn't come from selected tab  " +
                Http.safeGetRequestName(subject), context);
            return;
        }

        var persist = Chrome.getGlobalAttribute("cmd_togglePersistNet", "checked");
        persist = (persist == "true");

        // New page loaded, clear UI if 'Persist' isn't active.
        if (!persist)
            context.netProgress.clear();

        // Since new top document starts loading we need to reset some context flags.
        // loaded: is set as soon as 'load' even is fired
        // currentPhase: ensure that new phase is created.
        context.netProgress.loaded = false;
        context.netProgress.currentPhase = null;

        if (this.eventObserver)
            this.eventObserver.unregisterListeners();

        // Register an observer for window events (load, paint, etc.)
        this.eventObserver = new WindowEventObserver(context);
        this.eventObserver.registerListeners();

        if (FBTrace.DBG_NET)
            FBTrace.sysout("httpRequestObserver.onModifyRequest; Top document loading...");
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Activation

    initNetContext: function(context)
    {
        if (context.netProgress)
            return;

        if (!this.fbListeners)
            this.fbListeners = [];

        var netProgress = new NetProgress(context, this.fbListeners);
        context.netProgress = netProgress;
    },

    destroyNetContext: function(context)
    {
        delete context.netProgress;
        context.netProgress = null;
    },

    attachObservers: function(context)
    {
        var netProgress = context.netProgress;
        if (!netProgress)
            return;

        // Register activity-distributor observer if available (#488270)
        netProgress.httpActivityObserver = new HttpActivityObserver(context);
        netProgress.httpActivityObserver.registerObserver();

        // Register observer for HTTP events
        netProgress.httpRequestObserver = new HttpRequestObserver(context);
        netProgress.httpRequestObserver.registerObserver();

        // Add cache listener so, net panel has always fresh responses.
        // Safe to call multiple times.
        netProgress.cacheListener = new NetCacheListener(netProgress);
        netProgress.cacheListener.register(context.sourceCache);
    },

    detachObservers: function(context)
    {
        var netProgress = context.netProgress;
        if (!netProgress)
            return;

        netProgress.httpActivityObserver.unregisterObserver();
        delete netProgress.httpActivityObserver;

        netProgress.httpRequestObserver.registerObserver();
        delete netProgress.httpRequestObserver;

        netProgress.cacheListener.unregister();
        delete netProgress.cacheListener;
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // User Actions

    clear: function(context)
    {
        // The user pressed a Clear button so, remove all HTTP collected data. The Net panel
        // is context handler and so the clear action will be automatically forwarded to it.
        if (context.netProgress)
            context.netProgress.clear();
    },

    onToggleFilter: function(context, filterCategory)
    {
        if (!context.netProgress)
            return;

        Options.set("netFilterCategory", filterCategory);

        // The content filter has been changed. Make sure that the content
        // of the panel is updated (CSS is used to hide or show individual files).
        var panel = context.getPanel(panelName, true);
        if (panel)
        {
            panel.setFilter(filterCategory);
            panel.updateSummaries(NetUtils.now(), true);
        }
    },

    syncFilterButtons: function()
    {
        var id = "fbNetFilter-" + Options.get("netFilterCategory");
        var button = Chrome.$(id);
        if (!button)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.sysout("netMonitor.syncFilterButtons; ERROR no button? " + id);

            return;
        }

        button.checked = true;
    },

    togglePersist: function(context)
    {
        var panel = context.getPanel(panelName);
        panel.persistContent = panel.persistContent ? false : true;
        Chrome.setGlobalAttribute("cmd_togglePersistNet", "checked", panel.persistContent);
    },

    updateOption: function(name, value)
    {
        if (name == "net.logLimit")
            this.updateMaxLimit();
    },

    updateMaxLimit: function()
    {
        var value = Options.get("net.logLimit");
        this.maxQueueRequests = value ? value : this.maxQueueRequests;
    },

    // xxxHonza: console.timeStamp() API implementation should really be here?
    addTimeStamp: function(context, time, label, color)
    {
        if (context.netProgress)
            context.netProgress.post(timeStamp, [context.window, time, label, color]);
    },

    /**
     * Used to resend an existing requests.
     *
     * @param {Object} file The structure representing an existing request.
     */
    sendRequest: function(context, file)
    {
        if (FBTrace.DBG_NET)
            FBTrace.sysout("net.sendRequest;", file);

        try
        {
            var win = Win.unwrap(context.window);
            var request = new win.XMLHttpRequest();
            request.open(file.method, file.href, true);

            var headers = file.requestHeaders;
            for (var i=0; headers && i<headers.length; i++)
            {
                var header = headers[i];
                request.setRequestHeader(header.name, header.value);
            }

            request.send(file.postText);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.sysout("netMonitor.sendRequest; EXCEPTION " + err, err);
        }
    }
});

// ********************************************************************************************* //
// Registration

Chrome.registerModule(NetMonitor);

return NetMonitor;

// ********************************************************************************************* //
});
<commit_msg>Update tracing<commit_after>/* See license.txt for terms of usage */

define([
    "httpmonitor/lib/trace",
    "httpmonitor/lib/object",
    "httpmonitor/lib/options",
    "httpmonitor/lib/string",
    "httpmonitor/lib/http",
    "httpmonitor/net/httpActivityObserver",
    "httpmonitor/net/httpRequestObserver",
    "httpmonitor/net/netProgress",          //xxxHonza:is this dep correct?.
    "httpmonitor/net/netUtils",
    "httpmonitor/lib/events",
    "httpmonitor/net/netCacheListener",
    "httpmonitor/base/module",
    "httpmonitor/chrome/chrome",
    "httpmonitor/lib/window",
    "httpmonitor/chrome/defaultPrefs",
    "httpmonitor/net/documentLoadObserver",
    "httpmonitor/net/windowEventObserver",
],
function(FBTrace, Obj, Options, Str, Http, HttpActivityObserver, HttpRequestObserver,
    NetProgress, NetUtils, Events, NetCacheListener, Module, Chrome, Win, DefaultPrefs,
    DocumentLoadObserver, WindowEventObserver) {

// ********************************************************************************************* //
// Constants

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;

var panelName = "net";

var windowPaint = NetProgress.prototype.windowPaint;
var timeStamp = NetProgress.prototype.timeStamp;
var windowLoad = NetProgress.prototype.windowLoad;
var contentLoad = NetProgress.prototype.contentLoad;

// ********************************************************************************************* //

/**
 * @module Represents a module object for the Net panel. This object is derived
 * from Module in order to support activation (enable/disable).
 * This allows to avoid (performance) expensive features if the functionality is not necessary
 * for the user.
 */
var NetMonitor = Obj.extend(Module,
{
    dispatchName: "netMonitor",
    maxQueueRequests: 500,

    // Observes document load.
    loadObserver: new DocumentLoadObserver(),

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Module

    initialize: function()
    {
        Module.initialize.apply(this, arguments);

        // Initialize options and pass in the pref domain for this application.
        Options.initialize("extensions.httpmonitor");
        Options.registerDefaultPrefs(DefaultPrefs);

        // Register document load observer to get notification about new top document
        // being requested to load.
        this.loadObserver.register(this);
    },

    initializeUI: function()
    {
        Module.initializeUI.apply(this, arguments);

        // Initialize max limit for logged requests.
        NetMonitor.updateMaxLimit();

        // Synchronize buttons with the current filter.
        this.syncFilterButtons();
    },

    shutdown: function()
    {
        Module.shutdown.apply(this, arguments);

        this.loadObserver.unregister();
    },

    initContext: function(context, persistedState)
    {
        Module.initContext.apply(this, arguments);

        if (FBTrace.DBG_NET)
            FBTrace.sysout("net.initContext for: " + context.getName());

        this.initNetContext(context);
        this.attachObservers(context);

        //xxxHonza: needed by NetExport, should be probably somewhere else.
        // Set Page title and id into all document objects.
        var netProgress = context.netProgress;
        for (var i=0; i<netProgress.documents.length; i++)
        {
            var doc = netProgress.documents[i];
            doc.id = context.uid;
            doc.title = NetUtils.getPageTitle(context);
        }
    },

    destroyContext: function(context, persistedState)
    {
        Module.destroyContext.apply(this, arguments);

        if (FBTrace.DBG_NET)
            FBTrace.sysout("net.destroyContext for: " +
                (context ? context.getName() : "No context"));

        this.destroyNetContext(context);
        this.detachObservers(context);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Document Load Observer

    onLoadDocument: function(request, win)
    {
        var context = Chrome.currentContext;
        if (!context || context.window != Win.getRootWindow(win))
        {
            FBTrace.sysout("This request doesn't come from selected tab " +
                Http.safeGetRequestName(request), context);
            return;
        }

        var persist = Chrome.getGlobalAttribute("cmd_togglePersistNet", "checked");
        persist = (persist == "true");

        // New page loaded, clear UI if 'Persist' isn't active.
        if (!persist)
            context.netProgress.clear();

        // Since new top document starts loading we need to reset some context flags.
        // loaded: is set as soon as 'load' even is fired
        // currentPhase: ensure that new phase is created.
        context.netProgress.loaded = false;
        context.netProgress.currentPhase = null;

        if (this.eventObserver)
            this.eventObserver.unregisterListeners();

        // Register an observer for window events (load, paint, etc.)
        this.eventObserver = new WindowEventObserver(context);
        this.eventObserver.registerListeners();

        if (FBTrace.DBG_NET)
            FBTrace.sysout("httpRequestObserver.onModifyRequest; Top document loading...");
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Activation

    initNetContext: function(context)
    {
        if (context.netProgress)
            return;

        if (!this.fbListeners)
            this.fbListeners = [];

        var netProgress = new NetProgress(context, this.fbListeners);
        context.netProgress = netProgress;
    },

    destroyNetContext: function(context)
    {
        delete context.netProgress;
        context.netProgress = null;
    },

    attachObservers: function(context)
    {
        var netProgress = context.netProgress;
        if (!netProgress)
            return;

        // Register activity-distributor observer if available (#488270)
        netProgress.httpActivityObserver = new HttpActivityObserver(context);
        netProgress.httpActivityObserver.registerObserver();

        // Register observer for HTTP events
        netProgress.httpRequestObserver = new HttpRequestObserver(context);
        netProgress.httpRequestObserver.registerObserver();

        // Add cache listener so, net panel has always fresh responses.
        // Safe to call multiple times.
        netProgress.cacheListener = new NetCacheListener(netProgress);
        netProgress.cacheListener.register(context.sourceCache);
    },

    detachObservers: function(context)
    {
        var netProgress = context.netProgress;
        if (!netProgress)
            return;

        netProgress.httpActivityObserver.unregisterObserver();
        delete netProgress.httpActivityObserver;

        netProgress.httpRequestObserver.registerObserver();
        delete netProgress.httpRequestObserver;

        netProgress.cacheListener.unregister();
        delete netProgress.cacheListener;
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // User Actions

    clear: function(context)
    {
        // The user pressed a Clear button so, remove all HTTP collected data. The Net panel
        // is context handler and so the clear action will be automatically forwarded to it.
        if (context.netProgress)
            context.netProgress.clear();
    },

    onToggleFilter: function(context, filterCategory)
    {
        if (!context.netProgress)
            return;

        Options.set("netFilterCategory", filterCategory);

        // The content filter has been changed. Make sure that the content
        // of the panel is updated (CSS is used to hide or show individual files).
        var panel = context.getPanel(panelName, true);
        if (panel)
        {
            panel.setFilter(filterCategory);
            panel.updateSummaries(NetUtils.now(), true);
        }
    },

    syncFilterButtons: function()
    {
        var id = "fbNetFilter-" + Options.get("netFilterCategory");
        var button = Chrome.$(id);
        if (!button)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.sysout("netMonitor.syncFilterButtons; ERROR no button? " + id);

            return;
        }

        button.checked = true;
    },

    togglePersist: function(context)
    {
        var panel = context.getPanel(panelName);
        panel.persistContent = panel.persistContent ? false : true;
        Chrome.setGlobalAttribute("cmd_togglePersistNet", "checked", panel.persistContent);
    },

    updateOption: function(name, value)
    {
        if (name == "net.logLimit")
            this.updateMaxLimit();
    },

    updateMaxLimit: function()
    {
        var value = Options.get("net.logLimit");
        this.maxQueueRequests = value ? value : this.maxQueueRequests;
    },

    // xxxHonza: console.timeStamp() API implementation should really be here?
    addTimeStamp: function(context, time, label, color)
    {
        if (context.netProgress)
            context.netProgress.post(timeStamp, [context.window, time, label, color]);
    },

    /**
     * Used to resend an existing requests.
     *
     * @param {Object} file The structure representing an existing request.
     */
    sendRequest: function(context, file)
    {
        if (FBTrace.DBG_NET)
            FBTrace.sysout("net.sendRequest;", file);

        try
        {
            var win = Win.unwrap(context.window);
            var request = new win.XMLHttpRequest();
            request.open(file.method, file.href, true);

            var headers = file.requestHeaders;
            for (var i=0; headers && i<headers.length; i++)
            {
                var header = headers[i];
                request.setRequestHeader(header.name, header.value);
            }

            request.send(file.postText);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.sysout("netMonitor.sendRequest; EXCEPTION " + err, err);
        }
    }
});

// ********************************************************************************************* //
// Registration

Chrome.registerModule(NetMonitor);

return NetMonitor;

// ********************************************************************************************* //
});
<|endoftext|>


<commit_before>// router
var thatjs = angular.module('thatjs', [
    'ngRoute',
    'pageControllers'
]);

// services
var services = angular.module('thatjs.services', ['ngResource']);

services.factory('Recipe', ['$resource',
    function ($resource) {
        return $resource('/recipes/:id', { id: '@id' });
    }]);

services.factory('MultiRecipeLoader', ['Recipe', '$q',
    function (Recipe, $q) {
        return function () {
            var delay = $q.defer();
            Recipe.query(function (recipes) {
                delay.resolve(recipes);
            },
                function () {
                    delay.reject('Unable to fetch recipes');
                });
            return delay.promise;
        };
    }]);

services.factory('RecipeLoader', ['Recipe', '$route', '$q',
    function (Recipe, $route, $q) {
        return function () {
            var delay = $q.defer();
            // ... stopped here ...
            Recipe.get(function (recipes) {
                delay.resolve(recipes);
            },
                function () {
                    delay.reject('Unable to fetch recipes');
                });
            return delay.promise;
        };
    }]);
<commit_msg>Added apiService ng service object.<commit_after>/*globals angular */
// apiService
// inject dependency into module, then call the service object method
//
// Usage:
// angular.module('thatjs.widget', ['thatjs.apiService'])
//   .controller('widget', function ($scope, $http, apiService) {
//     ...
//     apiService.getData(itemId).then(function (promise) {
//       $scope.myVar = promise.results;
//     });
//
// Notes:
//   $http methods return promise objects

angular.module('thatjs.apiService', [])
    .service('apiService', ['$http', function ($http) {
        return {
            baseUrl: '/api/Navigation',
            getNavigation: function () {
                var promise = $http.get(this.baseUrl)
                    .success(function (data, status, headers, config) {
                        return data;
                    })
                    .error(function (data, status, headers, config) {
                        return {
                            "status": false
                        };
                    });

                return promise;
            },

            getCommand: function (commandId) {
                // /api/Command(000267a3-5c30-40aa-80da-6773466d3a34)
                var promise = $http.get('/api/Command(' + commandId + ')')
                    .success(function (data, status, headers, config) {
                        return data;
                    })
                    .error(function (data, status, headers, config) {
                        return {
                            "status": false
                        };
                    });

                return promise;
            }
        };
    }]);
<|endoftext|>


<commit_before>#!/usr/bin/env node

const path = require('path');
const proc = require('child_process');
const startCase = require('lodash.startcase');

const baseDir = process.argv[2];

const files = proc.execFileSync(
  'find', [baseDir, '-type', 'f'], { encoding: 'utf8' },
).split('\n').filter(s => s !== '');

console.log('.API');

const links = files.map((file) => {
  const doc = file.replace(baseDir, '');
  const title = path.parse(file).name;

  return {
    xref: `* xref:${doc}[${startCase(title)}]`,
    title,
  };
});

// Case-insensitive sort based on titles (so 'token/ERC20' gets sorted as 'erc20')
const sortedLinks = links.sort(function (a, b) {
  return a.title.toLowerCase().localeCompare(b.title.toLowerCase(), undefined, { numeric: true });
});

for (const link of sortedLinks) {
  console.log(link.xref);
}
<commit_msg>Change title of meta transactions page in docs sidebar<commit_after>#!/usr/bin/env node

const path = require('path');
const proc = require('child_process');
const startCase = require('lodash.startcase');

const baseDir = process.argv[2];

const files = proc.execFileSync(
  'find', [baseDir, '-type', 'f'], { encoding: 'utf8' },
).split('\n').filter(s => s !== '');

console.log('.API');

function getPageTitle (directory) {
  if (directory === 'metatx') {
    return 'Meta Transactions';
  } else {
    return startCase(directory);
  }
}

const links = files.map((file) => {
  const doc = file.replace(baseDir, '');
  const title = path.parse(file).name;

  return {
    xref: `* xref:${doc}[${getPageTitle(title)}]`,
    title,
  };
});

// Case-insensitive sort based on titles (so 'token/ERC20' gets sorted as 'erc20')
const sortedLinks = links.sort(function (a, b) {
  return a.title.toLowerCase().localeCompare(b.title.toLowerCase(), undefined, { numeric: true });
});

for (const link of sortedLinks) {
  console.log(link.xref);
}
<|endoftext|>


<commit_before>const express = require('express');
const router = express.Router();
const qp = require('./query_parser');
const agg = require('./aggregation');
// --------------------------------------------------------------------------------------
// get unique users for realm
// --------------------------------------------------------------------------------------
router.get('/', function(req, res, next) {
  var query = qp.parse_query_string(req.url,
    [ 'timestamp', 'username', 'visinst_1', 'visinst_2', "revision", "diff_needed_timediff", "mac_diff" ],
    qp.validate_days);
  search(req, res, next, query);     // perform search with constructed mongo query
});
// --------------------------------------------------------------------------------------
// search database for specified data
// timestamp matches specific day or range of days
// --------------------------------------------------------------------------------------
function search(req, res, next, query) {
  // query for username with records for multiple days
  // gets results separated for each day !
  // this is defined by the query -> needs to be computed on the fly

  // ===================================================
  // if query.filter contains some conditions for data eg. count,
  // the condition must be applied to result of all records aggregated across given timestamps
  // -> the condition must be applied after aggregation !

  var cond = agg.check_filter(query.filter, [ "diff_needed_timediff" ]);
  var mac_diff = agg.check_filter(query.filter, [ "mac_diff" ]);

  // ===================================================
  // construct base query
  var aggregate_query = [
    { $match : query.filter },      // filter by query
    { $project : {
      _id : 0,
      timestamp     : 1,
      timestamp_1   : 1,
      timestamp_2   : 1,
      visinst_1     : 1,
      visinst_2     : 1,
      username      : 1,
      mac_address_1 : 1,
      mac_address_2 : 1,
      time_needed   : 1,
      dist          : 1,
      time_difference : { $divide : [ { $subtract : [ "$timestamp_2", "$timestamp_1" ] }, 1000 ] }, // difference is in milliseconds
      diff_needed_timediff : { $subtract : [ "$time_needed", { $divide : [ { $subtract : [ "$timestamp_2", "$timestamp_1" ] }, 1000 ] } ] }
    } },
  ];

  // ===================================================
  // add condition from original filter if defined
  agg.add_cond(aggregate_query, cond);

  // ===================================================
  // add redact stage if mac_diff is required
  if(Object.keys(mac_diff).length > 0) {
    if(mac_diff.mac_diff == true) // true - different mac addresses
      agg.add_stage(aggregate_query, { "$redact" : { "$cond" : [ { "$ne" : [ "$mac_address_1", "$mac_address_2" ] }, "$$KEEP", "$$PRUNE" ] } });
    else                          // false - same mac addresses
      agg.add_stage(aggregate_query, { "$redact" : { "$cond" : [ { "$eq" : [ "$mac_address_1", "$mac_address_2" ] }, "$$KEEP", "$$PRUNE" ] } });
  }

  // ===================================================
  // add other operators, if defined in query
  agg.add_ops(aggregate_query, query);

  // ===================================================
  // search

  req.db.concurrent_users.aggregate(aggregate_query,
  function(err1, items) {
    if(err1) {
      var err2 = new Error();      // just to detect where the original error happened
      console.error(err2);
      console.error(err1);
      next([err2, err1]);
      return;
    }

    respond(filter_data(req, convert(items)), res);
  });
}
// --------------------------------------------------------------------------------------
// convert timestamp in data
// --------------------------------------------------------------------------------------
function convert(data)
{
  var ret = [];

  for(var item in data) {
    data[item].timestamp = convert_time(data[item].timestamp);
    data[item].timestamp_1 = convert_time(data[item].timestamp_1);
    data[item].timestamp_2 = convert_time(data[item].timestamp_2);
    ret.push(data[item]);
  }

  return ret;
}
// --------------------------------------------------------------------------------------
// convert UTC to localtime based on input
// --------------------------------------------------------------------------------------
function convert_time(date)
{
  d = new Date(date);
  d.setTime(d.getTime() + (-1 * d.getTimezoneOffset() * 60 * 1000));
  return d;
}
// --------------------------------------------------------------------------------------
// filter results so each user can search only relevant records
// realm admin: only records for all administered realms
// --------------------------------------------------------------------------------------
function filter_data(req, data)
{
  var ret = [];

  if(req.session.user.role == "user")
    return ret;

  else if(req.session.user.role == "realm_admin") {
    for(var realm in req.session.user.administered_realms)
      for(var item in data)
        if(data[item].realm == req.session.user.administered_realms[realm])
          ret.push(data[item]);
  }

  else if(req.session.user.role == "admin")  // no filtration
    return data;

  return ret;
}
// --------------------------------------------------------------------------------------
// send data to user
// --------------------------------------------------------------------------------------
function respond(items, res) {
  res.json(items);
}
// --------------------------------------------------------------------------------------
module.exports = router;
<commit_msg>enable machine processing for concurrent_users<commit_after>const express = require('express');
const router = express.Router();
const qp = require('./query_parser');
const agg = require('./aggregation');
// --------------------------------------------------------------------------------------
// get unique users for realm
// --------------------------------------------------------------------------------------
router.get('/', function(req, res, next) {
  var query = qp.parse_query_string(req.url,
    [ 'timestamp', 'username', 'visinst_1', 'visinst_2', "revision", "diff_needed_timediff", "mac_diff" ],
    qp.validate_days);
  search(req, res, next, query);     // perform search with constructed mongo query
});
// --------------------------------------------------------------------------------------
// search database for specified data
// timestamp matches specific day or range of days
// --------------------------------------------------------------------------------------
function search(req, res, next, query) {
  // query for username with records for multiple days
  // gets results separated for each day !
  // this is defined by the query -> needs to be computed on the fly

  // ===================================================
  // if query.filter contains some conditions for data eg. count,
  // the condition must be applied to result of all records aggregated across given timestamps
  // -> the condition must be applied after aggregation !

  var cond = agg.check_filter(query.filter, [ "diff_needed_timediff" ]);
  var mac_diff = agg.check_filter(query.filter, [ "mac_diff" ]);

  // ===================================================
  // construct base query
  var aggregate_query = [
    { $match : query.filter },      // filter by query
    { $project : {
      _id : 0,
      timestamp     : 1,
      timestamp_1   : 1,
      timestamp_2   : 1,
      visinst_1     : 1,
      visinst_2     : 1,
      username      : 1,
      mac_address_1 : 1,
      mac_address_2 : 1,
      time_needed   : 1,
      dist          : 1,
      time_difference : { $divide : [ { $subtract : [ "$timestamp_2", "$timestamp_1" ] }, 1000 ] }, // difference is in milliseconds
      diff_needed_timediff : { $subtract : [ "$time_needed", { $divide : [ { $subtract : [ "$timestamp_2", "$timestamp_1" ] }, 1000 ] } ] }
    } },
  ];

  // ===================================================
  // add condition from original filter if defined
  agg.add_cond(aggregate_query, cond);

  // ===================================================
  // add redact stage if mac_diff is required
  if(Object.keys(mac_diff).length > 0) {
    if(mac_diff.mac_diff == true) // true - different mac addresses
      agg.add_stage(aggregate_query, { "$redact" : { "$cond" : [ { "$ne" : [ "$mac_address_1", "$mac_address_2" ] }, "$$KEEP", "$$PRUNE" ] } });
    else                          // false - same mac addresses
      agg.add_stage(aggregate_query, { "$redact" : { "$cond" : [ { "$eq" : [ "$mac_address_1", "$mac_address_2" ] }, "$$KEEP", "$$PRUNE" ] } });
  }

  // ===================================================
  // add other operators, if defined in query
  agg.add_ops(aggregate_query, query);

  // ===================================================
  // search

  req.db.concurrent_users.aggregate(aggregate_query,
  function(err1, items) {
    if(err1) {
      var err2 = new Error();      // just to detect where the original error happened
      console.error(err2);
      console.error(err1);
      next([err2, err1]);
      return;
    }

    respond(filter_data(req, convert(items)), res);
  });
}
// --------------------------------------------------------------------------------------
// convert timestamp in data
// --------------------------------------------------------------------------------------
function convert(data)
{
  var ret = [];

  for(var item in data) {
    data[item].timestamp = convert_time(data[item].timestamp);
    data[item].timestamp_1 = convert_time(data[item].timestamp_1);
    data[item].timestamp_2 = convert_time(data[item].timestamp_2);
    ret.push(data[item]);
  }

  return ret;
}
// --------------------------------------------------------------------------------------
// convert UTC to localtime based on input
// --------------------------------------------------------------------------------------
function convert_time(date)
{
  d = new Date(date);
  d.setTime(d.getTime() + (-1 * d.getTimezoneOffset() * 60 * 1000));
  return d;
}
// --------------------------------------------------------------------------------------
// filter results so each user can search only relevant records
// realm admin: only records for all administered realms
// --------------------------------------------------------------------------------------
function filter_data(req, data)
{
  var ret = [];
  var done = false;

  if(!req.headers["remote_user"]) {     // remote user not set for machine processing
    var ip = req.headers['x-forwarded-for'] ||
      req.connection.remoteAddress ||
      req.socket.remoteAddress ||
      req.connection.socket.remoteAddress;

    check_privileged_ips(req, ip, function(found) {
      if(found)
        ret = data;      // no filtering for machine processing

      done = true;
    });

    deasync.loopWhile(function() {
      return !done;
    });

    return ret;     // filter based on ip
  }

  if(req.session.user.role == "user")
    return ret;

  else if(req.session.user.role == "realm_admin") {
    for(var realm in req.session.user.administered_realms)
      for(var item in data)
        if(data[item].realm == req.session.user.administered_realms[realm])
          ret.push(data[item]);
  }

  else if(req.session.user.role == "admin")  // no filtration
    return data;

  return ret;
}
// --------------------------------------------------------------------------------------
// check database for specific privileged ip
// --------------------------------------------------------------------------------------
function check_privileged_ips(req, ip, callback)
{
  // search for privileged ip
  req.db.privileged_ips.find({ "ip" : ip }, { ip : 1, _id : 0 }, function(err1, items) {
    if(err1) {
      var err2 = new Error();      // just to detect where the original error happened
      console.error(err2);
      console.error(err1);
      next([err2, err1]);
      return;
    }

    if(items.length > 0)
      callback(true);
    else
      callback(false);
  });
}
// --------------------------------------------------------------------------------------
// send data to user
// --------------------------------------------------------------------------------------
function respond(items, res) {
  res.json(items);
}
// --------------------------------------------------------------------------------------
module.exports = router;
<|endoftext|>


<commit_before><commit_msg>Update board.js<commit_after><|endoftext|>


<commit_before>import qs from 'qs';
import { window } from 'global';
import { selectStory } from './actions';

// Ensure the story in the redux store and on the preview URL are in sync.
// In theory we should listen to pushState events but given it's an iframe
// the user can't actually change the URL.
// We should change this if we support a "preview only" mode in the future.
export default function syncUrlToStore(reduxStore) {
  // handle query params
  const queryParams = qs.parse(window.location.search.substring(1));
  if (queryParams.selectedKind) {
    reduxStore.dispatch(selectStory(queryParams.selectedKind, queryParams.selectedStory));
  }

  reduxStore.subscribe(() => {
    const { selectedKind, selectedStory } = reduxStore.getState();

    const queryString = qs.stringify({
      ...queryParams,
      selectedKind,
      selectedStory,
    });
    window.history.pushState({}, '', `?${queryString}`);
  });
}
<commit_msg>Fix browser navigation again<commit_after>import qs from 'qs';
import { window } from 'global';
import { selectStory } from './actions';

// Ensure the story in the redux store and on the preview URL are in sync.
// In theory we should listen to pushState events but given it's an iframe
// the user can't actually change the URL.
// We should change this if we support a "preview only" mode in the future.
export default function syncUrlToStore(reduxStore) {
  // handle query params
  const queryParams = qs.parse(window.location.search.substring(1));
  if (queryParams.selectedKind) {
    reduxStore.dispatch(selectStory(queryParams.selectedKind, queryParams.selectedStory));
  }

  reduxStore.subscribe(() => {
    const { selectedKind, selectedStory } = reduxStore.getState();

    const queryString = qs.stringify({
      ...queryParams,
      selectedKind,
      selectedStory,
    });
    window.history.replaceState({}, '', `?${queryString}`);
  });
}
<|endoftext|>


<commit_before>// var inp = `
// Modern NLP algorithms are based on machine learning, especially statistical machine learning. The paradigm of machine learning is different from that of most prior attempts at language processing. Prior implementations of language-processing tasks typically involved the direct hand coding of large sets of rules. The machine-learning paradigm calls instead for using general learning algorithms — often, although not always, grounded in statistical inference — to automatically learn such rules through the analysis of large corpora of typical real-world examples. A corpus (plural, "corpora") is a set of documents (or sometimes, individual sentences) that have been hand-annotated with the correct values to be learned.

// Many different classes of machine learning algorithms have been applied to NLP tasks. These algorithms take as input a large set of "features" that are generated from the input data. Some of the earliest-used algorithms, such as decision trees, produced systems of hard if-then rules similar to the systems of hand-written rules that were then common. Increasingly, however, research has focused on statistical models, which make soft, probabilistic decisions based on attaching real-valued weights to each input feature. Such models have the advantage that they can express the relative certainty of many different possible answers rather than only one, producing more reliable results when such a model is included as a component of a larger system.
// `
// if word ends a sentence
var isLastWord = word => (
  word[word.length-1] === '.' ||
  word[word.length-1] === '\n' && word[word.length-2] === '.'
);
var sample = arr => arr[Math.floor(Math.random() * arr.length)];
var capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);

function markov(input, limit) {
  var tokenized = input.split(' ');
  var textLen = tokenized.length;
  limit = limit || textLen;

  var nextWords = {};

  var startingWords = [];

  for (var i = 0; i < textLen - 1; i++) {
    var currentWord = tokenized[i];
    var nextWord = tokenized[i+1];
    var previousWord = i && tokenized[i-1];

    if (currentWord && !previousWord || isLastWord(previousWord)) {
      startingWords.push(currentWord);
    }

    if (nextWords[currentWord]) {
      nextWords[currentWord].push(nextWord);
    }
    else {
      nextWords[currentWord] = [nextWord];
    }
  }

  var output = [capitalize(sample(startingWords))]

  var previousWord;
  for (var i = 1; i < limit; i++) {
    previousWord = output[i-1];
    var nextWord = nextWords[previousWord] && sample(nextWords[previousWord])

    // this one's an edge case; if it encounters the last word in the text
    if (!nextWord) {
      output.push(capitalize(sample(startingWords)))
    }
    // if sentence just ended, start a new sentence
    else if (isLastWord(previousWord)) {
      output.push(capitalize(nextWord));
    }
    else {
      output.push(nextWord);
    }
  }

  // close out last sentence
  while (!isLastWord(previousWord)) {
    var nextWord = sample(nextWords[previousWord])
    output.push(nextWord);
    previousWord = nextWord
  }

  return output.join(' ')
}
<commit_msg>fixed bug<commit_after>// let inp = `
// Modern NLP algorithms are based on machine learning, especially statistical machine learning. The paradigm of machine learning is different from that of most prior attempts at language processing. Prior implementations of language-processing tasks typically involved the direct hand coding of large sets of rules. The machine-learning paradigm calls instead for using general learning algorithms — often, although not always, grounded in statistical inference — to automatically learn such rules through the analysis of large corpora of typical real-world examples. A corpus (plural, "corpora") is a set of documents (or sometimes, individual sentences) that have been hand-annotated with the correct values to be learned.

// Many different classes of machine learning algorithms have been applied to NLP tasks. These algorithms take as input a large set of "features" that are generated from the input data. Some of the earliest-used algorithms, such as decision trees, produced systems of hard if-then rules similar to the systems of hand-written rules that were then common. Increasingly, however, research has focused on statistical models, which make soft, probabilistic decisions based on attaching real-valued weights to each input feature. Such models have the advantage that they can express the relative certainty of many different possible answers rather than only one, producing more reliable results when such a model is included as a component of a larger system.
// `
// if word ends a sentence

'use strict';

const isLastWord = word => (
  word[word.length-1] === '.' ||
  word[word.length-1] === '\n' && word[word.length-2] === '.'
);
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);

function markov(input, limit) {
  let tokenized = input.split(' ');
  let textLen = tokenized.length;
  limit = limit || textLen;

  let nextWords = {};

  let startingWords = [];

  for (let i = 0; i < textLen - 1; i++) {
    let currentWord = tokenized[i];
    let nextWord = tokenized[i+1];
    let previousWord = i && tokenized[i-1];

    if (currentWord && !previousWord || isLastWord(previousWord)) {
      startingWords.push(currentWord);
    }

    if (nextWords[currentWord]) {
      nextWords[currentWord].push(nextWord);
    }
    else {
      nextWords[currentWord] = [nextWord];
    }
  }

  let output = [capitalize(sample(startingWords))]

  let previousWord;
  for (let i = 1; i < limit; i++) {
    previousWord = output[i-1].toLowerCase();
    let nextWord = nextWords[previousWord] && sample(nextWords[previousWord])

    // this one's an edge case; if it encounters the last word in the text
    if (!nextWord) {
      output.push(capitalize(sample(startingWords)))
    }
    // if sentence just ended, start a new sentence
    else if (isLastWord(previousWord)) {
      output.push(capitalize(nextWord));
    }
    else {
      output.push(nextWord);
    }
  }

  // close out last sentence
  while (!isLastWord(previousWord)) {
    let nextWord = sample(nextWords[previousWord])
    output.push(nextWord);
    previousWord = nextWord
  }
  console.log(output.join(' '))
  return output.join(' ')
}
<|endoftext|>


<commit_before>'use strict'
const Generator = require('yeoman-generator')
const _ = require('lodash')
const yaml = require('js-yaml')
const fs = require('fs')
const mkdirp = require('mkdirp')
const glob = require('glob')

module.exports = class extends Generator {
  initializing () {
    // this.currentDir = path.basename(process.cwd());
    this.props = {}
    this.byId = false
    this.resources = []

    // Find conf file
    let locate = () => {
      let files = glob.sync('{./,../,../../,../../../}/serverless.yml', {
        nodir: true,
        realpath: true
      })

      if (!files) {
        this.log.error('serverless.yml NOT FOUND, for overwrite go inside a project.')
      }

      return files ? files[0] : './'
    }

    this.configFile = locate()
  }

  prompting () {
    return this.prompt([
      {
        type: 'input',
        name: 'path',
        message: 'Path (can include parameters)',
        filter: value => (!value || !value.startsWith('/')) ? `/${value}` : _.toLower(value),
        validate: value => {
          // @TODO: cant have special chars
          return !_.isEmpty(value)
        }
      },

      {
        type: 'list',
        name: 'method',
        message: 'Which HTTP method?',
        choices: () => {
          return [
            'GET',
            'POST',
            'PUT',
            'DELETE',
            'HEAD',
            'CONNECT',
            'OPTIONS',
            'PATH'
          ]
        },
        filter: _.toLower
      },
      {
        type: 'input',
        name: 'description',
        message: 'Your function description',
        default: answers => {
          let by = ''
          this.resources = answers.path.split('/').filter(p => p !== '' && !p.match(/{|}/))
          if (answers.path.endsWith('}')) {
            this.byId = true
            by = ' by ' + answers.path.split(/[{}]/).filter(p => p !== '' && !p.includes('/')).pop()
          }

          return `${_.capitalize(answers.method)} ${this.resources.join(' ')}${by}`
        }
      }
    ]).then(answers => {
      this.props = answers
    })
  }

  writing () {
    let method = `${this.props.method}`
    let filename = method
    let lambda = `${method}-${this.resources.join('-')}`
    let folders = this.props.path.match(/[\w]+(?![^{]*\})/g)

    // only when by resource
    if (this.byId) {
      filename = 'id'
      if (method === 'get') {
        lambda += '-id'
      }
    }

    // build the configuration file
    try {
      // create function handler
      let destination = `functions/${folders.join('/')}`
      mkdirp(destination)
      let handler = `${destination}/${filename}.handler`
      this.fs.copyTpl(
        this.templatePath('handler'),
        this.destinationPath(`${destination}/${filename}.js`),
        {
          lambda,
          method,
          path: '../'.repeat(folders.length + 1)
        }
      )

      // overwrite serverless.yml
      let serverless = yaml.safeLoad(fs.readFileSync(this.configFile, 'utf8'))
      let name = typeof serverless.service === 'object' ? serverless.service.name : serverless.service
      serverless.functions[lambda] = {
        name: `${name}-${lambda}`,
        description: this.props.description,
        handler,
        events: [{
          http: {
            method: _.toUpper(this.props.method),
            path: this.props.path,
            cors: true
          }
        }]
      }

      // write the file
      fs.writeFile(
        this.configFile,
        yaml.safeDump(serverless),
        () => this.log.ok(`${_.toUpper(method)} ${this.props.path} ► ${handler} (${lambda})`)
      )
    } catch (err) {
      this.log.error(`Error: ${err.message}`)
    }
  }
}
<commit_msg>hotfix, start using `by` as universal parameter when get by some parameter<commit_after>'use strict'
const Generator = require('yeoman-generator')
const _ = require('lodash')
const yaml = require('js-yaml')
const fs = require('fs')
const mkdirp = require('mkdirp')
const glob = require('glob')

module.exports = class extends Generator {
  initializing () {
    this.props = {}
    this.id = null
    this.resources = []

    // Find conf file
    let locate = () => {
      let files = glob.sync('{./,../,../../,../../../}/serverless.yml', {
        nodir: true,
        realpath: true
      })

      if (!files) {
        this.log.error('serverless.yml NOT FOUND, for overwrite go inside a project.')
      }

      return files ? files[0] : './'
    }

    this.configFile = locate()
  }

  prompting () {
    return this.prompt([
      {
        type: 'input',
        name: 'path',
        message: 'Path (can include parameters)',
        filter: value => (!value || !value.startsWith('/')) ? `/${value}` : _.toLower(value),
        validate: value => {
          // @TODO: cant have special chars
          return !_.isEmpty(value)
        }
      },

      {
        type: 'list',
        name: 'method',
        message: 'Which HTTP method?',
        choices: () => {
          return [
            'GET',
            'POST',
            'PUT',
            'DELETE',
            'HEAD',
            'CONNECT',
            'OPTIONS',
            'PATH'
          ]
        },
        filter: _.toLower
      },
      {
        type: 'input',
        name: 'description',
        message: 'Your function description',
        default: answers => {
          let by = ''
          this.resources = answers.path.split('/').filter(p => p !== '' && !p.match(/{|}/))
          if (answers.path.endsWith('}')) {
            this.id = answers.path.split(/[{}]/).filter(p => p !== '' && !p.includes('/')).pop()
            by = ' by ' + this.id
          }

          return `${_.capitalize(answers.method)} ${this.resources.join(' ')}${by}`
        }
      }
    ]).then(answers => {
      this.props = answers
    })
  }

  writing () {
    let method = `${this.props.method}`
    let filename = method
    let lambda = `${method}-${this.resources.join('-')}`
    let folders = this.props.path.match(/[\w]+(?![^{]*\})/g)

    // only when by resource
    if (this.id) {
      filename = 'by'
      if (method === 'get') {
        lambda += `-${filename}`
      }
    }

    // build the configuration file
    try {
      // create function handler
      let destination = `functions/${folders.join('/')}`
      mkdirp(destination)
      let handler = `${destination}/${filename}.handler`
      this.fs.copyTpl(
        this.templatePath('handler'),
        this.destinationPath(`${destination}/${filename}.js`),
        {
          lambda,
          method,
          path: '../'.repeat(folders.length + 1)
        }
      )

      // overwrite serverless.yml
      let serverless = yaml.safeLoad(fs.readFileSync(this.configFile, 'utf8'))
      let name = typeof serverless.service === 'object' ? serverless.service.name : serverless.service
      serverless.functions[lambda] = {
        name: `${name}-${lambda}`,
        description: this.props.description,
        handler,
        events: [{
          http: {
            method: _.toUpper(this.props.method),
            path: this.props.path,
            cors: true
          }
        }]
      }

      // write the file
      fs.writeFile(
        this.configFile,
        yaml.safeDump(serverless),
        () => this.log.ok(`${_.toUpper(method)} ${this.props.path} ► ${handler} (${lambda})`)
      )
    } catch (err) {
      this.log.error(`Error: ${err.message}`)
    }
  }
}
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

define([
    "httpmonitor/lib/trace",
    "httpmonitor/lib/object",
    "httpmonitor/lib/options",
    "httpmonitor/lib/string",
    "httpmonitor/lib/http",
    "httpmonitor/net/httpActivityObserver",
    "httpmonitor/net/httpRequestObserver",
    "httpmonitor/net/netProgress",          //xxxHonza:is this dep correct?.
    "httpmonitor/net/netUtils",
    "httpmonitor/lib/events",
    "httpmonitor/net/netCacheListener",
    "httpmonitor/base/module",
    "httpmonitor/chrome/chrome",
    "httpmonitor/lib/window",
    "httpmonitor/chrome/defaultPrefs",
    "httpmonitor/net/documentLoadObserver",
    "httpmonitor/net/windowEventObserver",
],
function(FBTrace, Obj, Options, Str, Http, HttpActivityObserver, HttpRequestObserver,
    NetProgress, NetUtils, Events, NetCacheListener, Module, Chrome, Win, DefaultPrefs,
    DocumentLoadObserver, WindowEventObserver) {

// ********************************************************************************************* //
// Constants

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;

var panelName = "net";

var windowPaint = NetProgress.prototype.windowPaint;
var timeStamp = NetProgress.prototype.timeStamp;
var windowLoad = NetProgress.prototype.windowLoad;
var contentLoad = NetProgress.prototype.contentLoad;

// ********************************************************************************************* //

/**
 * @module Represents a module object for the Net panel. This object is derived
 * from Module in order to support activation (enable/disable).
 * This allows to avoid (performance) expensive features if the functionality is not necessary
 * for the user.
 */
var NetMonitor = Obj.extend(Module,
{
    dispatchName: "netMonitor",
    maxQueueRequests: 500,

    // Observes document load.
    loadObserver: new DocumentLoadObserver(),

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Module

    initialize: function()
    {
        Module.initialize.apply(this, arguments);

        // Initialize options and pass in the pref domain for this application.
        Options.initialize("extensions.httpmonitor");
        Options.registerDefaultPrefs(DefaultPrefs);

        // Register document load observer to get notification about new top document
        // being requested to load.
        this.loadObserver.register(this);
    },

    initializeUI: function()
    {
        Module.initializeUI.apply(this, arguments);

        // Initialize max limit for logged requests.
        NetMonitor.updateMaxLimit();

        // Synchronize buttons with the current filter.
        this.syncFilterButtons();
    },

    shutdown: function()
    {
        Module.shutdown.apply(this, arguments);

        this.loadObserver.unregister();
    },

    initContext: function(context, persistedState)
    {
        Module.initContext.apply(this, arguments);

        if (FBTrace.DBG_NET)
            FBTrace.sysout("net.initContext for: " + context.getName());

        this.initNetContext(context);
        this.attachObservers(context);

        //xxxHonza: needed by NetExport, should be probably somewhere else.
        // Set Page title and id into all document objects.
        var netProgress = context.netProgress;
        for (var i=0; i<netProgress.documents.length; i++)
        {
            var doc = netProgress.documents[i];
            doc.id = context.uid;
            doc.title = NetUtils.getPageTitle(context);
        }
    },

    destroyContext: function(context, persistedState)
    {
        Module.destroyContext.apply(this, arguments);

        if (FBTrace.DBG_NET)
            FBTrace.sysout("net.destroyContext for: " +
                (context ? context.getName() : "No context"));

        this.destroyNetContext(context);
        this.detachObservers(context);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Document Load Observer

    onLoadDocument: function(request, win)
    {
        var context = Chrome.currentContext;
        if (!context || context.window != Win.getRootWindow(win))
        {
            FBTrace.sysout("This request doesn't come from selected tab " +
                Http.safeGetRequestName(request), context);
            return;
        }

        var persist = Chrome.getGlobalAttribute("cmd_togglePersistNet", "checked");
        persist = (persist == "true");

        // New page loaded, clear UI if 'Persist' isn't active.
        if (!persist)
            context.netProgress.clear();

        // Since new top document starts loading we need to reset some context flags.
        // loaded: is set as soon as 'load' even is fired
        // currentPhase: ensure that new phase is created.
        context.netProgress.loaded = false;
        context.netProgress.currentPhase = null;

        if (this.eventObserver)
            this.eventObserver.unregisterListeners();

        // Register an observer for window events (load, paint, etc.)
        this.eventObserver = new WindowEventObserver(context);
        this.eventObserver.registerListeners();

        if (FBTrace.DBG_NET)
            FBTrace.sysout("httpRequestObserver.onModifyRequest; Top document loading...");
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Activation

    initNetContext: function(context)
    {
        if (context.netProgress)
            return;

        if (!this.fbListeners)
            this.fbListeners = [];

        var netProgress = new NetProgress(context, this.fbListeners);
        context.netProgress = netProgress;
    },

    destroyNetContext: function(context)
    {
        delete context.netProgress;
        context.netProgress = null;
    },

    attachObservers: function(context)
    {
        var netProgress = context.netProgress;
        if (!netProgress)
            return;

        // Register activity-distributor observer if available (#488270)
        netProgress.httpActivityObserver = new HttpActivityObserver(context);
        netProgress.httpActivityObserver.registerObserver();

        // Register observer for HTTP events
        netProgress.httpRequestObserver = new HttpRequestObserver(context);
        netProgress.httpRequestObserver.registerObserver();

        // Add cache listener so, net panel has always fresh responses.
        // Safe to call multiple times.
        netProgress.cacheListener = new NetCacheListener(netProgress);
        netProgress.cacheListener.register(context.sourceCache);
    },

    detachObservers: function(context)
    {
        var netProgress = context.netProgress;
        if (!netProgress)
            return;

        netProgress.httpActivityObserver.unregisterObserver();
        delete netProgress.httpActivityObserver;

        netProgress.httpRequestObserver.registerObserver();
        delete netProgress.httpRequestObserver;

        netProgress.cacheListener.unregister();
        delete netProgress.cacheListener;
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // User Actions

    clear: function(context)
    {
        // The user pressed a Clear button so, remove all HTTP collected data. The Net panel
        // is context handler and so the clear action will be automatically forwarded to it.
        if (context.netProgress)
            context.netProgress.clear();
    },

    onToggleFilter: function(context, filterCategory)
    {
        if (!context.netProgress)
            return;

        Options.set("netFilterCategory", filterCategory);

        // The content filter has been changed. Make sure that the content
        // of the panel is updated (CSS is used to hide or show individual files).
        var panel = context.getPanel(panelName, true);
        if (panel)
        {
            panel.setFilter(filterCategory);
            panel.updateSummaries(NetUtils.now(), true);
        }
    },

    syncFilterButtons: function()
    {
        var id = "fbNetFilter-" + Options.get("netFilterCategory");
        var button = Chrome.$(id);
        if (!button)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.sysout("netMonitor.syncFilterButtons; ERROR no button? " + id);

            return;
        }

        button.checked = true;
    },

    togglePersist: function(context)
    {
        var panel = context.getPanel(panelName);
        panel.persistContent = panel.persistContent ? false : true;
        Chrome.setGlobalAttribute("cmd_togglePersistNet", "checked", panel.persistContent);
    },

    updateOption: function(name, value)
    {
        if (name == "net.logLimit")
            this.updateMaxLimit();
    },

    updateMaxLimit: function()
    {
        var value = Options.get("net.logLimit");
        this.maxQueueRequests = value ? value : this.maxQueueRequests;
    },

    // xxxHonza: console.timeStamp() API implementation should really be here?
    addTimeStamp: function(context, time, label, color)
    {
        if (context.netProgress)
            context.netProgress.post(timeStamp, [context.window, time, label, color]);
    },

    /**
     * Used to resend an existing requests.
     *
     * @param {Object} file The structure representing an existing request.
     */
    sendRequest: function(context, file)
    {
        if (FBTrace.DBG_NET)
            FBTrace.sysout("net.sendRequest;", file);

        try
        {
            var win = Win.unwrap(context.window);
            var request = new win.XMLHttpRequest();
            request.open(file.method, file.href, true);

            var headers = file.requestHeaders;
            for (var i=0; headers && i<headers.length; i++)
            {
                var header = headers[i];
                request.setRequestHeader(header.name, header.value);
            }

            request.send(file.postText);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.sysout("netMonitor.sendRequest; EXCEPTION " + err, err);
        }
    }
});

// ********************************************************************************************* //
// Registration

Chrome.registerModule(NetMonitor);

return NetMonitor;

// ********************************************************************************************* //
});
<commit_msg>Register window event listener within attachObserver method where all the other observers are registered too.<commit_after>/* See license.txt for terms of usage */

define([
    "httpmonitor/lib/trace",
    "httpmonitor/lib/object",
    "httpmonitor/lib/options",
    "httpmonitor/lib/string",
    "httpmonitor/lib/http",
    "httpmonitor/net/httpActivityObserver",
    "httpmonitor/net/httpRequestObserver",
    "httpmonitor/net/netProgress",          //xxxHonza:is this dep correct?.
    "httpmonitor/net/netUtils",
    "httpmonitor/lib/events",
    "httpmonitor/net/netCacheListener",
    "httpmonitor/base/module",
    "httpmonitor/chrome/chrome",
    "httpmonitor/lib/window",
    "httpmonitor/chrome/defaultPrefs",
    "httpmonitor/net/documentLoadObserver",
    "httpmonitor/net/windowEventObserver",
],
function(FBTrace, Obj, Options, Str, Http, HttpActivityObserver, HttpRequestObserver,
    NetProgress, NetUtils, Events, NetCacheListener, Module, Chrome, Win, DefaultPrefs,
    DocumentLoadObserver, WindowEventObserver) {

// ********************************************************************************************* //
// Constants

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;

var panelName = "net";

var windowPaint = NetProgress.prototype.windowPaint;
var timeStamp = NetProgress.prototype.timeStamp;
var windowLoad = NetProgress.prototype.windowLoad;
var contentLoad = NetProgress.prototype.contentLoad;

// ********************************************************************************************* //

/**
 * @module Represents a module object for the Net panel. This object is derived
 * from Module in order to support activation (enable/disable).
 * This allows to avoid (performance) expensive features if the functionality is not necessary
 * for the user.
 */
var NetMonitor = Obj.extend(Module,
{
    dispatchName: "netMonitor",
    maxQueueRequests: 500,

    // Observes document load.
    loadObserver: new DocumentLoadObserver(),

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Module

    initialize: function()
    {
        Module.initialize.apply(this, arguments);

        // Initialize options and pass in the pref domain for this application.
        Options.initialize("extensions.httpmonitor");
        Options.registerDefaultPrefs(DefaultPrefs);

        // Register document load observer to get notification about new top document
        // being requested to load.
        this.loadObserver.register(this);
    },

    initializeUI: function()
    {
        Module.initializeUI.apply(this, arguments);

        // Initialize max limit for logged requests.
        NetMonitor.updateMaxLimit();

        // Synchronize buttons with the current filter.
        this.syncFilterButtons();
    },

    shutdown: function()
    {
        Module.shutdown.apply(this, arguments);

        this.loadObserver.unregister();
    },

    initContext: function(context, persistedState)
    {
        Module.initContext.apply(this, arguments);

        if (FBTrace.DBG_NET)
            FBTrace.sysout("net.initContext for: " + context.getName());

        this.initNetContext(context);
        this.attachObservers(context);

        //xxxHonza: needed by NetExport, should be probably somewhere else.
        // Set Page title and id into all document objects.
        var netProgress = context.netProgress;
        for (var i=0; i<netProgress.documents.length; i++)
        {
            var doc = netProgress.documents[i];
            doc.id = context.uid;
            doc.title = NetUtils.getPageTitle(context);
        }
    },

    destroyContext: function(context, persistedState)
    {
        Module.destroyContext.apply(this, arguments);

        if (FBTrace.DBG_NET)
            FBTrace.sysout("net.destroyContext for: " +
                (context ? context.getName() : "No context"));

        this.destroyNetContext(context);
        this.detachObservers(context);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Document Load Observer

    onLoadDocument: function(request, win)
    {
        var context = Chrome.currentContext;
        if (!context || context.window != Win.getRootWindow(win))
        {
            FBTrace.sysout("This request doesn't come from selected tab " +
                Http.safeGetRequestName(request), context);
            return;
        }

        var persist = Chrome.getGlobalAttribute("cmd_togglePersistNet", "checked");
        persist = (persist == "true");

        // New page loaded, clear UI if 'Persist' isn't active.
        if (!persist)
            context.netProgress.clear();

        // Since new top document starts loading we need to reset some context flags.
        // loaded: is set as soon as 'load' even is fired
        // currentPhase: ensure that new phase is created.
        context.netProgress.loaded = false;
        context.netProgress.currentPhase = null;

        if (FBTrace.DBG_NET)
            FBTrace.sysout("netMonitor.onModifyRequest; Top document loading...");
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Activation

    initNetContext: function(context)
    {
        if (context.netProgress)
            return;

        if (!this.fbListeners)
            this.fbListeners = [];

        var netProgress = new NetProgress(context, this.fbListeners);
        context.netProgress = netProgress;

        return netProgress;
    },

    destroyNetContext: function(context)
    {
        delete context.netProgress;
        context.netProgress = null;
    },

    attachObservers: function(context)
    {
        var netProgress = context.netProgress;
        if (!netProgress)
            return;

        // Register activity-distributor observer if available (#488270)
        if (!netProgress.httpActivityObserver)
        {
            netProgress.httpActivityObserver = new HttpActivityObserver(context);
            netProgress.httpActivityObserver.registerObserver();
        }

        // Register observer for HTTP events
        if (!netProgress.httpRequestObserver)
        {
            netProgress.httpRequestObserver = new HttpRequestObserver(context);
            netProgress.httpRequestObserver.registerObserver();
        }

        // Add cache listener so, net panel has always fresh responses.
        // Safe to call multiple times.
        if (!netProgress.cacheListener && context.sourceCache)
        {
            netProgress.cacheListener = new NetCacheListener(netProgress);
            netProgress.cacheListener.register(context.sourceCache);
        }

        // Register observer for window events (load, DOMContentLoaded)
        if (!netProgress.windowObserver && context.uid)
        {
            netProgress.windowObserver = new WindowEventObserver(context);
            netProgress.windowObserver.registerListeners();
        }
    },

    detachObservers: function(context)
    {
        var netProgress = context.netProgress;
        if (!netProgress)
            return;

        netProgress.httpActivityObserver.unregisterObserver();
        delete netProgress.httpActivityObserver;

        netProgress.httpRequestObserver.registerObserver();
        delete netProgress.httpRequestObserver;

        netProgress.cacheListener.unregister();
        delete netProgress.cacheListener;

        netProgress.windowObserver.unregisterListeners();
        delete netProgress.windowObserver;
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // User Actions

    clear: function(context)
    {
        // The user pressed a Clear button so, remove all HTTP collected data. The Net panel
        // is context handler and so the clear action will be automatically forwarded to it.
        if (context.netProgress)
            context.netProgress.clear();
    },

    onToggleFilter: function(context, filterCategory)
    {
        if (!context.netProgress)
            return;

        Options.set("netFilterCategory", filterCategory);

        // The content filter has been changed. Make sure that the content
        // of the panel is updated (CSS is used to hide or show individual files).
        var panel = context.getPanel(panelName, true);
        if (panel)
        {
            panel.setFilter(filterCategory);
            panel.updateSummaries(NetUtils.now(), true);
        }
    },

    syncFilterButtons: function()
    {
        var id = "fbNetFilter-" + Options.get("netFilterCategory");
        var button = Chrome.$(id);
        if (!button)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.sysout("netMonitor.syncFilterButtons; ERROR no button? " + id);

            return;
        }

        button.checked = true;
    },

    togglePersist: function(context)
    {
        var panel = context.getPanel(panelName);
        panel.persistContent = panel.persistContent ? false : true;
        Chrome.setGlobalAttribute("cmd_togglePersistNet", "checked", panel.persistContent);
    },

    updateOption: function(name, value)
    {
        if (name == "net.logLimit")
            this.updateMaxLimit();
    },

    updateMaxLimit: function()
    {
        var value = Options.get("net.logLimit");
        this.maxQueueRequests = value ? value : this.maxQueueRequests;
    },

    // xxxHonza: console.timeStamp() API implementation should really be here?
    addTimeStamp: function(context, time, label, color)
    {
        if (context.netProgress)
            context.netProgress.post(timeStamp, [context.window, time, label, color]);
    },

    /**
     * Used to resend an existing requests.
     *
     * @param {Object} file The structure representing an existing request.
     */
    sendRequest: function(context, file)
    {
        if (FBTrace.DBG_NET)
            FBTrace.sysout("net.sendRequest;", file);

        try
        {
            var win = Win.unwrap(context.window);
            var request = new win.XMLHttpRequest();
            request.open(file.method, file.href, true);

            var headers = file.requestHeaders;
            for (var i=0; headers && i<headers.length; i++)
            {
                var header = headers[i];
                request.setRequestHeader(header.name, header.value);
            }

            request.send(file.postText);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.sysout("netMonitor.sendRequest; EXCEPTION " + err, err);
        }
    }
});

// ********************************************************************************************* //
// Registration

Chrome.registerModule(NetMonitor);

return NetMonitor;

// ********************************************************************************************* //
});
<|endoftext|>