<commit_before>/*
 * Copyright (C) 2010 Chandra Sekar S
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var ghp = require('./ghp'),
    mime = require('./mime'),
    uuid = require('./uuid'),
    session = require('./session'),
    gh = require('./grasshopper'),
    fs = require('fs'),
    url = require('url'),
    sys = require('sys'),
    crypto = require('crypto');

var viewsDir = '.',
    defaultViewExtn = 'html',
    staticsDir = '.',
    defaultEncoding = 'utf8',
    layout = undefined;

exports.handleError = function(err, req, res, params) {
    if(params === undefined) {
        params={};
    }

    new RequestContext(req, res, params).handleError(err);
};

exports.configure = function(config) {
    if(config.viewsDir)
        viewsDir = config.viewsDir;
    if(config.defaultViewExtn)
        defaultViewExtn = config.defaultViewExtn;
    if(config.staticsDir)
        staticsDir = config.staticsDir;
    if(config.defaultEncoding)
        defaultEncoding = config.defaultEncoding;
    if(config.layout)
        layout = config.layout;
};

// Class: RequestContext
function RequestContext(request, response, params) {
    this.request = request;
    this.response = response;
    this.params = params;
    this.model = {};

    this.status = 200;
    this.extn = this.getExtn();
    this.encoding = defaultEncoding;
    this.headers = {
        'content-type': mime.mimes[this.extn]
                        ? mime.mimes[this.extn]
                        : 'application/octet-stream',
        'x-powered-by': 'Grasshopper/0.1-dev'
    };

    var cookieLine = request.headers['cookie'];
    if(cookieLine) {
        this.requestCookies = {};
        var cookies = cookieLine.split('; ');
        for(var i = 0; i < cookies.length; i++) {
            var cookieParts = cookies[i].split('=');
            if(cookieParts[0] == 'GHSESSION') {
                this.sessionId = decodeURIComponent(cookieParts[1]);
            } else {
                this.requestCookies[cookieParts[0]] = decodeURIComponent(cookieParts[1]);
            }
        }
    }
}

RequestContext.prototype.getExtn = function() {
    var extn = defaultViewExtn;
    var path = url.parse(this.request.url).pathname;
    if(path.match(/\.[^\/]+$/)) {
        extn = path.substring(path.lastIndexOf('.') + 1);
    }

    return extn;
};

RequestContext.prototype.addCookie = function(cookie) {
    var cookieLine = cookie.name + '=' + encodeURIComponent(cookie.value);
    cookieLine += cookie.path ? '; path=' + cookie.path : '';
    cookieLine += cookie.expires ? '; expires=' + cookie.expires : '';
    cookieLine += cookie.domain ? '; domain=' + cookie.domain : '';
    cookieLine += cookie.secure ? '; secure' : '';
    cookieLine += cookie.httpOnly ? '; HttpOnly' : '';

    if(this.headers['set-cookie']) {
        this.headers['set-cookie'] += '\r\nset-cookie: ' + cookieLine;
    } else {
        this.headers['set-cookie'] = cookieLine;
    }
};

RequestContext.prototype.render = function(view, useLayout) {
    if(view === undefined) {
        this.response.writeHead(this.status, this.headers);
        this.response.end();
    } else if(typeof view == 'function') {
        this.response.writeHead(this.status, this.headers);
        view();
        this.response.end();
    } else {
        if(useLayout === undefined) {
            useLayout = true;
        }
        var viewFile = viewsDir + '/' + view + '.' + this.extn;
        if(layout && useLayout) {
            this.model.view = view;
            viewFile = layout + '.' + this.extn;
        }

        try {
            var content = ghp.fill(viewFile, this.model, this.encoding, viewsDir, this.extn);
            this.send(content);
        } catch(e) {
            this.handleError(e);
        }
    }
};

RequestContext.prototype.renderText = function(text) {
    for(var i in this.model) {
        var hasModel = true;
		break;
    }
    if(!hasModel) {
        this.send(text);
    } else {
        this.send(ghp.fillText(text, this.model));
    }
};

RequestContext.prototype.send = function(text) {
    this.response.writeHead(this.status, this.headers);
    this.response.write(text, this.encoding);
    this.response.end();
};

RequestContext.prototype.renderStatic = function() {
    var staticFile = staticsDir + decodeURIComponent(url.parse(this.request.url).pathname);
    var self = this;
    fs.stat(staticFile, function(err, stats) {
        if(err || !stats.isFile()) {
            if((err && err.errno == 2) || !stats.isFile()) {
                self.extn = defaultViewExtn;
                self.headers['content-type'] = mime.mimes[defaultViewExtn];
                self.renderError(404);
            } else {
                self.handleError(err);
            }
        } else {
            self.headers['content-length'] = stats.size;
            var rs = fs.createReadStream(staticFile);
            self.response.writeHead(self.status, self.headers);
            sys.pump(rs, self.response, function() {
                self.response.end();
            });
        }
    });
};

RequestContext.prototype.renderError = function(status, error) {
    this.status = status;
    if(error === undefined) {
        error = {};
    }

    var viewFile = viewsDir + '/' + this.status + '.' + this.extn;

    var self = this;
    fs.stat(viewFile, function(err, stats) {
        if(!err && stats.isFile()) {
            try {
                var content = ghp.fill(viewFile, {error: error}, self.encoding, viewsDir, self.extn);
                self.send(content);
            } catch(e) {
                self.handleError(e);
            }
        } else {
            self.response.writeHead(self.status, self.headers);
            self.response.end();
        }
    });
};

RequestContext.prototype.handleError = function(err) {
    if(err) {
        console.log(err.stack);
    }
    this.renderError(500, err);
};

RequestContext.prototype.redirect = function(location) {
    this.headers['location'] = location;
    this.renderError(302, {location: location});
};

RequestContext.prototype.beginSession = function(callback) {
    var sessionId = crypto.createHash('sha1').update(uuid.generateUUID()).digest('hex');
    var self = this;
    session.getSessionStore().beginSession(sessionId, function(err) {
        if(!err) {
            this.sessionId = sessionId;
            self.addCookie(new gh.Cookie('GHSESSION', sessionId));
        }
        callback(err);
    });
};

RequestContext.prototype.setSessionValue = function(key, value, callback) {
    var store = session.getSessionStore();
    var setter = function (err) {
        if(err) {
            callback(err);
        } else {
            store.setValue(this.sessionId, key, value, callback);
        }
    };
    var self = this;
    store.hasSession(this.sessionId, function(err, has) {
        if(err) {
            callback(err);
        } else {
            if(!has) {
                self.beginSession(setter);
            } else {
                setter();
            }
        }
    });
};

RequestContext.prototype.getSessionValue = function(key, callback) {
    var store = session.getSessionStore();
    store.hasSession(this.sessionId, function(err, has) {
        if(!err && has) {
            store.getValue(this.sessionId, key, callback);
        } else {
            callback(err);
        }
    });
};

RequestContext.prototype.endSession = function(callback) {
    var store = session.getSessionStore();
    store.hasSession(this.sessionId, function(err, has) {
        if(!err && has) {
            store.endSession(this.sessionId, callback);
        } else {
            callback(err)
        }
    });
};

RequestContext.prototype.disableCache = function() {
    this.headers['expires'] = 'Thu, 11 Mar 2010 12:48:43 GMT';
    this.headers['cache-control'] = 'no-store, no-cache, must-revalidate';
    this.headers['pragma'] = 'no-cache';
};

exports.RequestContext = RequestContext;
<commit_msg>Added support for HEAD method.<commit_after>/*
 * Copyright (C) 2010 Chandra Sekar S
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var ghp = require('./ghp'),
    mime = require('./mime'),
    uuid = require('./uuid'),
    session = require('./session'),
    gh = require('./grasshopper'),
    fs = require('fs'),
    url = require('url'),
    sys = require('sys'),
    crypto = require('crypto');

var viewsDir = '.',
    defaultViewExtn = 'html',
    staticsDir = '.',
    defaultEncoding = 'utf8',
    layout = undefined;

exports.handleError = function(err, req, res, params) {
    if(params === undefined) {
        params={};
    }

    new RequestContext(req, res, params).handleError(err);
};

exports.configure = function(config) {
    if(config.viewsDir)
        viewsDir = config.viewsDir;
    if(config.defaultViewExtn)
        defaultViewExtn = config.defaultViewExtn;
    if(config.staticsDir)
        staticsDir = config.staticsDir;
    if(config.defaultEncoding)
        defaultEncoding = config.defaultEncoding;
    if(config.layout)
        layout = config.layout;
};

// Class: RequestContext
function RequestContext(request, response, params) {
    this.request = request;
    this.response = response;
    this.params = params;
    this.model = {};

    this.status = 200;
    this.extn = this.getExtn();
    this.encoding = defaultEncoding;
    this.headers = {
        'content-type': mime.mimes[this.extn]
                        ? mime.mimes[this.extn]
                        : 'application/octet-stream',
        'x-powered-by': 'Grasshopper/0.1-dev'
    };

    var cookieLine = request.headers['cookie'];
    if(cookieLine) {
        this.requestCookies = {};
        var cookies = cookieLine.split('; ');
        for(var i = 0; i < cookies.length; i++) {
            var cookieParts = cookies[i].split('=');
            if(cookieParts[0] == 'GHSESSION') {
                this.sessionId = decodeURIComponent(cookieParts[1]);
            } else {
                this.requestCookies[cookieParts[0]] = decodeURIComponent(cookieParts[1]);
            }
        }
    }
}

RequestContext.prototype.getExtn = function() {
    var extn = defaultViewExtn;
    var path = url.parse(this.request.url).pathname;
    if(path.match(/\.[^\/]+$/)) {
        extn = path.substring(path.lastIndexOf('.') + 1);
    }

    return extn;
};

RequestContext.prototype.addCookie = function(cookie) {
    var cookieLine = cookie.name + '=' + encodeURIComponent(cookie.value);
    cookieLine += cookie.path ? '; path=' + cookie.path : '';
    cookieLine += cookie.expires ? '; expires=' + cookie.expires : '';
    cookieLine += cookie.domain ? '; domain=' + cookie.domain : '';
    cookieLine += cookie.secure ? '; secure' : '';
    cookieLine += cookie.httpOnly ? '; HttpOnly' : '';

    if(this.headers['set-cookie']) {
        this.headers['set-cookie'] += '\r\nset-cookie: ' + cookieLine;
    } else {
        this.headers['set-cookie'] = cookieLine;
    }
};

RequestContext.prototype.render = function(view, useLayout) {
    if(view === undefined) {
        this.response.writeHead(this.status, this.headers);
        this.response.end();
    } else if(typeof view == 'function') {
        this.response.writeHead(this.status, this.headers);
        if(this.request.method != 'HEAD') {
            view();
        }
        this.response.end();
    } else {
        if(useLayout === undefined) {
            useLayout = true;
        }
        var viewFile = viewsDir + '/' + view + '.' + this.extn;
        if(layout && useLayout) {
            this.model.view = view;
            viewFile = layout + '.' + this.extn;
        }

        try {
            var content = ghp.fill(viewFile, this.model, this.encoding, viewsDir, this.extn);
            this.send(content);
        } catch(e) {
            this.handleError(e);
        }
    }
};

RequestContext.prototype.renderText = function(text) {
    for(var i in this.model) {
        var hasModel = true;
		break;
    }
    if(!hasModel) {
        this.send(text);
    } else {
        this.send(ghp.fillText(text, this.model));
    }
};

RequestContext.prototype.send = function(text) {
    this.response.writeHead(this.status, this.headers);
    if(this.request.method != 'HEAD') {
        this.response.write(text, this.encoding);
    }
    this.response.end();
};

RequestContext.prototype.renderStatic = function() {
    if(this.request.method != 'GET' && this.request.method != 'HEAD') {
        self.extn = defaultViewExtn;
        self.headers['content-type'] = mime.mimes[defaultViewExtn];
        self.renderError(404);
        return;
    }

    var staticFile = staticsDir + decodeURIComponent(url.parse(this.request.url).pathname);
    var self = this;
    fs.stat(staticFile, function(err, stats) {
        if(err || !stats.isFile()) {
            if((err && err.errno == 2) || !stats.isFile()) {
                self.extn = defaultViewExtn;
                self.headers['content-type'] = mime.mimes[defaultViewExtn];
                self.renderError(404);
            } else {
                self.handleError(err);
            }
        } else {
            self.headers['content-length'] = stats.size;
            var rs = fs.createReadStream(staticFile);
            self.response.writeHead(self.status, self.headers);
            if(this.request.method == 'GET') {
                sys.pump(rs, self.response, function() {
                    self.response.end();
                });
            } else {
                self.response.end();
            }
        }
    });
};

RequestContext.prototype.renderError = function(status, error) {
    this.status = status;
    if(error === undefined) {
        error = {};
    }

    var viewFile = viewsDir + '/' + this.status + '.' + this.extn;

    var self = this;
    fs.stat(viewFile, function(err, stats) {
        if(!err && stats.isFile()) {
            try {
                var content = ghp.fill(viewFile, {error: error}, self.encoding, viewsDir, self.extn);
                self.send(content);
            } catch(e) {
                self.handleError(e);
            }
        } else {
            self.response.writeHead(self.status, self.headers);
            self.response.end();
        }
    });
};

RequestContext.prototype.handleError = function(err) {
    if(err) {
        console.log(err.stack);
    }
    this.renderError(500, err);
};

RequestContext.prototype.redirect = function(location) {
    this.headers['location'] = location;
    this.renderError(302, {location: location});
};

RequestContext.prototype.beginSession = function(callback) {
    var sessionId = crypto.createHash('sha1').update(uuid.generateUUID()).digest('hex');
    var self = this;
    session.getSessionStore().beginSession(sessionId, function(err) {
        if(!err) {
            this.sessionId = sessionId;
            self.addCookie(new gh.Cookie('GHSESSION', sessionId));
        }
        callback(err);
    });
};

RequestContext.prototype.setSessionValue = function(key, value, callback) {
    var store = session.getSessionStore();
    var setter = function (err) {
        if(err) {
            callback(err);
        } else {
            store.setValue(this.sessionId, key, value, callback);
        }
    };
    var self = this;
    store.hasSession(this.sessionId, function(err, has) {
        if(err) {
            callback(err);
        } else {
            if(!has) {
                self.beginSession(setter);
            } else {
                setter();
            }
        }
    });
};

RequestContext.prototype.getSessionValue = function(key, callback) {
    var store = session.getSessionStore();
    store.hasSession(this.sessionId, function(err, has) {
        if(!err && has) {
            store.getValue(this.sessionId, key, callback);
        } else {
            callback(err);
        }
    });
};

RequestContext.prototype.endSession = function(callback) {
    var store = session.getSessionStore();
    store.hasSession(this.sessionId, function(err, has) {
        if(!err && has) {
            store.endSession(this.sessionId, callback);
        } else {
            callback(err)
        }
    });
};

RequestContext.prototype.disableCache = function() {
    this.headers['expires'] = 'Thu, 11 Mar 2010 12:48:43 GMT';
    this.headers['cache-control'] = 'no-store, no-cache, must-revalidate';
    this.headers['pragma'] = 'no-cache';
};

exports.RequestContext = RequestContext;
<|endoftext|>


<commit_before>/*
Copyright (c) 2011, Claus Augusti <claus@formatvorlage.de>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

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 <COPYRIGHT HOLDER> 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.
*/

"use strict";

module.exports = function (tagmanager, modulecontainer) {
    if (!tagmanager || !modulecontainer) { throw new Error('arguments missing'); }
    var parseHtmlView       = require('../lib/parser.js').parseHtmlView,
        tagmanager          = require('../lib/tagmanager.js'),
        Resource            = require('../lib/resources.js').Resource,
        TranslationManager  = require('../lib//translationmanager'),
        mod_path            = require('path'),
        mod_mu              = require('mu'),
        HTMLRenderer        = require('../lib/htmlrenderer.js').HTMLRenderer,
        logger              = require('../lib/logger.js').getLogger(mod_path.basename(module.filename), 10),
        rendererCount       = 0,
        c                   = console.log;

    function Renderer(url, mode, element, data) {
        if (!url) { throw new Error('missing arguments'); }
        this.moduleconfig   = modulecontainer.resolveFromRequestPath(url);
        this.url            = url;
        // [TBD] EVIL! Use resource manager
        this.resource       = new Resource('file://' + mod_path.join(__dirname, '..', url));
        this.resource.load();
        this.translationmanager = new TranslationManager(this.moduleconfig, data.req_lang);

        this.mode           = mode || Renderer.MODES.HTML;
        this.data           = data;
        this.state          = Renderer.STATES.INIT;
        this.uuid           = ++rendererCount;

        this.element        = element;                                      // reference to the element context object created by the parser
        this.parentcontent  = element ? element.elementContent : null;
        this.parentrenderer = null;
        this.parseresult    = null;
        this.childrenderers = [];
        var self            = this;
        this.resource.addListener('stateChanged', function (resource) {
            if (resource.state >= Resource.STATES.COMPLETE) {
                if (self.state < Renderer.STATES.PARSED) {
                    //logger.debug('resource loaded, parse');
                    self.parse();
                }
            }
        });
    }
    require('util').inherits(Renderer, require('events').EventEmitter);

    Object.defineProperty(Renderer.prototype, 'state', {
        get : function () {
            return this._state;
        },
        set : function (val) {
            if ('number' !== typeof val) { throw Error('expected number ' + val); }
            this._state = val;
            this.emit('stateChanged', this);
        }
    });

    Renderer.STATES = {
        INIT            : 0,
        PARSED          : 20,
        CHILDSPARSED    : 30,
        RENDERED        : 40
    };

    Renderer.prototype.parse = function () {
        var self = this,
            resourcecontent = null;
        logger.debug(this.uuid + ': parse');

        if (this.parentcontent) {
            resourcecontent = this.resource.data.toString().replace(new RegExp('<c:content/>'), this.parentcontent);
            logger.debug('include parent content '/* + resourcecontent*/);
        } else {
            resourcecontent = this.resource.data.toString();
        }

        parseHtmlView(resourcecontent, this.resource.url, tagmanager).then(function (parseresult) {
            logger.debug(self.uuid + ': parsed');
            self.parseresult = parseresult;
            if (parseresult.elements.length == 0) {
                self.parseresult = parseresult;
                self.render();
            } else {
                parseresult.elements.forEach(function (child) {
                    var moduleconfig = modulecontainer.getConfiguration(child.tag.module);
                    var viewurl = modulecontainer.getViewUrl(moduleconfig, child.tag.view);
                    var childrenderer = new Renderer(viewurl, 'json', child, { req_lang : self.data.req_lang});
                    child.renderer = childrenderer;
                    self.addChildRenderer(childrenderer);
                });
            }
            this.state = Renderer.STATES.PARSED;
        });
    };

    Renderer.prototype.addChildRenderer = function (renderer) {
        if (!renderer) { throw new Error('wrong type'); }
        var self = this;
        logger.debug(this.uuid + ': addChildRenderer ' + renderer.uuid);

        renderer.addListener('stateChanged', function (renderer) {
            logger.debug(self.uuid + ': renderer ' + renderer.uuid + ' changed state to ' + renderer.state);
            var rendered = self.childrenderers.every(function (renderer) {
                return renderer.state >= Renderer.STATES.RENDERED;
            });
            if (rendered) {
                logger.debug(self.uuid + ' all rendered');
                self.render();
            }
        });

        this.childrenderers.push(renderer);
        renderer.parentrenderer = this;
    };

    Renderer.prototype.render = function () {
        var self = this;
        logger.debug(this.uuid + ': render');
        this.renderTemplate(function (document) {
            self.renderView(document);
            self.state = Renderer.STATES.RENDERED;
        });
    };

    Renderer.prototype.renderTemplate = function (callback) {
        var document = this.parentrenderer == null ? this.parseresult.document : HTMLRenderer.getViewBody(this.parseresult.document),
            self = this,
            data = this.data || {};
        this.parseresult.elements.forEach(function (element) {
            data['__render__' + element.id] = element.renderer.renderresult.content;
        });

        // this sucks, because mustache sucks even more
        if (this.element) {
            this.element.attrs.forEach(function (keyvalue) {
                data['attr_' + keyvalue[0]] = keyvalue[1];
            });
        }

        var templating = function(template){
          // 4. Do templating
          var buffer = "";
          mod_mu.compileText('viewtemplate', template);
          var stream = mod_mu.render('viewtemplate', data)
            .on('data', function (c) {
              buffer += c;
            })
            .on('end' , function () {
                logger.debug(self.uuid + ': done templating');
                callback(buffer);
            });
        };

        var transmgr = this.translationmanager;
        switch(transmgr.__state){
          case transmgr.STATES.NO_LOCALES:
            templating(document);
            break;
          case transmgr.STATES.LOADED:
            this.translationRenderer(document, templating);
            break;
          default:
            transmgr.addListener('stateChanged', function (event) {
              if(transmgr.__state == transmgr.STATES.LOADED){
                self.translationRenderer(document, templating);
              } else {
                templating(document);
              }
            });
            break;
        };
    };

    Renderer.prototype.translationRenderer = function(template, callback){
      var self = this,
          transmgr = this.translationmanager;

      logger.debug('translationRenderer ' + self.uuid);
      this.translationmanager.parseTemplateAsXML(template, callback);
//      template = this.translationmanager.translateTemplate(template);
//
//      callback(template);
    };

    Renderer.prototype.renderView = function (document) {
        logger.debug(this.uuid + ': renderView');
        var self = this,
            deps = this.collectChildDependencies();
        this.renderresult = {
            dependencies : {
                css     : deps.css.concat(this.parseresult.dependencies.css.map(function (url) { return self.resolveUrl(url); })),
                script  : deps.script.concat(this.parseresult.dependencies.script.map(function (url) { return self.resolveUrl(url); })),
                locale  : deps.locale.concat(this.parseresult.dependencies.locale.map(function (url) { return self.resolveUrl(url); }))
            },
            clientcontroller : this.resolveUrl(this.parseresult.clientcontroller),
            content : document
        };

        if (this.parentrenderer == null) {
            logger.debug('root renderer');
            this.renderresult.dependencies.css      = Renderer.unique(this.renderresult.dependencies.css);
            this.renderresult.dependencies.script   = Renderer.unique(this.renderresult.dependencies.script);
            this.renderresult.dependencies.locale   = Renderer.unique(this.renderresult.dependencies.locale);
            if (this.mode == 'html') {
                this.renderresult.content = HTMLRenderer.renderDocument(this, modulecontainer);
            }
        }
    };

    Renderer.prototype.collectChildDependencies = function () {
        var self = this;
        var css = [],
            script = [],
            locale = [];

        this.childrenderers.forEach(function (renderer) {
            var deps = renderer.getDependencies();
            css      = deps.css.concat(css);
            script   = deps.script.concat(script);
            locale   = deps.locale.concat(locale);
        });

        return {
            css : css,
            script : script,
            locale : locale
        };
    };

    Renderer.prototype.getDependencies = function (isRemote) {
        // [TBD] isRemote
        var self = this, m = function (url) { return self.resolveUrl(url); };
        return {
            css     : this.renderresult.dependencies.css.map(m),
            script  : this.renderresult.dependencies.script.map(m),
            locale  : this.renderresult.dependencies.locale.map(m)
        };
    };

    Renderer.prototype.resolveUrl = function (url, isRemote) {
        if (!url) return;
        // [TBD] WORKAROUND, resolveUrl must only be called once for a URL
        if (url.indexOf('/module') == 0) {
            return url;
        }
        if (url.indexOf(modulecontainer.COMPONENT_PROTOCOL) == 0) {
            return modulecontainer.resolveUrl(this.moduleconfig, url);
        }
        if (url.indexOf('http') == -1) {
            return mod_path.join(this.moduleconfig.url, url);
        }

    };

    Renderer.MODES = {
        HTML    : 1,
        JSON    : 2
    };

    Renderer.unique = function (array) {
        var hlp = {},
            arr = [];
        array.forEach(function (item) {
            if (!hlp[item]) {
                arr.push(item);
                hlp[item] = true;
            }
        });
        return arr;
    };

    Renderer.showTree = function (renderer) {
        var spaces = '                                                       ';
        show(renderer, 0);

        function show(renderer, depth) {
            logger.debug(spaces.substring(0, depth*2) + ' ' + renderer.uuid + '; view template ' + renderer.resource.url);
            for (var i = 0; i < renderer.childrenderers.length; i++) {
                show(renderer.childrenderers[i], depth + 1);
            }
        }
    };

    return {
        Renderer : Renderer
    };
};<commit_msg>added resourcemanager to Resource<commit_after>/*
Copyright (c) 2011, Claus Augusti <claus@formatvorlage.de>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

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 <COPYRIGHT HOLDER> 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.
*/

"use strict";

module.exports = function (tagmanager, modulecontainer, resourcemgr) {
    if (!tagmanager || !modulecontainer) { throw new Error('arguments missing'); }
    var parseHtmlView       = require('../lib/parser.js').parseHtmlView,
        tagmanager          = require('../lib/tagmanager.js'),
        Resource            = require('../lib/resources.js').Resource,
        TranslationManager  = require('../lib//translationmanager'),
        mod_path            = require('path'),
        mod_mu              = require('mu'),
        HTMLRenderer        = require('../lib/htmlrenderer.js').HTMLRenderer,
        logger              = require('../lib/logger.js').getLogger(mod_path.basename(module.filename), 10),
        rendererCount       = 0,
        resourcemanager     = resourcemgr,
        c                   = console.log;

    function Renderer(url, mode, element, data) {
        if (!url) { throw new Error('missing arguments'); }
        this.moduleconfig   = modulecontainer.resolveFromRequestPath(url);
        this.url            = url;
        this.resource       = resourcemanager.loadResourceByUrl(url);
        this.resource.load();
        this.translationmanager = new TranslationManager(this.moduleconfig, data.req_lang);
        this.mode           = mode || Renderer.MODES.HTML;
        this.data           = data;
        this.state          = Renderer.STATES.INIT;
        this.uuid           = ++rendererCount;

        this.element        = element;                                      // reference to the element context object created by the parser
        this.parentcontent  = element ? element.elementContent : null;      // contains the original child content of the tag this component resolved to
        this.parseresult    = null;

        this.parentrenderer = null;
        this.childrenderers = [];
        var self            = this;
        this.resource.addListener('stateChanged', function (resource) {
            if (resource.state >= Resource.STATES.COMPLETE) {
                if (self.state < Renderer.STATES.PARSED) {
                    self.parse();
                }
            }
        });
    }
    require('util').inherits(Renderer, require('events').EventEmitter);

    Object.defineProperty(Renderer.prototype, 'state', {
        get : function () {
            return this._state;
        },
        set : function (val) {
            if ('number' !== typeof val) { throw Error('expected number ' + val); }
            this._state = val;
            this.emit('stateChanged', this);
        }
    });

    Renderer.STATES = {
        INIT            : 0,
        PARSED          : 20,
        CHILDSPARSED    : 30,
        RENDERED        : 40
    };

    Renderer.prototype.parse = function () {
        var self = this,
            resourcecontent = null;
        logger.debug(this.uuid + ': parse');

        if (this.parentcontent) {
            resourcecontent = this.resource.data.toString().replace(new RegExp('<c:content/>'), this.parentcontent);
            logger.debug('include parent content '/* + resourcecontent*/);
        } else {
            resourcecontent = this.resource.data.toString();
        }

        parseHtmlView(resourcecontent, this.resource.url, tagmanager).then(function (parseresult) {
            logger.debug(self.uuid + ': parsed');
            self.parseresult = parseresult;
            if (parseresult.elements.length == 0) {
                self.parseresult = parseresult;
                self.render();
            } else {
                parseresult.elements.forEach(function (child) {
                    var moduleconfig = modulecontainer.getConfiguration(child.tag.module);
                    var viewurl = modulecontainer.getViewUrl(moduleconfig, child.tag.view);
                    logger.debug('viewurl ' + viewurl);
                    var childrenderer = new Renderer(viewurl, 'json', child, { req_lang : self.data.req_lang});
                    child.renderer = childrenderer;
                    self.addChildRenderer(childrenderer);
                });
            }
            this.state = Renderer.STATES.PARSED;
        });
    };

    Renderer.prototype.addChildRenderer = function (renderer) {
        if (!renderer) { throw new Error('wrong type'); }
        var self = this;
        logger.debug(this.uuid + ': addChildRenderer ' + renderer.uuid + ', resurl ' + renderer.resource.url);

        renderer.addListener('stateChanged', function (renderer) {
            logger.debug(self.uuid + ': renderer ' + renderer.uuid + ' changed state to ' + renderer.state);
            var rendered = self.childrenderers.every(function (renderer) {
                return renderer.state >= Renderer.STATES.RENDERED;
            });
            if (rendered) {
                logger.debug(self.uuid + ' all rendered');
                self.render();
            }
        });

        this.childrenderers.push(renderer);
        renderer.parentrenderer = this;
    };

    Renderer.prototype.render = function () {
        var self = this;
        logger.debug(this.uuid + ': render');
        this.renderTemplate(function (document) {
            self.renderView(document);
            self.state = Renderer.STATES.RENDERED;
        });
    };

    Renderer.prototype.renderTemplate = function (callback) {
        var document = this.parentrenderer == null ? this.parseresult.document : HTMLRenderer.getViewBody(this.parseresult.document),
            self = this,
            data = this.data || {};
        this.parseresult.elements.forEach(function (element) {
            data['__render__' + element.id] = element.renderer.renderresult.content;
        });

        // this sucks, because mustache sucks even more
        if (this.element) {
            this.element.attrs.forEach(function (keyvalue) {
                data['attr_' + keyvalue[0]] = keyvalue[1];
            });
        }

        var templating = function(template){
          // 4. Do templating
          var buffer = "";
          mod_mu.compileText('viewtemplate', template);
          var stream = mod_mu.render('viewtemplate', data)
            .on('data', function (c) {
              buffer += c;
            })
            .on('end' , function () {
                logger.debug(self.uuid + ': done templating');
                callback(buffer);
            });
        };

        var transmgr = this.translationmanager;
        switch(transmgr.__state){
          case transmgr.STATES.NO_LOCALES:
            templating(document);
            break;
          case transmgr.STATES.LOADED:
            this.translationRenderer(document, templating);
            break;
          default:
            transmgr.addListener('stateChanged', function (event) {
              if(transmgr.__state == transmgr.STATES.LOADED){
                self.translationRenderer(document, templating);
              } else {
                templating(document);
              }
            });
            break;
        };
    };

    Renderer.prototype.translationRenderer = function(template, callback){
      var self = this,
          transmgr = this.translationmanager;

      logger.debug('translationRenderer ' + self.uuid);
      this.translationmanager.parseTemplateAsXML(template, callback);
//      template = this.translationmanager.translateTemplate(template);
//
//      callback(template);
    };

    Renderer.prototype.renderView = function (document) {
        logger.debug(this.uuid + ': renderView');
        var self = this,
            deps = this.collectChildDependencies();
        this.renderresult = {
            dependencies : {
                css     : deps.css.concat(this.parseresult.dependencies.css.map(function (url) { return self.resolveUrl(url); })),
                script  : deps.script.concat(this.parseresult.dependencies.script.map(function (url) { return self.resolveUrl(url); })),
                locale  : deps.locale.concat(this.parseresult.dependencies.locale.map(function (url) { return self.resolveUrl(url); }))
            },
            clientcontroller : this.resolveUrl(this.parseresult.clientcontroller),
            content : document
        };

        if (this.parentrenderer == null) {
            logger.debug('root renderer');
            this.renderresult.dependencies.css      = Renderer.unique(this.renderresult.dependencies.css);
            this.renderresult.dependencies.script   = Renderer.unique(this.renderresult.dependencies.script);
            this.renderresult.dependencies.locale   = Renderer.unique(this.renderresult.dependencies.locale);
            if (this.mode == 'html') {
                this.renderresult.content = HTMLRenderer.renderDocument(this, modulecontainer);
            }
        }
    };

    Renderer.prototype.collectChildDependencies = function () {
        var self = this;
        var css = [],
            script = [],
            locale = [];

        this.childrenderers.forEach(function (renderer) {
            var deps = renderer.getDependencies();
            css      = deps.css.concat(css);
            script   = deps.script.concat(script);
            locale   = deps.locale.concat(locale);
        });

        return {
            css : css,
            script : script,
            locale : locale
        };
    };

    Renderer.prototype.getDependencies = function (isRemote) {
        // [TBD] isRemote
        var self = this, m = function (url) { return self.resolveUrl(url); };
        return {
            css     : this.renderresult.dependencies.css.map(m),
            script  : this.renderresult.dependencies.script.map(m),
            locale  : this.renderresult.dependencies.locale.map(m)
        };
    };

    Renderer.prototype.resolveUrl = function (url, isRemote) {
        if (!url) return;
        // [TBD] WORKAROUND, resolveUrl must only be called once for a URL
        if (url.indexOf('/module') == 0) {
            return url;
        }
        if (url.indexOf(modulecontainer.COMPONENT_PROTOCOL) == 0) {
            return modulecontainer.resolveUrl(this.moduleconfig, url);
        }
        if (url.indexOf('http') == -1) {
            return mod_path.join(this.moduleconfig.url, url);
        }

    };

    Renderer.MODES = {
        HTML    : 1,
        JSON    : 2
    };

    Renderer.unique = function (array) {
        var hlp = {},
            arr = [];
        array.forEach(function (item) {
            if (!hlp[item]) {
                arr.push(item);
                hlp[item] = true;
            }
        });
        return arr;
    };

    Renderer.showTree = function (renderer) {
        var spaces = '                                                       ';
        show(renderer, 0);

        function show(renderer, depth) {
            logger.debug(spaces.substring(0, depth*2) + ' ' + renderer.uuid + '; view template ' + renderer.resource.url);
            for (var i = 0; i < renderer.childrenderers.length; i++) {
                show(renderer.childrenderers[i], depth + 1);
            }
        }
    };

    return {
        Renderer : Renderer
    };
};<|endoftext|>


<commit_before>var fmt = require('./fmt')
var log = require('./utils').log
var trace = require('./utils').trace

module.exports = function () {
	return this
		.on('fly_run', function (obj) {
			log('Flying with ' + fmt.path + '...', obj.path)
		})

		.on('flyfile_not_found', function (obj) {
			log('No Flyfile Error: ' + fmt.error, obj.error)
		})

		.on('fly_watch', function () {
			log(fmt.warn, 'Watching files...')
		})

		.on('plugin_load', function (obj) {
			log('Loading plugin ' + fmt.title, obj.plugin)
		})

		.on('plugin_error', function (obj) {
			log(
				fmt.error + ' failed due to ' + fmt.error,
				obj.plugin, obj.error
			)
		})

		.on('task_error', function (obj) {
			trace(obj.error)
			log(
				fmt.error + ' failed due to ' + fmt.error,
				obj.task, obj.error
			)
		})

		.on('task_start', function (obj) {
			log('Starting ' + fmt.start, obj.task)
		})

		.on('task_complete', function (obj) {
			var time = formatTime(obj.duration)
			log(
				'Finished ' + fmt.complete + ' in ' + fmt.secs,
				obj.task, time.duration, time.scale
			)
		})

		.on('task_not_found', function (obj) {
			log(fmt.error + ' not found in Flyfile.', obj.task)
		})
}

/**
 * Format the task's time duration
 * @param  {Integer} 	time 		The task's duration, in ms
 * @param  {String} 	unit 		The unit of time measurement
 * @return {Object}
 */
function formatTime(time, unit) {
	unit = unit || 'ms'

	if (time >= 1000) {
		time = Math.round((time / 1000) * 10) / 10
		unit = 's'
	}

	return {
		duration: time,
		scale: unit
	}
}
<commit_msg>fix console formatting for watch cmd<commit_after>var fmt = require('./fmt')
var log = require('./utils').log
var trace = require('./utils').trace

module.exports = function () {
	return this
		.on('fly_run', function (obj) {
			log('Flying with ' + fmt.path + '...', obj.path)
		})

		.on('flyfile_not_found', function (obj) {
			log('No Flyfile Error: ' + fmt.error, obj.error)
		})

		.on('fly_watch', function () {
			log(fmt.warn.toString(), 'Watching files...')
		})

		.on('plugin_load', function (obj) {
			log('Loading plugin ' + fmt.title, obj.plugin)
		})

		.on('plugin_error', function (obj) {
			log(
				fmt.error + ' failed due to ' + fmt.error,
				obj.plugin, obj.error
			)
		})

		.on('task_error', function (obj) {
			trace(obj.error)
			log(
				fmt.error + ' failed due to ' + fmt.error,
				obj.task, obj.error
			)
		})

		.on('task_start', function (obj) {
			log('Starting ' + fmt.start, obj.task)
		})

		.on('task_complete', function (obj) {
			var time = formatTime(obj.duration)
			log(
				'Finished ' + fmt.complete + ' in ' + fmt.secs,
				obj.task, time.duration, time.scale
			)
		})

		.on('task_not_found', function (obj) {
			log(fmt.error + ' not found in Flyfile.', obj.task)
		})
}

/**
 * Format the task's time duration
 * @param  {Integer} 	time 		The task's duration, in ms
 * @param  {String} 	unit 		The unit of time measurement
 * @return {Object}
 */
function formatTime(time, unit) {
	unit = unit || 'ms'

	if (time >= 1000) {
		time = Math.round((time / 1000) * 10) / 10
		unit = 's'
	}

	return {
		duration: time,
		scale: unit
	}
}
<|endoftext|>


<commit_before>const providers = {
  "env": require('provider/env'),
  "file": require('provider/file')
}

module.exports.resolve = function(config, cb) {
  const providerType = config.type
  const provider = providers[providerType]
  if(provider !== undefined) {
    provider.init(config, cb)
  } else {
    cb(new Error(`Provider ${providerType} not found.`))
  }
}
<commit_msg>Add provided as provider<commit_after>const providers = {
  "env": require('./provider/env'),
  "file": require('./provider/file'),
  "provided": require('./provider/provided')
}

module.exports.resolve = function(config, cb) {
  const providerType = config.type
  const provider = providers[providerType]
  if(provider !== undefined) {
    provider.init(config, cb)
  } else {
    cb(new Error(`Provider ${providerType} not found.`))
  }
}
<|endoftext|>


<commit_before>require(['module', '../src/gradient-descent.js'], function(module, GradientDescent) {
    var gd = new GradientDescent({ features: 3, cost_threshold: 0.01, normalize: true });

    var training_data = [
        { features: [1, 2, 3], label: 4 },
        { features: [2, 5, 3], label: 2 },
        { features: [2, 3, 6], label: 4 },
        { features: [5, 1, 4], label: 3 },
        { features: [8, 1, 4], label: 1 }
    ];

    gd.train(training_data);
});<commit_msg>updated the demo file<commit_after>require(['module', '../src/gradient-descent.js'], function(module, GradientDescent) {
    var gd = new GradientDescent({ features: 3, cost_threshold: 0.01, normalize: true });

    var training_data = [
        { features: [1, 2, 3], label: 4 },
        { features: [2, 5, 3], label: 2 },
        { features: [2, 3, 6], label: 4 },
        { features: [5, 1, 4], label: 3 },
        { features: [8, 1, 4], label: 1 }
    ];

    gd.train(training_data);
    gd.subscribe('done', function(e) {
        console.info('training done!');
        console.log(e);
    });
});<|endoftext|>


<commit_before>
/*!
 * Express - response
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var fs = require('fs')
  , http = require('http')
  , path = require('path')
  , connect = require('connect')
  , utils = connect.utils
  , parseRange = require('./utils').parseRange
  , res = http.ServerResponse.prototype
  , send = connect.static.send
  , join = require('path').join
  , mime = require('mime');

/**
 * Send a response with the given `body` and optional `headers` and `status` code.
 *
 * Examples:
 *
 *     res.send();
 *     res.send(new Buffer('wahoo'));
 *     res.send({ some: 'json' });
 *     res.send('
some html
');
 *     res.send('Sorry, cant find that', 404);
 *     res.send('text', { 'Content-Type': 'text/plain' }, 201);
 *     res.send(404);
 *
 * @param {String|Object|Number|Buffer} body or status
 * @param {Object|Number} headers or status
 * @param {Number} status
 * @return {ServerResponse}
 * @api public
 */

res.send = function(body, headers, status){
  // allow status as second arg
  if ('number' == typeof headers) {
    status = headers,
    headers = null;
  }

  // default status
  status = status || this.statusCode;

  // allow 0 args as 204
  if (!arguments.length || undefined === body) body = status = 204;

  // determine content type
  switch (typeof body) {
    case 'number':
      if (!this.header('Content-Type')) {
        this.contentType('.txt');
      }
      body = http.STATUS_CODES[status = body];
      break;
    case 'string':
      if (!this.header('Content-Type')) {
        this.charset = this.charset || 'utf-8';
        this.contentType('.html');
      }
      break;
    case 'boolean':
    case 'object':
      if (Buffer.isBuffer(body)) {
        if (!this.header('Content-Type')) {
          this.contentType('.bin');
        }
      } else {
        if (!this.header('Content-Type')) {
          this.charset = this.charset || 'utf-8';
          this.contentType('.json');
        }
        body = JSON.stringify(body);
        if (this.req.query.callback && this.app.set('jsonp callback')) {
          this.charset = this.charset || 'utf-8';
          this.header('Content-Type', 'text/javascript');
          body = this.req.query.callback.replace(/[^\w$.]/g, '') + '(' + body + ');';
        }
      }
      break;
  }

  // populate Content-Length
  if (!this.header('Content-Length')) {
    this.header('Content-Length', Buffer.isBuffer(body)
      ? body.length
      : Buffer.byteLength(body));
  }

  // merge headers passed
  if (headers) {
    var fields = Object.keys(headers);
    for (var i = 0, len = fields.length; i < len; ++i) {
      var field = fields[i];
      this.header(field, headers[field]);
    }
  }

  // strip irrelevant headers
  if (204 === status) {
    this.removeHeader('Content-Type');
    this.removeHeader('Content-Length');
  }

  // respond
  this.statusCode = status;
  this.end('HEAD' == this.req.method ? undefined : body);
};

/**
 * Transfer the file at the given `path`. Automatically sets
 * the _Content-Type_ response header field. `next()` is called
 * when `path` is a directory, or when an error occurs.
 *
 * Options:
 *
 *   - `maxAge` defaulting to 0
 *   - `root`   root directory for relative filenames
 *
 * @param {String} path
 * @param {Object|Function} options or fn
 * @param {Function} fn
 * @api public
 */

res.sendfile = function(path, options, fn){
  var next = this.req.next;
  options = options || {};

  // support function as second arg
  if ('function' == typeof options) {
    fn = options;
    options = {};
  }

  options.path = path;
  options.callback = fn;
  send(this.req, this, next, options);
};

/**
 * Set _Content-Type_ response header passed through `mime.lookup()`.
 *
 * Examples:
 *
 *     var filename = 'path/to/image.png';
 *     res.contentType(filename);
 *     // res.headers['Content-Type'] is now "image/png"
 *
 *     res.contentType('.html');
 *     res.contentType('html');
 *     res.contentType('json');
 *     res.contentType('png');
 *
 * @param {String} type
 * @return {String} the resolved mime type
 * @api public
 */

res.contentType = function(type){
  return this.header('Content-Type', mime.lookup(type));
};

/**
 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.
 *
 * @param {String} filename
 * @return {ServerResponse}
 * @api public
 */

res.attachment = function(filename){
  if (filename) this.contentType(filename);
  this.header('Content-Disposition', filename
    ? 'attachment; filename="' + path.basename(filename) + '"'
    : 'attachment');
  return this;
};

/**
 * Transfer the file at the given `path`, with optional
 * `filename` as an attachment and optional callback `fn(err)`,
 * and optional `fn2(err)` which is invoked when an error has
 * occurred after headers have been sent.
 *
 * @param {String} path
 * @param {String|Function} filename or fn
 * @param {Function} fn
 * @param {Function} fn2
 * @api public
 */

res.download = function(path, filename, fn, fn2){
  var self = this;

  // support callback as second arg
  if ('function' == typeof filename) {
    fn2 = fn;
    fn = filename;
    filename = null;
  }

  // transfer the file
  this.attachment(filename || path).sendfile(path, function(err){
    var sentHeader = self._header;
    if (err) {
      if (!sentHeader) self.removeHeader('Content-Disposition');
      if (sentHeader) {
        if (fn2) fn2(err);
      } else if (fn) {
        fn(err);
      } else {
        self.req.next(err);
      }
    } else if (fn) {
      fn();
    }
  });
};

/**
 * Set or get response header `name` with optional `val`.
 *
 * @param {String} name
 * @param {String} val
 * @return {String}
 * @api public
 */

res.header = function(name, val){
  if (val === undefined) {
    return this.getHeader(name);
  } else {
    this.setHeader(name, val);
    return val;
  }
};

/**
 * Clear cookie `name`.
 *
 * @param {String} name
 * @param {Object} options
 * @api public
 */

res.clearCookie = function(name, options){
  var opts = { expires: new Date(1) };
  this.cookie(name, '', options
    ? utils.merge(options, opts)
    : opts);
};

/**
 * Set cookie `name` to `val`, with the given `options`.
 *
 * Options:
 *
 *    - `maxAge`   max-age in milliseconds, converted to `expires`
 *
 * Examples:
 *
 *    // "Remember Me" for 15 minutes
 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
 *
 *    // save as above
 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
 *
 * @param {String} name
 * @param {String} val
 * @param {Options} options
 * @api public
 */

res.cookie = function(name, val, options){
  options = options || {};
  if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);
  var cookie = utils.serializeCookie(name, val, options);
  this.header('Set-Cookie', cookie);
};

/**
 * Redirect to the given `url` with optional response `status`
 * defauling to 302.
 *
 * The given `url` can also be the name of a mapped url, for
 * example by default express supports "back" which redirects
 * to the _Referrer_ or _Referer_ headers or the application's
 * "home" setting. Express also supports "home" out of the box,
 * which can be set via `app.set('home', '/blog');`, and defaults
 * to '/'.
 *
 * Redirect Mapping:
 *
 *  To extend the redirect mapping capabilities that Express provides,
 *  we may use the `app.redirect()` method:
 *
 *     app.redirect('google', 'http://google.com');
 *
 *  Now in a route we may call:
 *
 *     res.redirect('google');
 *
 *  We may also map dynamic redirects:
 *
 *      app.redirect('comments', function(req, res){
 *          return '/post/' + req.params.id + '/comments';
 *      });
 *
 *  So now we may do the following, and the redirect will dynamically adjust to
 *  the context of the request. If we called this route with _GET /post/12_ our
 *  redirect _Location_ would be _/post/12/comments_.
 *
 *      app.get('/post/:id', function(req, res){
 *        res.redirect('comments');
 *      });
 *
 *  Unless an absolute `url` is given, the app's mount-point
 *  will be respected. For example if we redirect to `/posts`,
 *  and our app is mounted at `/blog` we will redirect to `/blog/posts`.
 *
 * @param {String} url
 * @param {Number} code
 * @api public
 */

res.redirect = function(url, status){
  var app = this.app
    , req = this.req
    , base = app.set('home') || '/'
    , status = status || 302
    , body;

  // Setup redirect map
  var map = {
      back: req.header('Referrer', base)
    , home: base
  };

  // Support custom redirect map
  map.__proto__ = app.redirects;

  // Attempt mapped redirect
  var mapped = 'function' == typeof map[url]
    ? map[url](req, this)
    : map[url];

  // Perform redirect
  url = mapped || url;

  // Relative
  if (!~url.indexOf('://')) {
    // Respect mount-point
    if (app.route) {
      url = join(app.route, url);
    }

    // Absolute
    var host = req.headers.host
      , tls = req.connection.encrypted;
    url = 'http' + (tls ? 's' : '') + '://' + host + url;
  }

  // Support text/{plain,html} by default
  if (req.accepts('html')) {
    body = '
' + http.STATUS_CODES[status] + '. Redirecting to ' + url + '
';
    this.header('Content-Type', 'text/html');
  } else {
    body = http.STATUS_CODES[status] + '. Redirecting to ' + url;
    this.header('Content-Type', 'text/plain');
  }

  // Respond
  this.statusCode = status;
  this.header('Location', url);
  this.end(body);
};

/**
 * Assign the view local variable `name` to `val` or return the
 * local previously assigned to `name`.
 *
 * @param {String} name
 * @param {Mixed} val
 * @return {Mixed} val
 * @api public
 */

res.local = function(name, val){
  this._locals = this._locals || {};
  return undefined === val
    ? this._locals[name]
    : this._locals[name] = val;
};

/**
 * Assign several locals with the given `obj`,
 * or return the locals.
 *
 * @param {Object} obj
 * @return {Object|Undefined}
 * @api public
 */

res.locals =
res.helpers = function(obj){
  if (obj) {
    for (var key in obj) {
      this.local(key, obj[key]);
    }
  } else {
    return this._locals;
  }
};
<commit_msg>misc refactor<commit_after>
/*!
 * Express - response
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var fs = require('fs')
  , http = require('http')
  , path = require('path')
  , connect = require('connect')
  , utils = connect.utils
  , parseRange = require('./utils').parseRange
  , res = http.ServerResponse.prototype
  , send = connect.static.send
  , join = require('path').join
  , mime = require('mime');

/**
 * Send a response with the given `body` and optional `headers` and `status` code.
 *
 * Examples:
 *
 *     res.send();
 *     res.send(new Buffer('wahoo'));
 *     res.send({ some: 'json' });
 *     res.send('
some html
');
 *     res.send('Sorry, cant find that', 404);
 *     res.send('text', { 'Content-Type': 'text/plain' }, 201);
 *     res.send(404);
 *
 * @param {String|Object|Number|Buffer} body or status
 * @param {Object|Number} headers or status
 * @param {Number} status
 * @return {ServerResponse}
 * @api public
 */

res.send = function(body, headers, status){
  // allow status as second arg
  if ('number' == typeof headers) {
    status = headers,
    headers = null;
  }

  // default status
  status = status || this.statusCode;

  // allow 0 args as 204
  if (!arguments.length || undefined === body) body = status = 204;

  // determine content type
  switch (typeof body) {
    case 'number':
      if (!this.header('Content-Type')) {
        this.contentType('.txt');
      }
      body = http.STATUS_CODES[status = body];
      break;
    case 'string':
      if (!this.header('Content-Type')) {
        this.charset = this.charset || 'utf-8';
        this.contentType('.html');
      }
      break;
    case 'boolean':
    case 'object':
      if (Buffer.isBuffer(body)) {
        if (!this.header('Content-Type')) {
          this.contentType('.bin');
        }
      } else {
        if (!this.header('Content-Type')) {
          this.charset = this.charset || 'utf-8';
          this.contentType('.json');
        }
        body = JSON.stringify(body);
        if (this.req.query.callback && this.app.set('jsonp callback')) {
          this.charset = this.charset || 'utf-8';
          this.header('Content-Type', 'text/javascript');
          body = this.req.query.callback.replace(/[^\w$.]/g, '') + '(' + body + ');';
        }
      }
      break;
  }

  // populate Content-Length
  if (!this.header('Content-Length')) {
    this.header('Content-Length', Buffer.isBuffer(body)
      ? body.length
      : Buffer.byteLength(body));
  }

  // merge headers passed
  if (headers) {
    var fields = Object.keys(headers);
    for (var i = 0, len = fields.length; i < len; ++i) {
      var field = fields[i];
      this.header(field, headers[field]);
    }
  }

  // strip irrelevant headers
  if (204 === status) {
    this.removeHeader('Content-Type');
    this.removeHeader('Content-Length');
  }

  // respond
  this.statusCode = status;
  this.end('HEAD' == this.req.method ? undefined : body);
};

/**
 * Transfer the file at the given `path`. Automatically sets
 * the _Content-Type_ response header field. `next()` is called
 * when `path` is a directory, or when an error occurs.
 *
 * Options:
 *
 *   - `maxAge` defaulting to 0
 *   - `root`   root directory for relative filenames
 *
 * @param {String} path
 * @param {Object|Function} options or fn
 * @param {Function} fn
 * @api public
 */

res.sendfile = function(path, options, fn){
  var next = this.req.next;
  options = options || {};

  // support function as second arg
  if ('function' == typeof options) {
    fn = options;
    options = {};
  }

  options.path = path;
  options.callback = fn;
  send(this.req, this, next, options);
};

/**
 * Set _Content-Type_ response header passed through `mime.lookup()`.
 *
 * Examples:
 *
 *     var filename = 'path/to/image.png';
 *     res.contentType(filename);
 *     // res.headers['Content-Type'] is now "image/png"
 *
 *     res.contentType('.html');
 *     res.contentType('html');
 *     res.contentType('json');
 *     res.contentType('png');
 *
 * @param {String} type
 * @return {String} the resolved mime type
 * @api public
 */

res.contentType = function(type){
  return this.header('Content-Type', mime.lookup(type));
};

/**
 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.
 *
 * @param {String} filename
 * @return {ServerResponse}
 * @api public
 */

res.attachment = function(filename){
  if (filename) this.contentType(filename);
  this.header('Content-Disposition', filename
    ? 'attachment; filename="' + path.basename(filename) + '"'
    : 'attachment');
  return this;
};

/**
 * Transfer the file at the given `path`, with optional
 * `filename` as an attachment and optional callback `fn(err)`,
 * and optional `fn2(err)` which is invoked when an error has
 * occurred after headers have been sent.
 *
 * @param {String} path
 * @param {String|Function} filename or fn
 * @param {Function} fn
 * @param {Function} fn2
 * @api public
 */

res.download = function(path, filename, fn, fn2){
  var self = this;

  // support callback as second arg
  if ('function' == typeof filename) {
    fn2 = fn;
    fn = filename;
    filename = null;
  }

  // transfer the file
  this.attachment(filename || path).sendfile(path, function(err){
    var sentHeader = self._header;
    if (err) {
      if (!sentHeader) self.removeHeader('Content-Disposition');
      if (sentHeader) {
        fn2 && fn2(err);
      } else if (fn) {
        fn(err);
      } else {
        self.req.next(err);
      }
    } else if (fn) {
      fn();
    }
  });
};

/**
 * Set or get response header `name` with optional `val`.
 *
 * @param {String} name
 * @param {String} val
 * @return {String}
 * @api public
 */

res.header = function(name, val){
  if (val === undefined) {
    return this.getHeader(name);
  } else {
    this.setHeader(name, val);
    return val;
  }
};

/**
 * Clear cookie `name`.
 *
 * @param {String} name
 * @param {Object} options
 * @api public
 */

res.clearCookie = function(name, options){
  var opts = { expires: new Date(1) };
  this.cookie(name, '', options
    ? utils.merge(options, opts)
    : opts);
};

/**
 * Set cookie `name` to `val`, with the given `options`.
 *
 * Options:
 *
 *    - `maxAge`   max-age in milliseconds, converted to `expires`
 *
 * Examples:
 *
 *    // "Remember Me" for 15 minutes
 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
 *
 *    // save as above
 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
 *
 * @param {String} name
 * @param {String} val
 * @param {Options} options
 * @api public
 */

res.cookie = function(name, val, options){
  options = options || {};
  if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);
  var cookie = utils.serializeCookie(name, val, options);
  this.header('Set-Cookie', cookie);
};

/**
 * Redirect to the given `url` with optional response `status`
 * defauling to 302.
 *
 * The given `url` can also be the name of a mapped url, for
 * example by default express supports "back" which redirects
 * to the _Referrer_ or _Referer_ headers or the application's
 * "home" setting. Express also supports "home" out of the box,
 * which can be set via `app.set('home', '/blog');`, and defaults
 * to '/'.
 *
 * Redirect Mapping:
 *
 *  To extend the redirect mapping capabilities that Express provides,
 *  we may use the `app.redirect()` method:
 *
 *     app.redirect('google', 'http://google.com');
 *
 *  Now in a route we may call:
 *
 *     res.redirect('google');
 *
 *  We may also map dynamic redirects:
 *
 *      app.redirect('comments', function(req, res){
 *          return '/post/' + req.params.id + '/comments';
 *      });
 *
 *  So now we may do the following, and the redirect will dynamically adjust to
 *  the context of the request. If we called this route with _GET /post/12_ our
 *  redirect _Location_ would be _/post/12/comments_.
 *
 *      app.get('/post/:id', function(req, res){
 *        res.redirect('comments');
 *      });
 *
 *  Unless an absolute `url` is given, the app's mount-point
 *  will be respected. For example if we redirect to `/posts`,
 *  and our app is mounted at `/blog` we will redirect to `/blog/posts`.
 *
 * @param {String} url
 * @param {Number} code
 * @api public
 */

res.redirect = function(url, status){
  var app = this.app
    , req = this.req
    , base = app.set('home') || '/'
    , status = status || 302
    , body;

  // Setup redirect map
  var map = {
      back: req.header('Referrer', base)
    , home: base
  };

  // Support custom redirect map
  map.__proto__ = app.redirects;

  // Attempt mapped redirect
  var mapped = 'function' == typeof map[url]
    ? map[url](req, this)
    : map[url];

  // Perform redirect
  url = mapped || url;

  // Relative
  if (!~url.indexOf('://')) {
    // Respect mount-point
    if (app.route) {
      url = join(app.route, url);
    }

    // Absolute
    var host = req.headers.host
      , tls = req.connection.encrypted;
    url = 'http' + (tls ? 's' : '') + '://' + host + url;
  }

  // Support text/{plain,html} by default
  if (req.accepts('html')) {
    body = '
' + http.STATUS_CODES[status] + '. Redirecting to ' + url + '
';
    this.header('Content-Type', 'text/html');
  } else {
    body = http.STATUS_CODES[status] + '. Redirecting to ' + url;
    this.header('Content-Type', 'text/plain');
  }

  // Respond
  this.statusCode = status;
  this.header('Location', url);
  this.end(body);
};

/**
 * Assign the view local variable `name` to `val` or return the
 * local previously assigned to `name`.
 *
 * @param {String} name
 * @param {Mixed} val
 * @return {Mixed} val
 * @api public
 */

res.local = function(name, val){
  this._locals = this._locals || {};
  return undefined === val
    ? this._locals[name]
    : this._locals[name] = val;
};

/**
 * Assign several locals with the given `obj`,
 * or return the locals.
 *
 * @param {Object} obj
 * @return {Object|Undefined}
 * @api public
 */

res.locals =
res.helpers = function(obj){
  if (obj) {
    for (var key in obj) {
      this.local(key, obj[key]);
    }
  } else {
    return this._locals;
  }
};
<|endoftext|>


<commit_before>"use strict";

var knowledge = {
  concepts: [
    {
      id: "edit",
      name: "Click here to edit!"
    },
    {
      id: "dependency",
      name: "Click the top of the concept to add a dependency concept",
      dependencies: ["edit"]
    },
    {
      id: "dependent",
      name: "Click the bottom of the concept to add a dependent concept",
      dependencies: ["edit"]
    },
    {
      id: "joining",
      name: "Drag from one node to another to add dependencies",
      dependencies: ["edit"]
    }
  ]
};

// Create graph that visualises the knowledge
knowledgeGraph.create({
  graph: knowledge,
  plugins: [knowledgeGraph.plugins.editing],
});
<commit_msg>Added dependency deletion to editing demo<commit_after>"use strict";

var knowledge = {
  concepts: [
    {
      id: "edit",
      name: "Click here to edit!"
    },
    {
      id: "dependency",
      name: "Click the top of the concept to add a dependency concept",
      dependencies: ["edit"]
    },
    {
      id: "dependent",
      name: "Click the bottom of the concept to add a dependent concept",
      dependencies: ["edit"]
    },
    {
      id: "joining",
      name: "Drag from one concept to another to add dependencies",
      dependencies: ["edit"]
    },
    {
      id: "removing",
      name: "Drag between a concept and its dependency to remove the connection",
      dependencies: ["joining"]
    }
  ]
};

// Create graph that visualises the knowledge
knowledgeGraph.create({
  graph: knowledge,
  plugins: [knowledgeGraph.plugins.editing],
});
<|endoftext|>


<commit_before>config = {
    baseUrl: '/src',
    paths: {
        "jquery": "bower_components/jquery/jquery",
        "logging": "bower_components/logging/src/logging",
        "jquery.form": "bower_components/jquery-form/jquery.form",
        "jquery.anythingslider": "bower_components/AnythingSlider/js/jquery.anythingslider",
        "jcrop": "bower_components/jcrop/js/jquery.Jcrop",
        "klass": "bower_components/klass/src/klass",
        "photoswipe": "legacy/photoswipe",
        "parsley": "bower_components/parsleyjs/parsley",
        "parsley.extend": "bower_components/parsleyjs/parsley.extend",
        "patternslib.slides": "bower_components/slides/src/slides",
        "modernizr": "bower_components/modernizr/modernizr",
        "less": "bower_components/less.js/dist/less-1.6.2",
        "prefixfree": "bower_components/prefixfree/prefixfree.min",
        "Markdown.Converter": "legacy/Markdown.Converter",
        "Markdown.Extra": "legacy/Markdown.Extra",
        "Markdown.Sanitizer": "legacy/Markdown.Sanitizer",
        "select2": "bower_components/select2/select2.min",
        "jquery.chosen": "bower_components/chosen/chosen/chosen.jquery",
        "jquery.fullcalendar": "bower_components/fullcalendar/fullcalendar.min",
        "jquery.fullcalendar.dnd": "bower_components/fullcalendar/lib/jquery-ui.custom.min",
        "jquery.placeholder": "bower_components/jquery-placeholder/jquery.placeholder.min",
        "jquery.textchange": "bower_components/jquery-textchange/jquery.textchange",
        "tinymce": "bower_components/jquery.tinymce/jscripts/tiny_mce/jquery.tinymce",
        "spectrum": "bower_components/spectrum/spectrum",
        // Core
        "pat-utils": "core/utils",
        "pat-compat": "core/compat",
        "pat-jquery-ext": "core/jquery-ext",
        "pat-logger": "core/logger",
        "pat-parser": "core/parser",
        "pat-remove": "core/remove",
        "pat-url": "core/url",
        "pat-store": "core/store",
        "pat-registry": "core/registry",
        "pat-htmlparser": "lib/htmlparser",
        "pat-depends_parse": "lib/depends_parse",
        "pat-dependshandler": "lib/dependshandler",
        "pat-input-change-events": "lib/input-change-events",
        // Patterns
        "patterns": "patterns",
        "pat-ajax": "pat/ajax",
        "pat-autofocus": "pat/autofocus",
        "pat-autoscale": "pat/autoscale",
        "pat-autosubmit": "pat/autosubmit",
        "pat-autosuggest": "pat/autosuggest",
        "pat-breadcrumbs": "pat/breadcrumbs",
        "pat-bumper": "pat/bumper",
        "pat-carousel": "pat/carousel",
        "pat-checkedflag": "pat/checkedflag",
        "pat-checklist": "pat/checklist",
        "pat-chosen": "pat/chosen",
        "pat-collapsible": "pat/collapsible",
        "pat-colour-picket": "pat/colour-picker",
        "pat-depends": "pat/depends",
        "pat-edit-tinymce": "pat/edit-tinymce",
        "pat-equaliser": "pat/equaliser",
        "pat-expandable": "pat/expandable",
        "pat-focus": "pat/focus",
        "pat-formstate": "pat/form-state",
        "pat-forward": "pat/forward",
        "pat-fullcalendar": "pat/fullcalendar",
        "pat-gallery": "pat/gallery",
        "pat-image-crop": "pat/image-crop",
        "pat-inject": "pat/inject",
        "pat-legend": "pat/legend",
        "pat-markdown": "pat/markdown",
        "pat-menu": "pat/menu",
        "pat-modal": "pat/modal",
        "pat-navigation": "pat/navigation",
        "pat-notification": "pat/notification",
        "pat-placeholder": "pat/placeholder",
        "pat-selectbox": "pat/selectbox",
        "pat-skeleton": "pat/skeleton",
        "pat-slides": "pat/slides",
        "pat-slideshow-builder": "pat/slideshow-builder",
        "pat-sortable": "pat/sortable",
        "pat-stacks": "pat/stacks",
        "pat-subform": "pat/subform",
        "pat-switch": "pat/switch",
        "pat-toggle": "pat/toggle",
        "pat-tooltip": "pat/tooltip",
        "pat-validate": "pat/validate",
        "pat-zoom": "pat/zoom",
        // Calendar pattern
        "moment": "bower_components/moment/moment",
        "moment-timezone": "bower_components/moment-timezone/moment-timezone",
        "pat-calendar": "pat/calendar/calendar",
        "pat-calendar-dnd": "pat/calendar/dnd",
        "pat-calendar-moment-timezone-data": "pat/calendar/moment-timezone-data"
    },

    shim: {
        "jquery": {
            exports: "jQuery"
        },
        "jquery.fullcalendar.dnd": {
            depends: "jquery",
        },
        "tinymce": {
            depends: "jquery"
        },
        "photoswipe": {
            depends: "klass",
        }
    },
};

if (typeof(require) !== 'undefined') {
    require.config(config);
    require(["patterns"], function(patterns) {});
}
<commit_msg>Add missing shim declarations in main.js<commit_after>config = {
    baseUrl: '/src',
    paths: {
        "jquery": "bower_components/jquery/jquery",
        "logging": "bower_components/logging/src/logging",
        "jquery.form": "bower_components/jquery-form/jquery.form",
        "jquery.anythingslider": "bower_components/AnythingSlider/js/jquery.anythingslider",
        "jcrop": "bower_components/jcrop/js/jquery.Jcrop",
        "klass": "bower_components/klass/src/klass",
        "photoswipe": "legacy/photoswipe",
        "parsley": "bower_components/parsleyjs/parsley",
        "parsley.extend": "bower_components/parsleyjs/parsley.extend",
        "patternslib.slides": "bower_components/slides/src/slides",
        "modernizr": "bower_components/modernizr/modernizr",
        "less": "bower_components/less.js/dist/less-1.6.2",
        "prefixfree": "bower_components/prefixfree/prefixfree.min",
        "Markdown.Converter": "legacy/Markdown.Converter",
        "Markdown.Extra": "legacy/Markdown.Extra",
        "Markdown.Sanitizer": "legacy/Markdown.Sanitizer",
        "select2": "bower_components/select2/select2.min",
        "jquery.chosen": "bower_components/chosen/chosen/chosen.jquery",
        "jquery.fullcalendar": "bower_components/fullcalendar/fullcalendar.min",
        "jquery.fullcalendar.dnd": "bower_components/fullcalendar/lib/jquery-ui.custom.min",
        "jquery.placeholder": "bower_components/jquery-placeholder/jquery.placeholder.min",
        "jquery.textchange": "bower_components/jquery-textchange/jquery.textchange",
        "tinymce": "bower_components/jquery.tinymce/jscripts/tiny_mce/jquery.tinymce",
        "spectrum": "bower_components/spectrum/spectrum",
        // Core
        "pat-utils": "core/utils",
        "pat-compat": "core/compat",
        "pat-jquery-ext": "core/jquery-ext",
        "pat-logger": "core/logger",
        "pat-parser": "core/parser",
        "pat-remove": "core/remove",
        "pat-url": "core/url",
        "pat-store": "core/store",
        "pat-registry": "core/registry",
        "pat-htmlparser": "lib/htmlparser",
        "pat-depends_parse": "lib/depends_parse",
        "pat-dependshandler": "lib/dependshandler",
        "pat-input-change-events": "lib/input-change-events",
        // Patterns
        "patterns": "patterns",
        "pat-ajax": "pat/ajax",
        "pat-autofocus": "pat/autofocus",
        "pat-autoscale": "pat/autoscale",
        "pat-autosubmit": "pat/autosubmit",
        "pat-autosuggest": "pat/autosuggest",
        "pat-breadcrumbs": "pat/breadcrumbs",
        "pat-bumper": "pat/bumper",
        "pat-carousel": "pat/carousel",
        "pat-checkedflag": "pat/checkedflag",
        "pat-checklist": "pat/checklist",
        "pat-chosen": "pat/chosen",
        "pat-collapsible": "pat/collapsible",
        "pat-colour-picket": "pat/colour-picker",
        "pat-depends": "pat/depends",
        "pat-edit-tinymce": "pat/edit-tinymce",
        "pat-equaliser": "pat/equaliser",
        "pat-expandable": "pat/expandable",
        "pat-focus": "pat/focus",
        "pat-formstate": "pat/form-state",
        "pat-forward": "pat/forward",
        "pat-fullcalendar": "pat/fullcalendar",
        "pat-gallery": "pat/gallery",
        "pat-image-crop": "pat/image-crop",
        "pat-inject": "pat/inject",
        "pat-legend": "pat/legend",
        "pat-markdown": "pat/markdown",
        "pat-menu": "pat/menu",
        "pat-modal": "pat/modal",
        "pat-navigation": "pat/navigation",
        "pat-notification": "pat/notification",
        "pat-placeholder": "pat/placeholder",
        "pat-selectbox": "pat/selectbox",
        "pat-skeleton": "pat/skeleton",
        "pat-slides": "pat/slides",
        "pat-slideshow-builder": "pat/slideshow-builder",
        "pat-sortable": "pat/sortable",
        "pat-stacks": "pat/stacks",
        "pat-subform": "pat/subform",
        "pat-switch": "pat/switch",
        "pat-toggle": "pat/toggle",
        "pat-tooltip": "pat/tooltip",
        "pat-validate": "pat/validate",
        "pat-zoom": "pat/zoom",
        // Calendar pattern
        "moment": "bower_components/moment/moment",
        "moment-timezone": "bower_components/moment-timezone/moment-timezone",
        "pat-calendar": "pat/calendar/calendar",
        "pat-calendar-dnd": "pat/calendar/dnd",
        "pat-calendar-moment-timezone-data": "pat/calendar/moment-timezone-data"
    },

    shim: {
        "jcrop":                        { deps: "jquery" },
        "jquery":                       { exports: "jQuery" },
        "jquery.anythingslider":        { deps: "jquery" },
        "jquery.chosen":                { deps: "jquery" },
        "jquery.fullcalendar.dnd":      { deps: "jquery" },
        "jquery.placeholder":           { deps: "jquery" },
        "jquery.textchange":            { deps: "jquery" },
        "parsley":                      { deps: "jquery" },
        "parsley.extend":               { deps: "jquery" },
        "photoswipe":                   { deps: "klass" },
        "select2":                      { deps: "jquery" },
        "spectrum":                     { deps: "jquery" },
        "tinymce":                      { deps: "jquery" }
    },
};

if (typeof(require) !== 'undefined') {
    require.config(config);
    require(["patterns"], function(patterns) {});
}
<|endoftext|>


<commit_before>import React from 'react';
import { ThemeProvider } from 'styled-components';
import { Route } from 'react-router';
import { startRouter } from 'utils/router';
import 'moment/locale/fr'; // For testing the date picker
import 'utils/css';
import Highcharts from 'highcharts';
import { enableMock } from './xhr-mock';
import setupI18n from './i18n/config';

import Package from '../package.json';

// Languages
import './i18n/en';
// Additional components we expose to the window
import './expose';

// Demo
import Chrome from './views/chrome';
import SubPageChrome from './views/chrome/sub-page-chrome';
import Home from './views/pages/home';
import Sandbox from './views/pages/sandbox';
import SiteMap from './site-map';

global.Carbon = {
  version: Package.version
};

global.Highcharts = Highcharts;

setupI18n();

const routes = (
  <Route>
    <Route path='/sandbox' component={ Sandbox } />

    <Route component={ Chrome }>
      <ThemeProvider theme='classic'>
        <Route path='/' component={ Home } />

        <Route component={ SubPageChrome }>
          { SiteMap.generateRoutes() }
        </Route>
      </ThemeProvider>
    </Route>
  </Route>
);

startRouter(routes);

if (module.hot) {
  module.hot.accept();
} else {
  enableMock();
}
<commit_msg>FE-1425 - reverts main.js file<commit_after>import React from 'react';
import { Route } from 'react-router';
import { startRouter } from 'utils/router';
import 'moment/locale/fr'; // For testing the date picker
import 'utils/css';
import Highcharts from 'highcharts';
import { enableMock } from './xhr-mock';
import setupI18n from './i18n/config';

import Package from './../package.json';

// Languages
import './i18n/en';
// Additional components we expose to the window
import './expose';

// Demo
import Chrome from './views/chrome';
import SubPageChrome from './views/chrome/sub-page-chrome';
import Home from './views/pages/home';
import Sandbox from './views/pages/sandbox';
import News from './views/pages/news';
import SiteMap from './site-map';

global.Carbon = {
  version: Package.version
}

global.Highcharts = Highcharts;

setupI18n();

const routes = (
  <Route>
    <Route path='/sandbox' component={ Sandbox } />

    <Route component={ Chrome }>
      <Route path='/' component={ Home } />

      <Route component={ SubPageChrome }>
        { SiteMap.generateRoutes() }
      </Route>
    </Route>
  </Route>
);

startRouter(routes);

if (module.hot) {
  module.hot.accept();
} else {
  enableMock();
}
<|endoftext|>