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

define([
    "firebug/lib/object",
    "firebug/firebug",
    "firebug/dom/toggleBranch",
    "firebug/lib/events",
    "firebug/lib/dom",
    "firebug/lib/css",
    "firebug/js/stackFrame",
    "firebug/dom/domPanel",     // Firebug.DOMBasePanel, Firebug.DOMPanel.DirTable
],
function(Obj, Firebug, ToggleBranch, Events, Dom, Css, StackFrame) {

// ********************************************************************************************* //
// Watch Panel

Firebug.WatchPanel = function()
{
}

/**
 * Represents the Watch side panel available in the Script panel.
 */
Firebug.WatchPanel.prototype = Obj.extend(Firebug.DOMBasePanel.prototype,
/** @lends Firebug.WatchPanel */
{
    tag: Firebug.DOMPanel.DirTable.watchTag,

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // extends Panel

    name: "watches",
    order: 0,
    parentPanel: "script",
    enableA11y: true,
    deriveA11yFrom: "console",

    initialize: function()
    {
        this.onMouseDown = Obj.bind(this.onMouseDown, this);
        this.onMouseOver = Obj.bind(this.onMouseOver, this);
        this.onMouseOut = Obj.bind(this.onMouseOut, this);

        Firebug.DOMBasePanel.prototype.initialize.apply(this, arguments);
    },

    destroy: function(state)
    {
        state.watches = this.watches;

        Firebug.DOMBasePanel.prototype.destroy.apply(this, arguments);
    },

    show: function(state)
    {
        if (state && state.watches)
            this.watches = state.watches;
    },

    initializeNode: function(oldPanelNode)
    {
        this.panelNode.addEventListener("mousedown", this.onMouseDown, false);
        this.panelNode.addEventListener("mouseover", this.onMouseOver, false);
        this.panelNode.addEventListener("mouseout", this.onMouseOut, false);

        Firebug.DOMBasePanel.prototype.initializeNode.apply(this, arguments);
    },

    destroyNode: function()
    {
        this.panelNode.removeEventListener("mousedown", this.onMouseDown, false);
        this.panelNode.removeEventListener("mouseover", this.onMouseOver, false);
        this.panelNode.removeEventListener("mouseout", this.onMouseOut, false);

        Firebug.DOMBasePanel.prototype.destroyNode.apply(this, arguments);
    },

    refresh: function()
    {
        this.rebuild(true);
    },

    updateSelection: function(frame)
    {
        // this method is called while the debugger has halted JS,
        // so failures don't show up in FBS_ERRORS
        try
        {
            this.doUpdateSelection(frame);
        }
        catch (exc)
        {
            if (FBTrace.DBG_ERRORS && FBTrace.DBG_STACK)
                FBTrace.sysout("updateSelection FAILS " + exc, exc);
        }
    },

    doUpdateSelection: function(frame)
    {
        if (FBTrace.DBG_STACK)
            FBTrace.sysout("dom watch panel updateSelection frame " + frame, frame);

        Events.dispatch(this.fbListeners, "onBeforeDomUpdateSelection", [this]);

        var newFrame = frame && ("signature" in frame) &&
            (frame.signature() != this.frameSignature);

        if (newFrame)
        {
            this.toggles = new ToggleBranch.ToggleBranch();
            this.frameSignature = frame.signature();
        }

        if (frame instanceof StackFrame.StackFrame)
            var scopes = frame.getScopes(Firebug.viewChrome);
        else
            var scopes = [this.context.getGlobalScope()];

        if (FBTrace.DBG_STACK)
            FBTrace.sysout("dom watch frame isStackFrame " +
                (frame instanceof StackFrame.StackFrame) +
                " updateSelection scopes " + scopes.length, scopes);

        var members = [];

        if (this.watches)
        {
            for (var i = 0; i < this.watches.length; ++i)
            {
                var expr = this.watches[i];
                var value = null;

                Firebug.CommandLine.evaluate(expr, this.context, null, this.context.getGlobalScope(),
                    function success(result, context)
                    {
                        value = result;
                    },
                    function failed(result, context)
                    {
                        var exc = result;
                        value = new FirebugReps.ErrorCopy(exc+"");
                    }
                );

                this.addMember(scopes[0], "watch", members, expr, value, 0);

                if (FBTrace.DBG_DOM)
                    FBTrace.sysout("watch.updateSelection " + expr + " = " + value,
                        {expr: expr, value: value, members: members})
            }
        }

        if (frame && frame instanceof StackFrame.StackFrame)
        {
            var thisVar = frame.getThisValue();
            if (thisVar)
                this.addMember(scopes[0], "user", members, "this", thisVar, 0);

            // locals, pre-expanded
            members.push.apply(members, this.getMembers(scopes[0], 0, this.context));

            for (var i=1; i<scopes.length; i++)
                this.addMember(scopes[i], "scopes", members, scopes[i].toString(), scopes[i], 0);
        }

        this.expandMembers(members, this.toggles, 0, 0, this.context);
        this.showMembers(members, !newFrame);

        if (FBTrace.DBG_STACK)
            FBTrace.sysout("dom watch panel updateSelection members " + members.length, members);
    },

    rebuild: function()
    {
        this.updateSelection(this.selection);
    },

    showEmptyMembers: function()
    {
        this.tag.replace({domPanel: this, toggles: new ToggleBranch.ToggleBranch()},
            this.panelNode);
    },

    addWatch: function(expression)
    {
        if (!this.watches)
            this.watches = [];

        for (var i=0; i<this.watches.length; i++)
        {
            if (expression == this.watches[i])
                return;
        }

        this.watches.splice(0, 0, expression);
        this.rebuild(true);
    },

    removeWatch: function(expression)
    {
        if (!this.watches)
            return;

        var index = this.watches.indexOf(expression);
        if (index != -1)
            this.watches.splice(index, 1);
    },

    editNewWatch: function(value)
    {
        var watchNewRow = this.panelNode.getElementsByClassName("watchNewRow").item(0);
        if (watchNewRow)
            this.editProperty(watchNewRow, value);
    },

    setWatchValue: function(row, value)
    {
        var rowIndex = getWatchRowIndex(row);
        this.watches[rowIndex] = value;
        this.rebuild(true);
    },

    deleteWatch: function(row)
    {
        var rowIndex = getWatchRowIndex(row);
        this.watches.splice(rowIndex, 1);
        this.rebuild(true);

        this.context.setTimeout(Obj.bindFixed(function()
        {
            this.showToolbox(null);
        }, this));
    },

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

    showToolbox: function(row)
    {
        var toolbox = this.getToolbox();
        if (row)
        {
            if (Css.hasClass(row, "editing"))
                return;

            toolbox.watchRow = row;

            var offset = Dom.getClientOffset(row);
            toolbox.style.top = offset.y + "px";
            this.panelNode.appendChild(toolbox);
        }
        else
        {
            delete toolbox.watchRow;

            if (toolbox.parentNode)
                toolbox.parentNode.removeChild(toolbox);
        }
    },

    getToolbox: function()
    {
        if (!this.toolbox)
        {
            this.toolbox = Firebug.DOMBasePanel.ToolboxPlate.tag.replace(
                {domPanel: this}, this.document);
        }

        return this.toolbox;
    },

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

    onMouseDown: function(event)
    {
        var watchNewRow = Dom.getAncestorByClass(event.target, "watchNewRow");
        if (watchNewRow)
        {
            this.editProperty(watchNewRow);
            Events.cancelEvent(event);
        }
    },

    onMouseOver: function(event)
    {
        var watchRow = Dom.getAncestorByClass(event.target, "watchRow");
        if (watchRow)
            this.showToolbox(watchRow);
    },

    onMouseOut: function(event)
    {
        if (Dom.isAncestor(event.relatedTarget, this.getToolbox()))
            return;

        var watchRow = Dom.getAncestorByClass(event.relatedTarget, "watchRow");
        if (!watchRow)
            this.showToolbox(null);
    },
});

// ********************************************************************************************* //
// Local Helpers

function getWatchRowIndex(row)
{
    var index = -1;
    for (; row && Css.hasClass(row, "watchRow"); row = row.previousSibling)
        ++index;
    return index;
}

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

Firebug.registerPanel(Firebug.WatchPanel);

return Firebug.WatchPanel;

// ********************************************************************************************* //
});
<commit_msg>[1.9] Do not update Watch panel asynchronously (related to issue 10980<commit_after>/* See license.txt for terms of usage */

define([
    "firebug/lib/object",
    "firebug/firebug",
    "firebug/dom/toggleBranch",
    "firebug/lib/events",
    "firebug/lib/dom",
    "firebug/lib/css",
    "firebug/js/stackFrame",
    "firebug/dom/domPanel",     // Firebug.DOMBasePanel, Firebug.DOMPanel.DirTable
],
function(Obj, Firebug, ToggleBranch, Events, Dom, Css, StackFrame) {

// ********************************************************************************************* //
// Watch Panel

Firebug.WatchPanel = function()
{
}

/**
 * Represents the Watch side panel available in the Script panel.
 */
Firebug.WatchPanel.prototype = Obj.extend(Firebug.DOMBasePanel.prototype,
/** @lends Firebug.WatchPanel */
{
    tag: Firebug.DOMPanel.DirTable.watchTag,

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // extends Panel

    name: "watches",
    order: 0,
    parentPanel: "script",
    enableA11y: true,
    deriveA11yFrom: "console",

    initialize: function()
    {
        this.onMouseDown = Obj.bind(this.onMouseDown, this);
        this.onMouseOver = Obj.bind(this.onMouseOver, this);
        this.onMouseOut = Obj.bind(this.onMouseOut, this);

        Firebug.DOMBasePanel.prototype.initialize.apply(this, arguments);
    },

    destroy: function(state)
    {
        state.watches = this.watches;

        Firebug.DOMBasePanel.prototype.destroy.apply(this, arguments);
    },

    show: function(state)
    {
        if (state && state.watches)
            this.watches = state.watches;
    },

    initializeNode: function(oldPanelNode)
    {
        this.panelNode.addEventListener("mousedown", this.onMouseDown, false);
        this.panelNode.addEventListener("mouseover", this.onMouseOver, false);
        this.panelNode.addEventListener("mouseout", this.onMouseOut, false);

        Firebug.DOMBasePanel.prototype.initializeNode.apply(this, arguments);
    },

    destroyNode: function()
    {
        this.panelNode.removeEventListener("mousedown", this.onMouseDown, false);
        this.panelNode.removeEventListener("mouseover", this.onMouseOver, false);
        this.panelNode.removeEventListener("mouseout", this.onMouseOut, false);

        Firebug.DOMBasePanel.prototype.destroyNode.apply(this, arguments);
    },

    refresh: function()
    {
        this.rebuild(true);
    },

    updateSelection: function(frame)
    {
        // this method is called while the debugger has halted JS,
        // so failures don't show up in FBS_ERRORS
        try
        {
            this.doUpdateSelection(frame);
        }
        catch (exc)
        {
            if (FBTrace.DBG_ERRORS && FBTrace.DBG_STACK)
                FBTrace.sysout("updateSelection FAILS " + exc, exc);
        }
    },

    doUpdateSelection: function(frame)
    {
        if (FBTrace.DBG_STACK)
            FBTrace.sysout("dom watch panel updateSelection frame " + frame, frame);

        Events.dispatch(this.fbListeners, "onBeforeDomUpdateSelection", [this]);

        var newFrame = frame && ("signature" in frame) &&
            (frame.signature() != this.frameSignature);

        if (newFrame)
        {
            this.toggles = new ToggleBranch.ToggleBranch();
            this.frameSignature = frame.signature();
        }

        if (frame instanceof StackFrame.StackFrame)
            var scopes = frame.getScopes(Firebug.viewChrome);
        else
            var scopes = [this.context.getGlobalScope()];

        if (FBTrace.DBG_STACK)
            FBTrace.sysout("dom watch frame isStackFrame " +
                (frame instanceof StackFrame.StackFrame) +
                " updateSelection scopes " + scopes.length, scopes);

        var members = [];

        if (this.watches)
        {
            for (var i = 0; i < this.watches.length; ++i)
            {
                var expr = this.watches[i];
                var value = null;

                Firebug.CommandLine.evaluate(expr, this.context, null, this.context.getGlobalScope(),
                    function success(result, context)
                    {
                        value = result;
                    },
                    function failed(result, context)
                    {
                        var exc = result;
                        value = new FirebugReps.ErrorCopy(exc+"");
                    }
                );

                this.addMember(scopes[0], "watch", members, expr, value, 0);

                if (FBTrace.DBG_DOM)
                    FBTrace.sysout("watch.updateSelection " + expr + " = " + value,
                        {expr: expr, value: value, members: members})
            }
        }

        if (frame && frame instanceof StackFrame.StackFrame)
        {
            var thisVar = frame.getThisValue();
            if (thisVar)
                this.addMember(scopes[0], "user", members, "this", thisVar, 0);

            // locals, pre-expanded
            members.push.apply(members, this.getMembers(scopes[0], 0, this.context));

            for (var i=1; i<scopes.length; i++)
                this.addMember(scopes[i], "scopes", members, scopes[i].toString(), scopes[i], 0);
        }

        this.expandMembers(members, this.toggles, 0, 0, this.context);
        this.showMembers(members, false);

        if (FBTrace.DBG_STACK)
            FBTrace.sysout("dom watch panel updateSelection members " + members.length, members);
    },

    rebuild: function()
    {
        this.updateSelection(this.selection);
    },

    showEmptyMembers: function()
    {
        this.tag.replace({domPanel: this, toggles: new ToggleBranch.ToggleBranch()},
            this.panelNode);
    },

    addWatch: function(expression)
    {
        if (!this.watches)
            this.watches = [];

        for (var i=0; i<this.watches.length; i++)
        {
            if (expression == this.watches[i])
                return;
        }

        this.watches.splice(0, 0, expression);
        this.rebuild(true);
    },

    removeWatch: function(expression)
    {
        if (!this.watches)
            return;

        var index = this.watches.indexOf(expression);
        if (index != -1)
            this.watches.splice(index, 1);
    },

    editNewWatch: function(value)
    {
        var watchNewRow = this.panelNode.getElementsByClassName("watchNewRow").item(0);
        if (watchNewRow)
            this.editProperty(watchNewRow, value);
    },

    setWatchValue: function(row, value)
    {
        var rowIndex = getWatchRowIndex(row);
        this.watches[rowIndex] = value;
        this.rebuild(true);
    },

    deleteWatch: function(row)
    {
        var rowIndex = getWatchRowIndex(row);
        this.watches.splice(rowIndex, 1);
        this.rebuild(true);

        this.context.setTimeout(Obj.bindFixed(function()
        {
            this.showToolbox(null);
        }, this));
    },

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

    showToolbox: function(row)
    {
        var toolbox = this.getToolbox();
        if (row)
        {
            if (Css.hasClass(row, "editing"))
                return;

            toolbox.watchRow = row;

            var offset = Dom.getClientOffset(row);
            toolbox.style.top = offset.y + "px";
            this.panelNode.appendChild(toolbox);
        }
        else
        {
            delete toolbox.watchRow;

            if (toolbox.parentNode)
                toolbox.parentNode.removeChild(toolbox);
        }
    },

    getToolbox: function()
    {
        if (!this.toolbox)
        {
            this.toolbox = Firebug.DOMBasePanel.ToolboxPlate.tag.replace(
                {domPanel: this}, this.document);
        }

        return this.toolbox;
    },

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

    onMouseDown: function(event)
    {
        var watchNewRow = Dom.getAncestorByClass(event.target, "watchNewRow");
        if (watchNewRow)
        {
            this.editProperty(watchNewRow);
            Events.cancelEvent(event);
        }
    },

    onMouseOver: function(event)
    {
        var watchRow = Dom.getAncestorByClass(event.target, "watchRow");
        if (watchRow)
            this.showToolbox(watchRow);
    },

    onMouseOut: function(event)
    {
        if (Dom.isAncestor(event.relatedTarget, this.getToolbox()))
            return;

        var watchRow = Dom.getAncestorByClass(event.relatedTarget, "watchRow");
        if (!watchRow)
            this.showToolbox(null);
    },
});

// ********************************************************************************************* //
// Local Helpers

function getWatchRowIndex(row)
{
    var index = -1;
    for (; row && Css.hasClass(row, "watchRow"); row = row.previousSibling)
        ++index;
    return index;
}

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

Firebug.registerPanel(Firebug.WatchPanel);

return Firebug.WatchPanel;

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


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

  if (!window.location.origin) {
    window.location.origin = window.location.protocol+"//"+window.location.host;
  }
  var dirWebRoot =  window.location.origin + '/'+directoryApp+'/';
  angular.patchURLCI = dirWebRoot+'ci.php/';

  angular
    .module('caribbean')
    .config(config);

  /** @ngInject */
  function config($logProvider, $locationProvider) {
    // Enable log
    $logProvider.debugEnabled(true);

    $locationProvider.html5Mode(true);
    // remove ! hash prefix
    $locationProvider.hashPrefix('');

  }

})();

function handleError(error) {
  return function () {
    return {success: false, message: Notification.warning({message: error})};
  };
}
function handleSuccess(response) {
    return( response.data );
}
<commit_msg>bug config<commit_after>(function() {
  'use strict';

  if (!window.location.origin) {
    window.location.origin = window.location.protocol+"//"+window.location.host;
  }
  var dirWebRoot =  window.location.origin + directoryApp+'/';
  angular.patchURLCI = dirWebRoot+'ci.php/';

  angular
    .module('caribbean')
    .config(config);

  /** @ngInject */
  function config($logProvider, $locationProvider) {
    // Enable log
    $logProvider.debugEnabled(true);

    $locationProvider.html5Mode(true);
    // remove ! hash prefix
    $locationProvider.hashPrefix('');

  }

})();

function handleError(error) {
  return function () {
    return {success: false, message: Notification.warning({message: error})};
  };
}
function handleSuccess(response) {
    return( response.data );
}
<|endoftext|>


<commit_before>/**
 * .tablesorter.cookie - Cookie Jar Widget for Tablesorter 2
 *
 * Version: 1.0
 * Updated: 2007-08-11
 *
 * Store, then restores the sort order of tables from tablesorter using cookieJar
 *
 * Copyright (c) 2007 jdempster (letssurf@gmail.com, http://www.jdempster.com/category/jquery/tablesorterCookie/)
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 **/

/**
 * Requirements:
 * - jQuery (John Resig, http://www.jquery.com/)
 * - tablesorter (Christian Bach, http://tablesorter.com/)
 * - cookieJar (James Dempster, http://www.jdempster.com/category/jquery/cookieJar/)
 **/
(function($) {
    $.tablesorter.addWidget({
        id: 'cookie',
        format: function(table) {
            var sortList = table.config.sortList;
            var tablesorterCookieJar = $.cookieJar('tablesorter', {
	        cookie: {
                    path: '/'
		}
	    });
            if ( sortList.length > 0) {
                tablesorterCookieJar.set($(table).attr('id'), sortList);
            } else {
               var sortList = tablesorterCookieJar.get($(table).attr('id'));
               if (sortList && sortList.length > 0) {
                    jQuery(table).trigger('sorton', [sortList]);
               }
            }
        }
    });
})(jQuery);
<commit_msg>updated to include page<commit_after>/**
 * .tablesorter.cookie - Cookie Jar Widget for Tablesorter 2
 *
 * Version: 1.0
 * Updated: 2007-08-11
 *
 * Store, then restores the sort order of tables from tablesorter using cookieJar
 *
 * Copyright (c) 2007 jdempster (letssurf@gmail.com, http://www.jdempster.com/category/jquery/tablesorterCookie/)
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 **/

/**
 * Requirements:
 * - jQuery (John Resig, http://www.jquery.com/)
 * - tablesorter (Christian Bach, http://tablesorter.com/)
 * - cookieJar (James Dempster, http://www.jdempster.com/category/jquery/cookieJar/)
 **/
(function($) {
    $.tablesorter.addWidget({
        id: 'cookie',
        format: function(table) {
            var sortList = table.config.sortList;
            var pageNum = table.config.page;
            var tablesorterCookieJar = $.cookieJar('tablesorter', {
                cookie: {
                    path: '/'
                }
            });
            if ( sortList.length > 0) {
                tablesorterCookieJar.set($(table).attr('id')+'-sort', sortList);
            } else {
               var sortList = tablesorterCookieJar.get($(table).attr('id')+'-sort');
               if (sortList && sortList.length > 0) {
                    jQuery(table).trigger('sorton', [sortList]);
               }
            }

            if ( pageNum > 0 ) {
                tablesorterCookieJar.set($(table).attr('id')+'-page', pageNum);
            } else {
               var pageNum = tablesorterCookieJar.get($(table).attr('id')+'-page');
               if (pageNum && pageNum > 1) {
                   table.config.page = pageNum;
                    jQuery(table).trigger('sorton', [sortList]);
               }
            }
        }
    });
})(jQuery);
<|endoftext|>


<commit_before>// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
var vscode = require('vscode');

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {

    // Use the console to output diagnostic information (console.log) and errors (console.error)
    // This line of code will only be executed once when your extension is activated
    console.log('Congratulations, your extension "quick-pick-related-files" is now active!');

    // The command has been defined in the package.json file
    // Now provide the implementation of the command with  registerCommand
    // The commandId parameter must match the command field in package.json
    var disposable = vscode.commands.registerCommand('extension.sayHello', function () {
        // The code you place here will be executed every time your command is executed

        // Display a message box to the user
        vscode.window.showInformationMessage('Hello World!');
    });

    context.subscriptions.push(disposable);
}
exports.activate = activate;

// this method is called when your extension is deactivated
function deactivate() {
}
exports.deactivate = deactivate;<commit_msg>Create basic proof of concept<commit_after>const vscode = require('vscode');

function quickOpen() {
  const { fileName } = vscode.window.activeTextEditor.document;
  const fileNameParts = fileName.split('/');
  const prefilledText = fileNameParts[fileNameParts.length - 1];
  vscode.commands.executeCommand('workbench.action.quickOpen', prefilledText);
}

function activate(context) {
  context.subscriptions.push(vscode.commands.registerCommand('extension.sayHello', quickOpen));
}

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


<commit_before>import { Given, When, Then } from 'cucumber';
import { expect } from 'chai';
import { waitAndClick, getVisibleElementsCountForSelector } from '../support/helpers/shared-helpers';

Given('I generate {int} addresses', async function (numberOfAddresses) {
  for (let i = 0; i < numberOfAddresses; i++) {
    await waitAndClick(this.client, '.generateAddressButton:not(.WalletReceive_spinning)');
  }
});

When('I click the ShowUsed switch', async function () {
  await waitAndClick(this.client, '.SimpleSwitch_switch');
});

Then('I should see {int} addresses', async function (numberOfAddresses) {
  const addressesFound = await getVisibleElementsCountForSelector(this.client, '.WalletReceive_walletAddress', `.generatedAddress-${numberOfAddresses}`);
  expect(addressesFound).to.equal(numberOfAddresses);
});

Then('I should see the following addresses:', async function (table) {
  const expectedAdresses = table.hashes();
  let addresses;

  await this.client.waitUntil(async () => {
    addresses = await this.client.getAttribute('.WalletReceive_walletAddress','class');
    return addresses.length === 3;
  });

  addresses.forEach((address, index) => expect(address.indexOf(expectedAdresses[index]) > -1))

});

Then('The active address should be the newest one', async function () {
  const { value: { id: lastGeneratedAddress } } = await this.client.execute(() => daedalus.stores.ada.addresses.lastGeneratedAddress);
  const activeAddress = await this.client.getText('.WalletReceive_hash');
  expect(lastGeneratedAddress).to.equal(activeAddress);
});
<commit_msg>[DDW-39] Adjustments<commit_after>import { Given, When, Then } from 'cucumber';
import { expect } from 'chai';
import { waitAndClick, getVisibleElementsCountForSelector } from '../support/helpers/shared-helpers';

Given('I generate {int} addresses', async function (numberOfAddresses) {
  for (let i = 0; i < numberOfAddresses; i++) {
    await waitAndClick(this.client, '.generateAddressButton:not(.WalletReceive_spinning)');
  }
});

When('I click the ShowUsed switch', async function () {
  await waitAndClick(this.client, '.SimpleSwitch_switch');
});

Then('I should see {int} addresses', async function (numberOfAddresses) {
  const addressesFound = await getVisibleElementsCountForSelector(this.client, '.WalletReceive_walletAddress', `.generatedAddress-${numberOfAddresses}`);
  expect(addressesFound).to.equal(numberOfAddresses);
});

Then('I should see the following addresses:', async function (table) {
  const expectedAdresses = table.hashes();
  let addresses;

  await this.client.waitUntil(async () => {
    addresses = await this.client.getAttribute('.WalletReceive_walletAddress','class');
    return addresses.length === expectedAdresses.length;
  });

  addresses.forEach((address, index) => expect(address).to.include(expectedAdresses[index].ClassName));

});

Then('The active address should be the newest one', async function () {
  const { value: { id: lastGeneratedAddress } } = await this.client.execute(() => daedalus.stores.ada.addresses.lastGeneratedAddress);
  const activeAddress = await this.client.getText('.WalletReceive_hash');
  expect(lastGeneratedAddress).to.equal(activeAddress);
});
<|endoftext|>


<commit_before>var ProfileSummaryBio = React.createClass ({
  render: function () {
    return (

                        Dan Ochieng

                          Front-End Developer

                        Thimrock Ventures

      );
  }
});
var ProfileSummaryStats = React.createClass ({
  render: function () {
    return (

                            <data className="number" value="4373">4373</data>

Recommendations

                          <data className="number" value="138">138</data>

Interests

      );
  }
});
var ProfileSummaryActions = React.createClass ({
  render: function () {
    return (

                        <button type="button" data-toggle="popover" data-trigger="hover" data-content="Message" data-placement="top" data-modal="profile-modal-message" className="mdl-button mdl-js-button mdl-button--fab mdl-button--mini-fab mdl-js-ripple-effect">
                            message
                        </button>
                        <button type="button" data-toggle="popover" data-trigger="hover" data-content="Recommend" data-placement="bottom" className="mdl-button mdl-js-button mdl-button--fab mdl-button--mini-fab mdl-button--colored mdl-js-ripple-effect" data-state="follow" data-profile-id="9373ea86-06b3-3a51-90b9-f99cda6577ad">
                          thumb_up
                        </button>
                        <button type="button" data-toggle="popover" data-trigger="hover" data-content="Show Interest" data-placement="right" className="mdl-button mdl-js-button mdl-button--fab mdl-button--mini-fab mdl-button--primary mdl-js-ripple-effect" data-state="follow" data-profile-id="9373ea86-06b3-3a51-90b9-f99cda6577ad">
                          remove_red_eye
                        </button>

      );
  }
});
var ProfileSummary = React.createClass ({
	render: function () {
		return (

                              <ProfileSummaryBio />

                              <ProfileSummaryStats />
                              <ProfileSummaryActions />

			);
	}
});
var ProfileInterests = React.createClass ({
  render: function () {
    const divStyleOne = {
      display: 'none',
    };
    const divStyleTwo = {
      height: 'auto',
    };
    return (

                      Job Interests

                          User Modeling
                          Adaptive Hypermedia
                          Adaptive Web
                          Personalized E-Learning
                          Student Modeling
                          Social Information Access

                      <button className="js-expandable-link basic-link with-icon-before icon-navigatedown" data-expand="more" style={divStyleOne}>View more</button>
                      <button className="js-expandable-link basic-link with-icon-before icon-navigateup" data-expand="less" style={divStyleOne}>View less</button>

    );
  }
});
var ProfileAbout = React.createClass ({
  render: function () {
    return (

    );
  }
});
var InterestedEmployersList = React.createClass ({
  render: function () {
    const styleIEButton = {
      lineHeight: '10px',
      padding: '1px 1px 1px 1px',
      textTransform: 'unset',
    };
    return (

                    Hellen Achieng
                      University of Nairobi

                  <button type="button" style={styleIEButton} className="basic-link mdl-button mdl-js-button mdl-js-ripple-effect">
                    Profile account_box
                  </button>

                    Hellen Achieng
                      University of Nairobi

                  <button type="button" style={styleIEButton} className=" basic-link mdl-button mdl-js-button mdl-js-ripple-effect">
                    Profile account_box
                  </button>

                    Hellen Achieng
                      University of Nairobi

                  <button type="button" style={styleIEButton} className="basic-link mdl-button mdl-js-button mdl-js-ripple-effect">
                    Profile account_box
                  </button>

    );
  }
});
var ProfileInterestedEmployers = React.createClass ({
  render: function () {
    return (

Interested Employers (26)

                        <InterestedEmployersList />

                        <button href="#" id="followers-network" className="mdl-button mdl-js-button mdl-js-ripple-effect">Explore network keyboard_arrow_right</button>

    );
  }
});
var ProfileInterestedIn = React.createClass ({
  render: function () {
    return (

Interested In (106)

                        <InterestedEmployersList />

                        <button href="#" id="followers-network" className="mdl-button mdl-js-button mdl-js-ripple-effect">Explore network keyboard_arrow_right</button>

    );
  }
});
var ProfessionalExperience = React.createClass ({
  render: function () {
    return (

                Professional experience

Professor

University of Pittsburgh

                            August 2000
                              -
                                Present

    );
  }
});
var EducationBackground = React.createClass ({
  render: function () {
    return (

                Education history

Kenyatta University/Faculty of Computational Mathematics and Cybernetics

PhD

                          September 1983
                              -
                              February 1988

                       (4 years)

    );
  }
});
var Skills = React.createClass ({
  render: function () {
    return (

    );
  }
});
var ProfileData =  React.createClass ({
  render: function () {
    return (

                  <ProfileSummary />

                        <ProfileInterests />
                        <ProfileInterestedEmployers />
                        <ProfileInterestedIn />

                        <Skills />
                        <ProfessionalExperience />
                        <EducationBackground />

    );
  }
});
ReactDOM.render (<ProfileData />, document.getElementById('content')
	);
<commit_msg>basic details and contact details components added<commit_after>var ProfileSummaryBio = React.createClass ({
  render: function () {
    return (

                        Dan Ochieng

                          Front-End Developer

                        Thimrock Ventures

      );
  }
});
var ProfileSummaryStats = React.createClass ({
  render: function () {
    return (

                            <data className="number" value="4373">4373</data>

Recommendations

                          <data className="number" value="138">138</data>

Interests

      );
  }
});
var ProfileSummaryActions = React.createClass ({
  render: function () {
    return (

                        <button type="button" data-toggle="popover" data-trigger="hover" data-content="Message" data-placement="top" data-modal="profile-modal-message" className="mdl-button mdl-js-button mdl-button--fab mdl-button--mini-fab mdl-js-ripple-effect">
                            message
                        </button>
                        <button type="button" data-toggle="popover" data-trigger="hover" data-content="Recommend" data-placement="bottom" className="mdl-button mdl-js-button mdl-button--fab mdl-button--mini-fab mdl-button--colored mdl-js-ripple-effect" data-state="follow" data-profile-id="9373ea86-06b3-3a51-90b9-f99cda6577ad">
                          thumb_up
                        </button>
                        <button type="button" data-toggle="popover" data-trigger="hover" data-content="Show Interest" data-placement="right" className="mdl-button mdl-js-button mdl-button--fab mdl-button--mini-fab mdl-button--primary mdl-js-ripple-effect" data-state="follow" data-profile-id="9373ea86-06b3-3a51-90b9-f99cda6577ad">
                          remove_red_eye
                        </button>

      );
  }
});
var ProfileSummary = React.createClass ({
  render: function () {
    return (

                              <ProfileSummaryBio />

                              <ProfileSummaryStats />
                              <ProfileSummaryActions />

      );
  }
});
var ProfileInterests = React.createClass ({
  render: function () {
    const divStyleOne = {
      display: 'none',
    };
    const divStyleTwo = {
      height: 'auto',
    };
    return (

                      Job Interests

                          User Modeling
                          Adaptive Hypermedia
                          Adaptive Web
                          Personalized E-Learning
                          Student Modeling
                          Social Information Access

                      <button className="js-expandable-link basic-link with-icon-before icon-navigatedown" data-expand="more" style={divStyleOne}>View more</button>
                      <button className="js-expandable-link basic-link with-icon-before icon-navigateup" data-expand="less" style={divStyleOne}>View less</button>

    );
  }
});
var ProfileAbout = React.createClass ({
  render: function () {
    return (

    );
  }
});
var InterestedEmployersList = React.createClass ({
  render: function () {
    const styleIEButton = {
      lineHeight: '10px',
      padding: '1px 1px 1px 1px',
      textTransform: 'unset',
    };
    return (

                    Hellen Achieng
                      University of Nairobi

                  <button type="button" style={styleIEButton} className="basic-link mdl-button mdl-js-button mdl-js-ripple-effect">
                    Profile account_box
                  </button>

                    Hellen Achieng
                      University of Nairobi

                  <button type="button" style={styleIEButton} className=" basic-link mdl-button mdl-js-button mdl-js-ripple-effect">
                    Profile account_box
                  </button>

                    Hellen Achieng
                      University of Nairobi

                  <button type="button" style={styleIEButton} className="basic-link mdl-button mdl-js-button mdl-js-ripple-effect">
                    Profile account_box
                  </button>

    );
  }
});
var ProfileInterestedEmployers = React.createClass ({
  render: function () {
    return (

Interested Employers (26)

                        <InterestedEmployersList />

                        <button href="#" id="followers-network" className="mdl-button mdl-js-button mdl-js-ripple-effect">Explore network keyboard_arrow_right</button>

    );
  }
});
var ProfileInterestedIn = React.createClass ({
  render: function () {
    return (

Interested In (106)

                        <InterestedEmployersList />

                        <button href="#" id="followers-network" className="mdl-button mdl-js-button mdl-js-ripple-effect">Explore network keyboard_arrow_right</button>

    );
  }
});
var ContactDetails = React.createClass ({
  render: function () {
    return (

                Contact Details

0728623213

                        Mobile Number

ochiodhis@gmail.com

                        Email Address

P O Box 57161

0020 - Nairobi

                        Address

    );
  }
});

var BasicDetails = React.createClass ({
  render: function () {
    return (

                Basic Details

Male

                        Gender

Nairobi

Umoja

                        City/Town

June 1987

                        Date of Birth

Single

                        Marital Status

    );
  }
 });
var ProfessionalExperience = React.createClass ({
  render: function () {
    return (

                Professional experience

Professor

University of Pittsburgh

                            August 2000
                              -
                                Present

    );
  }
});
var EducationBackground = React.createClass ({
  render: function () {
    return (

                Education history

Kenyatta University/Faculty of Computational Mathematics and Cybernetics

PhD

                          September 1983
                              -
                              February 1988

                       (4 years)

    );
  }
});
var Skills = React.createClass ({
  render: function () {
    return (

    );
  }
});
var ProfileData =  React.createClass ({
  render: function () {
    return (

                  <ProfileSummary />

                        <ProfileInterests />
                        <ProfileInterestedEmployers />
                        <ProfileInterestedIn />

                        <BasicDetails />
                        <ContactDetails />
                        <Skills />
                        <ProfessionalExperience />
                        <EducationBackground />

    );
  }
});
ReactDOM.render (<ProfileData />, document.getElementById('content')
  );
<|endoftext|>


<commit_before>'use strict';

const vscode = require('vscode');
let copyPaste = null;
let open = null;
let got = null;
const Promise = require('bluebird');
const RecentLibraries = require('./RecentLibraries');
const Cache = require('./Cache');

let activate = (context) => {

  const baseUrl = 'https://api.cdnjs.com/libraries';
  const searchUrl = baseUrl + '?fields=version,description,homepage';
  const embedUrl = 'cdnjs.cloudflare.com/ajax/libs';
  const httpRequestTimeout = 5000; // 5 seconds
  const statusBarMessageTimeout = 5000; // 5 seconds
  const cacheTimeDefault = 21600 // 6 hours

  // Quote configuration values
  const quotes = {
    'single': "'",
    'double': '"'
  };
  const quoteDefault = "'";

  // Protocol configuration values
  const protocols = ['https://', 'http://', '//'];
  const protocolDefault = 'https://';

  // Maximum Recent Libraries configuration values
  const maxRecentLibrariesDefault = 10;

  // Recent Libraries interface
  let recentLibraries = new RecentLibraries(context, vscode.workspace);

  // Cache interfaces
  let searchCache = new Cache(context, 'search');
  let libraryCache = new Cache(context, 'library');

  // Set consistent status bar message using timeout with either promise or time in milliseconds
  let statusMessage = (text, promise) => {
    if (promise) {
      vscode.window.setStatusBarMessage("cdnjs: " + text, promise);
    } else {
      vscode.window.setStatusBarMessage("cdnjs: " + text, statusBarMessageTimeout);
    }
  }

  // Display search box and return input
  let showSearchInput = () => {

    return new Promise((resolve, reject) => {
      vscode.window.showInputBox({
        placeHolder: 'Search for a script or library. For example: jquery'
      }).then((value) => {

        // No search string was specified
        if (typeof (value) === 'undefined') {
          return reject('No search string was specified');
        }

        resolve(value);

      }, (err) => {
        reject(err);
      });
    });
  }

  // Perform search on cdnjs.com and return JSON results
  let search = (term) => {

    term = term.trim();

    let promise = new Promise((resolve, reject) => {

      // Ignore empty searches
      if (!term.length) {
        return reject('No search term provided');
      }

      // Check the cache
      if (searchCache.has(term)) {
        return resolve(searchCache.get(term));
      }

      // Lazy load got
      got = require('got');

      // Search for libraries
      got(searchUrl + '&search=' + term, {
        json: true,
        timeout: httpRequestTimeout
      }).then((res) => {

        // Reject non-200 status code responses
        if (res.statusCode !== 200) {
          return reject(res.body);
        }

        const body = res.body;

        // Display error message if no results were found
        if (!body.results || body.results.length === 0) {
          vscode.window.showErrorMessage(term + ": No libraries found");
          return false;
        }

        // Fetch the cache time setting
        let cacheTime = vscode.workspace.getConfiguration('cdnjs').get('cacheTime');
        cacheTime = Number.isInteger(cacheTime) ? cacheTime : cacheTimeDefault;

        // Save the result to cache and resolve the search result
        searchCache.put(term, body.results, cacheTime)
          .then(() => {

            // Search results
            resolve(body.results);

          }, (err) => {

            // searchCache.put error
            reject(err);

          });

      }).catch((err) => {

        // got http request error
        reject(err);

      });

    });

    // Update Status Bar Message
    statusMessage("Searching cdnjs.com for " + term, promise);
    return promise;

  };

  // Show picker of all libraries
  let showLibraryPicker = (results) => {

    // Build array of libraries
    let items = [];
    for (let result of results) {

      // Create QuickPickItem for library
      let item = {
        label: result.name,
        description: result.description,
        currentVersion: result.version,
        name: result.name
      };
      items.push(item);
    }

    // Update status bar message
    statusMessage('Found ' + items.length + ' libraries');

    return new Promise((resolve, reject) => {

      // Show QuickPick of search results
      vscode.window.showQuickPick(items, {
        placeHolder: 'Choose a library (found ' + items.length + ' libraries)',
        matchOnDescription: true
      }).then((libraryName) => {

        // No library was chosen
        if (typeof (libraryName) === 'undefined') {
          return reject('No library was chosen');
        }

        resolve(libraryName);

      }, (err) => {
        reject(err);
      });

    });

  }

  // Get library data from cdnjs
  let getLibrary = (libraryName) => {

    let promise = new Promise((resolve, reject) => {

      // Check the cache
      if (libraryCache.has(libraryName)) {
        return resolve(libraryCache.get(libraryName));
      }

      // Lazy load got
      got = require('got');

      // Request library versions
      got(baseUrl + '/' + libraryName, {
        json: true,
        timeout: httpRequestTimeout
      }).then((res) => {

        // Reject non-200 status code responses
        if (res.statusCode !== 200) {
          return reject(res.body);
        }

        const body = res.body;

        // Display error message if no results were found
        if (body.length === 0) {
          vscode.window.showErrorMessage("The library " + libraryName + " was not found");
          return false;
        }

        // Fetch the catch time setting
        let cacheTime = vscode.workspace.getConfiguration('cdnjs').get('cacheTime');
        cacheTime = Number.isInteger(cacheTime) ? cacheTime : cacheTimeDefault;

        // Save the result to cache and resolving the search result
        libraryCache.put(libraryName, body, cacheTime)
          .then(() => {

            // Library results
            resolve(body);

          }, (err) => {

            // libraryCache.put error
            reject(err);

          });

      });

    });

    // Update Status Bar Message
    statusMessage("Fetching data for " + libraryName, promise);
    return promise;
  }

  // Show library version picker
  let showLibraryVersionPicker = (library) => {

    return new Promise((resolve, reject) => {
      // Build array of library versions
      let items = [];
      for (let asset of library.assets) {

        // QuickPickItem for the library version
        let item = {
          label: asset.version,
          files: asset.files,
          version: asset.version,
          libraryName: library.name
        };

        // Add description if this is the current/latest/stable version
        if (asset.version === library.version) {
          item.description = 'current version';
        }
        items.push(item);
      }

      statusMessage('Found ' + items.length + ' versions');

      // Show QuickPick of library versions
      vscode.window.showQuickPick(items, {
        placeHolder: library.name
      }).then((asset) => {

        // No version was chosen
        if (typeof (asset) === 'undefined') {
          return reject('No library version was chosen');
        }

        resolve(asset);
      }, (err) => {
        reject(err);
      });
    });
  }

  // Show library version file picker
  let showFilePicker = (asset) => {

    return new Promise((resolve, reject) => {

      // Build array of files
      let items = [];
      for (let file of asset.files) {
        items.push(file);
      }

      statusMessage('Found ' + items.length + ' files');

      // Show QuickPick of asset files
      vscode.window.showQuickPick(items, {
        placeHolder: asset.libraryName + "/" + asset.version + "/"
      }).then((file) => {

        // No file was chosen
        if (typeof (file) === 'undefined') {
          return reject('No library file was chosen');
        }

        resolve(file);
      }, (err) => {
        reject(err);
      });

    });

  }

  // Show file action picker
  let showActionPicker = (chosen) => {

    return new Promise((resolve, reject) => {

      // Reject if any chosen file properties are missing
      if (!chosen.library || !chosen.version || !chosen.file) {
        return reject('Missing file asset parameters');
      }

      // Configuration
      const config = vscode.workspace.getConfiguration('cdnjs');

      // Determine the quote style from configuration
      const quote = quotes[config.get('quoteStyle')] || quoteDefault;

      // Determine url protocol
      const protocolConfig = config.get('protocol');
      const protocol = protocols.indexOf(protocolConfig) >= 0 ? protocolConfig : protocolDefault;

      // Build the url for the file
      let url = protocol + embedUrl + '/' + chosen.library + '/' + chosen.version + '/' + chosen.file;

      // Arrays of actions
      let actions = [];

      // Determine file extension
      let fileExtension = chosen.file.split('.').pop();
      let tag = "";
      switch (fileExtension) {

        case 'js':
          // JavaScript
          tag = '<script src=' + quote + url + quote + '></script>';

          // Insert <script> tag into document action
          if (vscode.window.activeTextEditor) {
            actions.push({
              label: '<script>: Insert into document',
              callback: () => {
                insertText(tag);
              }
            });
          }

          // Copy <script> tag to clipboard action
          actions.push({
            label: '<script>: Copy to clipboard',
            callback: () => {
              copy(tag, '<script> tag copied to the clipboard');
            }
          });

          break;

        case 'css':
          // CSS
          tag = '<link rel=' + quote + 'stylesheet' + quote + ' href=' + quote + url + quote + '/>';

          // Insert <link> tag into document action
          if (vscode.window.activeTextEditor) {
            actions.push({
              label: '<link>: Insert into document',
              callback: () => {
                insertText(tag);
              }
            });
          }

          // Copy <link> tag to clipboard action
          actions.push({
            label: '<link>: Copy to clipboard',
            callback: () => {
              copy(tag, '<link> tag copied to the clipboard');
            }
          });

          break;

        default:
          break;
      }

      // Insert URL into document action
      if (vscode.window.activeTextEditor) {
        actions.push({
          label: 'URL: Insert into document',
          callback: () => {
            insertText(url);
          }
        });
      }

      // Copy URL to clipboard action
      actions.push({
        label: 'URL: Copy to clipboard',
        callback: () => {
          copy(url, 'URL copied to the clipboard');
        }
      });

      // Open URL in browser action
      actions.push({
        label: 'URL: Open in browser',
        callback: () => {
          // Lazy load open
          open = require('open');

          open(url);
        }
      });

      return new Promise((resolve, reject) => {
        vscode.window.showQuickPick(actions, {
          placeHolder: url
        }).then((action) => {

          // No action was chosen
          if (typeof (action) === 'undefined') {
            return reject('No action was chosen');
          }

          // Execute action callback
          action.callback();

          resolve();
        }, (err) => {
          reject(err);
        });

      });

    });
  }

  // Insert text into active document at cursor positions
  let insertText = (text) => {

    let textEditor = vscode.window.activeTextEditor;

    // Ignore if no active TextEditor
    if (typeof (textEditor) === 'undefined') {
      return false;
    }

    // Get the active text document's uri
    let uri = textEditor.document.uri;

    // Create a new TextEdit for each selection
    let edits = [];
    for (let selection of textEditor.selections) {
      edits.push(vscode.TextEdit.insert(selection.active, text));
    }

    // New WorkspaceEdit
    let edit = new vscode.WorkspaceEdit();
    edit.set(uri, edits);

    // Applying the WorkspaceEdit
    vscode.workspace.applyEdit(edit)
      .then(() => {

        // Clear the selection
        textEditor.selection = new vscode.Selection(textEditor.selection.end, textEditor.selection.end);

      }, (err) => {
        reject(err);
      });

    return true;
  }

  // Copy text to clipboard and set statusBarMessage
  let copy = (text, message) => {
    // Lazy load copy-paste
    copyPaste = require('copy-paste');

    copyPaste.copy(text, () => {
      if (message) {
        statusMessage(message);
      }
    });
  }

  let searchDisposable = vscode.commands.registerCommand('cdnjs.search', () => {

    // The chosen file
    let chosen = {};

    showSearchInput().then((value) => {

      return search(value);

    }).then((results) => {

      return showLibraryPicker(results);

    }).then((library) => {

      chosen.library = library.name;

      return getLibrary(library.name);

    }).then((library) => {

      return showLibraryVersionPicker(library);

    }).then((asset) => {

      chosen.version = asset.version;

      recentLibraries.add(asset);

      return showFilePicker(asset);

    }).then((file) => {

      chosen.file = file;

      return showActionPicker(chosen);

    }).catch((err) => {

      console.error(err);

    });

  });

  let recentLibrariesDisposable = vscode.commands.registerCommand('cdnjs.recentLibraries', () => {

    // No Recent Libraries found
    if (recentLibraries.get().length < 1) {

      // Offer search instead
      return vscode.window.showInformationMessage("No Recent Libraries. Do you want to search instead?", 'Yes')
        .then((value) => {
          if (value === 'Yes') {
            vscode.commands.executeCommand('cdnjs.search');
          }
        }, (err) => {
          console.error(err);
        });
    }

    let chosen = {};

    new Promise((resolve, reject) => {

      // Build array of recent libraries
      let items = [];
      for (let library of recentLibraries.get()) {
        items.push({
          label: library.libraryName + '/' + library.version,
          asset: library
        });
      }

      // Clear recent libraries command
      items.push({
        label: 'Clear recent libraries list',
        clear: true
      });

      // Show quick pick of recent libraries
      vscode.window.showQuickPick(items, {
        placeHolder: 'Choose a recent library'
      }).then((value) => {

        // No recent library was chosen
        if (typeof(value) === 'undefined') {
          return reject('No library was chosen');
        }

        if (value.clear === true) {
          recentLibraries.clear();
          return true;
        }

        resolve(value.asset);

      }, (err) => {
        reject(err);
      });

    }).then((asset) => {

      // Set the chosen file's library and version'
      chosen.library = asset.libraryName;
      chosen.version = asset.version;

      recentLibraries.add(asset);

      return showFilePicker(asset);

    }).then((file) => {

      chosen.file = file;

      return showActionPicker(chosen);

    }).catch((err) => {

      console.error(err);

    });

  });

  let clearCacheDisposable = vscode.commands.registerCommand('cdnjs.clearCache', () => {

    // Clear the search cache
    searchCache.flush();

    // Clear the library cache
    libraryCache.flush();

    statusMessage("Cache has been cleared")

  });
}
exports.activate = activate;

let deactivate = () => {}
exports.deactivate = deactivate;<commit_msg>Various white-space changes<commit_after>'use strict';

const vscode = require('vscode');
let copyPaste = null;
let open = null;
let got = null;
const Promise = require('bluebird');
const RecentLibraries = require('./RecentLibraries');
const Cache = require('./Cache');

let activate = (context) => {

  const baseUrl = 'https://api.cdnjs.com/libraries';
  const searchUrl = baseUrl + '?fields=version,description,homepage';
  const embedUrl = 'cdnjs.cloudflare.com/ajax/libs';
  const httpRequestTimeout = 5000; // 5 seconds
  const statusBarMessageTimeout = 5000; // 5 seconds
  const cacheTimeDefault = 21600 // 6 hours

  // Quote configuration values
  const quotes = {
    'single': "'",
    'double': '"'
  };
  const quoteDefault = "'";

  // Protocol configuration values
  const protocols = ['https://', 'http://', '//'];
  const protocolDefault = 'https://';

  // Maximum Recent Libraries configuration values
  const maxRecentLibrariesDefault = 10;

  // Recent Libraries interface
  let recentLibraries = new RecentLibraries(context, vscode.workspace);

  // Cache interfaces
  let searchCache = new Cache(context, 'search');
  let libraryCache = new Cache(context, 'library');

  // Set consistent status bar message using timeout with either promise or time in milliseconds
  let statusMessage = (text, promise) => {
    if (promise) {
      vscode.window.setStatusBarMessage("cdnjs: " + text, promise);
    } else {
      vscode.window.setStatusBarMessage("cdnjs: " + text, statusBarMessageTimeout);
    }
  }

  // Display search box and return input
  let showSearchInput = () => {

    return new Promise((resolve, reject) => {
      vscode.window.showInputBox({
        placeHolder: 'Search for a script or library. For example: jquery'
      }).then((value) => {

        // No search string was specified
        if (typeof(value) === 'undefined') {
          return reject('No search string was specified');
        }

        resolve(value);

      }, (err) => {
        reject(err);
      });
    });
  }

  // Perform search on cdnjs.com and return JSON results
  let search = (term) => {

    term = term.trim();

    let promise = new Promise((resolve, reject) => {

      // Ignore empty searches
      if (!term.length) {
        return reject('No search term provided');
      }

      // Check the cache
      if (searchCache.has(term)) {
        return resolve(searchCache.get(term));
      }

      // Lazy load got
      got = require('got');

      // Search for libraries
      got(searchUrl + '&search=' + term, {
        json: true,
        timeout: httpRequestTimeout
      }).then((res) => {

        // Reject non-200 status code responses
        if (res.statusCode !== 200) {
          return reject(res.body);
        }

        const body = res.body;

        // Display error message if no results were found
        if (!body.results || body.results.length === 0) {
          vscode.window.showErrorMessage(term + ": No libraries found");
          return false;
        }

        // Fetch the cache time setting
        let cacheTime = vscode.workspace.getConfiguration('cdnjs').get('cacheTime');
        cacheTime = Number.isInteger(cacheTime) ? cacheTime : cacheTimeDefault;

        // Save the result to cache and resolve the search result
        searchCache.put(term, body.results, cacheTime)
          .then(() => {

            // Search results
            resolve(body.results);

          }, (err) => {

            // searchCache.put error
            reject(err);

          });

      }).catch((err) => {

        // got http request error
        reject(err);

      });

    });

    // Update Status Bar Message
    statusMessage("Searching cdnjs.com for " + term, promise);
    return promise;

  };

  // Show picker of all libraries
  let showLibraryPicker = (results) => {

    // Build array of libraries
    let items = [];
    for (let result of results) {

      // Create QuickPickItem for library
      let item = {
        label: result.name,
        description: result.description,
        currentVersion: result.version,
        name: result.name
      };
      items.push(item);
    }

    // Update status bar message
    statusMessage('Found ' + items.length + ' libraries');

    return new Promise((resolve, reject) => {

      // Show QuickPick of search results
      vscode.window.showQuickPick(items, {
        placeHolder: 'Choose a library (found ' + items.length + ' libraries)',
        matchOnDescription: true
      }).then((libraryName) => {

        // No library was chosen
        if (typeof(libraryName) === 'undefined') {
          return reject('No library was chosen');
        }

        resolve(libraryName);

      }, (err) => {
        reject(err);
      });

    });

  }

  // Get library data from cdnjs
  let getLibrary = (libraryName) => {

    let promise = new Promise((resolve, reject) => {

      // Check the cache
      if (libraryCache.has(libraryName)) {
        return resolve(libraryCache.get(libraryName));
      }

      // Lazy load got
      got = require('got');

      // Request library versions
      got(baseUrl + '/' + libraryName, {
        json: true,
        timeout: httpRequestTimeout
      }).then((res) => {

        // Reject non-200 status code responses
        if (res.statusCode !== 200) {
          return reject(res.body);
        }

        const body = res.body;

        // Display error message if no results were found
        if (body.length === 0) {
          vscode.window.showErrorMessage("The library " + libraryName + " was not found");
          return false;
        }

        // Fetch the catch time setting
        let cacheTime = vscode.workspace.getConfiguration('cdnjs').get('cacheTime');
        cacheTime = Number.isInteger(cacheTime) ? cacheTime : cacheTimeDefault;

        // Save the result to cache and resolving the search result
        libraryCache.put(libraryName, body, cacheTime)
          .then(() => {

            // Library results
            resolve(body);

          }, (err) => {

            // libraryCache.put error
            reject(err);

          });

      });

    });

    // Update Status Bar Message
    statusMessage("Fetching data for " + libraryName, promise);
    return promise;
  }

  // Show library version picker
  let showLibraryVersionPicker = (library) => {

    return new Promise((resolve, reject) => {
      // Build array of library versions
      let items = [];
      for (let asset of library.assets) {

        // QuickPickItem for the library version
        let item = {
          label: asset.version,
          files: asset.files,
          version: asset.version,
          libraryName: library.name
        };

        // Add description if this is the current/latest/stable version
        if (asset.version === library.version) {
          item.description = 'current version';
        }
        items.push(item);
      }

      statusMessage('Found ' + items.length + ' versions');

      // Show QuickPick of library versions
      vscode.window.showQuickPick(items, {
        placeHolder: library.name
      }).then((asset) => {

        // No version was chosen
        if (typeof(asset) === 'undefined') {
          return reject('No library version was chosen');
        }

        resolve(asset);
      }, (err) => {
        reject(err);
      });
    });
  }

  // Show library version file picker
  let showFilePicker = (asset) => {

    return new Promise((resolve, reject) => {

      // Build array of files
      let items = [];
      for (let file of asset.files) {
        items.push(file);
      }

      statusMessage('Found ' + items.length + ' files');

      // Show QuickPick of asset files
      vscode.window.showQuickPick(items, {
        placeHolder: asset.libraryName + "/" + asset.version + "/"
      }).then((file) => {

        // No file was chosen
        if (typeof(file) === 'undefined') {
          return reject('No library file was chosen');
        }

        resolve(file);
      }, (err) => {
        reject(err);
      });

    });

  }

  // Show file action picker
  let showActionPicker = (chosen) => {

    return new Promise((resolve, reject) => {

      // Reject if any chosen file properties are missing
      if (!chosen.library || !chosen.version || !chosen.file) {
        return reject('Missing file asset parameters');
      }

      // Configuration
      const config = vscode.workspace.getConfiguration('cdnjs');

      // Determine the quote style from configuration
      const quote = quotes[config.get('quoteStyle')] || quoteDefault;

      // Determine url protocol
      const protocolConfig = config.get('protocol');
      const protocol = protocols.indexOf(protocolConfig) >= 0 ? protocolConfig : protocolDefault;

      // Build the url for the file
      let url = protocol + embedUrl + '/' + chosen.library + '/' + chosen.version + '/' + chosen.file;

      // Arrays of actions
      let actions = [];

      // Determine file extension
      let fileExtension = chosen.file.split('.').pop();
      let tag = "";
      switch (fileExtension) {

        case 'js':
          // JavaScript
          tag = '<script src=' + quote + url + quote + '></script>';

          // Insert <script> tag into document action
          if (vscode.window.activeTextEditor) {
            actions.push({
              label: '<script>: Insert into document',
              callback: () => {
                insertText(tag);
              }
            });
          }

          // Copy <script> tag to clipboard action
          actions.push({
            label: '<script>: Copy to clipboard',
            callback: () => {
              copy(tag, '<script> tag copied to the clipboard');
            }
          });

          break;

        case 'css':
          // CSS
          tag = '<link rel=' + quote + 'stylesheet' + quote + ' href=' + quote + url + quote + '/>';

          // Insert <link> tag into document action
          if (vscode.window.activeTextEditor) {
            actions.push({
              label: '<link>: Insert into document',
              callback: () => {
                insertText(tag);
              }
            });
          }

          // Copy <link> tag to clipboard action
          actions.push({
            label: '<link>: Copy to clipboard',
            callback: () => {
              copy(tag, '<link> tag copied to the clipboard');
            }
          });

          break;

        default:
          break;
      }

      // Insert URL into document action
      if (vscode.window.activeTextEditor) {
        actions.push({
          label: 'URL: Insert into document',
          callback: () => {
            insertText(url);
          }
        });
      }

      // Copy URL to clipboard action
      actions.push({
        label: 'URL: Copy to clipboard',
        callback: () => {
          copy(url, 'URL copied to the clipboard');
        }
      });

      // Open URL in browser action
      actions.push({
        label: 'URL: Open in browser',
        callback: () => {
          // Lazy load open
          open = require('open');

          open(url);
        }
      });

      return new Promise((resolve, reject) => {
        vscode.window.showQuickPick(actions, {
          placeHolder: url
        }).then((action) => {

          // No action was chosen
          if (typeof(action) === 'undefined') {
            return reject('No action was chosen');
          }

          // Execute action callback
          action.callback();

          resolve();
        }, (err) => {
          reject(err);
        });

      });

    });
  }

  // Insert text into active document at cursor positions
  let insertText = (text) => {

    let textEditor = vscode.window.activeTextEditor;

    // Ignore if no active TextEditor
    if (typeof(textEditor) === 'undefined') {
      return false;
    }

    // Get the active text document's uri
    let uri = textEditor.document.uri;

    // Create a new TextEdit for each selection
    let edits = [];
    for (let selection of textEditor.selections) {
      edits.push(vscode.TextEdit.insert(selection.active, text));
    }

    // New WorkspaceEdit
    let edit = new vscode.WorkspaceEdit();
    edit.set(uri, edits);

    // Applying the WorkspaceEdit
    vscode.workspace.applyEdit(edit)
      .then(() => {

        // Clear the selection
        textEditor.selection = new vscode.Selection(textEditor.selection.end, textEditor.selection.end);

      }, (err) => {
        reject(err);
      });

    return true;
  }

  // Copy text to clipboard and set statusBarMessage
  let copy = (text, message) => {
    // Lazy load copy-paste
    copyPaste = require('copy-paste');

    copyPaste.copy(text, () => {
      if (message) {
        statusMessage(message);
      }
    });
  }

  let searchDisposable = vscode.commands.registerCommand('cdnjs.search', () => {

    // The chosen file
    let chosen = {};

    showSearchInput().then((value) => {

      return search(value);

    }).then((results) => {

      return showLibraryPicker(results);

    }).then((library) => {

      chosen.library = library.name;

      return getLibrary(library.name);

    }).then((library) => {

      return showLibraryVersionPicker(library);

    }).then((asset) => {

      chosen.version = asset.version;

      recentLibraries.add(asset);

      return showFilePicker(asset);

    }).then((file) => {

      chosen.file = file;

      return showActionPicker(chosen);

    }).catch((err) => {

      console.error(err);

    });

  });

  let recentLibrariesDisposable = vscode.commands.registerCommand('cdnjs.recentLibraries', () => {

    // No Recent Libraries found
    if (recentLibraries.get().length < 1) {

      // Offer search instead
      return vscode.window.showInformationMessage("No Recent Libraries. Do you want to search instead?", 'Yes')
        .then((value) => {
          if (value === 'Yes') {
            vscode.commands.executeCommand('cdnjs.search');
          }
        }, (err) => {
          console.error(err);
        });
    }

    let chosen = {};

    new Promise((resolve, reject) => {

      // Build array of recent libraries
      let items = [];
      for (let library of recentLibraries.get()) {
        items.push({
          label: library.libraryName + '/' + library.version,
          asset: library
        });
      }

      // Clear recent libraries command
      items.push({
        label: 'Clear recent libraries list',
        clear: true
      });

      // Show quick pick of recent libraries
      vscode.window.showQuickPick(items, {
        placeHolder: 'Choose a recent library'
      }).then((value) => {

        // No recent library was chosen
        if (typeof(value) === 'undefined') {
          return reject('No library was chosen');
        }

        if (value.clear === true) {
          recentLibraries.clear();
          return true;
        }

        resolve(value.asset);

      }, (err) => {
        reject(err);
      });

    }).then((asset) => {

      // Set the chosen file's library and version'
      chosen.library = asset.libraryName;
      chosen.version = asset.version;

      recentLibraries.add(asset);

      return showFilePicker(asset);

    }).then((file) => {

      chosen.file = file;

      return showActionPicker(chosen);

    }).catch((err) => {

      console.error(err);

    });

  });

  let clearCacheDisposable = vscode.commands.registerCommand('cdnjs.clearCache', () => {

    // Clear the search cache
    searchCache.flush();

    // Clear the library cache
    libraryCache.flush();

    statusMessage("Cache has been cleared")

  });
}
exports.activate = activate;

let deactivate = () => {}
exports.deactivate = deactivate;<|endoftext|>


<commit_before>/*global describe, it, browser */

describe('listbuilder', function () {
    'use strict';

    function listbuilderTest(screenWidth) {

        return browser
            .setupTest('/listbuilder/fixtures/test.full.html', screenWidth)
            .compareScreenshot({
                screenshotName: 'listbuilder',
                selector: '#screenshot-listbuilder',
                checkAccessibility: true
            });
    }

    it('match the baseline listbuilder screenshot', function () {
        return listbuilderTest(1280);
    });

    it('match the baseline listbuilder screenshot on small screens', function () {
        return listbuilderTest(480);
    });

    it('match the listbuilder open view switcher screenshot', function () {
        return browser
            .setupTest('/listbuilder/fixtures/test.full.html')
            .click('.bb-listbuilder-switcher button')
            .pause(1000)
            .compareScreenshot({
                screenshotName: 'listbuilder_switcher',
                selector: '#screenshot-listbuilder',
                checkAccessibility: true
            });
    });

    it('match the listbuilder repeater screenshot', function () {
        return browser
            .setupTest('/listbuilder/fixtures/test.full.html')
            .click('.bb-listbuilder-switcher button')
            .click('.bb-listbuilder-switcher-menu a')
            .pause(1000)
            .compareScreenshot({
                screenshotName: 'listbuilder_repeater',
                selector: '#screenshot-listbuilder',
                checkAccessibility: true
            });
    });

    it('match the listbuilder screenshot when using multiselect', function () {
        return browser
            .setupTest('/listbuilder/fixtures/test.full.html')
            .click('.bb-list-multiselect-button')
            .click('.bb-card input')
            .pause(1000)
            .compareScreenshot({
                screenshotName: 'listbuilder_multiselect',
                selector: '#screenshot-listbuilder',
                checkAccessibility: true
            });
    });
});<commit_msg>Remove accessibility check from listbuilder multiselect for now<commit_after>/*global describe, it, browser */

describe('listbuilder', function () {
    'use strict';

    function listbuilderTest(screenWidth) {

        return browser
            .setupTest('/listbuilder/fixtures/test.full.html', screenWidth)
            .compareScreenshot({
                screenshotName: 'listbuilder',
                selector: '#screenshot-listbuilder',
                checkAccessibility: true
            });
    }

    it('match the baseline listbuilder screenshot', function () {
        return listbuilderTest(1280);
    });

    it('match the baseline listbuilder screenshot on small screens', function () {
        return listbuilderTest(480);
    });

    it('match the listbuilder open view switcher screenshot', function () {
        return browser
            .setupTest('/listbuilder/fixtures/test.full.html')
            .click('.bb-listbuilder-switcher button')
            .pause(1000)
            .compareScreenshot({
                screenshotName: 'listbuilder_switcher',
                selector: '#screenshot-listbuilder',
                checkAccessibility: true
            });
    });

    it('match the listbuilder repeater screenshot', function () {
        return browser
            .setupTest('/listbuilder/fixtures/test.full.html')
            .click('.bb-listbuilder-switcher button')
            .click('.bb-listbuilder-switcher-menu a')
            .pause(1000)
            .compareScreenshot({
                screenshotName: 'listbuilder_repeater',
                selector: '#screenshot-listbuilder',
                checkAccessibility: true
            });
    });

    it('match the listbuilder screenshot when using multiselect', function () {
        return browser
            .setupTest('/listbuilder/fixtures/test.full.html')
            .click('.bb-list-multiselect-button')
            .click('.bb-card input')
            .pause(1000)
            .compareScreenshot({
                screenshotName: 'listbuilder_multiselect',
                selector: '#screenshot-listbuilder'
            });
    });
});<|endoftext|>


<commit_before>// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
var vscode = require('vscode');
var beautify = require('js-beautify');

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {
	// The command has been defined in the package.json file
	// Now provide the implementation of the command with  registerCommand
	// The commandId parameter must match the command field in package.json
	var disposable = vscode.commands.registerCommand('HookyQR.beautify', function () {
		// The code you place here will be executed every time your command is executed
		var active = vscode.window.activeTextEditor;
		if (!active) return;
		var doc = active.document;
		if (!doc) return;
		var better = doc.getText();
		var type = doc.isUntitled ? "js" : doc.fileName.split('.').pop();

		if (type === 'htm' || type === 'html') better = beautify.html(better);
		else if (type === 'css' ) better = beautify.css(better);
		else if (type === 'js') better = beautify.js(better);
		else return;
		//get the whole file:
		var range = new vscode.Range(new vscode.Position(0, 0), doc.positionAt(Infinity));
		//and make the change:
		active.edit(editor=> editor.replace(range, better));
	});
	context.subscriptions.push(disposable);
}
exports.activate = activate;<commit_msg>added rc file search<commit_after>// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
var vscode = require('vscode');
var beautify = require('js-beautify');
var path = require('path');
var fs = require('fs');
function findRecursive(dir, fileName) {
    var fullPath = path.join(dir, fileName);
    var nextDir = path.dirname(dir);
    var result = fs.existsSync(fullPath) ? fullPath : null;
    if (!result && (nextDir !== dir)) {
       result = findRecursive(nextDir, fileName);
    }
    return result;
}
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {
	// The command has been defined in the package.json file
	// Now provide the implementation of the command with  registerCommand
	// The commandId parameter must match the command field in package.json

	var disposable = vscode.commands.registerCommand('HookyQR.beautify', function () {
		// The code you place here will be executed every time your command is executed
		//walk to find a .jsbeautifyrc

		var active = vscode.window.activeTextEditor;
		if (!active) return;
		var doc = active.document;
		if (!doc) return;
		//get a settings file
		var base = vscode.workspace.rootPath;
		if (!doc.isUntitled) base = doc.fileName;
		var beautFile = findRecursive(base, ".jsbeautifyrc");
		if (beautFile) fs.readFile(beautFile, function (ee, d) {
			if (ee && !d) d = "{}";
			var better = doc.getText();
			var opts = {};
			try {
				opts = JSON.parse(d.toString());
			} catch (e) {
				opts = {};//just use the default opts
			}
			var type = doc.isUntitled ? "js" : doc.fileName.split('.').pop();

			if (type === 'htm' || type === 'html') better = beautify.html(better, opts);
			else if (type === 'css') better = beautify.css(better, opts);
			else if (type === 'js') better = beautify.js(better, opts);
			else return;
			//get the whole file:
			var range = new vscode.Range(new vscode.Position(0, 0), doc.positionAt(Infinity));
			//and make the change:
			active.edit(editor=> editor.replace(range, better));
		});
	});
	context.subscriptions.push(disposable);
}
exports.activate = activate;<|endoftext|>


<commit_before>'use strict';

/**
 * Module Dependences
 */

var Team          = require('../models/Team');
var User          = require('../models/User');
var Project          = require('../models/Project');
var passportConf  = require('../config/passport');

/**
 * Account Controller
 */

module.exports.controller = function (app) {

 /**
   * GET /project*
   * *ALL* project routes must be authenticated first
   */

  app.all('/project*', passportConf.isAuthenticated);

  /**
   * GET /project
   * Render Projects Page
   */

  app.get('/projects', function (req, res) {
    res.render('project/projects', {
      url: req.url
    });
  });

  /**
   * GET /projectlist
   * JSON projects api
   */

  app.get('/projectlist', passportConf.isAuthenticated, passportConf.isAdministrator, function (req, res) {
    Project.find({}).populate('teams').exec( function (err, items) {
      if (err) {
        return (err, null);
      }
      res.json(items);
    });
  });

  /**
   * GET /projectlist/:id
   * JSON specefic project api
   */

  app.get('/projectlist/:id', passportConf.isAuthenticated, passportConf.isAdministrator, function (req, res) {
    Project.findOne({ _id : req.params.id }).populate('users').exec( function (err, item) {
      if (err) {
        return (err, null);
      }
      res.json(item);
    });
  });

  /**
   * DEL /projectlist/:id
   * JSON projects delete api
   */

  app.delete('/projectlist/:id', passportConf.isAuthenticated, passportConf.isAdministrator, function (req, res) {
    // Find Project to delete
    Project.findById(req.params.id, function (err, project) {
      // Loops through Teams and removes the teams from the project
      project.teams.forEach( function (team) {
        Team.findByIdAndUpdate({ _id:team }, { $pull: { projects:project._id }}, function (err) {
          if (err) {
            return res.send({ msg: err });
          }
        });
      });

      // Remove Project from Users
      User.find({ projects:project._id}, function (err, users) {
        users.forEach( function (user) {
          user.update({ $pull: {projects:project._id }}, function (err) {
            if (err) {
              return res.send({ msg: err });
            }
          });
        });
      });

      // Delete Project
      Project.remove({ _id:project._id },  function (err, result) {
        console.log(result);
        res.send((result === 1) ? { msg: '' } : { msg: 'error: ' + err });
      });
    });
  });

  /**
   * GET project/create
   * Render Create Project page
   */

  app.get('/project/create', passportConf.isAuthenticated, passportConf.isAdministrator, function (req, res) {
    res.render('project/create', {
      url: req.url
    });
  });

  /**
   * POST project/create
   * Process create project
   */

  app.post('/project/create', function (req, res, next) {

    // Begin a workflow
    var workflow = new (require('events').EventEmitter)();

    /**
     * Step 1: Validate the form fields
     */

    workflow.on('validate', function () {

      // Check for form errors
      req.assert('name', 'Project name cannot be empty.').notEmpty();

      var errors = req.validationErrors();

      if (errors) {
        req.flash('error', errors);
        return res.redirect('back');
      }

      // next step
      workflow.emit('createProject');
    });

    /**
     * Step 2: Create a new project
     */

    workflow.on('createProject', function () {
      // Create project
      var project = new Project({
        name: req.body.name.trim(),
        'docker_opts.image': req.body.image.trim(),
        'docker_opts.cmd': req.body.cmd.trim(),
        'docker_opts.container_port': req.body.containerPort.trim(),
        'docker_opts.host_port': req.body.hostPort.trim(),
      });

      // Save project
      project.save(function (err) {
        if (err) {
          if (err.code === 11000) {
            req.flash('error', { msg: 'A project with that name already exists!' });
          }
          req.flash('error', { msg: 'Could not create project!' });
          return res.redirect('back');
        }
      });

      req.flash('info', { msg: 'Your project has been successfully created.' });
      return res.redirect('/projects');

      // WORKFLOW COMPLETED

    });

    /**
     * Initiate the workflow
     */

    workflow.emit('validate');

  });

  /**
   * GET project/update
   * Render Update Project page
   */

  app.get('/project/update?:id', passportConf.isAuthenticated, passportConf.isAdministrator, function (req, res) {
    res.render('project/update', {
      url: req.url
    });
  });

  /**
   * POST project/update
   * Process update project
   */

  app.post('/project/update', function (req, res, next) {

    // Begin a workflow
    var workflow = new (require('events').EventEmitter)();

    /**
     * Step 1: Validate the form fields
     */

    workflow.on('validate', function () {

      // Check for form errors
      req.assert('name', 'Project name cannot be empty.').notEmpty();

      var errors = req.validationErrors();

      if (errors) {
        req.flash('error', errors);
        return res.redirect('back');
      }

      // next step
      workflow.emit('updateProject');
    });

    /**
     * Step 2: Update the project
     */

    workflow.on('updateProject', function () {
      Project.findById(req.body.projectId, function (err, project) {
        project.name = req.body.name.trim();
        project.docker_opts.image = req.body.image.trim();
        project.docker_opts.cmd = req.body.cmd.trim();
        project.docker_opts.container_port = req.body.containerPort.trim();
        project.docker_opts.host_port = req.body.hostPort.trim();

        // Save project
        project.save(function (err) {
          if (err) {
            if (err.code === 11000) {
              req.flash('error', { msg: 'A project with that name already exists!' });
            }
            req.flash('info', { msg: err });
            return res.redirect('back');
          }
        });

        req.flash('info', { msg: 'Your project has been successfully updated.' });
        return res.redirect('/projects');
      });

      // WORKFLOW COMPLETED

    });

    /**
     * Initiate the workflow
     */

    workflow.emit('validate');

  });

};
<commit_msg>Style tweaking<commit_after>'use strict';

/**
 * Module Dependences
 */

var Team          = require('../models/Team');
var User          = require('../models/User');
var Project          = require('../models/Project');
var passportConf  = require('../config/passport');

/**
 * Account Controller
 */

module.exports.controller = function (app) {

 /**
   * GET /project*
   * *ALL* project routes must be authenticated first
   */

  app.all('/project*', passportConf.isAuthenticated);

  /**
   * GET /project
   * Render Projects Page
   */

  app.get('/projects', function (req, res) {
    res.render('project/projects', {
      url: req.url
    });
  });

  /**
   * GET /projectlist
   * JSON projects api
   */

  app.get('/projectlist', passportConf.isAuthenticated, passportConf.isAdministrator, function (req, res) {
    Project.find({}).populate('teams').exec( function (err, items) {
      if (err) {
        return (err, null);
      }
      res.json(items);
    });
  });

  /**
   * GET /projectlist/:id
   * JSON specefic project api
   */

  app.get('/projectlist/:id', passportConf.isAuthenticated, passportConf.isAdministrator, function (req, res) {
    Project.findOne({ _id : req.params.id }).populate('users').exec( function (err, item) {
      if (err) {
        return (err, null);
      }
      res.json(item);
    });
  });

  /**
   * DEL /projectlist/:id
   * JSON projects delete api
   */

  app.delete('/projectlist/:id', passportConf.isAuthenticated, passportConf.isAdministrator, function (req, res) {
    // Find Project to delete
    Project.findById(req.params.id, function (err, project) {
      // Loops through Teams and removes the teams from the project
      project.teams.forEach( function (team) {
        Team.findByIdAndUpdate({ _id:team }, { $pull: { projects:project._id }}, function (err) {
          if (err) {
            return res.send({ msg: err });
          }
        });
      });

      // Remove Project from Users
      User.find({ projects:project._id }, function (err, users) {
        users.forEach( function (user) {
          user.update({ $pull: { projects:project._id }}, function (err) {
            if (err) {
              return res.send({ msg: err });
            }
          });
        });
      });

      // Delete Project
      Project.remove({ _id:project._id },  function (err, result) {
        console.log(result);
        res.send((result === 1) ? { msg: '' } : { msg: 'error: ' + err });
      });
    });
  });

  /**
   * GET project/create
   * Render Create Project page
   */

  app.get('/project/create', passportConf.isAuthenticated, passportConf.isAdministrator, function (req, res) {
    res.render('project/create', {
      url: req.url
    });
  });

  /**
   * POST project/create
   * Process create project
   */

  app.post('/project/create', function (req, res, next) {

    // Begin a workflow
    var workflow = new (require('events').EventEmitter)();

    /**
     * Step 1: Validate the form fields
     */

    workflow.on('validate', function () {

      // Check for form errors
      req.assert('name', 'Project name cannot be empty.').notEmpty();

      var errors = req.validationErrors();

      if (errors) {
        req.flash('error', errors);
        return res.redirect('back');
      }

      // next step
      workflow.emit('createProject');
    });

    /**
     * Step 2: Create a new project
     */

    workflow.on('createProject', function () {
      // Create project
      var project = new Project({
        name: req.body.name.trim(),
        'docker_opts.image': req.body.image.trim(),
        'docker_opts.cmd': req.body.cmd.trim(),
        'docker_opts.container_port': req.body.containerPort.trim(),
        'docker_opts.host_port': req.body.hostPort.trim(),
      });

      // Save project
      project.save(function (err) {
        if (err) {
          if (err.code === 11000) {
            req.flash('error', { msg: 'A project with that name already exists!' });
          }
          req.flash('error', { msg: 'Could not create project!' });
          return res.redirect('back');
        }
      });

      req.flash('info', { msg: 'Your project has been successfully created.' });
      return res.redirect('/projects');

      // WORKFLOW COMPLETED

    });

    /**
     * Initiate the workflow
     */

    workflow.emit('validate');

  });

  /**
   * GET project/update
   * Render Update Project page
   */

  app.get('/project/update?:id', passportConf.isAuthenticated, passportConf.isAdministrator, function (req, res) {
    res.render('project/update', {
      url: req.url
    });
  });

  /**
   * POST project/update
   * Process update project
   */

  app.post('/project/update', function (req, res, next) {

    // Begin a workflow
    var workflow = new (require('events').EventEmitter)();

    /**
     * Step 1: Validate the form fields
     */

    workflow.on('validate', function () {

      // Check for form errors
      req.assert('name', 'Project name cannot be empty.').notEmpty();

      var errors = req.validationErrors();

      if (errors) {
        req.flash('error', errors);
        return res.redirect('back');
      }

      // next step
      workflow.emit('updateProject');
    });

    /**
     * Step 2: Update the project
     */

    workflow.on('updateProject', function () {
      Project.findById(req.body.projectId, function (err, project) {
        project.name = req.body.name.trim();
        project.docker_opts.image = req.body.image.trim();
        project.docker_opts.cmd = req.body.cmd.trim();
        project.docker_opts.container_port = req.body.containerPort.trim();
        project.docker_opts.host_port = req.body.hostPort.trim();

        // Save project
        project.save(function (err) {
          if (err) {
            if (err.code === 11000) {
              req.flash('error', { msg: 'A project with that name already exists!' });
            }
            req.flash('info', { msg: err });
            return res.redirect('back');
          }
        });

        req.flash('info', { msg: 'Your project has been successfully updated.' });
        return res.redirect('/projects');
      });

      // WORKFLOW COMPLETED

    });

    /**
     * Initiate the workflow
     */

    workflow.emit('validate');

  });

};
<|endoftext|>