<commit_before>var HTMLLinkElement=function(t){var e={},n=document.querySelector("link#"+t+"[rel=import], link[href*="+t+"][rel=import]"),r=function(t,e){return HTMLImports&&!HTMLImports.useNative?HTMLImports.whenReady(function(){return e({target:n})}):n.addEventListener(t,e)};return Object.defineProperties(e,{addEventListener:{writable:!1,value:function(t,o){n?r(t,o):o({target:e})}}}),e},TokenList=function(t){var e=this,n=function(t){return(t.text=t.textContent)&&t.textContent.match(/{(\w+|#)}/g).map(function(t){return t.match(/(\w+|#)/g)[0]}).map(r(t))},r=function(t){return function(n){return(e[n]=e[n]||[])&&e[n].push(t)}};this.sift(t).map(n)};TokenList.prototype.sift=function(t){for(var e=[],n=function(t){return t.nodeType===Node.TEXT_NODE?r(t)&&NodeFilter.FILTER_ACCEPT:o(t.attributes)&&NodeFilter.FILTER_REJECT},r=function(t){return/{(\w+|#)}/.test(t.textContent)},o=function(t){return Array.from(t).filter(function(t){return/{(\w+|#)}/g.test(t.value)}).map(function(t){return e.push(t)})},i=document.createNodeIterator(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,n);t=i.nextNode();)e.push(t);return e},TokenList.prototype.bind=function(t){var e=this,n=function(t){return e[t].map(function(t){return t.textContent=t.text})&&e[t].map(r(t))},r=function(e){return function(n){return n.textContent=n.textContent.replace("{"+e+"}",t[e])}};Object.keys(this).filter(function(e){return void 0!==t[e]}).map(n)};var HTMLTemplateElement=Template=function(t){function e(t){var e=this;contexts=(o=[]).concat.apply(o,[t]);var n,r=this.cloneNode(!1);return r.innerHTML=contexts.map(function(t){return t}).map(function(t,r){return t="object"==typeof t?t:{self:t},t["#"]=r,n=e.cloneNode(!0),void new TokenList(n.content).bind(t),n.innerHTML}).join(""),void(this.dependents||[]).map(function(t){return t.remove()}),this.dependents=Array.from(r.content.childNodes),this.after(r.content),this;var o}return Object.assign(document.querySelector("template[name="+t+"]"),{bind:e})},EventTarget=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.connectedCallback=function(){new HTMLLinkElement(this.tagName.toLowerCase()).addEventListener("load",this.onimport.bind(this))},e.prototype.on=function(t,e){this.addEventListener(t,e)},e}(t)},ParentNode=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.selectAll=function(t){return this.querySelectorAll(t)},e.prototype.select=function(t){return this.selectAll(t)[0]},e}(t)},GlobalEventHandlers=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.onimport=function(e,n){void 0===n&&(n=e.target["import"]),n&&this.clone(n.querySelector("template")),t.onconnect&&t.onconnect.call(this),this.render()},e.prototype.register=function(e){var n=this;void 0===e&&(e=function(t){return/^on/.test(t.name||t)});var r=function(e){return null===n[e]&&(n[e]=t[e].bind(n))},o=":not(script):not(template):not(style):not(link)",i=Array.from(this.querySelectorAll(o)),u=function(t){return Array.from(t.attributes).filter(e).map(c(t))},c=function(t){return function(e){return t[e]=a(t[e])}},a=function(e,r){void 0===r&&(r=/{\s*(\w+)\s*}/.exec(e)||[]);var o=(r[0],r[1]);return o&&t[o]&&t[o].bind(n)||e||null};Object.getOwnPropertyNames(t).filter(e).map(r),void[this].concat(i).map(u)},e}(t)},Component=function(t){return function(e){function n(){e.call(this),this.context={},this.initialize&&this.initialize(),this.tokens=new TokenList(this)}return e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.prototype.render=function(){var e=this;this.tokens.bind(this),Array.from(this.selectAll("template[name]")).map(function(t){return t.getAttribute("name")}).map(function(t){return new Template(t).bind(e[t])}),this.register(),t.onidle&&t.onidle.call(this)},n.prototype.clone=function(t){var e=this,n=t.content.cloneNode(!0),r=Array.from(n.querySelectorAll("slot")),o=function(t){return r.filter(i(t)).map(u(t))},i=function(t){return function(e){return t.getAttribute("slot")===e.getAttribute("name")}},u=function(t){return function(e){return e.parentNode.replaceChild(t,e)}};Array.from(t.attributes).map(function(t){return e.setAttribute(t.name,t.value)}),Array.from(this.querySelectorAll("[slot]")).map(o),this.innerHTML=t.innerHTML},n}(EventTarget(ParentNode(GlobalEventHandlers(t))))},ElementPrototype=window.Element.prototype,Element=function(t,e){return void 0===e&&(e=window.customElements),function(n){return e.define.apply(e,t.concat([Component(n)]))}};Element.prototype=ElementPrototype;<commit_msg>:muscle: bump distribution for dist/snuggsi.min.js<commit_after>var HTMLLinkElement=function(t){var e={},n=document.querySelector("link#"+t+"[rel=import], link[href*="+t+"][rel=import]"),r=function(t,e){return HTMLImports&&!HTMLImports.useNative?HTMLImports.whenReady(function(){return e({target:n})}):n.addEventListener(t,e)};return Object.defineProperties(e,{addEventListener:{writable:!1,value:function(t,o){n?r(t,o):o({target:e})}}}),e},TokenList=function(t){var e=this,n=function(t){return(t.text=t.textContent)&&t.textContent.match(/{(\w+|#)}/g).map(function(t){return t.match(/(\w+|#)/g)[0]}).map(r(t))},r=function(t){return function(n){return(e[n]=e[n]||[])&&e[n].push(t)}};this.sift(t).map(n)};TokenList.prototype.sift=function(t){for(var e=[],n=function(t){return t.nodeType===Node.TEXT_NODE?r(t)&&NodeFilter.FILTER_ACCEPT:o(t.attributes)&&NodeFilter.FILTER_REJECT},r=function(t){return/{(\w+|#)}/.test(t.textContent)},o=function(t){return Array.from(t).filter(function(t){return/{(\w+|#)}/g.test(t.value)}).map(function(t){return e.push(t)})},i=document.createNodeIterator(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,n);t=i.nextNode();)e.push(t);return e},TokenList.prototype.bind=function(t){var e=this,n=function(t){return e[t].map(function(t){return t.textContent=t.text})&&e[t].map(r(t))},r=function(e){return function(n){return n.textContent=n.textContent.replace("{"+e+"}",t[e])}};Object.keys(this).filter(function(e){return void 0!==t[e]}).map(n)};var HTMLTemplateElement=Template=function(t){function e(t){var e=this;contexts=(o=[]).concat.apply(o,[t]);var n,r=this.cloneNode(!1);return r.innerHTML=contexts.map(function(t){return t}).map(function(t,r){return t="object"==typeof t?t:{self:t},t["#"]=r,n=e.cloneNode(!0),void new TokenList(n.content).bind(t),n.innerHTML}).join(""),void(this.dependents||[]).map(function(t){return t.remove()}),this.dependents=Array.from(r.content.childNodes),this.after(r.content),this;var o}return Object.assign(document.querySelector("template[name="+t+"]"),{bind:e})},EventTarget=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.connectedCallback=function(){new HTMLLinkElement(this.tagName.toLowerCase()).addEventListener("load",this.onimport.bind(this))},e.prototype.on=function(t,e){this.addEventListener(t,e)},e}(t)},ParentNode=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.selectAll=function(t){return this.querySelectorAll(t)},e.prototype.select=function(t){return this.selectAll(t)[0]},e}(t)},GlobalEventHandlers=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.onimport=function(e,n){void 0===n&&(n=e.target["import"]),n&&this.clone(n.querySelector("template")),t.onconnect&&t.onconnect.call(this),this.render()},e.prototype.register=function(e){var n=this;void 0===e&&(e=function(t){return/^on/.test(t)});var r=function(r){return e(r)&&null===n[r]&&(n[r]=t[r].bind(n))},o="*",i=Array.from(this.querySelectorAll(o)),u=function(t){return Array.from(t.attributes).map(function(t){return t.name}).filter(e).map(c(t))},c=function(e){return function(r){return e[r]=/{\s*(\w+)\s*}/.exec(e[r])&&t[r]&&t[r].bind(n)||e[r]||null}};Object.getOwnPropertyNames(t).map(r),void[this].concat(i).map(u)},e}(t)},Component=function(t){return function(e){function n(){e.call(this),this.context={},this.initialize&&this.initialize(),this.tokens=new TokenList(this)}return e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.prototype.render=function(){var e=this;this.tokens.bind(this),Array.from(this.selectAll("template[name]")).map(function(t){return t.getAttribute("name")}).map(function(t){return new Template(t).bind(e[t])}),this.register(),t.onidle&&t.onidle.call(this)},n.prototype.clone=function(t){var e=this,n=t.content.cloneNode(!0),r=Array.from(n.querySelectorAll("slot")),o=function(t){return r.filter(i(t)).map(u(t))},i=function(t){return function(e){return t.getAttribute("slot")===e.getAttribute("name")}},u=function(t){return function(e){return e.parentNode.replaceChild(t,e)}};Array.from(t.attributes).map(function(t){return e.setAttribute(t.name,t.value)}),Array.from(this.querySelectorAll("[slot]")).map(o),this.innerHTML=t.innerHTML},n}(EventTarget(ParentNode(GlobalEventHandlers(t))))},ElementPrototype=window.Element.prototype,Element=function(t,e){return void 0===e&&(e=window.customElements),function(n){return e.define.apply(e,t.concat([Component(n)]))}};Element.prototype=ElementPrototype;<|endoftext|>


<commit_before>var eppGenerator = require('./epp.js');
var eppConnection = require('./connection.js');
var parser = require('xml2json');

module.exports = function(registry, config) {
    var epp = eppGenerator(registry, config);
    var connection = eppConnection(config);
    return {
        "connection": connection,
        "state": "offline",
        "idle": function() {
            var self = this;
            this.state = 'idle';
            this.interval = setInterval(function() {
                self.command('hello', null, function() {
                    return {
                        "status": "OK"
                    };
                });
            },
            60000);
        },

        "resultOk": function(result) {
            if (result.status === 'OK') {
                return true;
            }
            return false;
        },

        // actions
        "login": function(data, callback) {
            var self = this;
            var xml = epp.login(data, 'test-1234');
            //console.log(xml);
            // send login
            this.connection.send(xml, callback);
            return xml;
        },

        "logout": function(callback) {
            var self = this;
            var xml = epp.logout('test-1234');
            console.log(xml);
            // send login
            this.connection.send(xml, callback);
            return xml;
        },

        "hello": function() {
            var self = this;
            var xml = epp.hello();
            console.log(xml);
            this.connection.send(xml, function(returnedXML) {
                var response = parser.toJson(returnedXML);
                self.idle();
            });
        },

        "createContact": function(data, callback) {
            var self = this;
            var xml = epp.createContact(data, 'test-check-1234');
            this.connection.send(xml, callback);
        },
        "checkContact": function(data, callback) {
            var self = this;
            var xml = epp.checkContact(data, 'test-check-1234');
            this.connection.send(xml, callback);
        },
        "infoContact": function(data, callback) {
            var self = this;
            var xml = epp.infoContact(data, 'test-info-1234');
            this.connection.send(xml, callback);
        },
        "checkDomain": function(data, callback) {
            var self = this;
            var xml = epp.checkDomain(data, 'test-check-1234');
            this.connection.send(xml, callback);
        },
        "createDomain": function(data, callback) {
            var self = this;
            var xml = epp.createDomain(data, 'test-create-1234');
            this.connection.send(xml, callback);
        },
        "infoDomain": function(data, callback) {
            var self = this;
            var xml = epp.infoDomain(data, 'test-info-1234');
            this.connection.send(xml, callback);
        },

        "domain_command": function(command, data, callback) {
            console.log("Executing a " + command + " with: ", data);
            var result = callback();
            this.idle();
            return result;
        },
        "contact_command": function(command, data, callback) {
            console.log("Executing a " + command + " with: ", data);
            var result = callback();
            this.idle();
            return result;
        },
        "processResponse": function (eppJson) {
            var eppData = eppJson.epp;
            if (eppData) {
                var eppResponse = eppData.response;
                var returnData = {
                    "result": eppResponse.result,
                    "data": eppResponse.resData,
                    "transactionId": eppResponse.trID
                };
                return JSON.stringify(returnData);
            }
            return JSON.stringify(eppJson);
        },
        "command": function(command, data, callback) {
            var self = this;
            var result;
            // TODO May have to check that we're not actually executing a
            // 'hello' command when this happens otherwise we could cause
            // a race condition.
            // stop hello loop
            if (this.interval) {
                clearInterval(this.interval);
            }

            // standard callbacks for all responses
            var returnCallback = function(returnedXML) {
                var response = parser.toJson(returnedXML, {"object": true});
                var processedResponse = self.processResponse(response);

                callback(processedResponse);
                self.idle();
            };

            this.state = 'command';
            var xml;
            try {
                switch (command) {
                case 'login':
                    this.login(data, returnCallback);
                    break;
                case 'logout':
                    this.logout(returnCallback);
                    break;
                case 'hello':
                    this.hello();
                    break;
                case 'checkDomain':
                    this.checkDomain(data, returnCallback);
                    break;
                case 'createDomain':
                    this.createDomain(data, returnCallback);
                    break;
                case 'infoDomain':
                case 'deleteDomain':
                    result = this.domain_command(command, data, returnCallback);
                    break;

                case 'checkContact':
                case 'infoContact':
                case 'createContact':
                    this.createContact(data, returnCallback);
                    break;
                case 'deleteContact':
                    result = this.contact_command(command, data, returnCallback);
                    break;
                default:
                    console.log("Unknown command: " + command);
                }

            } catch(e) {
                console.log("Encountered an error: ", e);
            }
            return result;
        },

    };
};

<commit_msg>see why json datastructure isn't coming back<commit_after>var eppGenerator = require('./epp.js');
var eppConnection = require('./connection.js');
var parser = require('xml2json');

module.exports = function(registry, config) {
    var epp = eppGenerator(registry, config);
    var connection = eppConnection(config);
    return {
        "connection": connection,
        "state": "offline",
        "idle": function() {
            var self = this;
            this.state = 'idle';
            this.interval = setInterval(function() {
                self.command('hello', null, function() {
                    return {
                        "status": "OK"
                    };
                });
            },
            60000);
        },

        "resultOk": function(result) {
            if (result.status === 'OK') {
                return true;
            }
            return false;
        },

        // actions
        "login": function(data, callback) {
            var self = this;
            var xml = epp.login(data, 'test-1234');
            //console.log(xml);
            // send login
            this.connection.send(xml, callback);
            return xml;
        },

        "logout": function(callback) {
            var self = this;
            var xml = epp.logout('test-1234');
            console.log(xml);
            // send login
            this.connection.send(xml, callback);
            return xml;
        },

        "hello": function() {
            var self = this;
            var xml = epp.hello();
            console.log(xml);
            this.connection.send(xml, function(returnedXML) {
                var response = parser.toJson(returnedXML);
                self.idle();
            });
        },

        "createContact": function(data, callback) {
            var self = this;
            var xml = epp.createContact(data, 'test-check-1234');
            this.connection.send(xml, callback);
        },
        "checkContact": function(data, callback) {
            var self = this;
            var xml = epp.checkContact(data, 'test-check-1234');
            this.connection.send(xml, callback);
        },
        "infoContact": function(data, callback) {
            var self = this;
            var xml = epp.infoContact(data, 'test-info-1234');
            this.connection.send(xml, callback);
        },
        "checkDomain": function(data, callback) {
            var self = this;
            var xml = epp.checkDomain(data, 'test-check-1234');
            this.connection.send(xml, callback);
        },
        "createDomain": function(data, callback) {
            var self = this;
            var xml = epp.createDomain(data, 'test-create-1234');
            this.connection.send(xml, callback);
        },
        "infoDomain": function(data, callback) {
            var self = this;
            var xml = epp.infoDomain(data, 'test-info-1234');
            this.connection.send(xml, callback);
        },

        "domain_command": function(command, data, callback) {
            console.log("Executing a " + command + " with: ", data);
            var result = callback();
            this.idle();
            return result;
        },
        "contact_command": function(command, data, callback) {
            console.log("Executing a " + command + " with: ", data);
            var result = callback();
            this.idle();
            return result;
        },
        "processResponse": function (eppJson) {
            console.log("Processing response: ", eppJson);
            var eppData = eppJson.epp;
            console.log("eppData is: ", eppData);
            if (eppData) {
                var eppResponse = eppData.response;
                var returnData = {
                    "result": eppResponse.result,
                    "data": eppResponse.resData,
                    "transactionId": eppResponse.trID
                };
                return JSON.stringify(returnData);
            }
            return JSON.stringify(eppJson);
        },
        "command": function(command, data, callback) {
            var self = this;
            var result;
            // TODO May have to check that we're not actually executing a
            // 'hello' command when this happens otherwise we could cause
            // a race condition.
            // stop hello loop
            if (this.interval) {
                clearInterval(this.interval);
            }

            // standard callbacks for all responses
            var returnCallback = function(returnedXML) {
                var response = parser.toJson(returnedXML, {"object": true});
                var processedResponse = self.processResponse(response);

                callback(processedResponse);
                self.idle();
            };

            this.state = 'command';
            var xml;
            try {
                switch (command) {
                case 'login':
                    this.login(data, returnCallback);
                    break;
                case 'logout':
                    this.logout(returnCallback);
                    break;
                case 'hello':
                    this.hello();
                    break;
                case 'checkDomain':
                    this.checkDomain(data, returnCallback);
                    break;
                case 'createDomain':
                    this.createDomain(data, returnCallback);
                    break;
                case 'infoDomain':
                case 'deleteDomain':
                    result = this.domain_command(command, data, returnCallback);
                    break;

                case 'checkContact':
                case 'infoContact':
                case 'createContact':
                    this.createContact(data, returnCallback);
                    break;
                case 'deleteContact':
                    result = this.contact_command(command, data, returnCallback);
                    break;
                default:
                    console.log("Unknown command: " + command);
                }

            } catch(e) {
                console.log("Encountered an error: ", e);
            }
            return result;
        },

    };
};

<|endoftext|>


<commit_before>'use strict';

let jwt = require('jsonwebtoken');
let User = require('../user/model');

function authenticate(req, res) {
  let body = {
    bnetId: req.user.id,
    battletag: req.user.battletag,
    token: req.user.token,
    provider: req.user.provider
  };

  User
   .findOneAndUpdate(
     {bnetId: req.user.id, battletag: req.user.battletag},
     body,
     {upsert: true}
   )
   .exec()
   .then(() => {
     let token = jwt.sign({
       bnetId: req.user.id,
       battletag: req.user.battletag
     }, req.app.get('superSecret'), {
       // expiresInMinutes: 1440 // expires in 24 hours
     });

     res.cookie('token', token, {
       domain: (app.get('env') === 'local') ? 'localhost' : '.nobreaksguild.com',
       secure: true
     });
     res.redirect(req.headers.referer || '/');
   });
}

function logout(req, res) {
  req.logout();
  res.cookie('token', '', { expires: new Date() });
  res.redirect(req.headers.referer);
}

module.exports = {
  authenticate: authenticate,
  logout: logout
};
<commit_msg>Fix cookies again<commit_after>'use strict';

let jwt = require('jsonwebtoken');
let User = require('../user/model');

function authenticate(req, res) {
  let body = {
    bnetId: req.user.id,
    battletag: req.user.battletag,
    token: req.user.token,
    provider: req.user.provider
  };

  User
   .findOneAndUpdate(
     {bnetId: req.user.id, battletag: req.user.battletag},
     body,
     {upsert: true}
   )
   .exec()
   .then(() => {
     let token = jwt.sign({
       bnetId: req.user.id,
       battletag: req.user.battletag
     }, req.app.get('superSecret'), {
       // expiresInMinutes: 1440 // expires in 24 hours
     });

     res.cookie('token', token, {
       domain: (req.app.get('env') === 'local') ? 'localhost' : '.nobreaksguild.com',
       secure: true
     });
     res.redirect(req.headers.referer || '/');
   });
}

function logout(req, res) {
  req.logout();
  res.cookie('token', '', { expires: new Date() });
  res.redirect(req.headers.referer);
}

module.exports = {
  authenticate: authenticate,
  logout: logout
};
<|endoftext|>


<commit_before> 'use strict';

var build       = module.exports = {};
var fs          = require('fs');
var fse         = require('fs-extra');
var expand      = require('fs-expand');
var node_path   = require('path');
var semver      = require('semver');
var stable      = require('semver-stable');
var async       = require('async');
var cortex_json   = require('read-cortex-json');
var semver_helper = require('../util/semver');
var lang        = require('../util/lang');
var spawns      = require('spawns');
var builder     = require('neuron-builder');

// @param {Object} options
//      see ./lib/option/build.js for details
build.run = function(options, callback) {
  var profile = this.profile;

  // if the destination is not specified by user
  if (!options.dest) {
    var entry_cwd = options['entry-cwd'];

    if (!profile.get('server_mode') && entry_cwd) {
      // if cortex is not running in server mode, see 'doc/<language>/server-mode.md',
      // we will build module into <root-cwd>/neurons folder
      options.dest = node_path.join(entry_cwd, 'neurons');

    } else {
      // If server_mode is on, we assume that we always use cortex server to develop,
      // and all packages will be built to a certain dir.
      options.dest = profile.get('built_root');
    }
  }

  this.MESSAGE = this.locale.require('command-build');

  var self = this;
  async.series([
    function(done) {
      self.read_package_json(options, done);
    },
    function(done) {
      self.run_preinstall_script(options, done);
    },
    function(done) {
      // run custom build script
      self.run_prebuild_script(options, done);
    },
    function(done) {
      // determine build tasks
      self.determine_tasks(options, done);
    },
    function(done) {
      // real building
      self.build(options, done);
    }
  ], function(err) {
    callback(err);
  });
};

build.read_package_json = function(options, callback) {
  cortex_json.read(options.cwd, function(err, pkg) {
    options.pkg = pkg;
    callback(err);
  });
};

// Run custom build scripts, such as 'grunt'
build.run_preinstall_script = function(options, callback) {
  if (!options.preinstall) {
    return callback(null);
  }

  this.run_script('preinstall', options, callback);
};

// Run custom build scripts, such as 'grunt'
build.run_prebuild_script = function(options, callback) {
  if (!options.prebuild) {
    return callback(null);
  }

  this.run_script('prebuild', options, callback);
};

build.run_script = function(script, options, callback) {
  var pkg = options.pkg;
  var scripts = lang.makeArray(pkg.scripts && pkg.scripts[script])
  // skip empty scripts
  .filter(Boolean);

  if (!scripts.length) {
    return callback(null);
  }

  var self = this;

  this.logger.info('{{cyan run}} "scripts.' + script + '" ...');

  spawns(scripts, {
    cwd: options.cwd,
    stdio: 'inherit'

  }).on('spawn', function(command) {
    self.logger.info(' - {{cyan exec}} "' + command + '" ...');

  }).on('close', function(code, signal) {
    if (code) {
      callback({
        code: 'EBUILDSCRIPT',
        message: 'build step "scripts.' + script + '" executes as a failure. exit code: ' + code,
        data: {
          code: code,
          signal: signal,
          script: script
        }
      });
    } else {
      callback(null);
    }

  }).on('error', function(err) {
    self.logger.warn('"scripts.' + script + '" let out an error: ' + err);
  });
};

build.determine_tasks = function(options, callback) {
  var cache_root = this.profile.get('cache_root');
  var tasks = options.tasks = {};
  var name = options.pkg.name;
  var version = options.pkg.version;
  var built_root = options.dest;

  var parsed = semver_helper.parse(version);

  if (!parsed) {
    return callback({
      code: 'EINVALIDVER',
      message: 'invalid semantic version "' + version + '" in package.json, see http://semver.org for details.',
      data: {
        version: version
      }
    });
  }

  // Cortex will no longer publish prerelease versions into the registry,
  // so use the original version directly.
  tasks[version] = node_path.join(built_root, name, version);

  var self = this;

  if (options.ranges) {
    cortex_json.cached_document(name, cache_root, function(err, json) {
      if (err) {
        return callback(err);
      }

      var versions = json && json.versions && Object.keys(json.versions) || [];
      versions.sort(semver.rcompare);

      // '1.2.3' -> '~1.2.0'
      var range = semver_helper.get_base_range(parsed);
      var max_patch = semver.maxSatisfying(versions, range);
      var max_stable_patch = stable.maxSatisfying(versions, range);
      var max = versions[0];
      var max_stable = stable.max(versions);

      if (
        // [1]
        // If the current minor(feature) doesn't exist, it is the max matched patch of the current minor
        !max_patch ||

        // Greater or equal to
        semver.gte(version, max_patch) ||

        // If the current version is greater or equal to the max stable patch,
        // we also let it go
        max_stable_patch && semver.gte(version, max_stable_patch)
      ) {
        // >>>> range
        tasks[range] = node_path.join(built_root, name, range);

        // if the package is not the latest patch,
        // it's impossible to be the latest of all versions
        if (
          // if there's no versions on the registry,
          // See 1
          !max ||

          // if current version is the greatest
          semver.gte(version, max) ||
          max_stable && semver.gte(version, max_stable)
        ) {
          // >>>> latest
          tasks.latest = node_path.join(built_root, name, 'latest');
        }
      }

      // {
      //     '1.2.3': '/xxx/~1.2.0',
      //     'latest': '/xxx/latest'
      // }
      callback(null, tasks);
    });

  } else {
    callback(null, tasks);
  }
};

build.build = function(options, callback) {
  var pkg = options.pkg;
  // distribution directory
  var dist = lang.object_member_by_namespaces(options.pkg, 'directories.dist');

  if (dist) {
    return this.dist(dist, options, callback);
  }

  var self = this;
  this.check_entry(options, function(err) {
    if (err) {
      return callback(err);
    }

    var tasks = options.tasks;
    async.each(Object.keys(tasks), function(target_version, done) {
      var to = tasks[target_version];
      async.parallel([
        function (done) {
          // Build JavaScript modules
          self.build_modules(target_version, to, options, done);
        },
        function (done) {
          self.copy(options.cwd, to, 'cortex-shrinkwrap.json', done);
        },
        function (done) {
          // Copy css
          self.copy_csses(to, options, done);
        },
        function (done) {
          // Copy directories
          self.copy_directories(to, options, done);
        }
      ], done);
    }, callback);
  });
};

build.dist = function (dist, options, callback) {
  dist = node_path.join(options.cwd, dist);
  // if `dist` dir exists, skip building and just copy it
  fs.exists(dist, function(exists) {
    if (!exists) {
      // if `cortex.directories.dist` is declared, the dir must be existed.
      return callback({
        code: 'EDISTNOTEXISTS',
        message: 'dist dir "' + dist + '" does not exist.',
        data: {
          dist: dist
        }
      });
    }

    this.logger.info('dist dir "' + dist + '" found, {{cyan skip}} building ...');
    this.copy_dist(dist, options, callback);
  }.bind(this));
};

// copy dist dir to the destination dirs
build.copy_dist = function(dist, options, callback) {
  var self = this;
  var tasks = options.tasks;
  async.each(Object.keys(tasks), function(task, done) {
    var to = tasks[task];
    self.logger.info('{{cyan copy}} "' + dist + '" to "' + to + '".');
    self.copy(dist, to, done);
  }, callback);
};

build.check_entry = function (options, callback) {
  var self = this;
  this.main_exists(options, function (exists) {
    if (exists) {
      var cwd = options.cwd;
      var pkg = options.pkg;
      // the module '<name>.js'
      var main_by_name = node_path.join(cwd, pkg.name) + '.js';
      var main_path = node_path.join(cwd, options.main_entry);

      fs.exists(main_by_name, function(exists) {
        if (exists && main_by_name !== main_path) {
          return callback({
            code: 'MAIN_CONFLICT',
            message: 'if "' + pkg.name + '.js" exists, it must be `package.main`, or you should rename it.',
            data: {
              name: pkg.name,
              main: pkg.main
            }
          });
        }
        self.get_entries(options, callback);
      });
      return;
    }

    if (!options.pkg.css) {
      return callback({
        code: 'NO_ENTRY_FOUND',
        message: 'Both `package.main` and `package.css` are not found. You need to define at least one.'
      });
    }
    callback(null);
  });
};

build.main_exists = function (options, callback) {
  var main_entry = options.pkg.main || 'index.js';

  // Standardize main entry
  // './index' -> './index.js'
  main_entry = this.ensure_ext(main_entry, 'js');
  // './index.js' -> 'index.js'
  main_entry = node_path.join('.', main_entry);
  var main_file = node_path.join(options.cwd, main_entry);

  fs.exists(main_file, function (exists) {
    if (exists) {
      options.main_entry = main_entry;
    }
    callback(exists);
  });
};

// Gets all entries, including
// - pkg.main
// - pkg.entries
build.get_entries = function(options, callback) {
  var pkg_entries = options.pkg.entries;
  if (!pkg_entries) {
    options.entries = [options.main_entry];
    return callback(null);
  }

  expand(pkg_entries, {
    cwd: options.cwd
  }, function (err, entries) {
    if (err) {
      return callback(err);
    }
    options.entries = entries;
    // prevent duplication
    if (!~entries.indexOf(options.main_entry)) {
      entries.push(options.main_entry);
    }

    callback(null);
  });
};

build.ensure_ext = function(path, ext) {
  var regex = new RegExp('\\.' + ext + '$', 'i');
  if (!regex.test(path)) {
    path += '.' + ext;
  }
  return path;
};

// Builds JavaScript modules
build.build_modules = function(target_version, to, options, callback) {
  // Pure css package.
  if (!options.main_entry) {
    return callback(null);
  }

  var self = this;
  var cwd = options.cwd;
  async.each(options.entries, function (entry, done) {
    // Standardize entries
    // './index.js' -> 'index.js'
    entry = node_path.join('.', entry);
    var from = node_path.join(cwd, entry);

    builder(from, {
      cwd: cwd,
      targetVersion: target_version,
      pkg: options.pkg

    }, function (err, content) {
      if (err) {
        return done(err);
      }

      var file_to = entry === options.main_entry
        // main entry will
        ? options.pkg.name + '.js'
        : entry;

      var path_to = node_path.join(to, file_to);
      fse.mkdirs( node_path.dirname(path_to), function (err) {
        if (err) {
          return done(err);
        }

        self.logger.info('{{cyan write}} ' + path_to);
        fs.writeFile(path_to, content, done);
      });
    });

  }, callback);
};

build.copy_csses = function (to, options, callback) {
  var css = options.pkg.css;
  if (!css) {
    return callback(null);
  }

  async.each(css, function (path, done) {
    this.copy(options.cwd, to, path, function (err) {
      if (err && err.code === 'SRC_NOT_FOUND') {
        err = {
          code: 'CSS_NOT_FOUND',
          message: '`pkg.css`, "' + path + '" is declared but not found.',
          data: {
            path: path
          }
        };
      }
      done(err);
    }, true);
  }.bind(this), callback);
};

build.copy_directories = function(to, options, callback) {
  var pkg = options.pkg;
  var directories = pkg.directories || {};

  var tasks = [
    // We only support `directories.src` for now.
    'src'
  ].filter(function (dir) {
    return directories[dir];
  });

  async.each(tasks, function (name, done) {
    var dir = directories[name];
    this.copy(options.cwd, to, dir, function (err) {
      if (err && err.code === 'SRC_NOT_FOUND') {
        err = {
          code: 'DIR_NOT_FOUND',
          message: '`directories.' + name + '` is defined in cortex.json, but not found.',
          data: {
            name: name,
            dir: dir
          }
        };
      }
      done(err);
    }, true);

  }.bind(this), callback);
};

// Copy files from `from` to `to`
// @param {Boolean} strict
build.copy = function(from, to, item, callback, strict) {
  var self = this;
  if (from === to) {
    callback(null);
    return;
  }

  from = node_path.join(from, item);
  to = node_path.join(to, item);
  fs.exists(from, function (exists) {
    if (!exists) {
      // if strict and the source is not found, an error will throw.
      if (strict) {
        return callback({
          code: 'SRC_NOT_FOUND'
        });
      } else {
        return callback(null);
      }
    }

    self.logger.info('{{cyan copy}} ' + from + ' -> ' + to);
    fse.copy(from, to, callback);
  });
};
<commit_msg>command/build: fixes directories.dist; #354<commit_after> 'use strict';

var build       = module.exports = {};
var fs          = require('fs');
var fse         = require('fs-extra');
var expand      = require('fs-expand');
var node_path   = require('path');
var semver      = require('semver');
var stable      = require('semver-stable');
var async       = require('async');
var cortex_json   = require('read-cortex-json');
var semver_helper = require('../util/semver');
var lang        = require('../util/lang');
var spawns      = require('spawns');
var builder     = require('neuron-builder');

// @param {Object} options
//      see ./lib/option/build.js for details
build.run = function(options, callback) {
  var profile = this.profile;

  // if the destination is not specified by user
  if (!options.dest) {
    var entry_cwd = options['entry-cwd'];

    if (!profile.get('server_mode') && entry_cwd) {
      // if cortex is not running in server mode, see 'doc/<language>/server-mode.md',
      // we will build module into <root-cwd>/neurons folder
      options.dest = node_path.join(entry_cwd, 'neurons');

    } else {
      // If server_mode is on, we assume that we always use cortex server to develop,
      // and all packages will be built to a certain dir.
      options.dest = profile.get('built_root');
    }
  }

  this.MESSAGE = this.locale.require('command-build');

  var self = this;
  async.series([
    function(done) {
      self.read_package_json(options, done);
    },
    function(done) {
      self.run_preinstall_script(options, done);
    },
    function(done) {
      // run custom build script
      self.run_prebuild_script(options, done);
    },
    function(done) {
      // determine build tasks
      self.determine_tasks(options, done);
    },
    function(done) {
      // real building
      self.build(options, done);
    }
  ], function(err) {
    callback(err);
  });
};

build.read_package_json = function(options, callback) {
  cortex_json.read(options.cwd, function(err, pkg) {
    options.pkg = pkg;
    callback(err);
  });
};

// Run custom build scripts, such as 'grunt'
build.run_preinstall_script = function(options, callback) {
  if (!options.preinstall) {
    return callback(null);
  }

  this.run_script('preinstall', options, callback);
};

// Run custom build scripts, such as 'grunt'
build.run_prebuild_script = function(options, callback) {
  if (!options.prebuild) {
    return callback(null);
  }

  this.run_script('prebuild', options, callback);
};

build.run_script = function(script, options, callback) {
  var pkg = options.pkg;
  var scripts = lang.makeArray(pkg.scripts && pkg.scripts[script])
  // skip empty scripts
  .filter(Boolean);

  if (!scripts.length) {
    return callback(null);
  }

  var self = this;

  this.logger.info('{{cyan run}} "scripts.' + script + '" ...');

  spawns(scripts, {
    cwd: options.cwd,
    stdio: 'inherit'

  }).on('spawn', function(command) {
    self.logger.info(' - {{cyan exec}} "' + command + '" ...');

  }).on('close', function(code, signal) {
    if (code) {
      callback({
        code: 'EBUILDSCRIPT',
        message: 'build step "scripts.' + script + '" executes as a failure. exit code: ' + code,
        data: {
          code: code,
          signal: signal,
          script: script
        }
      });
    } else {
      callback(null);
    }

  }).on('error', function(err) {
    self.logger.warn('"scripts.' + script + '" let out an error: ' + err);
  });
};

build.determine_tasks = function(options, callback) {
  var cache_root = this.profile.get('cache_root');
  var tasks = options.tasks = {};
  var name = options.pkg.name;
  var version = options.pkg.version;
  var built_root = options.dest;

  var parsed = semver_helper.parse(version);

  if (!parsed) {
    return callback({
      code: 'EINVALIDVER',
      message: 'invalid semantic version "' + version + '" in package.json, see http://semver.org for details.',
      data: {
        version: version
      }
    });
  }

  // Cortex will no longer publish prerelease versions into the registry,
  // so use the original version directly.
  tasks[version] = node_path.join(built_root, name, version);

  var self = this;

  if (options.ranges) {
    cortex_json.cached_document(name, cache_root, function(err, json) {
      if (err) {
        return callback(err);
      }

      var versions = json && json.versions && Object.keys(json.versions) || [];
      versions.sort(semver.rcompare);

      // '1.2.3' -> '~1.2.0'
      var range = semver_helper.get_base_range(parsed);
      var max_patch = semver.maxSatisfying(versions, range);
      var max_stable_patch = stable.maxSatisfying(versions, range);
      var max = versions[0];
      var max_stable = stable.max(versions);

      if (
        // [1]
        // If the current minor(feature) doesn't exist, it is the max matched patch of the current minor
        !max_patch ||

        // Greater or equal to
        semver.gte(version, max_patch) ||

        // If the current version is greater or equal to the max stable patch,
        // we also let it go
        max_stable_patch && semver.gte(version, max_stable_patch)
      ) {
        // >>>> range
        tasks[range] = node_path.join(built_root, name, range);

        // if the package is not the latest patch,
        // it's impossible to be the latest of all versions
        if (
          // if there's no versions on the registry,
          // See 1
          !max ||

          // if current version is the greatest
          semver.gte(version, max) ||
          max_stable && semver.gte(version, max_stable)
        ) {
          // >>>> latest
          tasks.latest = node_path.join(built_root, name, 'latest');
        }
      }

      // {
      //     '1.2.3': '/xxx/~1.2.0',
      //     'latest': '/xxx/latest'
      // }
      callback(null, tasks);
    });

  } else {
    callback(null, tasks);
  }
};

build.build = function(options, callback) {
  var pkg = options.pkg;
  // distribution directory
  var dist = lang.object_member_by_namespaces(options.pkg, 'directories.dist');

  if (dist) {
    return this.dist(dist, options, callback);
  }

  var self = this;
  this.check_entry(options, function(err) {
    if (err) {
      return callback(err);
    }

    var tasks = options.tasks;
    async.each(Object.keys(tasks), function(target_version, done) {
      var to = tasks[target_version];
      async.parallel([
        function (done) {
          // Build JavaScript modules
          self.build_modules(target_version, to, options, done);
        },
        function (done) {
          self.copy(options.cwd, to, 'cortex-shrinkwrap.json', done);
        },
        function (done) {
          // Copy css
          self.copy_csses(to, options, done);
        },
        function (done) {
          // Copy directories
          self.copy_directories(to, options, done);
        }
      ], done);
    }, callback);
  });
};

build.dist = function (dist, options, callback) {
  var rel_dist = dist;
  var dist = node_path.join(options.cwd, dist);
  // if `dist` dir exists, skip building and just copy it
  fs.exists(dist, function(exists) {
    if (!exists) {
      // if `cortex.directories.dist` is declared, the dir must be existed.
      return callback({
        code: 'DIST_NOT_FOUND',
        message: 'dist dir "' + dist + '" does not exist.',
        data: {
          dist: dist
        }
      });
    }

    this.logger.info('dist dir "' + dist + '" found, {{cyan skip}} building ...');
    this.copy_dist(rel_dist, options, callback);
  }.bind(this));
};

// copy dist dir to the destination dirs
build.copy_dist = function(dist, options, callback) {
  var self = this;
  var tasks = options.tasks;
  async.each(Object.keys(tasks), function(task, done) {
    var to = tasks[task];
    self.copy(options.cwd, to, dist, done);
  }, callback);
};

build.check_entry = function (options, callback) {
  var self = this;
  this.main_exists(options, function (exists) {
    if (exists) {
      var cwd = options.cwd;
      var pkg = options.pkg;
      // the module '<name>.js'
      var main_by_name = node_path.join(cwd, pkg.name) + '.js';
      var main_path = node_path.join(cwd, options.main_entry);

      fs.exists(main_by_name, function(exists) {
        if (exists && main_by_name !== main_path) {
          return callback({
            code: 'MAIN_CONFLICT',
            message: 'if "' + pkg.name + '.js" exists, it must be `package.main`, or you should rename it.',
            data: {
              name: pkg.name,
              main: pkg.main
            }
          });
        }
        self.get_entries(options, callback);
      });
      return;
    }

    if (!options.pkg.css) {
      return callback({
        code: 'NO_ENTRY_FOUND',
        message: 'Both `package.main` and `package.css` are not found. You need to define at least one.'
      });
    }
    callback(null);
  });
};

build.main_exists = function (options, callback) {
  var main_entry = options.pkg.main || 'index.js';

  // Standardize main entry
  // './index' -> './index.js'
  main_entry = this.ensure_ext(main_entry, 'js');
  // './index.js' -> 'index.js'
  main_entry = node_path.join('.', main_entry);
  var main_file = node_path.join(options.cwd, main_entry);

  fs.exists(main_file, function (exists) {
    if (exists) {
      options.main_entry = main_entry;
    }
    callback(exists);
  });
};

// Gets all entries, including
// - pkg.main
// - pkg.entries
build.get_entries = function(options, callback) {
  var pkg_entries = options.pkg.entries;
  if (!pkg_entries) {
    options.entries = [options.main_entry];
    return callback(null);
  }

  expand(pkg_entries, {
    cwd: options.cwd
  }, function (err, entries) {
    if (err) {
      return callback(err);
    }
    options.entries = entries;
    // prevent duplication
    if (!~entries.indexOf(options.main_entry)) {
      entries.push(options.main_entry);
    }

    callback(null);
  });
};

build.ensure_ext = function(path, ext) {
  var regex = new RegExp('\\.' + ext + '$', 'i');
  if (!regex.test(path)) {
    path += '.' + ext;
  }
  return path;
};

// Builds JavaScript modules
build.build_modules = function(target_version, to, options, callback) {
  // Pure css package.
  if (!options.main_entry) {
    return callback(null);
  }

  var self = this;
  var cwd = options.cwd;
  async.each(options.entries, function (entry, done) {
    // Standardize entries
    // './index.js' -> 'index.js'
    entry = node_path.join('.', entry);
    var from = node_path.join(cwd, entry);

    builder(from, {
      cwd: cwd,
      targetVersion: target_version,
      pkg: options.pkg

    }, function (err, content) {
      if (err) {
        return done(err);
      }

      var file_to = entry === options.main_entry
        // main entry will
        ? options.pkg.name + '.js'
        : entry;

      var path_to = node_path.join(to, file_to);
      fse.mkdirs( node_path.dirname(path_to), function (err) {
        if (err) {
          return done(err);
        }

        self.logger.info('{{cyan write}} ' + path_to);
        fs.writeFile(path_to, content, done);
      });
    });

  }, callback);
};

build.copy_csses = function (to, options, callback) {
  var css = options.pkg.css;
  if (!css) {
    return callback(null);
  }

  async.each(css, function (path, done) {
    this.copy(options.cwd, to, path, function (err) {
      if (err && err.code === 'SRC_NOT_FOUND') {
        err = {
          code: 'CSS_NOT_FOUND',
          message: '`pkg.css`, "' + path + '" is declared but not found.',
          data: {
            path: path
          }
        };
      }
      done(err);
    }, true);
  }.bind(this), callback);
};

build.copy_directories = function(to, options, callback) {
  var pkg = options.pkg;
  var directories = pkg.directories || {};

  var tasks = [
    // We only support `directories.src` for now.
    'src'
  ].filter(function (dir) {
    return directories[dir];
  });

  async.each(tasks, function (name, done) {
    var dir = directories[name];
    this.copy(options.cwd, to, dir, function (err) {
      if (err && err.code === 'SRC_NOT_FOUND') {
        err = {
          code: 'DIR_NOT_FOUND',
          message: '`directories.' + name + '` is defined in cortex.json, but not found.',
          data: {
            name: name,
            dir: dir
          }
        };
      }
      done(err);
    }, true);

  }.bind(this), callback);
};

// Copy files from `from` to `to`
// @param {Boolean} strict
build.copy = function(from, to, item, callback, strict) {
  var self = this;
  if (from === to) {
    callback(null);
    return;
  }

  from = node_path.join(from, item);
  to = node_path.join(to, item);
  fs.exists(from, function (exists) {
    if (!exists) {
      // if strict and the source is not found, an error will throw.
      if (strict) {
        return callback({
          code: 'SRC_NOT_FOUND'
        });
      } else {
        return callback(null);
      }
    }

    self.logger.info('{{cyan copy}} ' + from + ' -> ' + to);
    fse.copy(from, to, callback);
  });
};
<|endoftext|>


<commit_before>exports.escape = function escape(s) {
  return s.replace(/[\+\-\!\(\)\{\}\[\]\^\"\?\:\\\&\|\'\/\ \*\~]/g, prefixCharWithBackslashes);
};

function prefixCharWithBackslashes(char) {
  return '\\' + char;
}

exports.unescape = function unescape(s) {
  return s.replace(/\\([\+\-\!\(\)\{\}\[\]\^\"\?\:\\\&\|\'\/\ \*\~])/g, extractChar);
};

function extractChar(match, char) {
  return char;
}

exports.escapePhrase = function escapePhrase(s) {
  return s.replace(/"/g, prefixCharWithBackslashes);
};

exports.unescapePhrase = function unescapePhrase(s) {
  return s.replace(/\\(")/g, extractChar);
};
<commit_msg>escape any whitespace<commit_after>exports.escape = function escape(s) {
  return s.replace(/[\+\-\!\(\)\{\}\[\]\^\"\?\:\\\&\|\'\/\s\*\~]/g, prefixCharWithBackslashes);
};

function prefixCharWithBackslashes(char) {
  return '\\' + char;
}

exports.unescape = function unescape(s) {
  return s.replace(/\\([\+\-\!\(\)\{\}\[\]\^\"\?\:\\\&\|\'\/\s\*\~])/g, extractChar);
};

function extractChar(match, char) {
  return char;
}

exports.escapePhrase = function escapePhrase(s) {
  return s.replace(/"/g, prefixCharWithBackslashes);
};

exports.unescapePhrase = function unescapePhrase(s) {
  return s.replace(/\\(")/g, extractChar);
};
<|endoftext|>


<commit_before>$(document).ready(function() {
    "use strict";
    document.title = "Fakedata Explorer - D3";

    $(".breadcrumb").nfBreadcrumbs({
        crumbs : [
            { text : "d3" }
        ]
    });

    function firstBarChart(){
        var chartScale = d3.scale.linear()
            .domain([0, d3.max(getFakeData())])
            .range([0, 500]),
        width = 500,
        barHeight = 20,
        chartPlace = $(".chart-placeholder"),
        chartSvg;

        chartPlace.append("svg");

        chartSvg =d3.select(chartPlace.find(".chart-svg") )
            .attr("width", width)
            .attr("height", barHeight * getFakeData().length);

        /*========= svg bar chart */
        var bar = chartSvg.selectAll("g")
            .data(getFakeData())
            .enter().append("g")
            .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

        bar.append("rect")
            .attr("width", chartScale)
            .attr("height", barHeight - 1);

        bar.append("text")
            .attr("x", function(d) { return chartScale(d) - 3; })
            .attr("y", barHeight / 2)
            .attr("dy", ".35em")
            .text(function(d) { return d; });
    }

    function getFakeData(){ //todo - replace with call to service that provides it
        return [5000,4000,3000,2000,1000];
    }

    function secondBarChart(){
        d3.select("#chart")
            .selectAll("div")
            .data(getFakeData())
            .enter().append("div")
            .style("width", function(d) { return chartScale(d)  + "px"; })
            .text(function(d) { return d; });

        var chart = d3.select(".chart-svg")
            .attr("width",width)
            .attr("height",barHeight * getFakeData().length);

        var bar = chart.selectAll("g")
            .data(getFakeData())
            .enter().append("g")
            .attr("transform", function(d,i){return "translate(0," + i * barHeight + ")"; }) ;

        bar.append("rect")
            .attr("width",chartScale)
            .attr("height",barHeight -1);

        bar.append("text")
            .attr("x", function(d){return chartScale(d) -3; })
            .attr("y", barHeight /2)
            .attr("dy", ".35em")
            .text(function(d){return d;}) ;
    }

    function getInstallationsByZip(){
        var notifier=$(".notifier");
        notifier.append("retrieving data...").show();
        $.ajax({
            url: "solardata/installationCountByZip.json",
            success: function(data,textStatus,jqXHR){
                var serverData = {};
                serverData.children = data.installationCountByZip;
                doPack(serverData);
            },
            failure: function(jqXHR, textStatus, errorThrown){
                var notifier=$(".notifier");
                notifier.hide();
                notifier.empty();
                notifier.attr("background-color","firebrick");
                notifier.attr("color","white");
                notifier.append(" STATUS: "+textStatus+ "  ERROR: " + errorThrown +"").show();
            },
            complete: function(){}
        });
    }

    function doPack(data){
        var notifier=$(".notifier");
        notifier.hide();
        notifier.empty();
        notifier.append("got it!").show();
    }

    var jsonZips = {
            children: [
                {zipCode: "90638",
                    value: 651},
                {zipCode: "93004",
                    value: 139},
                {zipCode: "93003",
                    value: 115},
                {zipCode: "95120",
                    value: 80}
            ]}
        ;

    function circlePackLayout() {

        var packWidth = 960,packHeight = 500,
            format = d3.format(",d"),
            fill = d3.scale.category10(),
            bubbleScale=d3.scale.linear()
                .domain([0, d3.max(jsonZips.children,function(d){return d.value;})])
                .range([0, packHeight]);

        var pack = d3.layout.pack()
            .sort(d3.descending)
            .size([packWidth, packHeight])
            .padding(1.5);

        var svg = d3.select("#next-chart").append("svg")
            .attr("width", packWidth)
            .attr("height", packHeight);

        var node = svg.data([jsonZips]).selectAll(".node")
            .data(pack.nodes)
            .enter().append("g")
                .attr("transform", function(d) {
                    return "translate(" + bubbleScale(d.x) + "," + bubbleScale(d.y) +")";
                });

            node.append("circle")
            .attr("class", "node")
            .attr("r", function(d) {
                return bubbleScale(d.r);
            })
            .style("fill", function(d) {
                return fill(d.value);
            });

        node.append("title")
            .text(function(d) {
                return d.zipCode + ": " + format(d.value);
            });

        node.append("text")
            .attr("text-anchor", "middle")
            .attr("dy", ".3em")
            .text(function(d) {
                return d.zipCode;
            });
    }
    //============= Just plain Yellow Circles

    function yellowCircles(){

        var circleChartScale = d3.scale.linear()
            .domain([0, d3.max(jsonZips.children,function(d){return d.value;})])
            .range([0, 500]),
            circlePadding= 5,
            circleChart = d3.select("div#circle-chart").append("svg").attr("width", 1000).attr("height", 500),
            circle = circleChart.selectAll("g")
                .data(jsonZips.children)
                .enter()
                .append("g")
                .attr("transform", function(d, i) {
                    var xOffset= parseInt(circlePadding,10) + circleChartScale(d.value)/2;
                    return "translate(" + xOffset + ",250)";
                });

        circle.append("circle")
    //        .attr("cx", function (d) {
    //            return circleChartScale(d.value);
    //        })
    //        .attr("cy", 25)
            .attr("r", function (d) {
                return circleChartScale(d.value)/2;
            })
            .attr("fill", "yellow")
            .attr("stroke", "orange")
            .attr("stroke-width", 5);

        circle.append("text")
            .attr("text-anchor", "middle")
            .attr("dx", function(d){return -20;})
            .attr("fill", "black")
            .text(function(d) {
                return d.zipCode;
            });
    }

    circlePackLayout();
    yellowCircles();

});<commit_msg>ajax call to get installationsByZipCount<commit_after>$(document).ready(function() {
    "use strict";
    document.title = "Fakedata Explorer - D3";

    $(".breadcrumb").nfBreadcrumbs({
        crumbs : [
            { text : "d3" }
        ]
    });

    function firstBarChart(){
        var chartScale = d3.scale.linear()
            .domain([0, d3.max(getFakeData())])
            .range([0, 500]),
        width = 500,
        barHeight = 20,
        chartPlace = $(".chart-placeholder"),
        chartSvg;

        chartPlace.append("svg");

        chartSvg =d3.select(chartPlace.find(".chart-svg") )
            .attr("width", width)
            .attr("height", barHeight * getFakeData().length);

        /*========= svg bar chart */
        var bar = chartSvg.selectAll("g")
            .data(getFakeData())
            .enter().append("g")
            .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

        bar.append("rect")
            .attr("width", chartScale)
            .attr("height", barHeight - 1);

        bar.append("text")
            .attr("x", function(d) { return chartScale(d) - 3; })
            .attr("y", barHeight / 2)
            .attr("dy", ".35em")
            .text(function(d) { return d; });
    }

    function getFakeData(){ //todo - replace with call to service that provides it
        return [5000,4000,3000,2000,1000];
    }

    function secondBarChart(){
        d3.select("#chart")
            .selectAll("div")
            .data(getFakeData())
            .enter().append("div")
            .style("width", function(d) { return chartScale(d)  + "px"; })
            .text(function(d) { return d; });

        var chart = d3.select(".chart-svg")
            .attr("width",width)
            .attr("height",barHeight * getFakeData().length);

        var bar = chart.selectAll("g")
            .data(getFakeData())
            .enter().append("g")
            .attr("transform", function(d,i){return "translate(0," + i * barHeight + ")"; }) ;

        bar.append("rect")
            .attr("width",chartScale)
            .attr("height",barHeight -1);

        bar.append("text")
            .attr("x", function(d){return chartScale(d) -3; })
            .attr("y", barHeight /2)
            .attr("dy", ".35em")
            .text(function(d){return d;}) ;
    }

    function getInstallationsByZip(){
        var notifier=$(".notifier");
        notifier.append("retrieving data...").show();
        $.ajax({
            url: "../solardata/installationCountByZip.json",
            success: function(data,textStatus,jqXHR){
                var serverData = {};
                serverData.children = data.installationCountByZip;
                doPack(serverData);
            },
            failure: function(jqXHR, textStatus, errorThrown){
                var notifier=$(".notifier");
                notifier.hide();
                notifier.empty();
                notifier.attr("background-color","firebrick");
                notifier.attr("color","white");
                notifier.append(" STATUS: "+textStatus+ "  ERROR: " + errorThrown +"").show();
            }
        });
    }

    function doPack(data){
        var notifier=$(".notifier");
        notifier.hide();
        notifier.empty();
        notifier.append("got " +data.children.length + " zipcode records").show();
        notifier.fadeOut(5000);
    }

    var jsonZips = {
            children: [
                {zipCode: "90638",
                    value: 651},
                {zipCode: "93004",
                    value: 139},
                {zipCode: "93003",
                    value: 115},
                {zipCode: "95120",
                    value: 80}
            ]}
        ;

    function circlePackLayout() {

        var packWidth = 960,packHeight = 500,
            format = d3.format(",d"),
            fill = d3.scale.category10(),
            bubbleScale=d3.scale.linear()
                .domain([0, d3.max(jsonZips.children,function(d){return d.value;})])
                .range([0, packHeight]);

        var pack = d3.layout.pack()
            .sort(d3.descending)
            .size([packWidth, packHeight])
            .padding(1.5);

        var svg = d3.select("#next-chart").append("svg")
            .attr("width", packWidth)
            .attr("height", packHeight);

        var node = svg.data([jsonZips]).selectAll(".node")
            .data(pack.nodes)
            .enter().append("g")
                .attr("transform", function(d) {
                    return "translate(" + bubbleScale(d.x) + "," + bubbleScale(d.y) +")";
                });

            node.append("circle")
            .attr("class", "node")
            .attr("r", function(d) {
                return bubbleScale(d.r);
            })
            .style("fill", function(d) {
                return fill(d.value);
            });

        node.append("title")
            .text(function(d) {
                return d.zipCode + ": " + format(d.value);
            });

        node.append("text")
            .attr("text-anchor", "middle")
            .attr("dy", ".3em")
            .text(function(d) {
                return d.zipCode;
            });
    }
    //============= Just plain Yellow Circles

    function yellowCircles(){

        var circleChartScale = d3.scale.linear()
            .domain([0, d3.max(jsonZips.children,function(d){return d.value;})])
            .range([0, 500]),
            circlePadding= 5,
            circleChart = d3.select("div#circle-chart").append("svg").attr("width", 1000).attr("height", 500),
            circle = circleChart.selectAll("g")
                .data(jsonZips.children)
                .enter()
                .append("g")
                .attr("transform", function(d, i) {
                    var xOffset= parseInt(circlePadding,10) + circleChartScale(d.value)/2;
                    return "translate(" + xOffset + ",250)";
                });

        circle.append("circle")
    //        .attr("cx", function (d) {
    //            return circleChartScale(d.value);
    //        })
    //        .attr("cy", 25)
            .attr("r", function (d) {
                return circleChartScale(d.value)/2;
            })
            .attr("fill", "yellow")
            .attr("stroke", "orange")
            .attr("stroke-width", 5);

        circle.append("text")
            .attr("text-anchor", "middle")
            .attr("dx", function(d){return -20;})
            .attr("fill", "black")
            .text(function(d) {
                return d.zipCode;
            });
    }

    circlePackLayout();
    yellowCircles();
    getInstallationsByZip();

});<|endoftext|>


<commit_before>/**
 * var connection = new Connection({ tag:        'groonga',
 *                                   host:       'localhost',
 *                                   port:       24224,
 *                                   listenPort: 10030 });
 *
 * // for REST APIs
 * connection.emitMessage(
 *   { command: 'search',
 *     query:   'foobar' },
 *   function callback(result) {
 *     // codes to handle results from the backend
 *   }
 * );
 *
 * // for socket.io APIs
 * connection.on('notification', function listener(messageBody) { ... });
 * // volatile message
 * connection.emitMessage({ command: 'reindex' });
 */

var EventEmitter = require('events').EventEmitter;
var socketIo = require('socket.io');
var fluent = require('fluent-logger');

var DEFAULT_FLUENT_TAG  = 'groonga';
var DEFAULT_FLUENT_HOST = 'localhost';
var DEFAULT_FLUENT_PORT = 24224;
var DEFAULT_LISTEN_PORT = 10030;

function Connection(params) {
  this._params = params || {};
  this._init();
}

Connection.prototype = new EventEmitter();

Connection.prototype._init = function() {
  this._callbacks = {};
  this._initSender();
  this._initReceiver();
};

Connection.prototype._initSender = function() {
  this._sender = (
    this._params.sender ||
    fluent.createFluentSender(this._params.tag || DEFAULT_FLUENT_TAG,
                              { host: this._params.host || DEFAULT_FLUENT_HOST,
                                port: this._params.port || DEFAULT_FLUENT_PORT })
  );
};

Connection.prototype._initReceiver = function() {
  this._receiver = (
    this._params.receiver ||
    socketIo.listen(this._params.listenPort || DEFAULT_LISTEN_PORT)
  );

  this._receiver.sockets.on(
    'connection',
    (function(socket) {
      socket.on((this._params.tag || DEFAULT_FLUENT_TAG)+ '.message',
                this._handleMessage.bind(this));
    }).bind(this)
  );
  this._receiver.set('log level', 1);
};

Connection.prototype._handleMessage = function(message) {
  var replyTo = message['reply_to'];
  if (replyTo) {
    this.emit('replyTo:' + replyTo, message.body);
  }
};

function createId() {
  return Date.now() + ':' + Math.round(Math.random() * 65536);
}

Connection.prototype.emitMessage = function(message, callback) {
  var id = createId();
  var message = {
    id:   id,
    body: message
  };
  if (callback) {
    this.once('replyTo:' + id, callback);
  }
  this._sender.emit('message', message);
};

exports.Connection = Connection;
<commit_msg>Make sent message stable (work in progress: prepare test framework)<commit_after>/**
 * var connection = new Connection({ tag:        'groonga',
 *                                   host:       'localhost',
 *                                   port:       24224,
 *                                   listenPort: 10030 });
 *
 * // for REST APIs
 * connection.emitMessage(
 *   { command: 'search',
 *     query:   'foobar' },
 *   function callback(result) {
 *     // codes to handle results from the backend
 *   }
 * );
 *
 * // for socket.io APIs
 * connection.on('notification', function listener(messageBody) { ... });
 * // volatile message
 * connection.emitMessage({ command: 'reindex' });
 */

var EventEmitter = require('events').EventEmitter;
var socketIo = require('socket.io');
var fluent = require('fluent-logger');

var DEFAULT_FLUENT_TAG  = 'groonga';
var DEFAULT_FLUENT_HOST = 'localhost';
var DEFAULT_FLUENT_PORT = 24224;
var DEFAULT_LISTEN_PORT = 10030;

function Connection(params) {
  this._params = params || {};
  this._init();
}

Connection.prototype = new EventEmitter();

Connection.prototype._init = function() {
  this._callbacks = {};
  this._initSender();
  this._initReceiver();
};

Connection.prototype._initSender = function() {
  this._sender = (
    this._params.sender ||
    fluent.createFluentSender(this._params.tag || DEFAULT_FLUENT_TAG,
                              { host: this._params.host || DEFAULT_FLUENT_HOST,
                                port: this._params.port || DEFAULT_FLUENT_PORT })
  );
};

Connection.prototype._initReceiver = function() {
  this._receiver = (
    this._params.receiver ||
    socketIo.listen(this._params.listenPort || DEFAULT_LISTEN_PORT)
  );

  this._receiver.sockets.on(
    'connection',
    (function(socket) {
      socket.on((this._params.tag || DEFAULT_FLUENT_TAG)+ '.message',
                this._handleMessage.bind(this));
    }).bind(this)
  );
  this._receiver.set('log level', 1);
};

Connection.prototype._handleMessage = function(message) {
  var replyTo = message['reply_to'];
  if (replyTo) {
    this.emit('replyTo:' + replyTo, message.body);
  }
};

function createId() {
  return Date.now() + ':' + Math.round(Math.random() * 65536);
}

Connection.prototype.emitMessage = function(message, callback) {
  var id = createId();
  var message = {
//    id:   id,
    body: message
  };
  if (callback) {
    this.once('replyTo:' + id, callback);
  }
  this._sender.emit('message', message);
};

exports.Connection = Connection;
<|endoftext|>


<commit_before>var utils = require('../utils'),
    packages = require('../packages'),
    logger = require('../logger'),
    couchdb = require('../couchdb'),
    kansorc = require('../kansorc'),
    argParse = require('../args').parse,
    exec = require('child_process').exec,
    path = require('path'),
    fs = require('fs'),
    pathExists = fs.exists || path.exists,
    url = require('url'),
    urlParse = url.parse,
    urlFormat = url.format;

exports.summary = 'Load a project and push to a CouchDB database';

exports.usage = '' +
'kanso push [PATH] [DB]\n' +
'\n' +
'Parameters:\n' +
'  PATH    Path to project directory to push (defaults to ".")\n' +
'  DB      The CouchDB database to upload the app to, will use "default"\n' +
'          env set in .kansorc if none provided and .kansorc exists\n' +
'\n' +
'Options:\n' +
'  --minify    Compress CommonJS modules attachment using UglifyJS\n' +
'  --open      Open the app URL in the browser after pushing\n' +
'  --baseURL   Add a custom baseURL property to the kanso.json values\n' +
'  --id        Specify a custom document id for the generated app,\n' +
'              defaults to "_design/<name>" where <name> is from kanso.json';

/**
 * Main command called when typing "kanso push ..." on the command line
 */

exports.run = function (settings, args) {
    var a = argParse(args, {
        'minify': {match: '--minify'},
        'open': {match: '--open'},
        'baseURL': {match: '--baseURL', value: true},
        'id': {match: '--id', value: true}
    });
    var url;
    var dir = a.positional[0] || '.';
    pathExists(dir, function (exists) {
        if (!exists) {
            dir = process.cwd();
            url = a.positional[0];
        }
        dir = utils.abspath(dir);
        kansorc.extend(settings, dir + '/.kansorc', function (err, settings) {
            if (err) {
                return logger.error(err);
            }
            if (a.positional.length > 1) {
                url = a.positional[1];
            }
            else if (a.positional.length && !exists) {
                url = a.positional[0];
            }

            var env = utils.argToEnv(settings, url);
            url = env.db;
            if (env.baseURL) {
                a.options.baseURL = env.baseURL;
            }
            if (env.minify) {
                a.options.minify = env.minify;
            }
            if (env.id) {
                a.options.id = env.id;
            }

            // these options will override values in kanso.json
            // the 'id' and 'open' options are not relevant to that data
            var opt = env.overrides || {};
            opt.minify = a.options.minify;
            opt.baseURL = a.options.baseURL;

            exports.loadApp(dir, url, opt, settings,
                function (err, url, cfg, doc) {
                    if (err) {
                        return logger.error(err);
                    }
                    var app_url = exports.getAppURL(url, cfg, doc);
                    var noauth_url = utils.noAuthURL(app_url);

                    if (a.options.open) {
                        exports.openInBrowser(app_url, function (err) {
                            if (err) {
                                return logger.error(err);
                            }
                            logger.end(noauth_url);
                        });
                    }
                    else {
                        logger.end(noauth_url);
                    }
                }
            );
        });
    });
};

/**
 * Builds the app prior to pushing
 */

exports.loadApp = function (dir, url, options, settings, callback) {
    var paths = settings.package_paths || [];
    var parent_dir = path.dirname(dir);
    if (path.basename(parent_dir) === 'packages') {
        paths.push(parent_dir);
    }
    var build_start = new Date().getTime();
    // make the url available to the modules
    options._url = url;
    packages.load(dir, paths, null, options, function (err, doc, cfg) {
        if (err) {
            if (callback) {
                return callback(err);
            }
            else {
                return logger.error(err);
            }
        }
        var build_end = new Date().getTime();
        console.log('Build complete: ' + (build_end - build_start) + 'ms');
        utils.completeAuth(url, false, function (err, url) {
            if (err) {
                return callback(err);
            }
            utils.catchAuthError(
                exports.push, url, [dir, options, cfg, doc], callback
            );
        });
    });
};

/**
 * Upload the app to the DB, catch auth errors and prompt for password
 */

exports.push = function (url, dir, options, cfg, doc, callback) {
    var db = couchdb(url);
    var root = couchdb(url);
    root.instance.pathname = '';
    root.session(function (err, info, resp) {
        if (err) {
            return callback(err);
        }
        var server_time = utils.ISODateString(new Date(resp.headers.date));
        if (!doc.kanso) {
            doc.kanso = {};
        }
        doc.kanso.push_time = server_time;
        doc.kanso.pushed_by = info.userCtx.name;

        db.ensureDB(function (err) {
            if (err) {
                return callback(err);
            }
            var id = options.id || '_design/' + cfg.name;
            logger.info('Uploading...');

            db.save(id, doc, {force: true}, function (err) {
                callback(err, url, cfg, doc);
            });
        });
    });
};

/**
 * Tries to determine the right URL to report on the command-line after a
 * successful push
 *
 * OK: <url>
 */

exports.getAppURL = function (url, cfg, doc) {
    var newurl= urlParse(url);
    delete newurl.auth;
    delete newurl.host;
    var ddoc_url = urlFormat(newurl) + '/' + doc._id;

    if (!/^_design\//.test(doc._id)) {
        // not pushed as a design doc, report doc url instead of app url
        return ddoc_url;
    }

    var app_url = ddoc_url;
    if (cfg.index) {
        // if there's an index property in kanso.json
        app_url = ddoc_url + cfg.index;
    }
    if (cfg.baseURL !== undefined) {
        // if there is a custom baseURL defined
        newurl.pathname = cfg.baseURL + '/';
        app_url = urlFormat(newurl);
    }
    else if (doc.rewrites && doc.rewrites.length) {
        app_url = ddoc_url + '/_rewrite/';
    }
    else if (doc._attachments && doc._attachments['index.html']) {
        app_url = ddoc_url + '/index.html';
    }
    else if (doc._attachments && doc._attachments['index.htm']) {
        app_url = ddoc_url + '/index.htm';
    }
    return app_url;
};

/**
 * Opens the app URL in the browser when the --open option is used
 */

exports.openInBrowser = function (url, callback) {
    if (process.platform === 'linux') {
        cmd = 'xdg-open';
    }
    else {
        // OSX
        cmd = 'open';
    }
    console.log('Opening URL in browser...');
    exec(cmd + ' ' + url, callback);
};
<commit_msg>Make utils available to modules, mainly for getAuth<commit_after>var utils = require('../utils'),
    packages = require('../packages'),
    logger = require('../logger'),
    couchdb = require('../couchdb'),
    kansorc = require('../kansorc'),
    argParse = require('../args').parse,
    exec = require('child_process').exec,
    path = require('path'),
    fs = require('fs'),
    pathExists = fs.exists || path.exists,
    url = require('url'),
    urlParse = url.parse,
    urlFormat = url.format;

exports.summary = 'Load a project and push to a CouchDB database';

exports.usage = '' +
'kanso push [PATH] [DB]\n' +
'\n' +
'Parameters:\n' +
'  PATH    Path to project directory to push (defaults to ".")\n' +
'  DB      The CouchDB database to upload the app to, will use "default"\n' +
'          env set in .kansorc if none provided and .kansorc exists\n' +
'\n' +
'Options:\n' +
'  --minify    Compress CommonJS modules attachment using UglifyJS\n' +
'  --open      Open the app URL in the browser after pushing\n' +
'  --baseURL   Add a custom baseURL property to the kanso.json values\n' +
'  --id        Specify a custom document id for the generated app,\n' +
'              defaults to "_design/<name>" where <name> is from kanso.json';

/**
 * Main command called when typing "kanso push ..." on the command line
 */

exports.run = function (settings, args) {
    var a = argParse(args, {
        'minify': {match: '--minify'},
        'open': {match: '--open'},
        'baseURL': {match: '--baseURL', value: true},
        'id': {match: '--id', value: true}
    });
    var url;
    var dir = a.positional[0] || '.';
    pathExists(dir, function (exists) {
        if (!exists) {
            dir = process.cwd();
            url = a.positional[0];
        }
        dir = utils.abspath(dir);
        kansorc.extend(settings, dir + '/.kansorc', function (err, settings) {
            if (err) {
                return logger.error(err);
            }
            if (a.positional.length > 1) {
                url = a.positional[1];
            }
            else if (a.positional.length && !exists) {
                url = a.positional[0];
            }

            var env = utils.argToEnv(settings, url);
            url = env.db;
            if (env.baseURL) {
                a.options.baseURL = env.baseURL;
            }
            if (env.minify) {
                a.options.minify = env.minify;
            }
            if (env.id) {
                a.options.id = env.id;
            }

            // these options will override values in kanso.json
            // the 'id' and 'open' options are not relevant to that data
            var opt = env.overrides || {};
            opt.minify = a.options.minify;
            opt.baseURL = a.options.baseURL;

            exports.loadApp(dir, url, opt, settings,
                function (err, url, cfg, doc) {
                    if (err) {
                        return logger.error(err);
                    }
                    var app_url = exports.getAppURL(url, cfg, doc);
                    var noauth_url = utils.noAuthURL(app_url);

                    if (a.options.open) {
                        exports.openInBrowser(app_url, function (err) {
                            if (err) {
                                return logger.error(err);
                            }
                            logger.end(noauth_url);
                        });
                    }
                    else {
                        logger.end(noauth_url);
                    }
                }
            );
        });
    });
};

/**
 * Builds the app prior to pushing
 */

exports.loadApp = function (dir, url, options, settings, callback) {
    var paths = settings.package_paths || [];
    var parent_dir = path.dirname(dir);
    if (path.basename(parent_dir) === 'packages') {
        paths.push(parent_dir);
    }
    var build_start = new Date().getTime();
    // make the url available to the modules
    options._url = url;
    options._utils = utils;
    packages.load(dir, paths, null, options, function (err, doc, cfg) {
        if (err) {
            if (callback) {
                return callback(err);
            }
            else {
                return logger.error(err);
            }
        }
        var build_end = new Date().getTime();
        console.log('Build complete: ' + (build_end - build_start) + 'ms');
        utils.completeAuth(url, false, function (err, url) {
            if (err) {
                return callback(err);
            }
            utils.catchAuthError(
                exports.push, url, [dir, options, cfg, doc], callback
            );
        });
    });
};

/**
 * Upload the app to the DB, catch auth errors and prompt for password
 */

exports.push = function (url, dir, options, cfg, doc, callback) {
    var db = couchdb(url);
    var root = couchdb(url);
    root.instance.pathname = '';
    root.session(function (err, info, resp) {
        if (err) {
            return callback(err);
        }
        var server_time = utils.ISODateString(new Date(resp.headers.date));
        if (!doc.kanso) {
            doc.kanso = {};
        }
        doc.kanso.push_time = server_time;
        doc.kanso.pushed_by = info.userCtx.name;

        db.ensureDB(function (err) {
            if (err) {
                return callback(err);
            }
            var id = options.id || '_design/' + cfg.name;
            logger.info('Uploading...');

            db.save(id, doc, {force: true}, function (err) {
                callback(err, url, cfg, doc);
            });
        });
    });
};

/**
 * Tries to determine the right URL to report on the command-line after a
 * successful push
 *
 * OK: <url>
 */

exports.getAppURL = function (url, cfg, doc) {
    var newurl= urlParse(url);
    delete newurl.auth;
    delete newurl.host;
    var ddoc_url = urlFormat(newurl) + '/' + doc._id;

    if (!/^_design\//.test(doc._id)) {
        // not pushed as a design doc, report doc url instead of app url
        return ddoc_url;
    }

    var app_url = ddoc_url;
    if (cfg.index) {
        // if there's an index property in kanso.json
        app_url = ddoc_url + cfg.index;
    }
    if (cfg.baseURL !== undefined) {
        // if there is a custom baseURL defined
        newurl.pathname = cfg.baseURL + '/';
        app_url = urlFormat(newurl);
    }
    else if (doc.rewrites && doc.rewrites.length) {
        app_url = ddoc_url + '/_rewrite/';
    }
    else if (doc._attachments && doc._attachments['index.html']) {
        app_url = ddoc_url + '/index.html';
    }
    else if (doc._attachments && doc._attachments['index.htm']) {
        app_url = ddoc_url + '/index.htm';
    }
    return app_url;
};

/**
 * Opens the app URL in the browser when the --open option is used
 */

exports.openInBrowser = function (url, callback) {
    if (process.platform === 'linux') {
        cmd = 'xdg-open';
    }
    else {
        // OSX
        cmd = 'open';
    }
    console.log('Opening URL in browser...');
    exec(cmd + ' ' + url, callback);
};
<|endoftext|>