<commit_before>define([
           'dojo/_base/declare',
           'dojo/_base/array',
           'dojo/_base/lang',
           'JBrowse/Util/FastPromise',
           'JBrowse/View/FeatureGlyph',
           './_FeatureLabelMixin'
       ],
       function(
           declare,
           array,
           lang,
           FastPromise,
           FeatureGlyph,
           FeatureLabelMixin
       ) {

return declare([ FeatureGlyph, FeatureLabelMixin], {

    constructor: function() {
        this._embeddedImagePromises = {};
    },

    _defaultConfig: function() {
        return this._mergeConfigs(
            this.inherited(arguments),
            {
                style: {
                    maxDescriptionLength: 70,

                    color: 'goldenrod',
                    mouseovercolor: 'rgba(0,0,0,0.3)',
                    borderColor: null,
                    borderWidth: 0.5,
                    height: 11,
                    marginBottom: 2,

                    strandArrow: true,

                    label: 'name, id',
                    textFont: 'normal 12px Univers,Helvetica,Arial,sans-serif',
                    textColor:  'black',
                    text2Color: 'blue',
                    text2Font: 'normal 12px Univers,Helvetica,Arial,sans-serif',

                    description: 'note, description'
                }
            });
    },

    _getFeatureHeight: function( viewArgs, feature ) {
        var h = this.getStyle( feature, 'height');

        if( viewArgs.displayMode == 'compact' )
            h = Math.round( 0.45 * h );

        if( this.getStyle( feature, 'strandArrow' ) ) {
            var strand = feature.get('strand');
            if( strand == 1 )
                h = Math.max( this._embeddedImages.plusArrow.height, h );
            else if( strand == -1 )
                h = Math.max( this._embeddedImages.minusArrow.height, h );
        }

        return h;
    },

    _getFeatureRectangle: function( viewArgs, feature ) {
        var block = viewArgs.block;
        var fRect = {
            l: block.bpToX( feature.get('start') ),
            h: this._getFeatureHeight(viewArgs, feature),
            viewInfo: viewArgs,
            f: feature,
            glyph: this
        };

        fRect.w = block.bpToX( feature.get('end') ) - fRect.l;

        // save the original rect in `rect` as the dimensions
        // we'll use for the rectangle itself
        fRect.rect = { l: fRect.l, h: fRect.h, w: Math.max( fRect.w, 2 ), t: 0 };
        fRect.w = fRect.rect.w; // in case it was increased
        if( viewArgs.displayMode != 'compact' )
            fRect.h += this.getStyle( feature, 'marginBottom' ) || 0
;
        // if we are showing strand arrowheads, expand the frect a little
        if( this.getStyle( feature, 'strandArrow') ) {
            var strand = fRect.strandArrow = feature.get('strand');

            if( strand == -1 ) {
                var i = this._embeddedImages.minusArrow;
                fRect.w += i.width;
                fRect.l -= i.width;
            }
            else {
                var i = this._embeddedImages.plusArrow;
                fRect.w += i.width;
            }
        }

        // no labels or descriptions if displayMode is collapsed, so stop here
        if( viewArgs.displayMode == "collapsed")
            return fRect;

        this._expandRectangleWithLabels( viewArgs, feature, fRect );
        this._addMasksToRect( viewArgs, feature, fRect );

        return fRect;
    },

    layoutFeature: function( viewArgs, layout, feature ) {
        var rect = this.inherited( arguments );
        if( ! rect ) return rect;

        // need to set the top of the inner rect
        rect.rect.t = rect.t;

        return rect;
    },

    // given an under-construction feature layout rectangle, expand it
    // to accomodate a label and/or a description
    _expandRectangleWithLabels: function( viewArgs, feature, fRect ) {
        // maybe get the feature's name, and update the layout box
        // accordingly
        if( viewArgs.showLabels ) {
            var label = this.makeFeatureLabel( feature, fRect );
            if( label ) {
                fRect.h += label.h;
                fRect.w = Math.max( label.w, fRect.w );
                fRect.label = label;
                label.yOffset = fRect.rect.h + label.h;
            }
        }

        // maybe get the feature's description if available, and
        // update the layout box accordingly
        if( viewArgs.showDescriptions ) {
            var description = this.makeFeatureDescriptionLabel( feature, fRect );
            if( description ) {
                fRect.description = description;
                fRect.h += description.h;
                fRect.w = Math.max( description.w, fRect.w );
                description.yOffset = fRect.h-(this.getStyle( feature, 'marginBottom' ) || 0);
            }
        }
    },

    _embeddedImages: {
         plusArrow: {
             data: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAFCAYAAACXU8ZrAAAATUlEQVQIW2NkwATGQKFYIG4A4g8gacb///+7AWlBmNq+vj6V4uLiJiD/FRBXA/F8xu7u7kcVFRWyMEVATQz//v0Dcf9CxaYRZxIxbgIARiAhmifVe8UAAAAASUVORK5CYII=",
             width: 9,
             height: 5
         },

         minusArrow: {
             data: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAFCAYAAACXU8ZrAAAASklEQVQIW2NkQAABILMBiBcD8VkkcQZGIAeEE4G4FYjFent764qKiu4gKXoPUjAJiLOggsxMTEwMjIwgYQjo6Oh4TLRJME043QQA+W8UD/sdk9IAAAAASUVORK5CYII=",
             width: 9,
             height: 5
         }
    },

    /**
     * Returns a promise for an Image object for the image with the
     * given name.  Image data comes from a data URL embedded in this
     * source code.
     */
    getEmbeddedImage: function( name ) {
        return (this._embeddedImagePromises[name] || function() {
                    var p = new FastPromise();
                    var imgRec = this._embeddedImages[ name ];
                    if( ! imgRec ) {
                        p.resolve( null );
                    }
                    else {
                        var i = new Image();
                        var thisB = this;
                        i.onload = function() {
                            p.resolve( this );
                        };
                        i.src = imgRec.data;
                    }
                    return this._embeddedImagePromises[name] = p;
                }.call(this));
    },

    renderFeature: function( context, fRect ) {
        if( this.track.displayMode != 'collapsed' )
            context.clearRect( Math.floor(fRect.l), fRect.t, Math.ceil(fRect.w-Math.floor(fRect.l)+fRect.l), fRect.h );

        this.renderBox( context, fRect.viewInfo, fRect.f, fRect.t, fRect.rect.h, fRect.f );
        this.renderLabel( context, fRect );
        this.renderDescription( context, fRect );
        this.renderArrowhead( context, fRect );
    },

    // top and height are in px
    renderBox: function( context, viewInfo, feature, top, overallHeight, parentFeature, style ) {
        var left  = viewInfo.block.bpToX( feature.get('start') );
        var width = viewInfo.block.bpToX( feature.get('end') ) - left;
        //left = Math.round( left );
        //width = Math.round( width );

        style = style || lang.hitch( this, 'getStyle' );

        var height = this._getFeatureHeight( viewInfo, feature );
        if( ! height )
            return;
        if( height != overallHeight )
            top += Math.round( (overallHeight - height)/2 );

        // background
        var bgcolor = style( feature, 'color' );
        if( bgcolor ) {
            context.fillStyle = bgcolor;
            context.fillRect( left, top, Math.max(1,width), height );
        }
        else {
            context.clearRect( left, top, Math.max(1,width), height );
        }

        // foreground border
        var borderColor, lineWidth;
        if( (borderColor = style( feature, 'borderColor' )) && ( lineWidth = style( feature, 'borderWidth')) ) {
            if( width > 3 ) {
                context.lineWidth = lineWidth;
                context.strokeStyle = borderColor;

                // need to stroke a smaller rectangle to remain within
                // the bounds of the feature's overall height and
                // width, because of the way stroking is done in
                // canvas.  thus the +0.5 and -1 business.
                context.strokeRect( left+lineWidth/2, top+lineWidth/2, width-lineWidth, height-lineWidth );
            }
            else {
                context.globalAlpha = lineWidth*2/width;
                context.fillStyle = borderColor;
                context.fillRect( left, top, Math.max(1,width), height );
                context.globalAlpha = 1;
            }
        }
    },

    // feature label
    renderLabel: function( context, fRect ) {
        if( fRect.label ) {
            context.font = fRect.label.font;
            context.fillStyle = fRect.label.fill;
            context.textBaseline = fRect.label.baseline;
            context.fillText( fRect.label.text,
                              fRect.l+(fRect.label.xOffset||0),
                              fRect.t+(fRect.label.yOffset||0)
                            );
        }
    },

    // feature description
    renderDescription: function( context, fRect ) {
        if( fRect.description ) {
            context.font = fRect.description.font;
            context.fillStyle = fRect.description.fill;
            context.textBaseline = fRect.description.baseline;
            context.fillText(
                fRect.description.text,
                fRect.l+(fRect.description.xOffset||0),
                fRect.t + (fRect.description.yOffset||0)
            );
        }
    },

    // strand arrowhead
    renderArrowhead: function( context, fRect ) {
        if( fRect.strandArrow ) {
            if( fRect.strandArrow == 1 && fRect.rect.l+fRect.rect.w <= context.canvas.width ) {
                this.getEmbeddedImage( 'plusArrow' )
                    .then( function( img ) {
                               context.imageSmoothingEnabled = false;
                               context.drawImage( img, fRect.rect.l + fRect.rect.w, fRect.t + (fRect.rect.h-img.height)/2 );
                           });
            }
            else if( fRect.strandArrow == -1 && fRect.rect.l >= 0 ) {
                this.getEmbeddedImage( 'minusArrow' )
                    .then( function( img ) {
                               context.imageSmoothingEnabled = false;
                               context.drawImage( img, fRect.rect.l-9, fRect.t + (fRect.rect.h-img.height)/2 );
                           });
            }
        }
    },

    updateStaticElements: function( context, fRect, viewArgs ) {
        var vMin = viewArgs.minVisible;
        var vMax = viewArgs.maxVisible;
        var block = fRect.viewInfo.block;

        if( !( block.containsBp( vMin ) || block.containsBp( vMax ) ) )
            return;

        var scale = block.scale;
        var bpToPx = viewArgs.bpToPx;
        var lWidth = viewArgs.lWidth;
        var labelBp = lWidth / scale;
        var feature = fRect.f;
        var fMin = feature.get('start');
        var fMax = feature.get('end');

        if( fRect.strandArrow ) {
            if( fRect.strandArrow == 1 && fMax >= vMax && fMin <= vMax ) {
                this.getEmbeddedImage( 'plusArrow' )
                    .then( function( img ) {
                               context.imageSmoothingEnabled = false;
                               context.drawImage( img, bpToPx(vMax) - bpToPx(vMin) - 9, fRect.t + (fRect.rect.h-img.height)/2 );
                           });
            }
            else if( fRect.strandArrow == -1 && fMin <= vMin && fMax >= vMin ) {
                this.getEmbeddedImage( 'minusArrow' )
                    .then( function( img ) {
                               context.imageSmoothingEnabled = false;
                               context.drawImage( img, 0, fRect.t + (fRect.rect.h-img.height)/2 );
                           });
            }
        }

        var fLabelWidth = fRect.label ? fRect.label.w : 0;
        var fDescriptionWidth = fRect.description ? fRect.description.w : 0;
        var maxLeft = bpToPx( fMax ) - Math.max(fLabelWidth, fDescriptionWidth) - bpToPx( vMin );
        var minLeft = bpToPx( fMin ) - bpToPx( vMin );

        if( fRect.label ) {
            if( fMin <= vMin && fMax > vMin) {
                context.font = fRect.label.font;
                context.fillStyle = fRect.label.fill;
                context.textBaseline = fRect.label.baseline;
                context.fillText( fRect.label.text,
                                  0,
                                  fRect.t+(fRect.label.yOffset||0)
                                );
            }
        }
        if( fRect.description ) {
            if( fMin <= vMin && fMax > vMin) {
                context.font = fRect.description.font;
                context.fillStyle = fRect.description.fill;
                context.textBaseline = fRect.description.baseline;
                context.fillText(
                    fRect.description.text,
                    0,
                    fRect.t + (fRect.description.yOffset||0)
                );
            }
        }
    }

});
});
<commit_msg>Use minLeft as the leftmost render point<commit_after>define([
           'dojo/_base/declare',
           'dojo/_base/array',
           'dojo/_base/lang',
           'JBrowse/Util/FastPromise',
           'JBrowse/View/FeatureGlyph',
           './_FeatureLabelMixin'
       ],
       function(
           declare,
           array,
           lang,
           FastPromise,
           FeatureGlyph,
           FeatureLabelMixin
       ) {

return declare([ FeatureGlyph, FeatureLabelMixin], {

    constructor: function() {
        this._embeddedImagePromises = {};
    },

    _defaultConfig: function() {
        return this._mergeConfigs(
            this.inherited(arguments),
            {
                style: {
                    maxDescriptionLength: 70,

                    color: 'goldenrod',
                    mouseovercolor: 'rgba(0,0,0,0.3)',
                    borderColor: null,
                    borderWidth: 0.5,
                    height: 11,
                    marginBottom: 2,

                    strandArrow: true,

                    label: 'name, id',
                    textFont: 'normal 12px Univers,Helvetica,Arial,sans-serif',
                    textColor:  'black',
                    text2Color: 'blue',
                    text2Font: 'normal 12px Univers,Helvetica,Arial,sans-serif',

                    description: 'note, description'
                }
            });
    },

    _getFeatureHeight: function( viewArgs, feature ) {
        var h = this.getStyle( feature, 'height');

        if( viewArgs.displayMode == 'compact' )
            h = Math.round( 0.45 * h );

        if( this.getStyle( feature, 'strandArrow' ) ) {
            var strand = feature.get('strand');
            if( strand == 1 )
                h = Math.max( this._embeddedImages.plusArrow.height, h );
            else if( strand == -1 )
                h = Math.max( this._embeddedImages.minusArrow.height, h );
        }

        return h;
    },

    _getFeatureRectangle: function( viewArgs, feature ) {
        var block = viewArgs.block;
        var fRect = {
            l: block.bpToX( feature.get('start') ),
            h: this._getFeatureHeight(viewArgs, feature),
            viewInfo: viewArgs,
            f: feature,
            glyph: this
        };

        fRect.w = block.bpToX( feature.get('end') ) - fRect.l;

        // save the original rect in `rect` as the dimensions
        // we'll use for the rectangle itself
        fRect.rect = { l: fRect.l, h: fRect.h, w: Math.max( fRect.w, 2 ), t: 0 };
        fRect.w = fRect.rect.w; // in case it was increased
        if( viewArgs.displayMode != 'compact' )
            fRect.h += this.getStyle( feature, 'marginBottom' ) || 0
;
        // if we are showing strand arrowheads, expand the frect a little
        if( this.getStyle( feature, 'strandArrow') ) {
            var strand = fRect.strandArrow = feature.get('strand');

            if( strand == -1 ) {
                var i = this._embeddedImages.minusArrow;
                fRect.w += i.width;
                fRect.l -= i.width;
            }
            else {
                var i = this._embeddedImages.plusArrow;
                fRect.w += i.width;
            }
        }

        // no labels or descriptions if displayMode is collapsed, so stop here
        if( viewArgs.displayMode == "collapsed")
            return fRect;

        this._expandRectangleWithLabels( viewArgs, feature, fRect );
        this._addMasksToRect( viewArgs, feature, fRect );

        return fRect;
    },

    layoutFeature: function( viewArgs, layout, feature ) {
        var rect = this.inherited( arguments );
        if( ! rect ) return rect;

        // need to set the top of the inner rect
        rect.rect.t = rect.t;

        return rect;
    },

    // given an under-construction feature layout rectangle, expand it
    // to accomodate a label and/or a description
    _expandRectangleWithLabels: function( viewArgs, feature, fRect ) {
        // maybe get the feature's name, and update the layout box
        // accordingly
        if( viewArgs.showLabels ) {
            var label = this.makeFeatureLabel( feature, fRect );
            if( label ) {
                fRect.h += label.h;
                fRect.w = Math.max( label.w, fRect.w );
                fRect.label = label;
                label.yOffset = fRect.rect.h + label.h;
            }
        }

        // maybe get the feature's description if available, and
        // update the layout box accordingly
        if( viewArgs.showDescriptions ) {
            var description = this.makeFeatureDescriptionLabel( feature, fRect );
            if( description ) {
                fRect.description = description;
                fRect.h += description.h;
                fRect.w = Math.max( description.w, fRect.w );
                description.yOffset = fRect.h-(this.getStyle( feature, 'marginBottom' ) || 0);
            }
        }
    },

    _embeddedImages: {
         plusArrow: {
             data: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAFCAYAAACXU8ZrAAAATUlEQVQIW2NkwATGQKFYIG4A4g8gacb///+7AWlBmNq+vj6V4uLiJiD/FRBXA/F8xu7u7kcVFRWyMEVATQz//v0Dcf9CxaYRZxIxbgIARiAhmifVe8UAAAAASUVORK5CYII=",
             width: 9,
             height: 5
         },

         minusArrow: {
             data: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAFCAYAAACXU8ZrAAAASklEQVQIW2NkQAABILMBiBcD8VkkcQZGIAeEE4G4FYjFent764qKiu4gKXoPUjAJiLOggsxMTEwMjIwgYQjo6Oh4TLRJME043QQA+W8UD/sdk9IAAAAASUVORK5CYII=",
             width: 9,
             height: 5
         }
    },

    /**
     * Returns a promise for an Image object for the image with the
     * given name.  Image data comes from a data URL embedded in this
     * source code.
     */
    getEmbeddedImage: function( name ) {
        return (this._embeddedImagePromises[name] || function() {
                    var p = new FastPromise();
                    var imgRec = this._embeddedImages[ name ];
                    if( ! imgRec ) {
                        p.resolve( null );
                    }
                    else {
                        var i = new Image();
                        var thisB = this;
                        i.onload = function() {
                            p.resolve( this );
                        };
                        i.src = imgRec.data;
                    }
                    return this._embeddedImagePromises[name] = p;
                }.call(this));
    },

    renderFeature: function( context, fRect ) {
        if( this.track.displayMode != 'collapsed' )
            context.clearRect( Math.floor(fRect.l), fRect.t, Math.ceil(fRect.w-Math.floor(fRect.l)+fRect.l), fRect.h );

        this.renderBox( context, fRect.viewInfo, fRect.f, fRect.t, fRect.rect.h, fRect.f );
        this.renderLabel( context, fRect );
        this.renderDescription( context, fRect );
        this.renderArrowhead( context, fRect );
    },

    // top and height are in px
    renderBox: function( context, viewInfo, feature, top, overallHeight, parentFeature, style ) {
        var left  = viewInfo.block.bpToX( feature.get('start') );
        var width = viewInfo.block.bpToX( feature.get('end') ) - left;
        //left = Math.round( left );
        //width = Math.round( width );

        style = style || lang.hitch( this, 'getStyle' );

        var height = this._getFeatureHeight( viewInfo, feature );
        if( ! height )
            return;
        if( height != overallHeight )
            top += Math.round( (overallHeight - height)/2 );

        // background
        var bgcolor = style( feature, 'color' );
        if( bgcolor ) {
            context.fillStyle = bgcolor;
            context.fillRect( left, top, Math.max(1,width), height );
        }
        else {
            context.clearRect( left, top, Math.max(1,width), height );
        }

        // foreground border
        var borderColor, lineWidth;
        if( (borderColor = style( feature, 'borderColor' )) && ( lineWidth = style( feature, 'borderWidth')) ) {
            if( width > 3 ) {
                context.lineWidth = lineWidth;
                context.strokeStyle = borderColor;

                // need to stroke a smaller rectangle to remain within
                // the bounds of the feature's overall height and
                // width, because of the way stroking is done in
                // canvas.  thus the +0.5 and -1 business.
                context.strokeRect( left+lineWidth/2, top+lineWidth/2, width-lineWidth, height-lineWidth );
            }
            else {
                context.globalAlpha = lineWidth*2/width;
                context.fillStyle = borderColor;
                context.fillRect( left, top, Math.max(1,width), height );
                context.globalAlpha = 1;
            }
        }
    },

    // feature label
    renderLabel: function( context, fRect ) {

    },

    // feature description
    renderDescription: function( context, fRect ) {

    },

    // strand arrowhead
    renderArrowhead: function( context, fRect ) {
        if( fRect.strandArrow ) {
            if( fRect.strandArrow == 1 && fRect.rect.l+fRect.rect.w <= context.canvas.width ) {
                this.getEmbeddedImage( 'plusArrow' )
                    .then( function( img ) {
                               context.imageSmoothingEnabled = false;
                               context.drawImage( img, fRect.rect.l + fRect.rect.w, fRect.t + (fRect.rect.h-img.height)/2 );
                           });
            }
            else if( fRect.strandArrow == -1 && fRect.rect.l >= 0 ) {
                this.getEmbeddedImage( 'minusArrow' )
                    .then( function( img ) {
                               context.imageSmoothingEnabled = false;
                               context.drawImage( img, fRect.rect.l-9, fRect.t + (fRect.rect.h-img.height)/2 );
                           });
            }
        }
    },

    updateStaticElements: function( context, fRect, viewArgs ) {
        var vMin = viewArgs.minVisible;
        var vMax = viewArgs.maxVisible;
        var block = fRect.viewInfo.block;

        if( !( block.containsBp( vMin ) || block.containsBp( vMax ) ) )
            return;

        var scale = block.scale;
        var bpToPx = viewArgs.bpToPx;
        var lWidth = viewArgs.lWidth;
        var labelBp = lWidth / scale;
        var feature = fRect.f;
        var fMin = feature.get('start');
        var fMax = feature.get('end');

        if( fRect.strandArrow ) {
            if( fRect.strandArrow == 1 && fMax >= vMax && fMin <= vMax ) {
                this.getEmbeddedImage( 'plusArrow' )
                    .then( function( img ) {
                               context.imageSmoothingEnabled = false;
                               context.drawImage( img, bpToPx(vMax) - bpToPx(vMin) - 9, fRect.t + (fRect.rect.h-img.height)/2 );
                           });
            }
            else if( fRect.strandArrow == -1 && fMin <= vMin && fMax >= vMin ) {
                this.getEmbeddedImage( 'minusArrow' )
                    .then( function( img ) {
                               context.imageSmoothingEnabled = false;
                               context.drawImage( img, 0, fRect.t + (fRect.rect.h-img.height)/2 );
                           });
            }
        }

        var fLabelWidth = fRect.label ? fRect.label.w : 0;
        var fDescriptionWidth = fRect.description ? fRect.description.w : 0;
        var maxLeft = bpToPx( fMax ) - Math.max(fLabelWidth, fDescriptionWidth) - bpToPx( vMin );
        var minLeft = bpToPx( fMin ) - bpToPx( vMin );

        if( fRect.label ) {
            if( fMin <= vMin && fMax > vMin) {
                context.font = fRect.label.font;
                context.fillStyle = fRect.label.fill;
                context.textBaseline = fRect.label.baseline;
                context.fillText( fRect.label.text,
                                  0,
                                  fRect.t+(fRect.label.yOffset||0)
                                );
            } else {
                context.font = fRect.label.font;
                context.fillStyle = fRect.label.fill;
                context.textBaseline = fRect.label.baseline;
                context.fillText( fRect.label.text,
                                  minLeft+(fRect.label.xOffset||0),
                                  fRect.t+(fRect.label.yOffset||0)
                                );
            }
        }
        if( fRect.description ) {
            if( fMin <= vMin && fMax > vMin) {
                context.font = fRect.description.font;
                context.fillStyle = fRect.description.fill;
                context.textBaseline = fRect.description.baseline;
                context.fillText(
                    fRect.description.text,
                    0,
                    fRect.t + (fRect.description.yOffset||0)
                );
            } else {
                context.font = fRect.description.font;
                context.fillStyle = fRect.description.fill;
                context.textBaseline = fRect.description.baseline;
                context.fillText(
                    fRect.description.text,
                    minLeft+(fRect.description.xOffset||0),
                    fRect.t + (fRect.description.yOffset||0)
                );
            }
        }
    }

});
});
<|endoftext|>


<commit_before>var spawn = require('child_process').spawn;

// Expose to the world
module.exports = SendmailTransport;

/**
 *
Generates a Transport object for Sendmail

 *
 * @constructor
 * @param {String} [config] path to the sendmail command
 */
function SendmailTransport(config){
    this.path = "sendmail";
    this.args = false;
    if(typeof config=="string") {
        this.path = config;
    } else if(typeof config=="object") {
        if(config.path) {
            this.path = config.path;
        }
        if(Array.isArray(config.args)) {
            this.args = config.args;
        }
    }
}

/**
 *
Spawns a 'sendmail -t' command and streams the outgoing
 * message to sendmail stdin. Return callback checks if the sendmail process
 * ended with 0 (no error) or not.

 *
 * @param {Object} emailMessage MailComposer object
 * @param {Function} callback Callback function to run when the sending is completed
 */
SendmailTransport.prototype.sendMail = function(emailMessage, callback) {

    var envelope = emailMessage.getEnvelope();
    var sendmail = spawn(this.path, this.args || ["-f"].concat(envelope.from).concat(envelope.to));
    sendmail.on('exit', function (code) {
        var msg = "Sendmail exited with "+code;
        if(typeof callback == "function"){
            callback(code?new Error(msg):null, {message: msg, messageId: emailMessage._messageId});
        }
    });

    emailMessage.pipe(sendmail.stdin);
    emailMessage.streamMessage();

};<commit_msg>force -i flag for sendmail<commit_after>var spawn = require('child_process').spawn;

// Expose to the world
module.exports = SendmailTransport;

/**
 *
Generates a Transport object for Sendmail

 *
 * @constructor
 * @param {String} [config] path to the sendmail command
 */
function SendmailTransport(config){
    this.path = "sendmail";
    this.args = false;
    if(typeof config=="string") {
        this.path = config;
    } else if(typeof config=="object") {
        if(config.path) {
            this.path = config.path;
        }
        if(Array.isArray(config.args)) {
            this.args = config.args;
        }
    }
}

/**
 *
Spawns a 'sendmail -t' command and streams the outgoing
 * message to sendmail stdin. Return callback checks if the sendmail process
 * ended with 0 (no error) or not.

 *
 * @param {Object} emailMessage MailComposer object
 * @param {Function} callback Callback function to run when the sending is completed
 */
SendmailTransport.prototype.sendMail = function(emailMessage, callback) {

    var envelope = emailMessage.getEnvelope();
    var args = this.args || ["-f"].concat(envelope.from).concat(envelope.to);
    args.unshift("-i"); // force -i to keep single dots

    var sendmail = spawn(this.path, args);
    sendmail.on('exit', function (code) {
        var msg = "Sendmail exited with "+code;
        if(typeof callback == "function"){
            callback(code?new Error(msg):null, {message: msg, messageId: emailMessage._messageId});
        }
    });

    emailMessage.pipe(sendmail.stdin);
    emailMessage.streamMessage();

};<|endoftext|>


<commit_before>'use strict';

module.exports = ExpressionStack;

function ExpressionStack() {
  var priv = {};

  var pub = {};
  bindMethods(pub, [push, pop], priv);
  bindProperties(pub, [stackId, stackName, syntax], priv);
  return pub;
}

function push(priv, stackName) {
}

function pop(priv, force) {
}

function stackId(priv) {
}

function stackName(priv) {
  return "bottom";
}

function syntax(priv) {
}

function bindMethods(pub, methods, priv) {
  methods.forEach(function(method) { pub[method.name] = method.bind(null, priv) });
}

function bindProperties(pub, getters, priv) {
  getters.forEach(function(getter) {
    Object.defineProperty(pub, getter.name, {
      get: getter.bind(null, priv),
      set: function() { throw new Error('property '+ getter.name +' is read-only'); }
    });
  });
}

/*
  eslint-env node
 */

<commit_msg>+ ExpressionStack: implemented pushing with stack name<commit_after>'use strict';

module.exports = ExpressionStack;

function ExpressionStack() {
  var priv = {
    current: new Level('bottom'),
  };

  var pub = {};
  bindMethods(pub, [push, pop], priv);
  bindProperties(pub, [stackId, stackName, syntax], priv);
  return pub;
}

function push(priv, stackName) {
  priv.current = new Level(stackName);
}

function pop(priv, force) {
}

function stackId(priv) {
}

function stackName(priv) {
  return priv.current.stackName;
}

function syntax(priv) {
}

// level

function Level(stackName) {
  this.stackName = stackName;
}

// utils

function bindMethods(pub, methods, priv) {
  methods.forEach(function(method) { pub[method.name] = method.bind(null, priv) });
}

function bindProperties(pub, getters, priv) {
  getters.forEach(function(getter) {
    Object.defineProperty(pub, getter.name, {
      get: getter.bind(null, priv),
      set: function() { throw new Error('property '+ getter.name +' is read-only'); }
    });
  });
}

/*
  eslint-env node
 */

<|endoftext|>


<commit_before>'use strict';

var db = require('mano').db,
	user = db.User.prototype;

exports.step = function () {
	div(
		{ class: 'content' },
		h1("2. Fill the form"),
		div({ class: 'error-main' },
			p(span({ class: 'fa fa-exclamation-circle' }), "Please fill the Guide first")),
		div(
			{ class: 'disabler-range', id: 'forms-disabler-range' },
			section(
				form(
					fieldset({ class: 'section-primary' },
						h2("Business Owner basic informations"),
						hr(),
						ul({ class: 'form-elements fieldset' },
							['firstName', 'lastName', 'dateOfBirth', 'userEmail'],
							function (name) { return field({ dbjs: user.getObservable(name) }); }
							),
						p({ class: 'submit-placeholder' },
							input({ type: 'submit' }, "Submit")
							)
						)
				)
			),

			section({ class: 'section-primary' },
				form(
					h2("Business Owner secondary informations"),
					hr(),
					fieldset({ class: 'sub-section' },
						h3("First subsection"),
						ul({ class: 'form-elements fieldset' },
							['companyType', 'members', 'inventory', 'surfaceArea', 'isOwner', 'businessActivity',
								'registerIds'],
							function (name) { return field({ dbjs: user.getObservable(name) }); }
							),
						p({ class: 'submit-placeholder' },
							input({ type: 'submit' }, "Submit")
							)
						),
					fieldset({ class: 'sub-section' },
						h3("Second subsection"),
						ul({ class: 'form-elements fieldset' },
							['companyType', 'members', 'inventory', 'surfaceArea', 'isOwner', 'businessActivity',
								'registerIds'],
							function (name) { return field({ dbjs: user.getObservable(name) }); }
							),
						p({ class: 'submit-placeholder' },
							input({ type: 'submit' }, "Submit")
							)
						)
				)
				),

			section({ class: 'section-primary' },
				div(
					div(
						h2("Directors & non-directors owner / partners"),
						hr(),
						table(
							{ class: 'partners-list' },
							thead(
								tr(
									th({ class: 'desktop-only' }, "Entity"),
									th("First name"),
									th("Surname"),
									th({ class: 'desktop-only' }, "Director?"),
									th({ class: 'desktop-only' }, "Subscriber?"),
									th({ class: 'desktop-only' }, ""),
									th({ class: 'actions' }, "Actions")
								)
							),
							tbody(
								tr(
									td({ class: 'desktop-only' },
										a({ href: '/forms/partner-id/' }, "Lorem")
										),
									td(a({ href: '/forms/partner-id/' }, "John")),
									td(a({ href: '/forms/partner-id/' }, "Watson")),
									td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
									td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
									td({ class: 'desktop-only confirmed' }, "✓"),
									td({ class: 'actions' },
										a("Edit"),
										a("Delete")
										)
								),
								tr(
									td({ class: 'desktop-only' },
										a({ href: '/forms/partner-id/' }, "Lorem")
										),
									td(a({ href: '/forms/partner-id/' }, "John")),
									td(a({ href: '/forms/partner-id/' }, "Watson")),
									td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
									td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
									td({ class: 'desktop-only confirmed' }, "✓"),
									td({ class: 'actions' },
										a("Edit"),
										a("Delete")
										)
								),
								tr(
									td({ class: 'desktop-only' },
										a({ href: '/forms/partner-id/' }, "Lorem")
										),
									td(a({ href: '/forms/partner-id/' }, "John")),
									td(a({ href: '/forms/partner-id/' }, "Watson")),
									td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
									td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
									td({ class: 'desktop-only confirmed' }, "✓"),
									td({ class: 'actions' },
										a("Edit"),
										a("Delete")
										)
								),
								tr(
									td({ class: 'desktop-only' },
										a({ href: '/forms/partner-id/' }, "Lorem")
										),
									td(a({ href: '/forms/partner-id/' }, "John")),
									td(a({ href: '/forms/partner-id/' }, "Watson")),
									td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
									td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
									td({ class: 'desktop-only confirmed' }, "✓"),
									td({ class: 'actions' },
										a("Edit"),
										a("Delete")
										)
								),
								tr(
									td({ class: 'desktop-only' },
										a({ href: '/forms/partner-id/' }, "Lorem")
										),
									td(a({ href: '/forms/partner-id/' }, "John")),
									td(a({ href: '/forms/partner-id/' }, "Watson")),
									td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
									td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
									td({ class: 'desktop-only confirmed' }, "✓"),
									td({ class: 'actions' },
										a("Edit"),
										a("Delete")
										)
								)
							)
						),
						a(
							{ class: 'new-entity', href: '/forms/partner-add/' },
							"Add new partner"
						)
					)
				)
				),

			div({ class: 'next-step' },
				a({ href: '/documents/' }, "Continue to next step")
				),
			div({ class: 'disabler' })
		)
	);
};
<commit_msg>User forms page refatore based on new section-priamary, #114<commit_after>'use strict';

var db = require('mano').db,
	user = db.User.prototype;

exports.step = function () {
	h1("2. Fill the form");
	div({ class: 'error-main' },
		p(span({ class: 'fa fa-exclamation-circle' }), "Please fill the Guide first"));
	div(
		{ class: 'disabler-range', id: 'forms-disabler-range' },
		section(
			form(
				fieldset({ class: 'section-primary' },
					h2("Business Owner basic informations"),
					hr(),
					ul({ class: 'form-elements fieldset' },
						['firstName', 'lastName', 'dateOfBirth', 'userEmail'],
						function (name) { return field({ dbjs: user.getObservable(name) }); }
						),
					p({ class: 'submit-placeholder' },
						input({ type: 'submit' }, "Submit")
						)
					)
			)
		),

		section({ class: 'section-primary' },
			form(
				h2("Business Owner secondary informations"),
				hr(),
				fieldset({ class: 'sub-section' },
					h3("First subsection"),
					ul({ class: 'form-elements fieldset' },
						['companyType', 'members', 'inventory', 'surfaceArea', 'isOwner', 'businessActivity',
							'registerIds'],
						function (name) { return field({ dbjs: user.getObservable(name) }); }
						),
					p({ class: 'submit-placeholder' },
						input({ type: 'submit' }, "Submit")
						)
					),
				fieldset({ class: 'sub-section' },
					h3("Second subsection"),
					ul({ class: 'form-elements fieldset' },
						['companyType', 'members', 'inventory', 'surfaceArea', 'isOwner', 'businessActivity',
							'registerIds'],
						function (name) { return field({ dbjs: user.getObservable(name) }); }
						),
					p({ class: 'submit-placeholder' },
						input({ type: 'submit' }, "Submit")
						)
					)
			)
			),

		section({ class: 'section-primary' },
			div(
				div(
					h2("Directors & non-directors owner / partners"),
					hr(),
					table(
						{ class: 'partners-list' },
						thead(
							tr(
								th({ class: 'desktop-only' }, "Entity"),
								th("First name"),
								th("Surname"),
								th({ class: 'desktop-only' }, "Director?"),
								th({ class: 'desktop-only' }, "Subscriber?"),
								th({ class: 'desktop-only' }, ""),
								th({ class: 'actions' }, "Actions")
							)
						),
						tbody(
							tr(
								td({ class: 'desktop-only' },
									a({ href: '/forms/partner-id/' }, "Lorem")
									),
								td(a({ href: '/forms/partner-id/' }, "John")),
								td(a({ href: '/forms/partner-id/' }, "Watson")),
								td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
								td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
								td({ class: 'desktop-only confirmed' }, "✓"),
								td({ class: 'actions' },
									a("Edit"),
									a("Delete")
									)
							),
							tr(
								td({ class: 'desktop-only' },
									a({ href: '/forms/partner-id/' }, "Lorem")
									),
								td(a({ href: '/forms/partner-id/' }, "John")),
								td(a({ href: '/forms/partner-id/' }, "Watson")),
								td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
								td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
								td({ class: 'desktop-only confirmed' }, "✓"),
								td({ class: 'actions' },
									a("Edit"),
									a("Delete")
									)
							),
							tr(
								td({ class: 'desktop-only' },
									a({ href: '/forms/partner-id/' }, "Lorem")
									),
								td(a({ href: '/forms/partner-id/' }, "John")),
								td(a({ href: '/forms/partner-id/' }, "Watson")),
								td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
								td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
								td({ class: 'desktop-only confirmed' }, "✓"),
								td({ class: 'actions' },
									a("Edit"),
									a("Delete")
									)
							),
							tr(
								td({ class: 'desktop-only' },
									a({ href: '/forms/partner-id/' }, "Lorem")
									),
								td(a({ href: '/forms/partner-id/' }, "John")),
								td(a({ href: '/forms/partner-id/' }, "Watson")),
								td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
								td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
								td({ class: 'desktop-only confirmed' }, "✓"),
								td({ class: 'actions' },
									a("Edit"),
									a("Delete")
									)
							),
							tr(
								td({ class: 'desktop-only' },
									a({ href: '/forms/partner-id/' }, "Lorem")
									),
								td(a({ href: '/forms/partner-id/' }, "John")),
								td(a({ href: '/forms/partner-id/' }, "Watson")),
								td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
								td({ class: 'desktop-only' }, a({ href: '/forms/partner-id/' }, "Yes")),
								td({ class: 'desktop-only confirmed' }, "✓"),
								td({ class: 'actions' },
									a("Edit"),
									a("Delete")
									)
							)
						)
					),
					a(
						{ class: 'new-entity', href: '/forms/partner-add/' },
						"Add new partner"
					)
				)
			)
			),

		div({ class: 'next-step' },
			a({ href: '/documents/' }, "Continue to next step")
			),
		div({ class: 'disabler' })
	);
};
<|endoftext|>


<commit_before>/*!
 * OS.js - JavaScript Cloud/Web Desktop Platform
 *
 * Copyright (c) 2011-2016, Anders Evenrud <andersevenrud@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author  Anders Evenrud <andersevenrud@gmail.com>
 * @licence Simplified BSD License
 */
(function(Application, Window, Utils, API, VFS, GUI) {
  'use strict';

  var DEFAULT_GROUP = 'misc';

  var _groups = {
    personal: {
      label: 'LBL_PERSONAL'
    },
    system: {
      label: 'LBL_SYSTEM'
    },
    user: {
      label: 'LBL_USER'
    },
    misc: {
      label: 'LBL_OTHER'
    }
  };

  var categoryMap = {
    'theme': 'Theme',
    'desktop': 'Desktop',
    'panel': 'Panel',
    'user': 'User',
    'fileview': 'VFS',
    'search': 'Search'
  };

  /////////////////////////////////////////////////////////////////////////////
  // WINDOWS
  /////////////////////////////////////////////////////////////////////////////

  function ApplicationSettingsWindow(app, metadata, scheme) {
    Window.apply(this, ['ApplicationSettingsWindow', {
      icon: metadata.icon,
      title: metadata.name,
      width: 500,
      height: 450,
      allow_resize: true
    }, app, scheme]);
  }

  ApplicationSettingsWindow.prototype = Object.create(Window.prototype);
  ApplicationSettingsWindow.constructor = Window.prototype;

  ApplicationSettingsWindow.prototype.init = function(wmRef, app, scheme) {
    var self = this;
    var root = Window.prototype.init.apply(this, arguments);
    var wm = OSjs.Core.getWindowManager();
    var _ = OSjs.Applications.ApplicationSettings._;

    // Load and render `scheme.html` file
    scheme.render(this, 'SettingsWindow', root, null, null, {_: _});

    this._find('ButtonOK').son('click', this, this.onButtonOK);
    this._find('ButtonCancel').son('click', this, this.onButtonCancel);

    // Adds all groups and their respective entries
    var container = document.createElement('div');
    container.className = 'ListView gui-generic-zebra-container';

    var containers = {};
    var tmpcontent = document.createDocumentFragment();

    Object.keys(_groups).forEach(function(k) {
      var c = document.createElement('ul');
      var h = document.createElement('span');
      var d = document.createElement('div');

      d.className = 'gui-generic-double-padded';
      h.appendChild(document.createTextNode(_(_groups[k].label)));

      containers[k] = c;

      d.appendChild(h);
      d.appendChild(c);
      container.appendChild(d);
    });

    app.modules.forEach(function(m) {
      if ( containers[m.group] ) {
        var i = document.createElement('img');
        i.setAttribute('src', API.getIcon(m.icon, '32x32'));
        i.setAttribute('title', m.name);

        var s = document.createElement('span');
        s.appendChild(document.createTextNode(_(m.label || m.name)));

        var c = document.createElement('li');
        c.className = 'gui-generic-hoverable';
        c.setAttribute('data-module', String(m.name));
        c.appendChild(i);
        c.appendChild(s);

        containers[m.group].appendChild(c);

        root.querySelector('[data-module="' + m.name +  '"]').className  = 'gui-generic-padded';

        var settings = Utils.cloneObject(wm.getSettings());
        m.render(self, scheme, tmpcontent, settings, wm);
        m.update(self, scheme, settings, wm);
        m._inited = true;
      }
    });

    Object.keys(containers).forEach(function(k) {
      if ( !containers[k].children.length ) {
        containers[k].parentNode.style.display = 'none';
      }
    });

    Utils.$bind(container, 'click', function(ev) {
      var t = ev.isTrusted ? ev.target : (ev.relatedTarget || ev.target);
      if ( t && t.tagName === 'LI' && t.hasAttribute('data-module') ) {
        ev.preventDefault();
        var m = t.getAttribute('data-module');
        self.onModuleSelect(m);
      }
    }, true);

    root.querySelector('[data-id="ContainerSelection"]').appendChild(container);

    containers = {};
    tmpcontent = null;

    return root;
  };

  ApplicationSettingsWindow.prototype.destroy = function() {
    // This is where you remove objects, dom elements etc attached to your
    // instance. You can remove this if not used.
    if ( Window.prototype.destroy.apply(this, arguments) ) {
      this.currentModule = null;

      return true;
    }
    return false;
  };

  ApplicationSettingsWindow.prototype.onWindowInited = function(modules, cat) {
    this.onExternalAttention(cat);
  };

  ApplicationSettingsWindow.prototype.onModuleSelect = function(name) {
    var wm = OSjs.Core.getWindowManager();
    var root = this._$element;
    var self = this;

    function _d(d) {
      root.querySelector('[data-id="ContainerSelection"]').style.display = d ? 'block' : 'none';
      root.querySelector('[data-id="ContainerContent"]').style.display = d ? 'none' : 'block';
      root.querySelector('[data-id="ContainerButtons"]').style.display = d ? 'none' : 'block';
    }

    root.querySelectorAll('div[data-module]').forEach(function(mod) {
      mod.style.display = 'none';
    });

    _d(true);

    this._setTitle(null);

    var found;
    if ( name ) {
      this._app.modules.forEach(function(m) {
        if ( !found && m.name === name ) {
          found = m;
        }
      });
    }

    if ( found ) {
      var mod = root.querySelector('div[data-module="' + found.name +  '"]');
      if ( mod ) {
        mod.style.display = 'block';
        var settings = Utils.cloneObject(wm.getSettings());
        found.update(this, this._scheme, settings, wm, true);

        _d(false);
        this._setTitle(found.name, true);

        if ( found.button === false ) {
          this._find('ButtonOK').hide();
        } else {
          this._find('ButtonOK').show();
        }
      }
    } else {
      if ( !name ) { // Resets values to original (or current)
        var settings = Utils.cloneObject(wm.getSettings());
        this._app.modules.forEach(function(m) {
          if ( m._inited ) {
            m.update(self, self._scheme, settings, wm);
          }
        });
      }
    }

    this._app.setModule(found);
  };

  ApplicationSettingsWindow.prototype.onButtonOK = function() {
    var self = this;
    var settings = {};
    var wm = OSjs.Core.getWindowManager();
    var saves = [];

    this._app.modules.forEach(function(m) {
      if ( m._inited ) {
        var res = m.save(self, self._scheme, settings, wm);
        if ( typeof res === 'function' ) {
          saves.push(res);
        }
      }
    });

    this._toggleLoading(true);
    this._app.saveSettings(settings, saves, function() {
      self._toggleLoading(false);
    });
  };

  ApplicationSettingsWindow.prototype.onButtonCancel = function() {
    this.onModuleSelect(null);
  };

  ApplicationSettingsWindow.prototype.onExternalAttention = function(cat) {
    this.onModuleSelect(categoryMap[cat] || cat);
    this._focus();
  };

  /////////////////////////////////////////////////////////////////////////////
  // APPLICATION
  /////////////////////////////////////////////////////////////////////////////

  function ApplicationSettings(args, metadata) {
    Application.apply(this, ['ApplicationSettings', args, metadata]);

    var self = this;
    var registered = OSjs.Applications.ApplicationSettings.Modules;

    this.watches = {};
    this.currentModule = null;

    this.modules = Object.keys(registered).map(function(name) {
      var opts = Utils.argumentDefaults(registered[name], {
        _inited: false,
        name: name,
        group: DEFAULT_GROUP,
        icon: 'status/error.png',
        init: function() {},
        update: function() {},
        render: function() {},
        save: function() {}
      });

      if ( Object.keys(_groups).indexOf(opts.group) === -1 ) {
        opts.group = DEFAULT_GROUP;
      }

      Object.keys(opts).forEach(function(k) {
        if ( typeof opts[k] === 'function' ) {
          opts[k] = opts[k].bind(opts);
        }
      });

      return opts;
    });

    this.modules.forEach(function(m) {
      m.init(self);

      if ( m.watch ) {
        m.watch.forEach(function(w) {
          self.watches[m.name] = OSjs.Core.getSettingsManager().watch(w, function() {
            var win = self._getMainWindow();
            if ( m && win ) {
              if ( self.currentModule && self.currentModule.name === m.name ) {
                win.onModuleSelect(m.name);
              }
            }
          });
        });
      }
    });
  }

  ApplicationSettings.prototype = Object.create(Application.prototype);
  ApplicationSettings.constructor = Application;

  ApplicationSettings.prototype.destroy = function() {
    // This is where you remove objects, dom elements etc attached to your
    // instance. You can remove this if not used.
    if ( Application.prototype.destroy.apply(this, arguments) ) {

      var self = this;
      Object.keys(this.watches).forEach(function(k) {
        OSjs.Core.getSettingsManager().unwatch(self.watches[k]);
      });
      this.watches = {};

      return true;
    }
    return false;
  };

  ApplicationSettings.prototype.init = function(settings, metadata, scheme) {
    Application.prototype.init.apply(this, arguments);

    var self = this;
    var win = this._addWindow(new ApplicationSettingsWindow(this, metadata, scheme));
    var category = this._getArgument('category') || settings.category;

    win._on('inited', function() {
      win.onWindowInited(self.modules, category);
    });

    this._on('attention', function(args) {
      if ( win && args.category ) {
        win.onExternalAttention(args.category);
      }
    });
  };

  ApplicationSettings.prototype.saveSettings = function(settings, saves, cb) {
    var wm = OSjs.Core.getWindowManager();
    wm.applySettings(settings, false, function() {
      Utils.asyncs(saves, function(iter, idx, next) {
        iter(next);
      }, cb);
    }, false);
  };

  ApplicationSettings.prototype.setModule = function(m) {
    this.currentModule = m;
  };

  /////////////////////////////////////////////////////////////////////////////
  // EXPORTS
  /////////////////////////////////////////////////////////////////////////////

  OSjs.Applications = OSjs.Applications || {};
  OSjs.Applications.ApplicationSettings = OSjs.Applications.ApplicationSettings || {};
  OSjs.Applications.ApplicationSettings.Class = Object.seal(ApplicationSettings);
  OSjs.Applications.ApplicationSettings.Modules = OSjs.Applications.ApplicationSettings.Modules || {};

})(OSjs.Core.Application, OSjs.Core.Window, OSjs.Utils, OSjs.API, OSjs.VFS, OSjs.GUI);
<commit_msg>Settings: Prevent raising error when module watches are invalid (Closes #498)<commit_after>/*!
 * OS.js - JavaScript Cloud/Web Desktop Platform
 *
 * Copyright (c) 2011-2016, Anders Evenrud <andersevenrud@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author  Anders Evenrud <andersevenrud@gmail.com>
 * @licence Simplified BSD License
 */
(function(Application, Window, Utils, API, VFS, GUI) {
  'use strict';

  var DEFAULT_GROUP = 'misc';

  var _groups = {
    personal: {
      label: 'LBL_PERSONAL'
    },
    system: {
      label: 'LBL_SYSTEM'
    },
    user: {
      label: 'LBL_USER'
    },
    misc: {
      label: 'LBL_OTHER'
    }
  };

  var categoryMap = {
    'theme': 'Theme',
    'desktop': 'Desktop',
    'panel': 'Panel',
    'user': 'User',
    'fileview': 'VFS',
    'search': 'Search'
  };

  /////////////////////////////////////////////////////////////////////////////
  // WINDOWS
  /////////////////////////////////////////////////////////////////////////////

  function ApplicationSettingsWindow(app, metadata, scheme) {
    Window.apply(this, ['ApplicationSettingsWindow', {
      icon: metadata.icon,
      title: metadata.name,
      width: 500,
      height: 450,
      allow_resize: true
    }, app, scheme]);
  }

  ApplicationSettingsWindow.prototype = Object.create(Window.prototype);
  ApplicationSettingsWindow.constructor = Window.prototype;

  ApplicationSettingsWindow.prototype.init = function(wmRef, app, scheme) {
    var self = this;
    var root = Window.prototype.init.apply(this, arguments);
    var wm = OSjs.Core.getWindowManager();
    var _ = OSjs.Applications.ApplicationSettings._;

    // Load and render `scheme.html` file
    scheme.render(this, 'SettingsWindow', root, null, null, {_: _});

    this._find('ButtonOK').son('click', this, this.onButtonOK);
    this._find('ButtonCancel').son('click', this, this.onButtonCancel);

    // Adds all groups and their respective entries
    var container = document.createElement('div');
    container.className = 'ListView gui-generic-zebra-container';

    var containers = {};
    var tmpcontent = document.createDocumentFragment();

    Object.keys(_groups).forEach(function(k) {
      var c = document.createElement('ul');
      var h = document.createElement('span');
      var d = document.createElement('div');

      d.className = 'gui-generic-double-padded';
      h.appendChild(document.createTextNode(_(_groups[k].label)));

      containers[k] = c;

      d.appendChild(h);
      d.appendChild(c);
      container.appendChild(d);
    });

    app.modules.forEach(function(m) {
      if ( containers[m.group] ) {
        var i = document.createElement('img');
        i.setAttribute('src', API.getIcon(m.icon, '32x32'));
        i.setAttribute('title', m.name);

        var s = document.createElement('span');
        s.appendChild(document.createTextNode(_(m.label || m.name)));

        var c = document.createElement('li');
        c.className = 'gui-generic-hoverable';
        c.setAttribute('data-module', String(m.name));
        c.appendChild(i);
        c.appendChild(s);

        containers[m.group].appendChild(c);

        root.querySelector('[data-module="' + m.name +  '"]').className  = 'gui-generic-padded';

        var settings = Utils.cloneObject(wm.getSettings());
        m.render(self, scheme, tmpcontent, settings, wm);
        m.update(self, scheme, settings, wm);
        m._inited = true;
      }
    });

    Object.keys(containers).forEach(function(k) {
      if ( !containers[k].children.length ) {
        containers[k].parentNode.style.display = 'none';
      }
    });

    Utils.$bind(container, 'click', function(ev) {
      var t = ev.isTrusted ? ev.target : (ev.relatedTarget || ev.target);
      if ( t && t.tagName === 'LI' && t.hasAttribute('data-module') ) {
        ev.preventDefault();
        var m = t.getAttribute('data-module');
        self.onModuleSelect(m);
      }
    }, true);

    root.querySelector('[data-id="ContainerSelection"]').appendChild(container);

    containers = {};
    tmpcontent = null;

    return root;
  };

  ApplicationSettingsWindow.prototype.destroy = function() {
    // This is where you remove objects, dom elements etc attached to your
    // instance. You can remove this if not used.
    if ( Window.prototype.destroy.apply(this, arguments) ) {
      this.currentModule = null;

      return true;
    }
    return false;
  };

  ApplicationSettingsWindow.prototype.onWindowInited = function(modules, cat) {
    this.onExternalAttention(cat);
  };

  ApplicationSettingsWindow.prototype.onModuleSelect = function(name) {
    var wm = OSjs.Core.getWindowManager();
    var root = this._$element;
    var self = this;

    function _d(d) {
      root.querySelector('[data-id="ContainerSelection"]').style.display = d ? 'block' : 'none';
      root.querySelector('[data-id="ContainerContent"]').style.display = d ? 'none' : 'block';
      root.querySelector('[data-id="ContainerButtons"]').style.display = d ? 'none' : 'block';
    }

    root.querySelectorAll('div[data-module]').forEach(function(mod) {
      mod.style.display = 'none';
    });

    _d(true);

    this._setTitle(null);

    var found;
    if ( name ) {
      this._app.modules.forEach(function(m) {
        if ( !found && m.name === name ) {
          found = m;
        }
      });
    }

    if ( found ) {
      var mod = root.querySelector('div[data-module="' + found.name +  '"]');
      if ( mod ) {
        mod.style.display = 'block';
        var settings = Utils.cloneObject(wm.getSettings());
        found.update(this, this._scheme, settings, wm, true);

        _d(false);
        this._setTitle(found.name, true);

        if ( found.button === false ) {
          this._find('ButtonOK').hide();
        } else {
          this._find('ButtonOK').show();
        }
      }
    } else {
      if ( !name ) { // Resets values to original (or current)
        var settings = Utils.cloneObject(wm.getSettings());
        this._app.modules.forEach(function(m) {
          if ( m._inited ) {
            m.update(self, self._scheme, settings, wm);
          }
        });
      }
    }

    this._app.setModule(found);
  };

  ApplicationSettingsWindow.prototype.onButtonOK = function() {
    var self = this;
    var settings = {};
    var wm = OSjs.Core.getWindowManager();
    var saves = [];

    this._app.modules.forEach(function(m) {
      if ( m._inited ) {
        var res = m.save(self, self._scheme, settings, wm);
        if ( typeof res === 'function' ) {
          saves.push(res);
        }
      }
    });

    this._toggleLoading(true);
    this._app.saveSettings(settings, saves, function() {
      self._toggleLoading(false);
    });
  };

  ApplicationSettingsWindow.prototype.onButtonCancel = function() {
    this.onModuleSelect(null);
  };

  ApplicationSettingsWindow.prototype.onExternalAttention = function(cat) {
    this.onModuleSelect(categoryMap[cat] || cat);
    this._focus();
  };

  /////////////////////////////////////////////////////////////////////////////
  // APPLICATION
  /////////////////////////////////////////////////////////////////////////////

  function ApplicationSettings(args, metadata) {
    Application.apply(this, ['ApplicationSettings', args, metadata]);

    var self = this;
    var registered = OSjs.Applications.ApplicationSettings.Modules;

    this.watches = {};
    this.currentModule = null;

    this.modules = Object.keys(registered).map(function(name) {
      var opts = Utils.argumentDefaults(registered[name], {
        _inited: false,
        name: name,
        group: DEFAULT_GROUP,
        icon: 'status/error.png',
        init: function() {},
        update: function() {},
        render: function() {},
        save: function() {}
      });

      if ( Object.keys(_groups).indexOf(opts.group) === -1 ) {
        opts.group = DEFAULT_GROUP;
      }

      Object.keys(opts).forEach(function(k) {
        if ( typeof opts[k] === 'function' ) {
          opts[k] = opts[k].bind(opts);
        }
      });

      return opts;
    });

    this.modules.forEach(function(m) {
      m.init(self);

      if ( m.watch && m.watch instanceof Array ) {
        m.watch.forEach(function(w) {
          self.watches[m.name] = OSjs.Core.getSettingsManager().watch(w, function() {
            var win = self._getMainWindow();
            if ( m && win ) {
              if ( self.currentModule && self.currentModule.name === m.name ) {
                win.onModuleSelect(m.name);
              }
            }
          });
        });
      }
    });
  }

  ApplicationSettings.prototype = Object.create(Application.prototype);
  ApplicationSettings.constructor = Application;

  ApplicationSettings.prototype.destroy = function() {
    // This is where you remove objects, dom elements etc attached to your
    // instance. You can remove this if not used.
    if ( Application.prototype.destroy.apply(this, arguments) ) {

      var self = this;
      Object.keys(this.watches).forEach(function(k) {
        OSjs.Core.getSettingsManager().unwatch(self.watches[k]);
      });
      this.watches = {};

      return true;
    }
    return false;
  };

  ApplicationSettings.prototype.init = function(settings, metadata, scheme) {
    Application.prototype.init.apply(this, arguments);

    var self = this;
    var win = this._addWindow(new ApplicationSettingsWindow(this, metadata, scheme));
    var category = this._getArgument('category') || settings.category;

    win._on('inited', function() {
      win.onWindowInited(self.modules, category);
    });

    this._on('attention', function(args) {
      if ( win && args.category ) {
        win.onExternalAttention(args.category);
      }
    });
  };

  ApplicationSettings.prototype.saveSettings = function(settings, saves, cb) {
    var wm = OSjs.Core.getWindowManager();
    wm.applySettings(settings, false, function() {
      Utils.asyncs(saves, function(iter, idx, next) {
        iter(next);
      }, cb);
    }, false);
  };

  ApplicationSettings.prototype.setModule = function(m) {
    this.currentModule = m;
  };

  /////////////////////////////////////////////////////////////////////////////
  // EXPORTS
  /////////////////////////////////////////////////////////////////////////////

  OSjs.Applications = OSjs.Applications || {};
  OSjs.Applications.ApplicationSettings = OSjs.Applications.ApplicationSettings || {};
  OSjs.Applications.ApplicationSettings.Class = Object.seal(ApplicationSettings);
  OSjs.Applications.ApplicationSettings.Modules = OSjs.Applications.ApplicationSettings.Modules || {};

})(OSjs.Core.Application, OSjs.Core.Window, OSjs.Utils, OSjs.API, OSjs.VFS, OSjs.GUI);
<|endoftext|>


<commit_before>export default datastore => {
  datastore.watch(state => state.currentGroup.id, currentGroupId => {
    if (!currentGroupId) return
    datastore.dispatch('pickups/fetchListByGroupId', currentGroupId, { root: true })
    datastore.dispatch('pickups/fetchFeedbackPossible', currentGroupId, { root: true })
  }, { immediate: true })

  datastore.watch((state, getters) => getters['auth/isLoggedIn'], isLoggedIn => {
    if (!isLoggedIn) {
      datastore.dispatch('pickups/clear')
    }
  })
}
<commit_msg>fix pickup clear on logout<commit_after>export default datastore => {
  datastore.watch(state => state.currentGroup.id, currentGroupId => {
    if (!currentGroupId) return
    datastore.dispatch('pickups/fetchListByGroupId', currentGroupId, { root: true })
    datastore.dispatch('pickups/fetchFeedbackPossible', currentGroupId, { root: true })
  }, { immediate: true })

  datastore.watch((state, getters) => getters['auth/isLoggedIn'], isLoggedIn => {
    if (!isLoggedIn) {
      datastore.commit('pickups/clear')
    }
  })
}
<|endoftext|>


<commit_before>'use strict';

var gulp        = require('gulp'),
    browserSync = require('browser-sync'),
    config      = require('../config'),
    reload      = browserSync.reload;

gulp.task('watch', function() {
  gulp.watch(config.path.html.all, ['html']);
  gulp.watch(config.path.src + 'php/*.*', ['copy']);
  gulp.watch(config.path.src + 'fav/*.*', ['copy']);
  gulp.watch(config.path.css.all, ['styles']);
  gulp.watch(config.path.img.all, ['images']);
  gulp.watch(config.path.src + 'fonts/**/*.*', ['copy']);
  gulp.watch(config.path.js.all, ['scripts']);
});
<commit_msg>Add ES6<commit_after>'use strict';

import gulp from 'gulp';
import browserSync from 'browser-sync';
import config from '../config';
import {reload} from 'browser-sync';

gulp.task('watch', function() {
  gulp.watch(config.path.html.all, ['html']);
  gulp.watch(config.path.src + 'php/*.*', ['copy']);
  gulp.watch(config.path.src + 'fav/*.*', ['copy']);
  gulp.watch(config.path.css.all, ['styles']);
  gulp.watch(config.path.img.all, ['images']);
  gulp.watch(config.path.src + 'fonts/**/*.*', ['copy']);
  gulp.watch(config.path.js.all, ['scripts']);
});
<|endoftext|>


<commit_before>var FixCategoryHeight = (function () {
    function setHeight() {
        $(".category-page-category-list-wrapper").each(function () {
            var ele = $(this),
                maxHHeight = 0,
                maxPHeight = 0;

            ele.find('h4').each(function () {
                if (maxHHeight < $(this).innerHeight()) {
                    maxHHeight = $(this).innerHeight();
                }
            });

            ele.find('p').each(function () {
                if (maxPHeight < $(this).innerHeight()) {
                    maxPHeight = $(this).innerHeight();
                }
            });

            ele.find('h4').each(function () {
                $(this).css("height", maxHHeight + "px");
            });
            ele.find('p').each(function () {
                $(this).css("height", maxPHeight + "px");
            });
        });
    }

    return {
        init: function () {
            setHeight();
        }
    };
})();

var FixCarousalHeight = (function () {
    function setHeight() {
        var featureListHeight = $(".featured-list").innerHeight();
        $(".fill-image").css("height", featureListHeight);
    }

    function trigger() {
        if ($(".featured-list").length >0 && $(".featured-list").offset().left > 200) {
            setHeight();
        }
    }

    return{
        init: function () {
            trigger();
        }
    }
})();

var PageEventsList = (function () {
    function resizeHandler() {
        FixCarousalHeight.init();
    }

    return {
        init: function () {
            $(window).resize(function () {
                resizeHandler();
            });
        }
    }
})();

var LoadMoreCallback = (function(jq){
    function callback(){
         jq.endlessPaginate({
            onCompleted:function(){
                FixCategoryHeight.init();
            }
        });
        jq.endlessPaginate();
    }
    return{
        init: function(){
            callback();
        }
    };
})($);

var CategoryHeightFix = (function(){
    function setHeight(){
        var maxLIHeight = 0;
        $("#category-list li").each(function () {
            if (maxLIHeight < $(this).innerHeight()) {
                maxLIHeight = $(this).innerHeight();
            }
        });
        $("#category-list li").each(function () {
            $(this).css("height", maxLIHeight + "px");
        });
    }
    return{
        init : function(){
            setHeight();
        }
    }
})();

var SetPageSeparatorBar  = (function(){
    function setIt(){
        if($(".right-section").length > 0 && $(".right-section").offset().top > 200 )
            return;
        if($(".left-section").innerHeight() < $(".right-section").innerHeight()){
            $(".left-section").removeClass("right-border-separator");
            $(".right-section").addClass("left-border-separator");
        }
        else{
            $(".left-section").addClass("right-border-separator");
            $(".right-section").removeClass("left-border-separator");
        }
    }
    return{
        init: function(){
            setIt();
        }
    }
})();

var CommentsUI = (function(){
    function bindEvent(){
        $("#addNewCommentBtn").click(function(){
            $("#addNewCommentsFormWrapper").toggle("fast");
        });
    }
    function setLevels(){
        var buckets = [];
        function hasElement(num){
            for(var i=0; i< buckets.length; i++){
                if(buckets[i] === num)
                return true;
            }
            return false;
        }

        function getIndex(num){
            for(var i=0; i< buckets.length; i++){
                if(buckets[i] == num)
                return i;
            }
        }

        function getBuckets(){
            $("#comments ul").each(function(index){
                var value = $(this).offset().left;
                if(!hasElement(value)){
                    buckets.push(value);
                }
            });

            buckets.sort(function(a, b){
                return a > b;
            });
        }

        function setLevelClasses(){
            $("#comments ul").each(function(index){
                var value = $(this).offset().left;
                var index = getIndex(value);
                $(this).attr("data-level", index);
            });
        }
        function applyLevelClass(){
            $("#comments ul").each(function(index){
                var value = $(this).attr("data-level")
                if(value > 2)
                    $(this).addClass("dont-style");
            });

        }

        getBuckets();
        setLevelClasses();
        applyLevelClass();
    }
    return {
        init: function(){
            try{
                bindEvent();
                setLevels();
            }catch(e){}
        }
    }
})();

var LanguageSelection = (function(){

    function submitForm(){
        $("#langaugeSelection label").click(function(){
            $("#languageHiddenElement").val($(this).find("input").val());
            $("#languageHiddenElement").closest("form").submit();
        });
    }
    return {
        init: function(){
            submitForm();
        }
    }
})();

var CollapseDescription = (function(){
    var wrapper = $(".category-description");

    function showHideBinding(){
        $(".category-description p.short a").click(function(){
            $(".category-description p.short").hide();
            $(".category-description p.long").show();
        });

        $(".category-description p.long a").click(function(){
            $(".category-description p.long").hide();
            $(".category-description p.short").show();
        });
    }

    return {
        init : function(){
            showHideBinding();
        }
    }
})();

$(document).ready(function () {
    $('a#feature-article').hover(function () {
        $(this).find('p').toggle();
    });

    PageEventsList.init();
    LoadMoreCallback.init();
    LanguageSelection.init();
    CollapseDescription.init();
});

$(window).load(function () {
    FixCategoryHeight.init();
    FixCarousalHeight.init();
    CategoryHeightFix.init();
    SetPageSeparatorBar.init();
    CommentsUI.init();
});
<commit_msg>[Anil] fixed category height by adjusting the text in header<commit_after>var FixCategoryHeight = (function () {
    function setHeight() {
        $(".category-page-category-list-wrapper").each(function () {
            var ele = $(this),
                maxHHeight = 0,
                maxPHeight = 0,
                maxAHeight = 0;

            ele.find('h4').each(function () {
                if (maxHHeight < $(this).innerHeight()) {
                    maxHHeight = $(this).innerHeight();
                }
            });

            ele.find('p').each(function () {
                if (maxPHeight < $(this).innerHeight()) {
                    maxPHeight = $(this).innerHeight();
                }
            });

            ele.find('.category-title-wrapper').each(function () {
                if (maxAHeight < $(this).innerHeight()) {
                    maxAHeight = $(this).innerHeight();
                }
            });

            ele.find('h4').each(function () {
                $(this).css("height", maxHHeight + "px");
            });
            ele.find('p').each(function () {
                $(this).css("height", maxAHeight + "px");
            });
            ele.find('.category-title-wrapper').each(function () {
                $(this).css("height", maxAHeight + "px");
            });
        });
    }

    return {
        init: function () {
            setHeight();
        }
    };
})();

var FixCarousalHeight = (function () {
    function setHeight() {
        var featureListHeight = $(".featured-list").innerHeight();
        $(".fill-image").css("height", featureListHeight);
    }

    function trigger() {
        if ($(".featured-list").length >0 && $(".featured-list").offset().left > 200) {
            setHeight();
        }
    }

    return{
        init: function () {
            trigger();
        }
    }
})();

var PageEventsList = (function () {
    function resizeHandler() {
        FixCarousalHeight.init();
    }

    return {
        init: function () {
            $(window).resize(function () {
                resizeHandler();
            });
        }
    }
})();

var LoadMoreCallback = (function(jq){
    function callback(){
         jq.endlessPaginate({
            onCompleted:function(){
                FixCategoryHeight.init();
            }
        });
        jq.endlessPaginate();
    }
    return{
        init: function(){
            callback();
        }
    };
})($);

var CategoryHeightFix = (function(){
    function setHeight(){
        var maxLIHeight = 0;
        $("#category-list li").each(function () {
            if (maxLIHeight < $(this).innerHeight()) {
                maxLIHeight = $(this).innerHeight();
            }
        });
        $("#category-list li").each(function () {
            $(this).css("height", maxLIHeight + "px");
        });
    }
    return{
        init : function(){
            setHeight();
        }
    }
})();

var SetPageSeparatorBar  = (function(){
    function setIt(){
        if($(".right-section").length > 0 && $(".right-section").offset().top > 200 )
            return;
        if($(".left-section").innerHeight() < $(".right-section").innerHeight()){
            $(".left-section").removeClass("right-border-separator");
            $(".right-section").addClass("left-border-separator");
        }
        else{
            $(".left-section").addClass("right-border-separator");
            $(".right-section").removeClass("left-border-separator");
        }
    }
    return{
        init: function(){
            setIt();
        }
    }
})();

var CommentsUI = (function(){
    function bindEvent(){
        $("#addNewCommentBtn").click(function(){
            $("#addNewCommentsFormWrapper").toggle("fast");
        });
    }
    function setLevels(){
        var buckets = [];
        function hasElement(num){
            for(var i=0; i< buckets.length; i++){
                if(buckets[i] === num)
                return true;
            }
            return false;
        }

        function getIndex(num){
            for(var i=0; i< buckets.length; i++){
                if(buckets[i] == num)
                return i;
            }
        }

        function getBuckets(){
            $("#comments ul").each(function(index){
                var value = $(this).offset().left;
                if(!hasElement(value)){
                    buckets.push(value);
                }
            });

            buckets.sort(function(a, b){
                return a > b;
            });
        }

        function setLevelClasses(){
            $("#comments ul").each(function(index){
                var value = $(this).offset().left;
                var index = getIndex(value);
                $(this).attr("data-level", index);
            });
        }
        function applyLevelClass(){
            $("#comments ul").each(function(index){
                var value = $(this).attr("data-level")
                if(value > 2)
                    $(this).addClass("dont-style");
            });

        }

        getBuckets();
        setLevelClasses();
        applyLevelClass();
    }
    return {
        init: function(){
            try{
                bindEvent();
                setLevels();
            }catch(e){}
        }
    }
})();

var LanguageSelection = (function(){

    function submitForm(){
        $("#langaugeSelection label").click(function(){
            $("#languageHiddenElement").val($(this).find("input").val());
            $("#languageHiddenElement").closest("form").submit();
        });
    }
    return {
        init: function(){
            submitForm();
        }
    }
})();

var CollapseDescription = (function(){
    var wrapper = $(".category-description");

    function showHideBinding(){
        $(".category-description p.short a").click(function(){
            $(".category-description p.short").hide();
            $(".category-description p.long").show();
        });

        $(".category-description p.long a").click(function(){
            $(".category-description p.long").hide();
            $(".category-description p.short").show();
        });
    }

    return {
        init : function(){
            showHideBinding();
        }
    }
})();

$(document).ready(function () {
    $('a#feature-article').hover(function () {
        $(this).find('p').toggle();
    });

    PageEventsList.init();
    LoadMoreCallback.init();
    LanguageSelection.init();
    CollapseDescription.init();
});

$(window).load(function () {
    FixCategoryHeight.init();
    FixCarousalHeight.init();
    CategoryHeightFix.init();
    SetPageSeparatorBar.init();
    CommentsUI.init();
});
<|endoftext|>


<commit_before>/**
 * @file Contains functions related to the creation of the data pipelines used
 * by this importer, like record streams for OpenAddresses files and the
 * elasticsearch sink.
 */

'use strict';

var fs = require( 'fs' );
var csvParse = require( 'csv-parse' );
var through = require( 'through2' );
var logger = require( 'pelias-logger' ).get( 'openaddresses' );
var peliasModel = require( 'pelias-model' );
var peliasDbclient = require( 'pelias-dbclient' );
var cleanup = require( './cleanup' );

function isValidCsvRecord( record ){
  return [ 'LON', 'LAT', 'NUMBER', 'STREET' ].every(function(prop) {
    return record[ prop ].length > 0;
  });
}

/**
 * Used to track the UID of individual records passing through the stream
 * created by `createRecordStream()`. Not bothering with a closure for
 * readability. See `peliasModel.Document.setId()` for information about UIDs.
 */
var uid = 0;

/**
 * Create a stream of Documents from an OpenAddresses file.
 *
 * @param {string} filePath The path of an OpenAddresses CSV file.
 * @return {stream.Readable} A stream of `Document` objects, one
 *    for every valid record inside the OA file.
 */
function createRecordStream( filePath ){
  /**
   * A stream to convert rows of a CSV to Document objects.
   */
  var numberBadRecords = 0;
  var intervalId = setInterval( function (){
    logger.verbose( 'Number of bad records: ' + numberBadRecords );
  }, 10000 );

  var documentCreator = through.obj(
    function write( record, enc, next ){
      if( isValidCsvRecord( record ) ){
        var model_id = ( uid++ ).toString();
        var addrDoc;
        try {
          var streetName = cleanup.streetName( record.STREET );
          addrDoc = new peliasModel.Document( 'openaddresses', model_id )
            .setName( 'default', (record.NUMBER + ' ' + streetName).replace(/ +/g, ' ') )
            .setCentroid( { lon: record.LON, lat: record.LAT } );

          try {
            addrDoc.setAddress( 'number', record.NUMBER );
          } catch ( ex ) {}

          try {
            addrDoc.setAddress( 'street', streetName );
          } catch ( ex ) {}

          try {
            addrDoc.setAddress( 'zip', record.POSTCODE );
          } catch ( ex ) {}
        }
        catch ( ex ){
          numberBadRecords++;
        }

        if( addrDoc !== undefined ){
          addrDoc.phrase = addrDoc.name;
          this.push( addrDoc );
        }
      }
      next();
    },
    function end( done ){
      clearInterval( intervalId );
      done();
    }
  );

  var csvParser = csvParse({
    trim: true,
    skip_empty_lines: true,
    relax: true,
    columns: true
  });
  return fs.createReadStream( filePath )
    .pipe( csvParser )
    .pipe( documentCreator );
}

/**
 * Create the Pelias elasticsearch import pipeline.
 *
 * @return {stream.Writable} The entry point to the elasticsearch pipeline,
 *    which will perform additional processing on inbound `Document` objects
 *    before indexing them in the elasticsearch pelias index.
 */
function createPeliasElasticsearchPipeline(){
  var dbclientMapper = through.obj( function( model, enc, next ){
    this.push({
      _index: 'pelias',
      _type: model.getType(),
      _id: model.getId(),
      data: model
    });
    next();
  });

  var entryPoint = dbclientMapper;
  entryPoint.pipe( peliasDbclient() );

  return entryPoint;
}

module.exports = {
  createRecordStream: createRecordStream,
  createPeliasElasticsearchPipeline: createPeliasElasticsearchPipeline,
  isValidCsvRecord: isValidCsvRecord
};
<commit_msg>Extract invalid record filtering into its own stream<commit_after>/**
 * @file Contains functions related to the creation of the data pipelines used
 * by this importer, like record streams for OpenAddresses files and the
 * elasticsearch sink.
 */

'use strict';

var fs = require( 'fs' );
var csvParse = require( 'csv-parse' );
var through = require( 'through2' );
var logger = require( 'pelias-logger' ).get( 'openaddresses' );
var peliasModel = require( 'pelias-model' );
var peliasDbclient = require( 'pelias-dbclient' );
var cleanup = require( './cleanup' );

/*
 * Return true if a record has all of LON, LAT, NUMBER and STREET defined
 */
function isValidCsvRecord( record ){
  return [ 'LON', 'LAT', 'NUMBER', 'STREET' ].every(function(prop) {
    return record[ prop ].length > 0;
  });
}

/*
 * Create a through2 stream to filter out invalid records
 */
function createValidRecordFilterStream() {
  return through.obj(function( record, enc, next ) {
    if (isValidCsvRecord(record)) {
      this.push(record);
    }
    next();
  });
}

/**
 * Used to track the UID of individual records passing through the stream
 * created by `createRecordStream()`. Not bothering with a closure for
 * readability. See `peliasModel.Document.setId()` for information about UIDs.
 */
var uid = 0;

/**
 * Create a stream of Documents from an OpenAddresses file.
 *
 * @param {string} filePath The path of an OpenAddresses CSV file.
 * @return {stream.Readable} A stream of `Document` objects, one
 *    for every valid record inside the OA file.
 */
function createRecordStream( filePath ){
  /**
   * A stream to convert rows of a CSV to Document objects.
   */
  var numberBadRecords = 0;
  var intervalId = setInterval( function (){
    logger.verbose( 'Number of bad records: ' + numberBadRecords );
  }, 10000 );

  var documentCreator = through.obj(
    function write( record, enc, next ){
      var model_id = ( uid++ ).toString();
      var addrDoc;
      try {
        var streetName = cleanup.streetName( record.STREET );
        addrDoc = new peliasModel.Document( 'openaddresses', model_id )
        .setName( 'default', (record.NUMBER + ' ' + streetName).replace(/ +/g, ' ') )
        .setCentroid( { lon: record.LON, lat: record.LAT } );

        try {
          addrDoc.setAddress( 'number', record.NUMBER );
        } catch ( ex ) {}

        try {
          addrDoc.setAddress( 'street', streetName );
        } catch ( ex ) {}

        try {
          addrDoc.setAddress( 'zip', record.POSTCODE );
        } catch ( ex ) {}
      }
      catch ( ex ){
        numberBadRecords++;
      }

      if( addrDoc !== undefined ){
        addrDoc.phrase = addrDoc.name;
        this.push( addrDoc );
      }
      next();
    },
    function end( done ){
      clearInterval( intervalId );
      done();
    }
  );

  var csvParser = csvParse({
    trim: true,
    skip_empty_lines: true,
    relax: true,
    columns: true
  });

  var validRecordFilterStream = createValidRecordFilterStream();

  return fs.createReadStream( filePath )
    .pipe( csvParser )
    .pipe( validRecordFilterStream )
    .pipe( documentCreator );
}

/**
 * Create the Pelias elasticsearch import pipeline.
 *
 * @return {stream.Writable} The entry point to the elasticsearch pipeline,
 *    which will perform additional processing on inbound `Document` objects
 *    before indexing them in the elasticsearch pelias index.
 */
function createPeliasElasticsearchPipeline(){
  var dbclientMapper = through.obj( function( model, enc, next ){
    this.push({
      _index: 'pelias',
      _type: model.getType(),
      _id: model.getId(),
      data: model
    });
    next();
  });

  var entryPoint = dbclientMapper;
  entryPoint.pipe( peliasDbclient() );

  return entryPoint;
}

module.exports = {
  createRecordStream: createRecordStream,
  createPeliasElasticsearchPipeline: createPeliasElasticsearchPipeline,
  isValidCsvRecord: isValidCsvRecord
};
<|endoftext|>


<commit_before>define(function () {
  return function (config, el, router, d) {
    var h2 = document.createElement("h2")
    h2.textContent = "Location: " + d.toString()
    el.appendChild(h2)

    getJSON("https://nominatim.openstreetmap.org/reverse?format=json&lat=" + d.lat + "&lon=" + d.lng + "&zoom=18&addressdetail=0")
    .then(function(result) {
      h2.textContent = result.display_name
    })

    var h3lat = document.createElement("h3")
    h3lat.textContent = "Breitengrad"
    el.appendChild(h3lat)
    var txt1 = document.createElement("textarea")
    txt1.id = "location-latitude"
    txt1.value = d.lat.toFixed(9)
    var p = document.createElement("p")
    p.appendChild(txt1)
    p.appendChild(createCopyButton(txt1.id))
    el.appendChild(p)

    var h3lng = document.createElement("h3")
    h3lng.textContent = "Längengrad"
    el.appendChild(h3lng)
    var txt2 = document.createElement("textarea")
    txt2.id = "location-longitude"
    txt2.value = d.lng.toFixed(9)
    var p2 = document.createElement("p")
    p2.appendChild(txt2)
    p2.appendChild(createCopyButton(txt2.id))
    el.appendChild(p2)

    var a1 = document.createElement("a")
    a1.textContent = "plain"
    a1.onclick = function() {
        switch2plain()
        return false
    }
    a1.href = config.siteURL
    var a2 = document.createElement("a")
    a2.textContent = "uci"
    a2.onclick = function() {
        switch2uci()
        return false
    }
    a2.href = config.siteURL

    var p3 = document.createElement("p")
    p3.textContent = "Du kannst zwischen "
    p3.appendChild(a1)
    var t1 = document.createTextNode(" und ")
    p3.appendChild(t1)
    p3.appendChild(a2)
    var t2 = document.createTextNode(" wechseln.")
    p3.appendChild(t2)
    el.appendChild(p3)

    function createCopyButton(id) {
        var btn = document.createElement("button")
        btn.className = "ion-ios-copy"
        btn.title = "Kopiere"
        btn.onclick = function() {
            copy2clip(id)
        }
        return btn
    }
    function copy2clip(id) {
        var copyTextarea = document.querySelector("#" + id)
        copyTextarea.select()
        try {
            var successful = document.execCommand("copy")
            var msg = successful ? "successful" : "unsuccessful"
            console.log("Copying text command was " + msg)
        } catch (err) {
            console.log("Oops, unable to copy")
        }
    }
    function switch2plain() {
    var box1 = document.getElementById("location-latitude")
    box1.value = d.lat.toFixed(9)
    var box2 = document.getElementById("location-longitude")
    box2.value = d.lng.toFixed(9)
    }
    function switch2uci() {
        var box1 = document.getElementById("location-latitude")
    box1.value = "uci set gluon-node-info.@location[0].latitude='" + d.lat.toFixed(9) + "'"
    var box2 = document.getElementById("location-longitude")
    box2.value = "uci set gluon-node-info.@location[0].longitude='" + d.lng.toFixed(9) + "'"
    }
  }
})
<commit_msg>infobox/location: show uci in one box<commit_after>define(function () {
  return function (config, el, router, d) {
    var h2 = document.createElement("h2")
    h2.textContent = "Location: " + d.toString()
    el.appendChild(h2)

    getJSON("https://nominatim.openstreetmap.org/reverse?format=json&lat=" + d.lat + "&lon=" + d.lng + "&zoom=18&addressdetail=0")
    .then(function(result) {
      h2.textContent = result.display_name
    })

    var latDiv = document.createElement("div")
    var h3lat = document.createElement("h3")
    h3lat.textContent = "Breitengrad"
    h3lat.id = "h3-latitude"
    latDiv.appendChild(h3lat)
    var txt1 = document.createElement("textarea")
    txt1.id = "location-latitude"
    txt1.value = d.lat.toFixed(9)
    var p = document.createElement("p")
    p.appendChild(txt1)
    p.appendChild(createCopyButton(txt1.id))
    latDiv.appendChild(p)
    el.appendChild(latDiv)

    var longDiv = document.createElement("div")
    var h3lng = document.createElement("h3")
    h3lng.textContent = "Längengrad"
    longDiv.appendChild(h3lng)
    var txt2 = document.createElement("textarea")
    txt2.id = "location-longitude"
    txt2.value = d.lng.toFixed(9)
    var p2 = document.createElement("p")
    p2.appendChild(txt2)
    p2.appendChild(createCopyButton(txt2.id))
    longDiv.appendChild(p2)
    longDiv.id = "div-longitude"
    el.appendChild(longDiv)

    var a1 = document.createElement("a")
    a1.textContent = "plain"
    a1.onclick = function() {
      switch2plain()
      return false
    }
    a1.href = config.siteURL
    var a2 = document.createElement("a")
    a2.textContent = "uci"
    a2.onclick = function() {
      switch2uci()
      return false
    }
    a2.href = "#"

    var p3 = document.createElement("p")
    p3.textContent = "Du kannst zwischen "
    p3.appendChild(a1)
    var t1 = document.createTextNode(" und ")
    p3.appendChild(t1)
    p3.appendChild(a2)
    var t2 = document.createTextNode(" wechseln.")
    p3.appendChild(t2)
    el.appendChild(p3)

    function createCopyButton(id) {
      var btn = document.createElement("button")
      btn.className = "ion-ios-copy"
      btn.title = "Kopieren"
      btn.onclick = function() {
        copy2clip(id)
      }
      return btn
    }

    function copy2clip(id) {
      var copyTextarea = document.querySelector("#" + id)
      copyTextarea.select()
      try {
        document.execCommand("copy")
      } catch (err) {
        console.log(err)
      }
    }

    function switch2plain() {
      var box1 = document.getElementById("location-latitude")
      box1.value = d.lat.toFixed(9)
      var box2 = document.getElementById("location-longitude")
      box2.value = d.lng.toFixed(9)
      document.getElementById("h3-latitude").textContent = "Breitengrad"
      document.getElementById("div-longitude").style.display = "block"
    }

    function switch2uci() {
      document.getElementById("location-latitude").value = "uci set gluon-node-info.@location[0].latitude='" + d.lat.toFixed(9) + "'; uci set gluon-node-info.@location[0].longitude='" + d.lng.toFixed(9) + "'"
      document.getElementById("h3-latitude").textContent = "Befehl"
      document.getElementById("div-longitude").style.display = "none"
    }
  }
})
<|endoftext|>


<commit_before>var base_input = require('../lib/base_input'),
  util = require('util'),
  logger = require('log4node');

// Require & Setup modules
var esl = require('modesl');

function InputESL() {
  base_input.BaseInput.call(this);
  this.mergeConfig(this.unserializer_config());
  this.mergeConfig({
    name: 'ESL',
    port_field: 'port',
    host_field: 'host',
    pass_field: 'pass',
    pass_wait: 'wait',
    optional_params: ['uuid'],
    start_hook: this.start,
  });
}

util.inherits(InputESL, base_input.BaseInput);

InputESL.prototype.start = function(callback) {
  this.port = this.parsed_url.params.port ? this.parsed_url.params.port : 8021;
  this.host = this.parsed_url.params.host ? this.parsed_url.params.host : '127.0.0.1';
  this.pass = this.parsed_url.params.pass ? this.parsed_url.params.pass : 'ClueCon';
  this.wait = this.parsed_url.params.wait ? this.parsed_url.params.wait : 60000;

  logger.info('Connecting ESL socket to '+this.host+':'+this.port);

  this.socket = new esl.Connection(this.host, this.port, this.pass)
  .on("error", function (error) {
      logger.info('ESL Connection Error ' + JSON.stringify(error));
      this.emit('error', error);
  }).on("esl::end", function (e) {
	logger.info('ESL Connection Ended from remote! Retrying in '+this.wait);
        setTimeout(function() { this.start(callback);}, this.wait);
  }).on("esl::ready", function (e) {
	logger.info('ESL Connected!');
  }).on("esl::event::**", function(e,headers,body) {
      // ESL event processing
      	console.log('Event: ' + e.getHeader('Event-Name'));
      	console.log('Unique-ID: ' + e.getHeader('Unique-ID'));
      	this.emit('event', e);
  }.bind(this));

  callback();

};

InputESL.prototype.close = function(callback) {
  logger.info('Closing ESL socket');
  try { this.socket.close(); } catch(err){ console.log('failed killing socket...'); };
  callback();
};

exports.create = function() {
  return new InputESL();
};

<commit_msg>Update input_esl.js<commit_after>var base_input = require('../lib/base_input'),
  util = require('util'),
  logger = require('log4node');

// Require & Setup modules
var esl = require('modesl');

function InputESL() {
  base_input.BaseInput.call(this);
  this.mergeConfig(this.unserializer_config());
  this.mergeConfig({
    name: 'ESL',
    port_field: 'port',
    host_field: 'host',
    pass_field: 'pass',
    wait_field: 'wait',
    optional_params: ['uuid'],
    start_hook: this.start
  });
}

util.inherits(InputESL, base_input.BaseInput);

InputESL.prototype.start = function(callback) {
  this.port = this.parsed_url.params.port ? this.parsed_url.params.port : 8021;
  this.host = this.parsed_url.params.host ? this.parsed_url.params.host : '127.0.0.1';
  this.pass = this.parsed_url.params.pass ? this.parsed_url.params.pass : 'ClueCon';
  this.wait = this.parsed_url.params.wait ? this.parsed_url.params.wait : 60000;

  logger.info('Connecting ESL socket to '+this.host+':'+this.port);

  this.socket = new esl.Connection(this.host, this.port, this.pass)
  .on("error", function (error) {
      logger.info('ESL Connection Error ' + JSON.stringify(error));
      this.emit('error', error);
  }).on("esl::end", function (e) {
	logger.info('ESL Connection Ended from remote! Retrying in '+this.wait);
        setTimeout(function() { this.start(callback);}, this.wait);
  }).on("esl::ready", function (e) {
	logger.info('ESL Connected!');
  }).on("esl::event::**", function(e,headers,body) {
      // ESL event processing
      	console.log('Event: ' + e.getHeader('Event-Name'));
      	console.log('Unique-ID: ' + e.getHeader('Unique-ID'));
      	this.emit('event', e);
  }.bind(this));

  callback();

};

InputESL.prototype.close = function(callback) {
  logger.info('Closing ESL socket');
  try { this.socket.close(); } catch(err){ console.log('failed killing socket...'); };
  callback();
};

exports.create = function() {
  return new InputESL();
};

<|endoftext|>