<commit_before>'use strict';

var assign          = require('es5-ext/object/assign')
  , copy            = require('es5-ext/object/copy')
  , value           = require('es5-ext/object/valid-value')
  , ee              = require('event-emitter')
  , d               = require('d')
  , autoBind        = require('d/auto-bind')
  , memoizeMethods  = require('memoizee/methods-plain')
  , ObservableValue = require('observable-value')
  , replaceContent  = require('dom-ext/element/#/replace-content')
  , formatUrl       = require('url3/format')
  , parseUrl        = require('url3/parse')
  , ns              = require('mano').domjs.ns
  , location        = require('mano/lib/client/location');

var PaginatorDom = function (paginator) {
	this.paginator = paginator;
	this.list = ns.ul({ class: 'pagination' });
	this.dom = ns._if(ns.gt(this.paginator.count, 0), this.list).toDOM(document);
	this.reload();
	this.paginator.count.on('change', this.reload);
};
Object.defineProperties(PaginatorDom.prototype, assign({
	toDOM: d(function (document) { return this.dom; })
}, autoBind({
	reload: d(function () {
		var i, l = this.paginator.count.value, buttons = [];
		if (l < 2) return;
		for (i = 1; i <= l; ++i) buttons.push(this.getPageButton(i));
		replaceContent.call(this.list, buttons);
	})
}), memoizeMethods({
	getPageButton: d(function (page) {
		return ns.li({ class: ns._if(this.paginator.current.eq(page), 'active') },
			ns.a({ href: this.paginator.getLink(page) }, page));
	})
})));

var Paginator = module.exports = function (pathname, count, current) {
	if (!(this instanceof Paginator)) return new Paginator(pathname, count, current);
	this.pathname = String(value(pathname));
	this.url = parseUrl(this.pathname, true);
	delete this.url.search;
	location.on('change', this.updateLinks);
	this.count = new ObservableValue(count);
	this.current = new ObservableValue(count);
};

ee(Object.defineProperties(Paginator.prototype, assign({
	toDOM: d(function (document) { return (new PaginatorDom(this)).toDOM(document); })
}, autoBind({
	updateLinks: d(function () {
		if (this.pathname !== location.pathname) return;
		this.url.query = copy(location.query);
		var i, l = this.count.value;
		for (i = 1; i <= l; ++i) {
			this.url.query.page = 1;
			this.getLink(i).value = formatUrl(this.url);
		}
	})
}), memoizeMethods({
	getLink: d(function (page) {
		this.url.query.page = page;
		return new ObservableValue(formatUrl(this.url));
	})
}))));
<commit_msg>Fix links update<commit_after>'use strict';

var assign          = require('es5-ext/object/assign')
  , copy            = require('es5-ext/object/copy')
  , value           = require('es5-ext/object/valid-value')
  , ee              = require('event-emitter')
  , d               = require('d')
  , autoBind        = require('d/auto-bind')
  , memoizeMethods  = require('memoizee/methods-plain')
  , ObservableValue = require('observable-value')
  , replaceContent  = require('dom-ext/element/#/replace-content')
  , formatUrl       = require('url3/format')
  , parseUrl        = require('url3/parse')
  , ns              = require('mano').domjs.ns
  , location        = require('mano/lib/client/location');

var PaginatorDom = function (paginator) {
	this.paginator = paginator;
	this.list = ns.ul({ class: 'pagination' });
	this.dom = ns._if(ns.gt(this.paginator.count, 0), this.list).toDOM(document);
	this.reload();
	this.paginator.count.on('change', this.reload);
};
Object.defineProperties(PaginatorDom.prototype, assign({
	toDOM: d(function (document) { return this.dom; })
}, autoBind({
	reload: d(function () {
		var i, l = this.paginator.count.value, buttons = [];
		if (l < 2) return;
		for (i = 1; i <= l; ++i) buttons.push(this.getPageButton(i));
		replaceContent.call(this.list, buttons);
	})
}), memoizeMethods({
	getPageButton: d(function (page) {
		return ns.li({ class: ns._if(this.paginator.current.eq(page), 'active') },
			ns.a({ href: this.paginator.getLink(page) }, page));
	})
})));

var Paginator = module.exports = function (pathname, count, current) {
	if (!(this instanceof Paginator)) return new Paginator(pathname, count, current);
	this.pathname = String(value(pathname));
	this.url = parseUrl(this.pathname, true);
	delete this.url.search;
	location.on('change', this.updateLinks);
	this.count = new ObservableValue(count);
	this.current = new ObservableValue(count);
};

ee(Object.defineProperties(Paginator.prototype, assign({
	toDOM: d(function (document) { return (new PaginatorDom(this)).toDOM(document); })
}, autoBind({
	updateLinks: d(function () {
		if (this.pathname !== location.pathname) return;
		this.url.query = copy(location.query);
		var i, l = this.count.value;
		for (i = 1; i <= l; ++i) {
			this.url.query.page = i;
			this.getLink(i).value = formatUrl(this.url);
		}
	})
}), memoizeMethods({
	getLink: d(function (page) {
		this.url.query.page = page;
		return new ObservableValue(formatUrl(this.url));
	})
}))));
<|endoftext|>


<commit_before>'use strict';
var util = require('util'),
  path = require('path'),
  yeoman = require('yeoman-generator'),
  _ = require('lodash'),
  _s = require('underscore.string');

var ViewGenerator = yeoman.generators.NamedBase.extend({
  init: function () {
    _.assign(this, this.config.getAll());
    this.viewFilename = _s.dasherize(this.name);
    this.viewPath = 'app/views/' + this.viewFilename + '/';
    this.moduleName = this.vendorPrefix + '.views.' + _s.classify(this.viewFilename);
    this.styleName = _s.camelize(this.name);

    this.ctrlName = _s.classify(this.viewFilename + '-ctrl');
    this.ctrlInstance = _s.camelize(this.viewFilename + '-ctrl');
    this.ctrlFilename = this.viewFilename + '-ctrl.js';
    this.ctrlSpecFilename = this.viewFilename + '-ctrl-spec.js';
  },

  files: function () {
    this.template('_controller.js', this.viewPath + this.ctrlFilename);
    this.template('_controller-spec.js', this.viewPath + this.ctrlSpecFilename);
    this.template('_view.jade', this.viewPath + this.viewFilename + '.jade');
    this.template('_view.scss', this.viewPath + this.viewFilename + '.scss');
  }
});

module.exports = ViewGenerator;<commit_msg>#16 update view generator to use nameHelper<commit_after>'use strict';
var yeoman = require('yeoman-generator'),
  _ = require('lodash'),
  nameHelper = require('../../lib/name-helper.js');

var ViewGenerator = yeoman.generators.NamedBase.extend({
  init: function () {
    _.assign(this, this.config.getAll());
    this.camelizedName = nameHelper.camelize(this.name);
    this.hyphenatedName = nameHelper.hyphenate(this.name);
    this.classifiedName = nameHelper.classify(this.name);

    this.viewFilename = this.hyphenatedName;
    this.viewPath = 'app/views/' + this.viewFilename + '/';
    this.moduleName = this.vendorPrefix + '.views.' + this.classifiedName;
    this.styleName = this.camelizedName;

    this.ctrlName = this.classifiedName.concat('Ctrl');
    this.ctrlInstance = this.camelizedName.concat('Ctrl');
    this.ctrlFilename = this.viewFilename.concat('-ctrl.js');
    this.ctrlSpecFilename = this.viewFilename.concat('-ctrl-spec.js');
  },

  files: function () {
    this.template('_controller.js', this.viewPath + this.ctrlFilename);
    this.template('_controller-spec.js', this.viewPath + this.ctrlSpecFilename);
    this.template('_view.jade', this.viewPath + this.viewFilename + '.jade');
    this.template('_view.scss', this.viewPath + this.viewFilename + '.scss');
  }
});

module.exports = ViewGenerator;<|endoftext|>


<commit_before>'use strict';

//
//  Yeoman bat:view sub-generator.
//

var generators      = require( 'yeoman-generator' )
,   yosay           = require( 'yosay' )
,   youtil          = require( './../../lib/youtil.js' )
,   chalk           = require( 'chalk' )
,   _               = require( 'lodash' )
;

var decapitalize    = require( 'underscore.string/decapitalize' );

var ViewGenerator = generators.Base.extend(
    {
        constructor: function ()
        {
            generators.Base.apply( this, arguments );

            this.argument(
                'viewName'
            ,   {
                    type:           String
                ,   required:       false
                ,   desc:           'The name of the view to create.'
                }
            );

            //  Also add 'viewName' as a - hidden - option, defaulting to the positional argument's value.
            //  This way `_promptsPruneByOptions()` can filter away prompting for the view name too.
            //
            this.option(
                'viewName'
            ,   {
                    type:           String
                ,   desc:           'The name of the view to create.'
                ,   default:        this.viewName
                ,   hide:           true
                }
            );

            //  Normal options.
            //
            this.option(
                'description'
            ,   {
                    type:           String
                ,   desc:           'The purpose of the view to create.'
                }
            );

            this.option(
                'sass'
            ,   {
                    type:           Boolean
                ,   desc:           'Specify whether this view should have a SASS file of its own.'
                }
            );
        }

    ,   description:
            chalk.bold(
                'This is the ' + chalk.cyan( 'backbone view' )
            +   ' generator for BAT, the Backbone Application Template'
            +   ' created by ' + chalk.blue( 'marv' ) + chalk.red( 'iq' ) + '.'
            )

    ,   initializing: function ()
        {
            this._assertBatApp();

            //  Container for template expansion data.
            //
            this.templateData = {};
        }

    ,   prompting:
        {
            askSomeQuestions: function ()
            {
                //  Ask only those question that have not yet been provided with answers via the command line.
                //
                var prompts = this._promptsPruneByOptions(
                        [
                            {
                                type:       'input'
                            ,   name:       'viewName'
                            ,   message:    'What is the name of this view you so desire?'
                            ,   default:    youtil.definedToString( this.options.viewName )
                            ,   validate:   youtil.isIdentifier
                            ,   filter: function ( value )
                                {
                                    return decapitalize( _.trim( value ).replace( /view$/i, '' ));
                                }
                            }
                        ,   {
                                type:       'input'
                            ,   name:       'description'
                            ,   message:    'What is the purpose (description) of this view?'
                            ,   validate:   youtil.isNonBlank
                            ,   filter:     youtil.sentencify
                            }
                        ,   {
                                type:       'confirm'
                            ,   name:       'sass'
                            ,   message:    'Would you like a SASS file for this view?'
                            ,   default:    true
                            ,   validate:   _.isBoolean
                            }
                        ]
                    )
                ;

                if ( prompts.length )
                {
                    //  Have Yeoman greet the user.
                    //
                    this.log( yosay( 'So you want a BAT view?' ) );

                    return (
                        this
                            .prompt( prompts )
                            .then( function ( answers ) { _.extend( this.templateData, answers ); }.bind( this ) )
                    );
                }
            }
        }

    ,   configuring: function ()
        {
            var data        = this.templateData
            ,   viewName    = data.viewName
            ;

            _.extend(
                data
            ,   {
                    className:          _.capitalize( viewName ) + 'View'
                ,   cssClassName:       _.kebabCase( viewName ) + '-view'
                ,   fileBase:           _.kebabCase( _.deburr( viewName ))

                ,   userName:           this.user.git.name()

                ,   backbone:           ( this.config.get( 'backbone' ) || { className: 'Backbone', modulePath: 'backbone' } )
                }
            );
        }

    ,   writing:
        {
            createView: function ()
            {
                var data        = this.templateData
                ,   templates   =
                    {
                        'view.hbs':     [ 'src/views/' + data.fileBase + '.hbs' ]
                    ,   'view.coffee':  [ 'src/views/' + data.fileBase + '.coffee' ]
                    }
                ;

                if ( data.sass )
                {
                    templates[ 'view.sass' ] = [ 'src/sass/views/_' + data.fileBase + '.sass' ];
                }

                this._templatesProcess( templates );
            }
        }

    ,   install: {

            updateViewsSass: function () {

                var data = this.templateData;

                /* jshint laxbreak: true */

                if ( !( data.sass )) { return; }

                //
                //  Add an `@import "views/_<fileBase>" statement to the '_views.sass' file.
                //

                var viewsPath   = 'src/sass/_views.sass'
                ,   fs          = this.fs
                ,   views       = fs.read( viewsPath )
                ,   statement   = '@import "views/_' + data.fileBase + '"'
                ;

                //  Do nothing if an `@import` for this sass file seems to exist already.
                //
                if ( views.indexOf( statement ) !== -1 )
                {
                    this.log(
                        'It appears that "' + viewsPath + '" already contains an `@import` for "' + data.fileBase + '.sass".\n'
                    +   'Leaving it untouched.'
                    );

                    return;
                }

                // Avoid the conflict warning and use force for the write
                //
                this.conflicter.force = true;

                //  Look for a place to insert, preferably at an alfanumerically ordered position.
                //
                var insertAt, match, matcher = /^@import.*/mg;

                while ( (( match = matcher.exec( views ) )) )
                {
                    if ( statement < match[ 0 ] ) { insertAt = match.index; }
                }

                if ( insertAt == null )
                {
                    var pad = (( views.length && views.slice( -1 ) !== '\n' ) ? '\n' : '' );

                    fs.write( viewsPath, views + pad + statement + '\n' );
                }
                else
                {
                    fs.write( viewsPath, views.slice( 0, insertAt ) + statement + '\n' + views.slice( insertAt ) );
                }
            }
        }
    }
);

_.extend(
    ViewGenerator.prototype
,   require( './../../lib/generator.js' )
,   require( './../../lib/sub-generator.js' )
);

module.exports = ViewGenerator;
<commit_msg>fix(generators/view): fix ordered insert<commit_after>'use strict';

//
//  Yeoman bat:view sub-generator.
//

var generators      = require( 'yeoman-generator' )
,   yosay           = require( 'yosay' )
,   youtil          = require( './../../lib/youtil.js' )
,   chalk           = require( 'chalk' )
,   _               = require( 'lodash' )
;

var decapitalize    = require( 'underscore.string/decapitalize' );

var ViewGenerator = generators.Base.extend(
    {
        constructor: function ()
        {
            generators.Base.apply( this, arguments );

            this.argument(
                'viewName'
            ,   {
                    type:           String
                ,   required:       false
                ,   desc:           'The name of the view to create.'
                }
            );

            //  Also add 'viewName' as a - hidden - option, defaulting to the positional argument's value.
            //  This way `_promptsPruneByOptions()` can filter away prompting for the view name too.
            //
            this.option(
                'viewName'
            ,   {
                    type:           String
                ,   desc:           'The name of the view to create.'
                ,   default:        this.viewName
                ,   hide:           true
                }
            );

            //  Normal options.
            //
            this.option(
                'description'
            ,   {
                    type:           String
                ,   desc:           'The purpose of the view to create.'
                }
            );

            this.option(
                'sass'
            ,   {
                    type:           Boolean
                ,   desc:           'Specify whether this view should have a SASS file of its own.'
                }
            );
        }

    ,   description:
            chalk.bold(
                'This is the ' + chalk.cyan( 'backbone view' )
            +   ' generator for BAT, the Backbone Application Template'
            +   ' created by ' + chalk.blue( 'marv' ) + chalk.red( 'iq' ) + '.'
            )

    ,   initializing: function ()
        {
            this._assertBatApp();

            //  Container for template expansion data.
            //
            this.templateData = {};
        }

    ,   prompting:
        {
            askSomeQuestions: function ()
            {
                //  Ask only those question that have not yet been provided with answers via the command line.
                //
                var prompts = this._promptsPruneByOptions(
                        [
                            {
                                type:       'input'
                            ,   name:       'viewName'
                            ,   message:    'What is the name of this view you so desire?'
                            ,   default:    youtil.definedToString( this.options.viewName )
                            ,   validate:   youtil.isIdentifier
                            ,   filter: function ( value )
                                {
                                    return decapitalize( _.trim( value ).replace( /view$/i, '' ));
                                }
                            }
                        ,   {
                                type:       'input'
                            ,   name:       'description'
                            ,   message:    'What is the purpose (description) of this view?'
                            ,   validate:   youtil.isNonBlank
                            ,   filter:     youtil.sentencify
                            }
                        ,   {
                                type:       'confirm'
                            ,   name:       'sass'
                            ,   message:    'Would you like a SASS file for this view?'
                            ,   default:    true
                            ,   validate:   _.isBoolean
                            }
                        ]
                    )
                ;

                if ( prompts.length )
                {
                    //  Have Yeoman greet the user.
                    //
                    this.log( yosay( 'So you want a BAT view?' ) );

                    return (
                        this
                            .prompt( prompts )
                            .then( function ( answers ) { _.extend( this.templateData, answers ); }.bind( this ) )
                    );
                }
            }
        }

    ,   configuring: function ()
        {
            var data        = this.templateData
            ,   viewName    = data.viewName
            ;

            _.extend(
                data
            ,   {
                    className:          _.capitalize( viewName ) + 'View'
                ,   cssClassName:       _.kebabCase( viewName ) + '-view'
                ,   fileBase:           _.kebabCase( _.deburr( viewName ))

                ,   userName:           this.user.git.name()

                ,   backbone:           ( this.config.get( 'backbone' ) || { className: 'Backbone', modulePath: 'backbone' } )
                }
            );
        }

    ,   writing:
        {
            createView: function ()
            {
                var data        = this.templateData
                ,   templates   =
                    {
                        'view.hbs':     [ 'src/views/' + data.fileBase + '.hbs' ]
                    ,   'view.coffee':  [ 'src/views/' + data.fileBase + '.coffee' ]
                    }
                ;

                if ( data.sass )
                {
                    templates[ 'view.sass' ] = [ 'src/sass/views/_' + data.fileBase + '.sass' ];
                }

                this._templatesProcess( templates );
            }
        }

    ,   install: {

            updateViewsSass: function () {

                var data = this.templateData;

                /* jshint laxbreak: true */

                if ( !( data.sass )) { return; }

                //
                //  Add an `@import "views/_<fileBase>" statement to the '_views.sass' file.
                //

                var viewsPath   = 'src/sass/_views.sass'
                ,   fs          = this.fs
                ,   views       = fs.read( viewsPath )
                ,   statement   = '@import "views/_' + data.fileBase + '"'
                ;

                //  Look for a place to insert, preferably at an alfanumerically ordered position.
                //  Do nothing if an `@import` for this sass file seems to exist already.
                //
                var insertAt, indent, match, matcher = /^([ \t]*)(@import.*)/mg;

                while ( (( match = matcher.exec( views ) )) )
                {
                    if ( statement > match[ 2 ] )
                    {
                        //  Use indent of the (possibly) preceding line.
                        //
                        indent      = match[ 1 ];
                        continue;
                    }

                    if ( statement < match[ 2 ] )
                    {
                        insertAt    = match.index;
                        break;
                    }

                    this.log(
                        'It appears that "' + viewsPath + '" already contains an `@import` for "' + data.fileBase + '.sass".\n'
                    +   'Leaving it untouched.'
                    );

                    return;
                }

                //  Avoid the conflict warning and use force for the write
                //
                this.conflicter.force = true;

                if ( indent == null )
                {
                    //  First @import; use indent of the following line, if any.
                    //
                    indent = match ? match[ 1 ] : '';
                }

                if ( insertAt == null )
                {
                    //  Append at end of file; Take care of possibly missing trailing newline.
                    //
                    fs.write( viewsPath, views + (( views.length && views.slice( -1 ) !== '\n' ) ? '\n' : '' ) + indent + statement + '\n' );
                }
                else
                {
                    fs.write( viewsPath, views.slice( 0, insertAt ) + indent + statement + '\n' + views.slice( insertAt ) );
                }
            }
        }
    }
);

_.extend(
    ViewGenerator.prototype
,   require( './../../lib/generator.js' )
,   require( './../../lib/sub-generator.js' )
);

module.exports = ViewGenerator;
<|endoftext|>


<commit_before>;(function ($, window) {
    'use strict';

    /**
     * Maps key codes to specific key names.
     *
     * @type {Object}
     **/
    var keyMap = {
        'UP': 38,
        'DOWN': 40,
        'ENTER': 13
    };

    /**
     * Shopware Live Search Plugin.
     *
     * The plugin fires the ajax search request, render the results inside the modal
     * and controlling the keyboard navigation inside the search results.
     *
     * @example
     *  <input type="search" data-live-search="true">
     */
    $.plugin('liveSearch', {

        /**
         * Plugin default configuration
         *
         * @type {Object}
         */
        defaults: {
            /**
             * Minimum amount of characters needed to trigger the search request
             *
             * @type {Number}
             */
            minLength: 3,

            /**
             * Time in milliseconds to wait after each key down event before
             * before starting the search request.
             * If a key was pressed in this time, the last request will be aborted.
             *
             * @type {Number}
             */
            searchDelay: 250,

            /**
             * Class that will be used to determine if the result list or a result item is active.
             *
             * @type {String}
             */
            activeCls: 'js--is-active',

            /**
             * Selector for the search result list.
             *
             * @type {String}
             */
            resultsSelector: '.main-search--results',

            /**
             * Selector for the ajax loading indicator.
             *
             * @type {String}
             */
            loadingIndicatorSelector: '.form--ajax-loader',

            /**
             * Selector for a single result entry.
             *
             * @type {String}
             */
            resultItemSelector: '.result--item',

            /**
             * Selector for the main search form.
             * Has to be the parent of the plugin element.
             *
             * @type {String}
             */
            formSelector: '.main-search--form',

            /**
             * Selector for the link in a result entry.
             *
             * @type {String}
             */
            resultLinkSelector: '.search-result--link',

            /**
             * The URL used for the search request.
             * This option has to be set or an error will be thrown.
             *
             * @type {String}
             */
            requestUrl: '',

            /**
             * Flag whether or not the keyboard navigation is enabled
             *
             * @type {Boolean}
             */
            keyBoardNavigation: true,

            /**
             * The speed of all animations.
             *
             * @type {String|Number}
             */
            animationSpeed: 'fast'
        },

        /**
         * Initializes the plugin and registers all needed events.
         */
        init: function () {
            var me = this,
                opts = me.opts,
                $el = me.$el;

            me.applyDataAttributes();

            me.requestURL = opts.requestUrl || $.controller.ajax_search;

            if (!me.requestURL) {
                throw new Error('Parameter "requestUrl" needs to be set.');
            }

            me.$parent = $el.parent(opts.formSelector);
            me.$results = me.$parent.next(opts.resultsSelector).hide();
            me.$loader = me.$parent.find(opts.loadingIndicatorSelector);
            me.lastSearchTerm = '';

            me._on($el, 'keyup', $.proxy(me.onKeyUp, me));
            me._on($el, 'keydown', $.proxy(me.onKeyDown, me));
            me._on($el, 'blur', $.proxy(me.onBlur, me));
        },

        /**
         * Will be called when search field lost its focus.
         *
         * @param {jQuery.Event} event
         */
        onBlur: function (event) {
            var me = this;

            if ($.contains(me.$results[0], (event.target || event.currentTarget))) {
                return;
            }

            me.closeResult();
        },

        /**
         * Will be called when a key was released on the search field.
         */
        onKeyUp: function () {
            var me = this,
                term = me.$el.val() + '',
                timeout = me._keyupTimeout;

            if (timeout) {
                window.clearTimeout(timeout);
            }

            if (term.length < ~~(me.opts.minLength)) {
                me.lastSearchTerm = '';
                me.closeResult();
                return;
            }

            if (term === me.lastSearchTerm) {
                return;
            }

            me._keyupTimeout = window.setTimeout($.proxy(me.triggerSearchRequest, me, term), me.opts.searchDelay);
        },

        /**
         * Event handler method which will be fired when the user presses a key when
         * focusing the field.
         *
         * @param {jQuery.Event} event
         */
        onKeyDown: function (event) {
            var me = this,
                opts = me.opts,
                keyCode = event.which,
                navKeyPressed = opts.keyBoardNavigation && (keyCode === keyMap.UP || keyCode === keyMap.DOWN || keyCode === keyMap.ENTER);

            if (navKeyPressed && me.$results.hasClass(opts.activeCls)) {
                me.onKeyboardNavigation(keyCode);
                event.preventDefault();
                return false;
            }

            return true;
        },

        /**
         * Triggers an AJAX request with the given search term.
         *
         * @param {String} searchTerm
         */
        triggerSearchRequest: function (searchTerm) {
            var me = this;

            me.$loader.fadeIn(me.opts.animationSpeed);

            me.lastSearchTerm = $.trim(searchTerm);

            $.ajax({
                'url': me.requestURL,
                'data': {
                    'sSearch': me.lastSearchTerm
                },
                'success': $.proxy(me.showResult, me)
            });
        },

        /**
         * Clears the result list and appends the given (AJAX) response to it.
         *
         * @param {String} response
         */
        showResult: function (response) {
            var me = this,
                opts = me.opts;

            me.$loader.fadeOut(opts.animationSpeed);
            me.$results.empty().html(response).slideDown().addClass(opts.activeCls);
        },

        /**
         * Closes the result list and removes all its items.
         */
        closeResult: function () {
            var me = this,
                opts = me.opts,
                $results = me.$results;

            $results.removeClass(opts.activeCls).fadeOut(opts.animationSpeed, $results.empty.bind($results));
        },

        /**
         * Adds support to navigate using the keyboard.
         *
         * @param {Number} keyCode
         */
        onKeyboardNavigation: function (keyCode) {
            var me = this,
                opts = me.opts,
                $results = me.$results,
                activeClass = opts.activeCls,
                $selected = $results.find('.' + activeClass),
                $resultItems,
                $nextSibling,
                firstLast;

            if (keyCode === keyMap.UP || keyCode === keyMap.DOWN) {
                $resultItems = $results.find(opts.resultItemSelector);
                firstLast = (keyCode === keyMap.DOWN) ? 'first' : 'last';

                if (!$selected.length) {
                    $resultItems[firstLast]().addClass(activeClass);
                    return;
                }

                $resultItems.removeClass(activeClass);

                $nextSibling = $selected[(keyCode === keyMap.DOWN) ? 'next' : 'prev']();

                if ($nextSibling.length) {
                    $nextSibling.addClass(activeClass);
                    return;
                }

                $selected.siblings()[firstLast]().addClass(activeClass);
            }

            if (keyCode === keyMap.ENTER) {
                if ($selected.length) {
                    window.location.href = $selected.find(opts.resultLinkSelector).attr('href');
                    return;
                }

                me.$parent.submit();
            }
        },

        /**
         * Destroys the plugin.
         */
        destroy: function () {
            this._destroy();
        }
    });
})(jQuery, window);<commit_msg>PT-2339: added missing events to the liveSearch plugin. Needed for SwagFuzzy<commit_after>;(function ($, window) {
    'use strict';

    /**
     * Maps key codes to specific key names.
     *
     * @type {Object}
     **/
    var keyMap = {
        'UP': 38,
        'DOWN': 40,
        'ENTER': 13
    };

    /**
     * Shopware Live Search Plugin.
     *
     * The plugin fires the ajax search request, render the results inside the modal
     * and controlling the keyboard navigation inside the search results.
     *
     * @example
     *  <input type="search" data-live-search="true">
     */
    $.plugin('liveSearch', {

        /**
         * Plugin default configuration
         *
         * @type {Object}
         */
        defaults: {
            /**
             * Minimum amount of characters needed to trigger the search request
             *
             * @type {Number}
             */
            minLength: 3,

            /**
             * Time in milliseconds to wait after each key down event before
             * before starting the search request.
             * If a key was pressed in this time, the last request will be aborted.
             *
             * @type {Number}
             */
            searchDelay: 250,

            /**
             * Class that will be used to determine if the result list or a result item is active.
             *
             * @type {String}
             */
            activeCls: 'js--is-active',

            /**
             * Selector for the search result list.
             *
             * @type {String}
             */
            resultsSelector: '.main-search--results',

            /**
             * Selector for the ajax loading indicator.
             *
             * @type {String}
             */
            loadingIndicatorSelector: '.form--ajax-loader',

            /**
             * Selector for a single result entry.
             *
             * @type {String}
             */
            resultItemSelector: '.result--item',

            /**
             * Selector for the main search form.
             * Has to be the parent of the plugin element.
             *
             * @type {String}
             */
            formSelector: '.main-search--form',

            /**
             * Selector for the link in a result entry.
             *
             * @type {String}
             */
            resultLinkSelector: '.search-result--link',

            /**
             * The URL used for the search request.
             * This option has to be set or an error will be thrown.
             *
             * @type {String}
             */
            requestUrl: '',

            /**
             * Flag whether or not the keyboard navigation is enabled
             *
             * @type {Boolean}
             */
            keyBoardNavigation: true,

            /**
             * The speed of all animations.
             *
             * @type {String|Number}
             */
            animationSpeed: 'fast'
        },

        /**
         * Initializes the plugin and registers all needed events.
         */
        init: function () {
            var me = this,
                opts = me.opts,
                $el = me.$el;

            me.applyDataAttributes();

            me.requestURL = opts.requestUrl || $.controller.ajax_search;

            if (!me.requestURL) {
                throw new Error('Parameter "requestUrl" needs to be set.');
            }

            me.$parent = $el.parent(opts.formSelector);
            me.$results = me.$parent.next(opts.resultsSelector).hide();
            me.$loader = me.$parent.find(opts.loadingIndicatorSelector);
            me.lastSearchTerm = '';

            me._on($el, 'keyup', $.proxy(me.onKeyUp, me));
            me._on($el, 'keydown', $.proxy(me.onKeyDown, me));
            me._on($el, 'blur', $.proxy(me.onBlur, me));
        },

        /**
         * Will be called when search field lost its focus.
         *
         * @param {jQuery.Event} event
         */
        onBlur: function (event) {
            var me = this;

            if ($.contains(me.$results[0], (event.target || event.currentTarget))) {
                return;
            }

            me.closeResult();
        },

        /**
         * Will be called when a key was released on the search field.
         */
        onKeyUp: function () {
            var me = this,
                term = me.$el.val() + '',
                timeout = me._keyupTimeout;

            if (timeout) {
                window.clearTimeout(timeout);
            }

            if (term.length < ~~(me.opts.minLength)) {
                me.lastSearchTerm = '';
                me.closeResult();
                return;
            }

            if (term === me.lastSearchTerm) {
                return;
            }

            me._keyupTimeout = window.setTimeout($.proxy(me.triggerSearchRequest, me, term), me.opts.searchDelay);
        },

        /**
         * Event handler method which will be fired when the user presses a key when
         * focusing the field.
         *
         * @param {jQuery.Event} event
         */
        onKeyDown: function (event) {
            var me = this,
                opts = me.opts,
                keyCode = event.which,
                navKeyPressed = opts.keyBoardNavigation && (keyCode === keyMap.UP || keyCode === keyMap.DOWN || keyCode === keyMap.ENTER);

            if (navKeyPressed && me.$results.hasClass(opts.activeCls)) {
                me.onKeyboardNavigation(keyCode);
                event.preventDefault();
                return false;
            }

            return true;
        },

        /**
         * Triggers an AJAX request with the given search term.
         *
         * @param {String} searchTerm
         */
        triggerSearchRequest: function (searchTerm) {
            var me = this;

            me.$loader.fadeIn(me.opts.animationSpeed);

            me.lastSearchTerm = $.trim(searchTerm);

            $.ajax({
                'url': me.requestURL,
                'data': {
                    'sSearch': me.lastSearchTerm
                },
                'success': function (response) {
                    me.showResult(response);
                    $.publish('plugin/liveSearch/onResponseSearchRequest', [ me, searchTerm ]);
                }
            });
        },

        /**
         * Clears the result list and appends the given (AJAX) response to it.
         *
         * @param {String} response
         */
        showResult: function (response) {
            var me = this,
                opts = me.opts;

            me.$loader.fadeOut(opts.animationSpeed);
            me.$results.empty().html(response).slideDown().addClass(opts.activeCls);
            $.publish('plugin/liveSearch/showResult');
        },

        /**
         * Closes the result list and removes all its items.
         */
        closeResult: function () {
            var me = this,
                opts = me.opts,
                $results = me.$results;

            $results.removeClass(opts.activeCls).fadeOut(opts.animationSpeed, $results.empty.bind($results));
            $.publish('plugin/liveSearch/closeResult');
        },

        /**
         * Adds support to navigate using the keyboard.
         *
         * @param {Number} keyCode
         */
        onKeyboardNavigation: function (keyCode) {
            var me = this,
                opts = me.opts,
                $results = me.$results,
                activeClass = opts.activeCls,
                $selected = $results.find('.' + activeClass),
                $resultItems,
                $nextSibling,
                firstLast;

            if (keyCode === keyMap.UP || keyCode === keyMap.DOWN) {
                $resultItems = $results.find(opts.resultItemSelector);
                firstLast = (keyCode === keyMap.DOWN) ? 'first' : 'last';

                if (!$selected.length) {
                    $resultItems[firstLast]().addClass(activeClass);
                    return;
                }

                $resultItems.removeClass(activeClass);

                $nextSibling = $selected[(keyCode === keyMap.DOWN) ? 'next' : 'prev']();

                if ($nextSibling.length) {
                    $nextSibling.addClass(activeClass);
                    return;
                }

                $selected.siblings()[firstLast]().addClass(activeClass);
            }

            if (keyCode === keyMap.ENTER) {
                if ($selected.length) {
                    window.location.href = $selected.find(opts.resultLinkSelector).attr('href');
                    return;
                }

                me.$parent.submit();
            }
        },

        /**
         * Destroys the plugin.
         */
        destroy: function () {
            this._destroy();
        }
    });
})(jQuery, window);<|endoftext|>


<commit_before>// Require Couchbase Module
var couchbase = require('couchbase');

// Setup Cluster Connection Object
var cluster = new couchbase.Cluster('couchbase://127.0.0.1');

// Setup Bucket object to be reused within the code
var bucket = cluster.openBucket('travel-sample');

// Setup Query
var N1qlQuery = couchbase.N1qlQuery;

// Make a N1QL specific Query, telling Couchbase this will be a prepared statement
var query = N1qlQuery.fromString("SELECT airportname, city, country FROM `travel-sample` " +
    "WHERE type=$1 AND city=$2").adhoc(false);

// Issue Query with parameters passed in array, running as a prepared statement
bucket.query(query,["airport","London"],function(err,result){
    if (err) throw err;

    // Print Results
    console.log("Result:",result);

    // Try a different query, using prepared
    bucket.query(query,["airport","Reno"],function(err,result){
        if(err) throw err;

        // Print Results
        console.log("Result:",result);
        console.log('Example Successful - Exiting');
        process.exit(0);
    });
});
<commit_msg>Added Timing for Prepared Example<commit_after>// Require Couchbase Module
var couchbase = require('couchbase');

// Setup Cluster Connection Object
var cluster = new couchbase.Cluster('couchbase://127.0.0.1');

// Setup Bucket object to be reused within the code
var bucket = cluster.openBucket('travel-sample');

// Setup Query
var N1qlQuery = couchbase.N1qlQuery;

// Make a N1QL specific Query, telling Couchbase this will be a prepared statement
var query = N1qlQuery.fromString("SELECT airportname, city, country FROM `travel-sample` " +
    "WHERE type=$1 AND city=$2").adhoc(false);

// Timing Variables to compare execution times
var t1,t2,t3,t4;

// QUERY 1 - PREPARE AND EXECUTE
// Issue Query with parameters passed in array, running as a prepared statement
bucket.query(query,["airport","London"],function(err,result,meta){
    if (err) throw err;

    // Print Results
    console.log("Result:",result);
    console.log("Time Query1:",meta.metrics.elapsedTime);
    t1=meta.metrics.elapsedTime;

    // QUERY 2 - EXECUTE THE IDENTICAL QUERY.
    // Try a the same query, again.  It should have a shorter elapsed time.
    bucket.query(query,["airport","London"],function(err,result,meta){
        if(err) throw err;

        // Print Results
        console.log("Result:",result);
        console.log("Time Query 2:",meta.metrics.elapsedTime);
        t2=meta.metrics.elapsedTime;

        // QUERY 3 - EXECUTE THE PLAN
        // Try the same query, with different parameters.  It should also be fast.
        bucket.query(query,["airport","Seattle"],function(err,result,meta) {
            if (err) throw err;

            // Print Results
            console.log("Result:", result);
            console.log("Time Query 3:", meta.metrics.elapsedTime);
            t3=meta.metrics.elapsedTime;

            // QUERY 4 - EXECUTE THE ORIGINAL.
            // Try the original query, again.
            bucket.query(query,["airport","London"],function(err,result,meta) {
                if (err) throw err;

                // Print Results
                console.log("Result:", result);
                console.log("Time Query 2:", meta.metrics.elapsedTime);
                t4 = meta.metrics.elapsedTime;

                console.log("=====");
                console.log("Query 1 - prepare, execute    :", t1);
                console.log("Query 2 - execute, same params:", t2);
                console.log("Query 3 - execute, new params :", t3);
                console.log("Query 4 - execute, og params  :", t4);
                console.log("=====");
                console.log('Example Successful - Exiting');
                process.exit(0);
            });
        });
    });
});
<|endoftext|>


<commit_before>module.exports = {
	process: async message => {
		if(message.args[0]) {
			let command = Object.keys(bot.commands)
				.map(key => bot.commands[key])
				.find(cmd => message.args[0] === cmd.name || ~cmd.aliases.indexOf(message.args[0]));
			if(!command) return __("commands.default.help.commandNotFound", message);

			let helpMsg = `__**Command Name**__: ${command.name}\n`;
			helpMsg += `Category: ${command.type}\n`;
			helpMsg += `Usage: ${command.usage}\n`;
			helpMsg += `Aliases: ${command.aliases.length ? command.aliases.join(", ") : "None"}\n`;
			helpMsg += `Description: ${command.description || "None provided"}\n`;
			if(command.perm) helpMsg += `Required Permission: ${command.perm}\n`;
			else if(command.guildOnly) helpMsg += `This command will only work in guilds\n`;
			helpMsg += `Uses: ${command.uses}`;

			return __("commands.default.help.commandInfo", message, {
				command: command.name,
				category: command.type,
				usage: command.usage,
				aliases: command.aliases.length ? command.aliases.join(", ") : __("words.none", message, {}, true),
				description: command.description || __("phrases.noneProvided", message),
				perm: command.perm || __("phrases.noneRequired", message)
			});
		} else {
			let disabled = await r.table("editedCommands")
				.getAll(message.guild.channel.id, { index: "guildID" })
				.filter({ enabled: false }).getField("command").run();

			let commandMsg = "", commandTypes = {};
			for(let cmd in bot.commands) {
				cmd = bot.commands[cmd];
				if(cmd.type === "creator") continue;
				else if(~disabled.indexOf(cmd.name)) continue;
				else if(!commandTypes[cmd.type]) commandTypes[cmd.type] = [];
				commandTypes[cmd.type].push(cmd.name);
				commandTypes[cmd.type].concat(cmd.aliases);
			}

			for(let category in commandTypes) {
				commandTypes[category].sort();
				commandMsg += `\n__${category.charAt(0).toUpperCase() + category.substring(1)}__\n`;
				commandMsg += commandTypes[category].join(", ");
				commandMsg += `\n`;
			}

			return __("commands.default.help.commandList", message, {
				count: Object.keys(bot.commands).length,
				commands: commandMsg
			});
		}
	},
	description: "List commands, or get info on one",
	args: [{
		type: "text",
		label: "command",
		optional: true
	}]
};
<commit_msg>fix help<commit_after>module.exports = {
	process: async message => {
		if(message.args[0]) {
			let command = Object.keys(bot.commands)
				.map(key => bot.commands[key])
				.find(cmd => message.args[0] === cmd.name || ~cmd.aliases.indexOf(message.args[0]));
			if(!command) return __("commands.default.help.commandNotFound", message);

			let helpMsg = `__**Command Name**__: ${command.name}\n`;
			helpMsg += `Category: ${command.type}\n`;
			helpMsg += `Usage: ${command.usage}\n`;
			helpMsg += `Aliases: ${command.aliases.length ? command.aliases.join(", ") : "None"}\n`;
			helpMsg += `Description: ${command.description || "None provided"}\n`;
			if(command.perm) helpMsg += `Required Permission: ${command.perm}\n`;
			else if(command.guildOnly) helpMsg += `This command will only work in guilds\n`;
			helpMsg += `Uses: ${command.uses}`;

			return __("commands.default.help.commandInfo", message, {
				command: command.name,
				category: command.type,
				usage: command.usage,
				aliases: command.aliases.length ? command.aliases.join(", ") : __("words.none", message, {}, true),
				description: command.description || __("phrases.noneProvided", message),
				perm: command.perm || __("phrases.noneRequired", message)
			});
		} else {
			let disabled;
			if(message.channel.guild) {
				disabled = await r.table("editedCommands")
					.getAll(message.channel.guild.id, { index: "guildID" })
					.filter({ enabled: false }).getField("command").run();
			} else {
				disabled = [];
			}

			let commandMsg = "", commandTypes = {};
			for(let cmd in bot.commands) {
				cmd = bot.commands[cmd];
				if(cmd.type === "creator") continue;
				else if(~disabled.indexOf(cmd.name)) continue;
				else if(!commandTypes[cmd.type]) commandTypes[cmd.type] = [];
				commandTypes[cmd.type].push(cmd.name);
				commandTypes[cmd.type].concat(cmd.aliases);
			}

			for(let category in commandTypes) {
				commandTypes[category].sort();
				commandMsg += `\n__${category.charAt(0).toUpperCase() + category.substring(1)}__\n`;
				commandMsg += commandTypes[category].join(", ");
				commandMsg += `\n`;
			}

			return __("commands.default.help.commandList", message, {
				count: Object.keys(bot.commands).length,
				commands: commandMsg
			});
		}
	},
	description: "List commands, or get info on one",
	args: [{
		type: "text",
		label: "command",
		optional: true
	}]
};
<|endoftext|>


<commit_before>const createTag = require('create-tag');
const assetsUtil = require('./util/util');

const rAbs = /^(\w+:)?\//;
const rSlash = /^\//;
const rSlashEnd = /\/$/;

class Helper {
  static startup(app) {
    const settings = app.settings;
    const config = settings.assets || {};

    const prefix = config.prefix || '/g';
    const urlPrefix = settings.development ? prefix :
      (config.urlPrefix || prefix);

    this.urlPrefix = urlPrefix.replace(rSlashEnd, '');
    this.manifest = assetsUtil.loadManifest(settings);
  }

  constructor(rd) {
    this.assets = rd.assets;
    this.viewType = rd.route.type;
    this.urlPrefix = Helper.urlPrefix;
    this.manifest = Helper.manifest;
  }

  url(url) {
    if (rAbs.test(url)) {
      return url;
    }
    url = url.replace(rSlash, '');
    if (this.manifest) {
      url = this.manifest.get(url) || url;
    }
    return this.urlPrefix + '/' + url;
  }

  css(url, group) {
    push(this, 'css', url, group);
  }

  js(url, group) {
    push(this, 'js', url, group);
  }

  cssTag(group, opts) {
    const urls = getUrls(this, group, 'css');
    return urls.map(url => {
      const attrs = Object.assign({
        rel: 'stylesheet',
        href: url
      }, opts);
      return createTag('link', attrs);
    }).join('\n');
  }

  jsTag(group, opts) {
    const urls = getUrls(this, group, 'js');
    return urls.map(url => {
      const attrs = Object.assign({ src: url }, opts);
      return createTag('script', attrs, '');
    }).join('\n');
  }
}

module.exports = Helper;

function push(self, type, url, group) {
  if (!group) {
    group = self.viewType === 'layout' ? 'layout' : 'default';
  }
  url = self.url(url);
  const bag = self.assets[group] ||
      (self.assets[group] = { css: [], js: [] });
  const list = bag[type];
  list.push({ url });
}

function getUrls(self, groups, type) {
  groups = groups || ['layout', 'default'];
  if (!Array.isArray(groups)) {
    groups = [groups];
  }

  return groups.reduce((acc, group) => {
    const list = (self.assets[group] || {})[type];
    return list ? acc.concat(list) : acc;
  }, []).map(item => item.url);
}
<commit_msg>fix: 修复manifest返回绝对地址时链接错误<commit_after>const createTag = require('create-tag');
const assetsUtil = require('./util/util');

const rAbs = /^(\w+:)?\/\//;
const rSlash = /^\//;
const rSlashEnd = /\/$/;

class Helper {
  static startup(app) {
    const settings = app.settings;
    const config = settings.assets || {};

    const prefix = config.prefix || '/g';
    const urlPrefix = settings.development ? prefix :
      (config.urlPrefix || prefix);

    this.urlPrefix = urlPrefix.replace(rSlashEnd, '');
    this.manifest = assetsUtil.loadManifest(settings);
  }

  constructor(rd) {
    this.assets = rd.assets;
    this.viewType = rd.route.type;
    this.urlPrefix = Helper.urlPrefix;
    this.manifest = Helper.manifest;
  }

  url(url) {
    if (rAbs.test(url)) {
      return url;
    }
    url = url.replace(rSlash, '');
    if (this.manifest) {
      url = this.manifest.get(url) || url;
    }
    return rAbs.test(url) ? url : this.urlPrefix + '/' + url;
  }

  css(url, group) {
    push(this, 'css', url, group);
  }

  js(url, group) {
    push(this, 'js', url, group);
  }

  cssTag(group, opts) {
    const urls = getUrls(this, group, 'css');
    return urls.map(url => {
      const attrs = Object.assign({
        rel: 'stylesheet',
        href: url
      }, opts);
      return createTag('link', attrs);
    }).join('\n');
  }

  jsTag(group, opts) {
    const urls = getUrls(this, group, 'js');
    return urls.map(url => {
      const attrs = Object.assign({ src: url }, opts);
      return createTag('script', attrs, '');
    }).join('\n');
  }
}

module.exports = Helper;

function push(self, type, url, group) {
  if (!group) {
    group = self.viewType === 'layout' ? 'layout' : 'default';
  }
  url = self.url(url);
  const bag = self.assets[group] ||
      (self.assets[group] = { css: [], js: [] });
  const list = bag[type];
  list.push({ url });
}

function getUrls(self, groups, type) {
  groups = groups || ['layout', 'default'];
  if (!Array.isArray(groups)) {
    groups = [groups];
  }

  return groups.reduce((acc, group) => {
    const list = (self.assets[group] || {})[type];
    return list ? acc.concat(list) : acc;
  }, []).map(item => item.url);
}
<|endoftext|>


<commit_before>define(['react', 'underscore', 'components/page_header',
'components/common/time', 'singletons/providers', 'collections/instances',
'controllers/volumes'], function(React, _, PageHeader, Time, providers,
Instances, VolumeController) {

    var VolumeInfo = React.createClass({
        render: function() {
            var volume = this.props.volume;
            var provider = providers.get(volume.get('identity').provider);
            var name = "(Unnamed Volume)";
            if (volume.get('name') !== undefined)
                name = volume.get('name');

            var items = [
                ["Name", name],
                ["ID", volume.id],
                ["Provider", provider.get('name')],
                ["Date Created", Time({date: volume.get('start_date')})]
            ];

            var result = React.DOM.div({}, React.DOM.h2({}, "Details"), React.DOM.dl({}, _.map(items, function(item) {
                return [
                    React.DOM.dt({}, item[0]),
                    React.DOM.dd({}, item[1])
                ];
            })));
            return result;
        }
    });

    var AttachmentForm = React.createClass({
        getInitialState: function() {
            return {
                instance: this.props.instances ? this.props.instances.at(0) : null
            };
        },
        componentWillReceiveProps: function(newProps) {
            var instances = newProps.instances;
            if (instances && instances.length)
                this.setState({instance: instances.at(0)});
        },
        handleSubmit: function(e) {
            e.preventDefault();
            var volume = this.props.volume;
            VolumeController
                .attach(this.props.volume, this.state.instance);
        },
        handleChange: function(e) {
            var instance = this.props.instances.get(e.target.value);
            this.setState({instance: instance});
        },
        getInstanceSelect: function() {
            var options = [];
            if (this.props.instances)
                options = this.props.instances.map(function(instance) {
                    return React.DOM.option({value: instance.id}, instance.get('name_or_id'));
                });
            var attaching = this.props.volume.get('status') == 'attaching';
            return React.DOM.select({
                className: 'form-control',
                disabled: attaching,
                onChange: this.handleChange,
                value: this.state.instance ? this.state.instance.id : null
            }, options);
        },
        getAttachButton: function() {
            var attaching = this.props.volume.get('status') == 'attaching';
            var attrs = {className: 'btn btn-primary btn-block'};
            if (attaching || !this.state.instance) {
                attrs.className += ' disabled';
                attrs.disabled = 'disabled';
            }
            return React.DOM.button(attrs, attaching ? "Attaching..." : "Attach");
        },
        render: function() {
            return React.DOM.form({onSubmit: this.handleSubmit},
                React.DOM.div({className: 'container-fluid'},
                    React.DOM.div({className: 'row'},
                        React.DOM.div({className: 'col-xs-9'}, this.getInstanceSelect()),
                        React.DOM.div({className: 'col-xs-3'}, this.getAttachButton()))));
        }
    });

    var DestroyForm = React.createClass({
        handleClick: function(e) {
            e.preventDefault();
            console.log("destroy");
            VolumeController.destroy(this.props.volume);
        },
        render: function() {
            return React.DOM.button({
                className: 'btn btn-default',
                onClick: this.handleClick
            }, "Destroy Volume");
        }
    });

    var DetachmentForm = React.createClass({
        handleSubmit: function(e) {
            e.preventDefault();
            VolumeController.detach(this.props.volume);
        },
        render: function() {
            var detaching = this.props.volume.get('status') === 'detaching';

            var buttonAttrs = {className: 'btn btn-primary'};
            if (detaching) {
                buttonAttrs.className += ' disabled';
                buttonAttrs.disabled = true;
            }

            return React.DOM.form({onSubmit: this.handleSubmit},
                React.DOM.label({htmlFor: 'attached_instance'}),
                React.DOM.button(buttonAttrs, detaching ? "Detaching..." : "Detach"));
        }
    });

    var AttachmentInfo = React.createClass({
        render: function() {
            var volume = this.props.volume;
            var content = [];
            var state = volume.get('status');
            var available = state == 'available' || state == 'attaching';
            var attached = state == 'in-use' || state == 'detaching';

            if (available) {
                content = [
                    React.DOM.p({key: 'statusText'}, "Available"),
                    React.DOM.p({key: 'attachment'},
                        AttachmentForm({volume: this.props.volume, instances: this.props.instances})),
                    React.DOM.p({key: 'destroy'},
                        DestroyForm({volume: this.props.volume}))
                ];
            } else if (attached) {
                content = [
                    React.DOM.p({key: 'statusText'}, "Attached"),
                    DetachmentForm({key: 'detachment', volume: this.props.volume})
                ];
            }

            return React.DOM.div({},
                React.DOM.h2({}, "Status"),
                content);
        }
    });

    var VolumeDetailPage = React.createClass({
        helpText: function() {
            var p1 = React.DOM.p({}, "A volume is available when it is not attached to an instance. Any newly created volume must be formatted and then mounted after it has been attached before you will be able to use it.");
            var links = [
                ["Creating a Volume", "https://pods.iplantcollaborative.org/wiki/x/UyWO"],
                ["Attaching a Volume to an Instance", "https://pods.iplantcollaborative.org/wiki/x/OKxm#AttachingaVolumetoanInstance-Attachingavolumetoaninstance"],
                ["Formatting a Volume", "https://pods.iplantcollaborative.org/wiki/x/OKxm#AttachingaVolumetoanInstance-Createthefilesystem%28onetimeeventpervolume%29"],
                ["Mounting a Volume", "https://pods.iplantcollaborative.org/wiki/x/OKxm#AttachingaVolumetoanInstance-Mountthefilesystemonthepartition"],
                ["Unmounting and Detaching Volume", "https://pods.iplantcollaborative.org/wiki/x/OKxm#AttachingaVolumetoanInstance-Detachingvolumesfrominstances"]
            ];
            var link_list = React.DOM.ul({}, _.map(links, function(item) {
                return React.DOM.li({}, React.DOM.a({href: item[1]}, item[0]));
            }));
            var p2 = React.DOM.p({}, "More information about volumes:", link_list);
            return React.DOM.div({}, p1, p2);
        },
        render: function() {
            var volume = this.props.volume;
            var instances = this.props.instances;
            return React.DOM.div({},
                PageHeader({title: "Volume: " + volume.get('name_or_id'), helpText: this.helpText}),
                VolumeInfo({volume: volume}),
                AttachmentInfo({volume: volume, instances: instances}));
        }
    });

    var VolumeDetail = React.createClass({
        getInitialState: function() {
            return {
                instances: null,
                volume: this.props.volume
            };
        },
        setVolume: function(volume) {
            this.setState({volume: volume});
        },
        setInstances: function(instances) {
            if (this.isMounted())
                this.setState({instances: instances});
        },
        componentDidMount: function() {
            var provider_id = this.props.volume.get('identity').provider;
            var identity_id = this.props.volume.get('identity').id;
            var instances = new Instances([], {provider_id: provider_id, identity_id: identity_id});
            instances.on('sync', this.setInstances);
            instances.fetch();

            this.state.volume.on('change', this.setVolume);
        },
        componentWillUnmount: function() {
            if (this.state.instances)
                this.state.instances.off('sync', this.setInstances);

            this.state.volume.off('change', this.setVolume);
        },
        render: function() {
            return VolumeDetailPage({
                volume: this.state.volume,
                instances: this.state.instances
            });
        }
    });

    return VolumeDetail;
});
<commit_msg>Add attachment data to in use volumes<commit_after>define(['react', 'underscore', 'components/page_header',
'components/common/time', 'singletons/providers', 'collections/instances',
'controllers/volumes'], function(React, _, PageHeader, Time, providers,
Instances, VolumeController) {

    var VolumeInfo = React.createClass({
        render: function() {
            var volume = this.props.volume;
            var provider = providers.get(volume.get('identity').provider);
            var name = "(Unnamed Volume)";
            if (volume.get('name') !== undefined)
                name = volume.get('name');

            var items = [
                ["Name", name],
                ["ID", volume.id],
                ["Provider", provider.get('name')],
                ["Date Created", Time({date: volume.get('start_date')})]
            ];

            var result = React.DOM.div({}, React.DOM.h2({}, "Details"), React.DOM.dl({}, _.map(items, function(item) {
                return [
                    React.DOM.dt({}, item[0]),
                    React.DOM.dd({}, item[1])
                ];
            })));
            return result;
        }
    });

    var AttachmentForm = React.createClass({
        getInitialState: function() {
            return {
                instance: this.props.instances ? this.props.instances.at(0) : null
            };
        },
        componentWillReceiveProps: function(newProps) {
            var instances = newProps.instances;
            if (instances && instances.length)
                this.setState({instance: instances.at(0)});
        },
        handleSubmit: function(e) {
            e.preventDefault();
            var volume = this.props.volume;
            VolumeController
                .attach(this.props.volume, this.state.instance);
        },
        handleChange: function(e) {
            var instance = this.props.instances.get(e.target.value);
            this.setState({instance: instance});
        },
        getInstanceSelect: function() {
            var options = [];
            if (this.props.instances)
                options = this.props.instances.map(function(instance) {
                    return React.DOM.option({value: instance.id}, instance.get('name_or_id'));
                });
            var attaching = this.props.volume.get('status') == 'attaching';
            return React.DOM.select({
                className: 'form-control',
                disabled: attaching,
                onChange: this.handleChange,
                value: this.state.instance ? this.state.instance.id : null
            }, options);
        },
        getAttachButton: function() {
            var attaching = this.props.volume.get('status') == 'attaching';
            var attrs = {className: 'btn btn-primary btn-block'};
            if (attaching || !this.state.instance) {
                attrs.className += ' disabled';
                attrs.disabled = 'disabled';
            }
            return React.DOM.button(attrs, attaching ? "Attaching..." : "Attach");
        },
        render: function() {
            return React.DOM.form({onSubmit: this.handleSubmit},
                React.DOM.div({className: 'container-fluid'},
                    React.DOM.div({className: 'row'},
                        React.DOM.div({className: 'col-xs-9'}, this.getInstanceSelect()),
                        React.DOM.div({className: 'col-xs-3'}, this.getAttachButton()))));
        }
    });

    var DestroyForm = React.createClass({
        handleClick: function(e) {
            e.preventDefault();
            console.log("destroy");
            VolumeController.destroy(this.props.volume);
        },
        render: function() {
            return React.DOM.button({
                className: 'btn btn-default',
                onClick: this.handleClick
            }, "Destroy Volume");
        }
    });

    var DetachmentForm = React.createClass({
        handleSubmit: function(e) {
            e.preventDefault();
            VolumeController.detach(this.props.volume);
        },
        render: function() {
            var detaching = this.props.volume.get('status') === 'detaching';

            var buttonAttrs = {className: 'btn btn-primary'};
            if (detaching) {
                buttonAttrs.className += ' disabled';
                buttonAttrs.disabled = true;
            }

            return React.DOM.form({onSubmit: this.handleSubmit},
                React.DOM.label({htmlFor: 'attached_instance'}),
                React.DOM.button(buttonAttrs, detaching ? "Detaching..." : "Detach"));
        }
    });

    var AttachmentInfo = React.createClass({
        render: function() {
            var volume = this.props.volume;
            var content = [];
            var state = volume.get('status');
            var available = state == 'available' || state == 'attaching';
            var attached = state == 'in-use' || state == 'detaching';

            if (available) {
                content = [
                    React.DOM.p({key: 'statusText'}, "Available"),
                    React.DOM.p({key: 'attachment'},
                        AttachmentForm({volume: this.props.volume, instances: this.props.instances})),
                    React.DOM.p({key: 'destroy'},
                        DestroyForm({volume: this.props.volume}))
                ];
            } else if (attached) {
                var attachData = volume.get('attach_data');
                var attachedText = [
                    "Attached to instance ",
                    attachData.instance_id,
                    " as device ",
                    React.DOM.code({}, attachData.device)
                ];
                content = [
                    React.DOM.p({key: 'statusText'}, attachedText),
                    DetachmentForm({key: 'detachment', volume: this.props.volume})
                ];
            }

            return React.DOM.div({},
                React.DOM.h2({}, "Status"),
                content);
        }
    });

    var VolumeDetailPage = React.createClass({
        helpText: function() {
            var p1 = React.DOM.p({}, "A volume is available when it is not attached to an instance. Any newly created volume must be formatted and then mounted after it has been attached before you will be able to use it.");
            var links = [
                ["Creating a Volume", "https://pods.iplantcollaborative.org/wiki/x/UyWO"],
                ["Attaching a Volume to an Instance", "https://pods.iplantcollaborative.org/wiki/x/OKxm#AttachingaVolumetoanInstance-Attachingavolumetoaninstance"],
                ["Formatting a Volume", "https://pods.iplantcollaborative.org/wiki/x/OKxm#AttachingaVolumetoanInstance-Createthefilesystem%28onetimeeventpervolume%29"],
                ["Mounting a Volume", "https://pods.iplantcollaborative.org/wiki/x/OKxm#AttachingaVolumetoanInstance-Mountthefilesystemonthepartition"],
                ["Unmounting and Detaching Volume", "https://pods.iplantcollaborative.org/wiki/x/OKxm#AttachingaVolumetoanInstance-Detachingvolumesfrominstances"]
            ];
            var link_list = React.DOM.ul({}, _.map(links, function(item) {
                return React.DOM.li({}, React.DOM.a({href: item[1]}, item[0]));
            }));
            var p2 = React.DOM.p({}, "More information about volumes:", link_list);
            return React.DOM.div({}, p1, p2);
        },
        render: function() {
            var volume = this.props.volume;
            var instances = this.props.instances;
            return React.DOM.div({},
                PageHeader({title: "Volume: " + volume.get('name_or_id'), helpText: this.helpText}),
                VolumeInfo({volume: volume}),
                AttachmentInfo({volume: volume, instances: instances}));
        }
    });

    var VolumeDetail = React.createClass({
        getInitialState: function() {
            return {
                instances: null,
                volume: this.props.volume
            };
        },
        setVolume: function(volume) {
            this.setState({volume: volume});
        },
        setInstances: function(instances) {
            if (this.isMounted())
                this.setState({instances: instances});
        },
        componentDidMount: function() {
            var provider_id = this.props.volume.get('identity').provider;
            var identity_id = this.props.volume.get('identity').id;
            var instances = new Instances([], {provider_id: provider_id, identity_id: identity_id});
            instances.on('sync', this.setInstances);
            instances.fetch();

            this.state.volume.on('change', this.setVolume);
        },
        componentWillUnmount: function() {
            if (this.state.instances)
                this.state.instances.off('sync', this.setInstances);

            this.state.volume.off('change', this.setVolume);
        },
        render: function() {
            return VolumeDetailPage({
                volume: this.state.volume,
                instances: this.state.instances
            });
        }
    });

    return VolumeDetail;
});
<|endoftext|>


<commit_before>var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mydb');

//schema//
var locationSchema = mongoose.Schema({
        city : String
    })
//Model//
var Locations = mongoose.model('location',locationSchema)

var db = mongoose.connection;
db.on('error',console.error.bind(console,'connection error'));
db.once('open',function(callback){
    console.log('Mongodb is connected');
});

module.exports.create = function(name_city){
    var cityLocation = new Locations({city:name_city})
    console.log(cityLocation.city)

    cityLocation.save(function(err,cityLocation){
        if(err) return console.log('The object has been added to the db ...');
    });
}

module.exports.update = function(name_city){
	db.collection.update({city_id:name_city},{upsert: true})
	cityLocation.update({city_id:name_city},{$set: {city:name_city}},function(err,cityLocation){
		if(err) return handleError(err);
		console.log('Update');
	});
}

module.exports.find = function(name_city){
	db.Collection('mydb').find({_id:name_city})
	cityLocation.findOne({_id:id},function(err,cityLocation){
		if(err) return handleError(err);
		console.log('Finded')
	});
}

module.exports.delete = function(name_city){
	cityLocation.remove({_id:'name_city'},function(err){
		if(err) return handleError(err);
		console.log('Deleted');
	});
}<commit_msg>module.exports<commit_after>var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mydb');

//schema//
var locationSchema = mongoose.Schema({
        city : String
    })
//Model//
var Locations = mongoose.model('location',locationSchema)

var db = mongoose.connection;
db.on('error',console.error.bind(console,'connection error'));
db.once('open',function(callback){
    console.log('Mongodb is connected');
});

module.exports.create = function(name_city){
    var cityLocation = new Locations({city:name_city})
    console.log(cityLocation.city)

    cityLocation.save(function(err,cityLocation){
        if(err) return console.log('The object has been added to the db ...');
    });
}

module.exports.update = function(name_city){
	db.collection.update({city_id:name_city},{upsert: true})
	cityLocation.update({city_id:name_city},{$set: {city:name_city}},function(err,cityLocation){
		if(err) return handleError(err);
		console.log('Update');
	});
}

module.exports.find = function(name_city){
	db.Collection('mydb').find({_id:name_city})
	cityLocation.findOne({_id:id},function(err,cityLocation){
		if(err) return handleError(err);
		console.log('Finded');
	});
}

module.exports.delete = function(name_city){
	cityLocation.remove({_id:'name_city'},function(err){
		if(err) return handleError(err);
		console.log('Deleted');
	});
}<|endoftext|>


<commit_before>const Jimp = require("jimp");

async function generate(text) {
	const textImage = await new Jimp(500, 500);
	const font = await Jimp.loadFont(Jimp.FONT_SANS_16_BLACK);
	textImage.print(font, 0, 250, text);
	textImage.rotate(-26, false);

	const image = await Jimp.read(`${__dirname}/byemom.png`);
	image.composite(textImage, 235, 150);
	image.getBase64(Jimp.MIME_PNG, (err, data) => {
		if(err) throw err;
		process.stdout.write(data);
	});
}

generate(process.env.TEXT);
<commit_msg>fix byemom again<commit_after>const Jimp = require("jimp");

async function generate(text) {
	const textImage = await new Jimp(500, 500);
	const font = await Jimp.loadFont(Jimp.FONT_SANS_16_BLACK);
	textImage.print(font, 0, 250, text);
	textImage.rotate(-25, false);

	const image = await Jimp.read(`${__dirname}/byemom.png`);
	image.composite(textImage, 325, 235);
	image.getBase64(Jimp.MIME_PNG, (err, data) => {
		if(err) throw err;
		process.stdout.write(data);
	});
}

generate(process.env.TEXT);
<|endoftext|>