<commit_before>var child_process = require('child_process');
var path = require('path');

/**
 * Do a simulated class inheritance using a function representing the
 * constructor of a base class and a function representing the constructor of
 * a child class. I could (of course) use yet another particular library to do
 * this, but this will also introduce another dependency on another package.
 * Therefore, I did it myself.
 *
 * I don't dislike the concept of prototypes, but the way it's implemented in
 * JavaScript is just too crazy. You have to do some crazy stuff to properly set
 * prototypes, as we cannot control them directly. Anyway, this function
 * abstracts over that burden so that we don't have to repeat this every time.
 *
 * @param {function} parent Constructor function of the simulated parent class
 * @param {function} child Constructor function of the simulated child class
 */

function inherit(parent, child) {
    function F() {}; /* Dummy constructor function used to create an empty object with the parent's prototype */
    F.prototype = parent.prototype; /* Assign the parent constructor function's prototype property (not the real prototype) to the dummy constructor function. */
    child.prototype = new F(); /* Create an instance of the dummy custructor. This call returns an empty object, which has the parent's prototype */
    child.prototype.constructor = child; /* Set the constructor to our child constructor function again, as it has been changed by the parent's prototype */
}

/**
 * Creates a Nix object that captures common properties for Nix language
 * constructs for which is no equivalent JavaScript type available.
 *
 * @constructor
 * @param {...} value Value of the reference
 */
function NixObject(value) {
    this.value = value;
};

exports.NixObject = NixObject;

/**
 * Creates a Nix file object that gets imported into the Nix store. Paths to a
 * file may be absolute (starting with a /) or relative. For relative paths a
 * module reference must be given so that it can be correctly resolved to a
 * correct absolute path.
 *
 * @constructor
 * @param {object} args Arguments to this function
 * @param {string} args.value An absolute or relative path to a file
 * @param {Module} args.module Reference to the CommonJS module that refers to a relative path (not needed for absolute paths)
 */

function NixFile(args) {
    NixObject.call(this, args.value);
    this.module = args.module;
};

inherit(NixObject, NixFile);

exports.NixFile = NixFile;

/**
 * Creates a Nix URL object that gets validates by the Nix expression evaluator.
 *
 * @constructor
 * @param {string} value Value containing a URL
 */

function NixURL(value) {
    NixObject.call(this, value);
};

inherit(NixObject, NixURL);

exports.NixURL = NixURL;

/**
 * Creates a Nix object that contains an already generated Nix expression.
 *
 * @constructor
 * @param {string} value Value containing a Nix expression
 */
function NixExpression(value) {
    NixObject.call(this, value);
};

inherit(NixObject, NixExpression);

exports.NixExpression = NixExpression;

/**
 * Creates a recursive attribute set in which members can refer to each other.
 *
 * @param {object} value An aribitrary object that should be represented as a recursive attribute set. This object is stored as a reference.
 * @constructor
 */
function NixRecursiveAttrSet(value) {
    NixObject.call(this, value);
}

inherit(NixObject, NixRecursiveAttrSet);

exports.NixRecursiveAttrSet = NixRecursiveAttrSet;

/**
 * Converts members of an object to members of an attribute set
 *
 * @param {object} obj Object to convert
 * @return {string} A string containing the Nix attribute set members
 */
function objectMembersToAttrsMembers(obj) {
    var str = "";

    for(var attrName in obj) {
        var attrValue = jsToNix(obj[attrName]);
            str += "  "+attrName+" = "+attrValue+";\n";
    }

    return str;
}

/**
 * Converts a collection of JavaScript objects to a sementically equivalent or
 * similar Nix expression language object.
 *
 * @param {...*} var_args A variable amount of parameters that can be of any JavaScript object type
 * @return {string} A string containing the converted Nix expression language object
 */
function jsToNix() {
    var expr = "";

    for(var i = 0; i < arguments.length; i++) {

        var arg = arguments[i];

        if(i > 0)
            expr += " "; /* Add white space between every argument */

        if(arg === null) {
            expr += "null"; /* We must check for the null reference explicitly */
        } else {

            /* Use a type match to determine the conversion from a JavaScript object to a Nix expression language object */
            var type = typeof arg;

            switch(type) {
                case "boolean":
                    if(arg)
                        expr += "true";
                    else
                        expr += "false";

                    break;

                case "number":
                    expr += arg;
                    break;

                case "string":
                    expr = '"'+arg.replace(/\"/g, '\\"')+'"';
                    break;

                case "object":
                    if(Array.isArray(arg)) { /* Arrays are also objects, but this will tell us the difference */
                        var str = "[\n";

                        for(var i = 0; i < arg.length; i++)
                            str += "("+exports.jsToNix(arg[i]) + ")\n";

                        str += "]";

                        expr += str;
                        break;

                    } else if(arg instanceof NixURL) {
                        expr += arg.value;
                        break;

                    } else if(arg instanceof NixFile) {
                        var dir = "";

                        /*
                         * If the path does not start with a / and a module is
                         * defined, we consider the file to have a relative path
                         * and we have to add the module's dirname as prefix
                         */

                        if(arg.value.substring(0, 1) != '/' && arg.module !== undefined)
                            dir = path.dirname(arg.module.filename) + "/";

                        /* Generate Nix file object */
                        if(dir.indexOf(" ") == -1 && arg.value.indexOf(" ") == -1)
                            expr += dir + arg.value; /* Filenames without spaces can be placed verbatim */
                        else
                            expr += '/. + "' + dir.replace(/\"/g, '\\"') + arg.value.replace(/\"/g, '\\"') + '"'; /* Filenames with spaces require some conversion */

                        break;

                    } else if(arg instanceof NixExpression) {
                        expr += "(" + arg.value + ")";
                        break;
                    } else if(arg instanceof NixRecursiveAttrSet) {

                        var str = "rec {\n" + objectMembersToAttrsMembers(arg.value) + "}";
                        expr += str;
                        break;

                    } else {
                        var str = "{\n" + objectMembersToAttrsMembers(arg) + "}";
                        expr += str;
                        break;
                    }

                case "function":
                    var str = "";

                    for(var i = 0; i < arg.length; i++)
                        str += "arg" + i + ":\n";

                    str += "nijsFunProxy {\n";
                    str += "  function = ''"+arg.toString()+"'';\n";
                    str += "  args = [\n";

                    for(var i = 0; i < arg.length; i++)
                        str += "    arg" + i + "\n";

                    str += "  ];\n";
                    str += "}\n";

                    expr += str;
                    break;

                case "xml":
                    expr += '"'+arg.toXMLString().replace(/\"/g, '\\"')+'"';
                    break;

                case "undefined":
                    throw "We cannot convert something that is undefined!";
            }
        }
    }

    return expr;
}

exports.jsToNix = jsToNix;

/**
 * Invokes the nix-build process to evaluate a given nix object containing a Nix
 * expression. As a side-effect, the declared package gets build.
 *
 * @param {object} args Nix build parameters
 * @param {NixExpression} args.nixObject An object instance of the NixExpression prototype, with a string value that contains a Nix expression
 * @param {Array.<string>} args.params An array of strings representing command-line parameters passed to nix-build
 * @param {function(string)} args.onSuccess Callback function that gets called with the resulting Nix store path, if the build succeeds
 * @param {function(number)} args.onFailure Callback function that gets called with the resulting non-zero exit status, if the build fails
 */
exports.nixBuild = function(args) {
    var output = "";

    var nixBuildProcess = child_process.spawn("nix-build", args.params.concat(["-"]));

    nixBuildProcess.stdin.write(args.expression);
    nixBuildProcess.stdin.end();

    nixBuildProcess.stdout.on("data", function(data) {
        output += data; /* Capture the Nix store path */
    });

    nixBuildProcess.stderr.on("data", function(data) {
        process.stderr.write(data);
    });

    nixBuildProcess.on("exit", function(code) {
        if(code == 0)
            args.onSuccess(output.substring(0, output.length - 1));
        else
            args.onFailure(code);
    });
};

/**
 * Augments a given Nix object with a Nix expression with a Nixpkgs and NiJS
 * reference and executes nix-build to evaluate the expression.
 *
 * @param {object} args Nix build parameters
 * @param {NixExpression} args.nixObject An object instance of the NixExpression prototype, with a string value that contains a Nix expression
 * @param {Array.<string>} args.params An array of strings representing command-line parameters passed to nix-build
 * @param {function(string)} args.onSuccess Callback function that gets called with the resulting Nix store path, if the build succeeds
 * @param {function(number)} args.onFailure Callback function that gets called with the resulting non-zero exit status, if the build fails
 */
exports.callNixBuild = function(args) {
    var expression = "let\n"+
      "  pkgs = import <nixpkgs> {};\n"+
      "  nijsFunProxy = import <nijs/lib/funProxy.nix> { inherit (pkgs) stdenv nodejs; };\n"+
      "in\n" + args.nixObject.value;

    exports.nixBuild({
        expression : expression,
        params : args.params,
        onSuccess : args.onSuccess,
        onFailure : args.onFailure
    });
}
<commit_msg>Some comment clarifications<commit_after>var child_process = require('child_process');
var path = require('path');

/**
 * Do a simulated class inheritance using a function representing the
 * constructor of a base class and a function representing the constructor of
 * a child class. I could (of course) use yet another particular library to do
 * this, but this will also introduce another dependency on another package.
 * Therefore, I did it myself.
 *
 * I don't dislike the concept of prototypes, but the way it's implemented in
 * JavaScript is just too crazy. You have to do some crazy stuff to properly set
 * prototypes, as we cannot control them directly. Anyway, this function
 * abstracts over that burden so that we don't have to repeat this every time.
 *
 * @param {function} parent Constructor function of the simulated parent class
 * @param {function} child Constructor function of the simulated child class
 */

function inherit(parent, child) {
    function F() {}; /* Dummy constructor function used to create an empty object with a prototype containing the parent's class definition */
    F.prototype = parent.prototype; /* Assign the parent constructor function's prototype property (not the real prototype) to the dummy constructor function. */
    child.prototype = new F(); /* Create an instance of the dummy constructor. This call returns an empty object, which prototype contains the parent's class definition */
    child.prototype.constructor = child; /* Set the constructor to our child constructor function again, as it has been changed by the parent's prototype */
}

/**
 * Creates a Nix object that captures common properties for Nix language
 * constructs for which is no equivalent JavaScript type available.
 *
 * @constructor
 * @param {...} value Value of the reference
 */
function NixObject(value) {
    this.value = value;
};

exports.NixObject = NixObject;

/**
 * Creates a Nix file object that gets imported into the Nix store. Paths to a
 * file may be absolute (starting with a /) or relative. For relative paths a
 * module reference must be given so that it can be correctly resolved to a
 * correct absolute path.
 *
 * @constructor
 * @param {object} args Arguments to this function
 * @param {string} args.value An absolute or relative path to a file
 * @param {Module} args.module Reference to the CommonJS module that refers to a relative path (not needed for absolute paths)
 */

function NixFile(args) {
    NixObject.call(this, args.value);
    this.module = args.module;
};

inherit(NixObject, NixFile);

exports.NixFile = NixFile;

/**
 * Creates a Nix URL object that gets validates by the Nix expression evaluator.
 *
 * @constructor
 * @param {string} value Value containing a URL
 */

function NixURL(value) {
    NixObject.call(this, value);
};

inherit(NixObject, NixURL);

exports.NixURL = NixURL;

/**
 * Creates a Nix object that contains an already generated Nix expression.
 *
 * @constructor
 * @param {string} value Value containing a Nix expression
 */
function NixExpression(value) {
    NixObject.call(this, value);
};

inherit(NixObject, NixExpression);

exports.NixExpression = NixExpression;

/**
 * Creates a recursive attribute set in which members can refer to each other.
 *
 * @param {object} value An aribitrary object that should be represented as a recursive attribute set. This object is stored as a reference.
 * @constructor
 */
function NixRecursiveAttrSet(value) {
    NixObject.call(this, value);
}

inherit(NixObject, NixRecursiveAttrSet);

exports.NixRecursiveAttrSet = NixRecursiveAttrSet;

/**
 * Converts members of an object to members of an attribute set
 *
 * @param {object} obj Object to convert
 * @return {string} A string containing the Nix attribute set members
 */
function objectMembersToAttrsMembers(obj) {
    var str = "";

    for(var attrName in obj) {
        var attrValue = jsToNix(obj[attrName]);
            str += "  "+attrName+" = "+attrValue+";\n";
    }

    return str;
}

/**
 * Converts a collection of JavaScript objects to a sementically equivalent or
 * similar Nix expression language object.
 *
 * @param {...*} var_args A variable amount of parameters that can be of any JavaScript object type
 * @return {string} A string containing the converted Nix expression language object
 */
function jsToNix() {
    var expr = "";

    for(var i = 0; i < arguments.length; i++) {

        var arg = arguments[i];

        if(i > 0)
            expr += " "; /* Add white space between every argument */

        if(arg === null) {
            expr += "null"; /* We must check for the null reference explicitly */
        } else {

            /* Use a type match to determine the conversion from a JavaScript object to a Nix expression language object */
            var type = typeof arg;

            switch(type) {
                case "boolean":
                    if(arg)
                        expr += "true";
                    else
                        expr += "false";

                    break;

                case "number":
                    expr += arg;
                    break;

                case "string":
                    expr = '"'+arg.replace(/\"/g, '\\"')+'"';
                    break;

                case "object":
                    if(Array.isArray(arg)) { /* Arrays are also objects, but this will tell us the difference */
                        var str = "[\n";

                        for(var i = 0; i < arg.length; i++)
                            str += "("+exports.jsToNix(arg[i]) + ")\n";

                        str += "]";

                        expr += str;
                        break;

                    } else if(arg instanceof NixURL) {
                        expr += arg.value;
                        break;

                    } else if(arg instanceof NixFile) {
                        var dir = "";

                        /*
                         * If the path does not start with a / and a module is
                         * defined, we consider the file to have a relative path
                         * and we have to add the module's dirname as prefix
                         */

                        if(arg.value.substring(0, 1) != '/' && arg.module !== undefined)
                            dir = path.dirname(arg.module.filename) + "/";

                        /* Generate Nix file object */
                        if(dir.indexOf(" ") == -1 && arg.value.indexOf(" ") == -1)
                            expr += dir + arg.value; /* Filenames without spaces can be placed verbatim */
                        else
                            expr += '/. + "' + dir.replace(/\"/g, '\\"') + arg.value.replace(/\"/g, '\\"') + '"'; /* Filenames with spaces require some conversion */

                        break;

                    } else if(arg instanceof NixExpression) {
                        expr += "(" + arg.value + ")";
                        break;
                    } else if(arg instanceof NixRecursiveAttrSet) {

                        var str = "rec {\n" + objectMembersToAttrsMembers(arg.value) + "}";
                        expr += str;
                        break;

                    } else {
                        var str = "{\n" + objectMembersToAttrsMembers(arg) + "}";
                        expr += str;
                        break;
                    }

                case "function":
                    var str = "";

                    for(var i = 0; i < arg.length; i++)
                        str += "arg" + i + ":\n";

                    str += "nijsFunProxy {\n";
                    str += "  function = ''"+arg.toString()+"'';\n";
                    str += "  args = [\n";

                    for(var i = 0; i < arg.length; i++)
                        str += "    arg" + i + "\n";

                    str += "  ];\n";
                    str += "}\n";

                    expr += str;
                    break;

                case "xml":
                    expr += '"'+arg.toXMLString().replace(/\"/g, '\\"')+'"';
                    break;

                case "undefined":
                    throw "We cannot convert something that is undefined!";
            }
        }
    }

    return expr;
}

exports.jsToNix = jsToNix;

/**
 * Invokes the nix-build process to evaluate a given nix object containing a Nix
 * expression. As a side-effect, the declared package gets build.
 *
 * @param {object} args Nix build parameters
 * @param {NixExpression} args.nixObject An object instance of the NixExpression prototype, with a string value that contains a Nix expression
 * @param {Array.<string>} args.params An array of strings representing command-line parameters passed to nix-build
 * @param {function(string)} args.onSuccess Callback function that gets called with the resulting Nix store path, if the build succeeds
 * @param {function(number)} args.onFailure Callback function that gets called with the resulting non-zero exit status, if the build fails
 */
exports.nixBuild = function(args) {
    var output = "";

    var nixBuildProcess = child_process.spawn("nix-build", args.params.concat(["-"]));

    nixBuildProcess.stdin.write(args.expression);
    nixBuildProcess.stdin.end();

    nixBuildProcess.stdout.on("data", function(data) {
        output += data; /* Capture the Nix store path */
    });

    nixBuildProcess.stderr.on("data", function(data) {
        process.stderr.write(data);
    });

    nixBuildProcess.on("exit", function(code) {
        if(code == 0)
            args.onSuccess(output.substring(0, output.length - 1));
        else
            args.onFailure(code);
    });
};

/**
 * Augments a given Nix object with a Nix expression with a Nixpkgs and NiJS
 * reference and executes nix-build to evaluate the expression.
 *
 * @param {object} args Nix build parameters
 * @param {NixExpression} args.nixObject An object instance of the NixExpression prototype, with a string value that contains a Nix expression
 * @param {Array.<string>} args.params An array of strings representing command-line parameters passed to nix-build
 * @param {function(string)} args.onSuccess Callback function that gets called with the resulting Nix store path, if the build succeeds
 * @param {function(number)} args.onFailure Callback function that gets called with the resulting non-zero exit status, if the build fails
 */
exports.callNixBuild = function(args) {
    var expression = "let\n"+
      "  pkgs = import <nixpkgs> {};\n"+
      "  nijsFunProxy = import <nijs/lib/funProxy.nix> { inherit (pkgs) stdenv nodejs; };\n"+
      "in\n" + args.nixObject.value;

    exports.nixBuild({
        expression : expression,
        params : args.params,
        onSuccess : args.onSuccess,
        onFailure : args.onFailure
    });
}
<|endoftext|>


<commit_before>var passport = require('passport'),
  LocalStrategy = require('passport-local').Strategy;

var mongoose = require('mongoose');

module.exports = function AuthLocal(pluginConf, web, next) {
  var self = this;

  web.auth = self;

  pluginConf = web.utils.extend({
    "loginView": "/node_modules/oils-plugin-auth/views/login.html",
    "registerView": "/node_modules/oils-plugin-auth/views/register.html",
    "userModel": "/node_modules/oils-plugin-auth/models/User.js",
    "redirectAfterLogin": "/"
    },
    pluginConf);

  web.auth.conf = pluginConf;

  web.on('beforeRender', function(view, options, callback, req, res) {
    options._user = req.user;
  })

  web.on('initServer', function() {
  var User = web.includeModel(pluginConf.userModel);

  web.auth.UserModel = User;
  web.auth.loginUtils = require('./utils/loginUtils');

  passport.use(new LocalStrategy(
    function(username, password, done) {

      User.findOne({ username: username }, function(err, user) {

        if (err) { return done(err); }
        if (!user) {
          return done(null, false, { message: 'Incorrect username or password.' });
        }

        user.comparePassword(password, function(err, isMatch) {
            if (err) throw err;

            if (isMatch) {
              return done(null, user);

            } else {
              return done(null, false, { message: 'Incorrect password or password.' });
            }
            //console.log('Password123:', isMatch); // -> Password123: true
        });

      });
    }
    ));

    var express = web.app;

    passport.serializeUser(function(user, done2) {
      done2(null, user._id);

    });

    passport.deserializeUser(function(id, done2) {
      var o_id = mongoose.Types.ObjectId(id);
      User.findOne({_id:o_id}, function (err, user) {
        done2(err, user);
      });
    });

    express.use(passport.initialize());

    express.use(passport.session());

  });

  web.applyRoutes({
    '/logout': function(req, res){
      req.logout();
      res.redirect('/');
    },

    //'/login-success': function(req,res) {
    //  res.redirect(pkg.oils.redirectAfterLogin);
    //},

    '/login': web.include('/node_modules/oils-plugin-auth/controllers/login.js'),

    '/register': web.include('/node_modules/oils-plugin-auth/controllers/register.js')
  });

  next();

}

<commit_msg>fixed middleware<commit_after>var passport = require('passport'),
  LocalStrategy = require('passport-local').Strategy;

var mongoose = require('mongoose');

module.exports = function AuthLocal(pluginConf, web, next) {
  var self = this;

  web.auth = self;

  pluginConf = web.utils.extend({
    "loginView": "/node_modules/oils-plugin-auth/views/login.html",
    "registerView": "/node_modules/oils-plugin-auth/views/register.html",
    "userModel": "/node_modules/oils-plugin-auth/models/User.js",
    "redirectAfterLogin": "/"
    },
    pluginConf);

  web.auth.conf = pluginConf;

  web.on('beforeRender', function(view, options, callback, req, res) {
    options._user = req.user;
  })

  var User = web.includeModel(pluginConf.userModel);

  web.auth.UserModel = User;
  web.auth.loginUtils = require('./utils/loginUtils');

  passport.use(new LocalStrategy(
    function(username, password, done) {

      User.findOne({ username: username }, function(err, user) {

        if (err) { return done(err); }
        if (!user) {
          return done(null, false, { message: 'Incorrect username or password.' });
        }

        user.comparePassword(password, function(err, isMatch) {
            if (err) throw err;

            if (isMatch) {
              return done(null, user);

            } else {
              return done(null, false, { message: 'Incorrect password or password.' });
            }
        });

      });
    }
    ));

    var express = web.app;

    passport.serializeUser(function(user, done2) {
      done2(null, user._id);

    });

    passport.deserializeUser(function(id, done2) {
      var o_id = mongoose.Types.ObjectId(id);
      User.findOne({_id:o_id}, function (err, user) {
        done2(err, user);
      });
    });

    express.use(passport.initialize());

    express.use(passport.session());

  web.applyRoutes({
    '/logout': function(req, res){
      req.logout();
      res.redirect('/');
    },

    '/login': web.include('/node_modules/oils-plugin-auth/controllers/login.js'),

    '/register': web.include('/node_modules/oils-plugin-auth/controllers/register.js')
  });

  next();

}

<|endoftext|>


<commit_before>'use strict';

/**
* Build benchmark assets.
*
* @module @stdlib/tools/benchmarks/browser-build
*
* @example
* var build = require( '@stdlib/tools/benchmarks/browser-build' );
*
* var root = '/foo/bar/benchmark';
* var out = '/beep/boop';
*
* var opts = {
*     'pattern': '\*\*\/benchmark*.js',
*     'bundle': 'benchmark_bundle.js',
*     'html': 'benchmarks.html'
* };
*
* build( root, out, opts, clbk );
*
* function clbk( error, bool ) {
*     if ( error ) {
*         throw error;
*     }
*     if ( bool ) {
*         console.log( 'Success!' );
*     } else {
*         console.log( 'No generated assets.' );
*     }
* }
*/

// MODULES //

var build = require( './build.js' );

// EXPORTS //

module.exports = build;
<commit_msg>Update package description<commit_after>'use strict';

/**
* Build assets for running benchmarks in a web browser.
*
* @module @stdlib/tools/benchmarks/browser-build
*
* @example
* var build = require( '@stdlib/tools/benchmarks/browser-build' );
*
* var root = '/foo/bar/benchmark';
* var out = '/beep/boop';
*
* var opts = {
*     'pattern': '\*\*\/benchmark*.js',
*     'bundle': 'benchmark_bundle.js',
*     'html': 'benchmarks.html'
* };
*
* build( root, out, opts, clbk );
*
* function clbk( error, bool ) {
*     if ( error ) {
*         throw error;
*     }
*     if ( bool ) {
*         console.log( 'Success!' );
*     } else {
*         console.log( 'No generated assets.' );
*     }
* }
*/

// MODULES //

var build = require( './build.js' );

// EXPORTS //

module.exports = build;
<|endoftext|>


<commit_before>// Copyright (c) 2012 Malte-Thorben Bruns <skenqbx@googlemail.com>

// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// 'Software'), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

/* enable ECMA-262 strict mode */
'use strict';

/* load node modules */
var util = require('util');
var events = require('events');
var dgram = require('dgram');

/* load modules */
var Caster = require('./caster');

/**
 * @param {Object.<string, *>=} opt_ions Multicast configuration object.
 * @constructor
 * @extends {events.EventEmitter}
 */
function Node(opt_ions) {
  events.EventEmitter.call(this);

  opt_ions = opt_ions || {};
  this.id = opt_ions.id || 'node' + Math.random().toString().substr(2);
  this.heartbeat = opt_ions.heartbeat || 1000;
  this.timeout = opt_ions.timeout || 2000;
  this._intervalId = null;
  this.expose = typeof opt_ions.expose === 'boolean' ? opt_ions.expose : true;

  this.nodes = {};
  this.caster = new Caster(opt_ions);
  var self = this;

  /**
   * @private
   */
  function onCasterMessage(message, rinfo) {
    try {
      message = JSON.parse(message);
    } catch (err) {
      self.emit('error', err);
      return;
    }

    if (!message.id) {
      self.emit('error', new Error('Invalid message'));
      return;
    }
    var id = message.id;
    if (message.id === self.id) {
      return;
    }

    if (self.nodes.hasOwnProperty(id)) {
      self.nodes[id].lastSeen = (new Date()).getTime();
    } else {
      self.nodes[id] = {
        id: id,
        address: rinfo.address,
        lastSeen: (new Date()).getTime()
      };
      self.emit('up', self.nodes[id]);
    }

    if (message.msg !== 'heartbeat') {
      self.emit('message', message.msg, self.nodes[id]);
    }
  }
  this._onCasterMessage = onCasterMessage;
  this._onCasterError = this.emit.bind(this, 'error');

  // register multicast event handlers
  this.caster.on('message', this._onCasterMessage);
  this.caster.on('error', this._onCasterError);

  // create getter for multicast address and port
  this.__defineGetter__('multicast', function() {
    return this.caster.multicast;
  });
  this.__defineGetter__('port', function() {
    return this.caster.port;
  });
}
util.inherits(Node, events.EventEmitter);
module.exports = Node;

/**
 * @param {String|Number|Object} message The message to send.
 * @param {function(Error, Number)} opt_callback
 *    An optional callback returning on error or when message is sent.
 */
Node.prototype.send = function(message, opt_callback) {
  var self = this;
  opt_callback = opt_callback || function(err) {
    if (err) {
      self.emit('error', err);
    }
  };

  try {
    message = JSON.stringify({id: this.id, msg: message});
  } catch (err) {
    return opt_callback(err);
  }
  this.caster.send(new Buffer(message, 'utf8'), opt_callback);
};

/**
 * @param {function(Error)} opt_callback
 *    An optional callback returning on error or when the node is up.
 */
Node.prototype.up = function(opt_callback) {
  var self = this;

  opt_callback = opt_callback || function(err) {
    if (err) {
      self.emit('error', err);
    }
  };

  /**
   * @private
   */
  function doHeartbeat() {
    self.send('heartbeat', function(err) {
      var i, keys = Object.keys(self.nodes);
      var length = keys.length;
      var low = (new Date()).getTime() - self.timeout;

      if (length > 0) {
        for (i = 0; i < length; ++i) {
          if (self.nodes[keys[i]].lastSeen < low) {
            self.emit('down', self.nodes[keys[i]]);
            delete self.nodes[keys[i]];
          }
        }
      }
    });
  }

  this.caster.bind(function(err) {
    if (err) {
      opt_callback(err);
    } else {
      if (self.expose) {
        self._intervalId = setInterval(doHeartbeat, self.heartbeat);
      }
      opt_callback(null);
    }
  });
};

/**
 * @param {function()} opt_callback
 *    An optional callback returning when the node is down.
 */
Node.prototype.down = function(opt_callback) {
  var self = this;

  if (self._intervalId) {
    clearInterval(this._intervalId);
    this._intervalId = null;
  }

  this.caster.close(function() {
    self.caster.removeListener('message', self._onCasterMessage);
    self.caster.removeListener('error', self._onCasterError);
    self.nodes = {};

    if (opt_callback) {
      opt_callback();
    }
  });
};
<commit_msg>removed unused require<commit_after>// Copyright (c) 2012 Malte-Thorben Bruns <skenqbx@googlemail.com>

// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// 'Software'), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

/* enable ECMA-262 strict mode */
'use strict';

/* load node modules */
var util = require('util');
var events = require('events');

/* load modules */
var Caster = require('./caster');

/**
 * @param {Object.<string, *>=} opt_ions Multicast configuration object.
 * @constructor
 * @extends {events.EventEmitter}
 */
function Node(opt_ions) {
  events.EventEmitter.call(this);

  opt_ions = opt_ions || {};
  this.id = opt_ions.id || 'node' + Math.random().toString().substr(2);
  this.heartbeat = opt_ions.heartbeat || 1000;
  this.timeout = opt_ions.timeout || 2000;
  this._intervalId = null;
  this.expose = typeof opt_ions.expose === 'boolean' ? opt_ions.expose : true;

  this.nodes = {};
  this.caster = new Caster(opt_ions);
  var self = this;

  /**
   * @private
   */
  function onCasterMessage(message, rinfo) {
    try {
      message = JSON.parse(message);
    } catch (err) {
      self.emit('error', err);
      return;
    }

    if (!message.id) {
      self.emit('error', new Error('Invalid message'));
      return;
    }
    var id = message.id;
    if (message.id === self.id) {
      return;
    }

    if (self.nodes.hasOwnProperty(id)) {
      self.nodes[id].lastSeen = (new Date()).getTime();
    } else {
      self.nodes[id] = {
        id: id,
        address: rinfo.address,
        lastSeen: (new Date()).getTime()
      };
      self.emit('up', self.nodes[id]);
    }

    if (message.msg !== 'heartbeat') {
      self.emit('message', message.msg, self.nodes[id]);
    }
  }
  this._onCasterMessage = onCasterMessage;
  this._onCasterError = this.emit.bind(this, 'error');

  // register multicast event handlers
  this.caster.on('message', this._onCasterMessage);
  this.caster.on('error', this._onCasterError);

  // create getter for multicast address and port
  this.__defineGetter__('multicast', function() {
    return this.caster.multicast;
  });
  this.__defineGetter__('port', function() {
    return this.caster.port;
  });
}
util.inherits(Node, events.EventEmitter);
module.exports = Node;

/**
 * @param {String|Number|Object} message The message to send.
 * @param {function(Error, Number)} opt_callback
 *    An optional callback returning on error or when message is sent.
 */
Node.prototype.send = function(message, opt_callback) {
  var self = this;
  opt_callback = opt_callback || function(err) {
    if (err) {
      self.emit('error', err);
    }
  };

  try {
    message = JSON.stringify({id: this.id, msg: message});
  } catch (err) {
    return opt_callback(err);
  }
  this.caster.send(new Buffer(message, 'utf8'), opt_callback);
};

/**
 * @param {function(Error)} opt_callback
 *    An optional callback returning on error or when the node is up.
 */
Node.prototype.up = function(opt_callback) {
  var self = this;

  opt_callback = opt_callback || function(err) {
    if (err) {
      self.emit('error', err);
    }
  };

  /**
   * @private
   */
  function doHeartbeat() {
    self.send('heartbeat', function(err) {
      var i, keys = Object.keys(self.nodes);
      var length = keys.length;
      var low = (new Date()).getTime() - self.timeout;

      if (length > 0) {
        for (i = 0; i < length; ++i) {
          if (self.nodes[keys[i]].lastSeen < low) {
            self.emit('down', self.nodes[keys[i]]);
            delete self.nodes[keys[i]];
          }
        }
      }
    });
  }

  this.caster.bind(function(err) {
    if (err) {
      opt_callback(err);
    } else {
      if (self.expose) {
        self._intervalId = setInterval(doHeartbeat, self.heartbeat);
      }
      opt_callback(null);
    }
  });
};

/**
 * @param {function()} opt_callback
 *    An optional callback returning when the node is down.
 */
Node.prototype.down = function(opt_callback) {
  var self = this;

  if (self._intervalId) {
    clearInterval(this._intervalId);
    this._intervalId = null;
  }

  this.caster.close(function() {
    self.caster.removeListener('message', self._onCasterMessage);
    self.caster.removeListener('error', self._onCasterError);
    self.nodes = {};

    if (opt_callback) {
      opt_callback();
    }
  });
};
<|endoftext|>


<commit_before>var passport = require('passport'),
  strategy = require('passport-local').Strategy;

this.addInitializer(function(opts) {
  this.strategy = Graft.Auth.request('createStrategy', 'local', strategy, {});

  Graft.Auth.execute('mount', 'local', strategy);
});

Graft.Auth.commands.setHandler('verify:local', function(username, password, done) {
//  if(username != 'user')
//    done('Error', {id: 'local'});
//  else
    done(null, {id: 'local'})
}, this);<commit_msg>use POST for the local auth<commit_after>var passport = require('passport'),
  strategy = require('passport-local').Strategy;

this.addInitializer(function(opts) {
  this.strategy = Graft.Auth.request('createStrategy', 'local', strategy, {});

  Graft.Auth.execute('mount', 'local', strategy, 'post');
});

Graft.Auth.commands.setHandler('verify:local', function(username, password, done) {
//  if(username != 'user')
//    done('Error', {id: 'local'});
//  else
    done(null, {id: 'local'});
}, this);
<|endoftext|>


<commit_before>import { EventTargetAssembler } from './eventtarget'

/**
 * Node DOM interface assembler
 */
export class NodeAssembler extends EventTargetAssembler {
    /**
     * @param {*} init
     * @returns {Node|*}
     */
    assemble(init) {
        if(init && init.node) this.init(init)
        else super.assemble(init)
        return this.node
    }

    /**
     * @param {Node|*} node
     */
    set node(node) {
        this.setInstance(node)
    }

    /**
     * @returns {Node|*}
     */
    get node() {
        return this._target
    }
}
<commit_msg>NodeAssembler: fix assemble method<commit_after>import { EventTargetAssembler } from './eventtarget'

/**
 * Node DOM interface assembler
 */
export class NodeAssembler extends EventTargetAssembler {
    /**
     * @param {*} init
     * @returns {Node|*}
     */
    assemble(init) {
        if(init && init.constructor === Object && init.node) {
            this.init(init)
        }
        else super.assemble(init)
        return this.node
    }

    /**
     * @param {Node|*} node
     */
    set node(node) {
        this.setInstance(node)
    }

    /**
     * @returns {Node|*}
     */
    get node() {
        return this._target
    }
}
<|endoftext|>


<commit_before>var util = require('util'),
redis = require('redis'),
h = require(__dirname + '/helpers');

/**
 * The Nohm object used for some general configuration and model creation.
 * @namespace Nohm
 */
function Nohm () {
}

/**
 * The redis key prefix.
 * Defaults to 'nohm' which then creates keys like 'nohm:idsets:someModel'.
 */
Nohm.prefix = h.getPrefix('nohm');
Nohm.indexNumberTypes = ['integer', 'float', 'timestamp'];
Nohm.client = null;
Nohm.meta = false; // default: do not save meta data of models to the database for the administration tool.
Nohm.meta_saved_models = [];

Nohm.model = function (name, options) {
  var obj = function (id) {
    this.init(name, options);
    if(typeof(id) === 'number') {
      this.id = id;
      this.load(id);
    }
  };
  obj.prototype = new Nohm();
  return obj;
};

Nohm.logError = function logError(err) {
  if (err) {
    console.dir({
      name: "Nohm Error",
      message: err
    });
  }
};

Nohm.prototype.getHashKey = function (id) {
  return Nohm.prefix.hash + this.modelName + ':' + id;
};

Nohm.prototype.getClient = function () {
  return this.client || Nohm.client;
};

Nohm.prototype.init = function (name, options) {
  if ( ! name )
    this.logError('When creating a new model you have to provide a name!');

  this.modelName = name;

  if (typeof(options.client) === 'undefined' && Nohm.client === null)
    Nohm.logError('Did not find a viable redis client in Nohm or the model: '+name);

  if (typeof(options.client) !== 'undefined') {
    this.client = options.client;
  }

  this.properties = {};
  this.errors = {};

  // initialize the properties
  if (options.hasOwnProperty('properties')) {
    for (var p in options.properties) {
      if (options.properties.hasOwnProperty(p)) {
        this.properties[p] = h.$extend(true, {}, options.properties[p]); // deep copy
        this.property(p, options.properties[p].value || 0); // this ensures typecasing/behaviours
        this.__resetProp(p);
        this.errors[p] = [];

        if ( Nohm.meta && ! Nohm.meta_saved_models.hasOwnProperty(this.modelName)) {
          // try saving the meta data of this model
          var metaargs = [Nohm.prefix.meta + this.modelName, p, JSON.stringify(this.properties[p])];
          client.hmset(metaargs);
        }
      }
    }
  }

  this.relationChanges = [];

  this.id = null;
  this.__inDB = false;
  this.__loaded = false;
};

Nohm.setClient = function (client) {
  Nohm.client = client;
};

var moduleNames = ['properties', 'retrieve', 'validation', 'store', 'relations'],
    modules = {};

moduleNames.forEach(function (name) {
  // first integrate all the modules
  modules[name] = require(__dirname+'/'+name);
  h.prototypeModule(Nohm, modules[name]);
});
moduleNames.forEach(function (name) {
  // then give them the complete Nohm.
  if (typeof(modules[name].setNohm) !== 'undefined')
    modules[name].setNohm(Nohm);
});

exports.Nohm = Nohm;

<commit_msg>Add some more documentation<commit_after>var util = require('util'),
redis = require('redis'),
h = require(__dirname + '/helpers');

/**
 * The Nohm object used for some general configuration and model creation.
 * @namespace Nohm
 */
function Nohm () {
}

/**
 * The redis prefixed key object.
 * Defaults to prefixing with 'nohm' which then creates keys like 'nohm:idsets:someModel'.
 */
Nohm.prefix = h.getPrefix('nohm'); // TODO: create setPrefix

/**
 * The property types that get indexed in a sorted set.
 * This should not be changed since it can invalidate already existing data.
 */
Nohm.indexNumberTypes = ['integer', 'float', 'timestamp'];

/**
 * The current global nohm redis client
 */
Nohm.client = null;

/**
 * Whether to store the meta values about models.
 * This is used for example by the admin app.
 * Defaults to false, since it's a little faster.
 */
Nohm.meta = false; // check if this should be defaulted to true.
Nohm.meta_saved_models = [];

/**
 * Creates and returns a new model with the given name and options.
 * @param {String} Name Name of the model. This needs to be unique and is used in data storage. Thus <b>changing this will invalidate existing data</b>!
 * @param {Object} Option This is an object containing the actual model definitions. These are: properties, methods (optional) and the client (optional) to be used.
 */
Nohm.model = function (name, options) { // TODO: implement methods!
  var obj = function (id) {
    this.init(name, options);
    if(typeof(id) === 'number') {
      this.id = id;
      this.load(id);
    }
  };
  obj.prototype = new Nohm();
  return obj;
};

/**
 * This function is used whenever an error occurs in nohm.
 * You can override this to whatever you want.
 * By default it only does a console.dir(errorObject);
 */
Nohm.logError = function logError(err) {
  if (err) {
    console.dir({
      name: "Nohm Error",
      message: err
    });
  }
};

/**
 * Returns the key needed to retreive a hash (properties) of an instance.
 * @param {Number} id Id of the model instance.
 */
Nohm.prototype.getHashKey = function (id) {
  return Nohm.prefix.hash + this.modelName + ':' + id;
};

/**
 * Returns the client of either the model (if set) or the global Nohm object.
 */
Nohm.prototype.getClient = function () {
  return this.client || Nohm.client;
};

Nohm.prototype.init = function (name, options) {
  if ( ! name )
    this.logError('When creating a new model you have to provide a name!');

  this.modelName = name;

  if (typeof(options.client) === 'undefined' && Nohm.client === null)
    Nohm.logError('Did not find a viable redis client in Nohm or the model: '+name);

  if (typeof(options.client) !== 'undefined') {
    this.client = options.client;
  }

  this.properties = {};
  this.errors = {};

  // initialize the properties
  if (options.hasOwnProperty('properties')) {
    for (var p in options.properties) {
      if (options.properties.hasOwnProperty(p)) {
        this.properties[p] = h.$extend(true, {}, options.properties[p]); // deep copy
        this.property(p, options.properties[p].value || 0); // this ensures typecasing/behaviours
        this.__resetProp(p);
        this.errors[p] = [];

        if ( Nohm.meta && ! Nohm.meta_saved_models.hasOwnProperty(this.modelName)) {
          // try saving the meta data of this model
          var metaargs = [Nohm.prefix.meta + this.modelName, p, JSON.stringify(this.properties[p])];
          client.hmset(metaargs);
        }
      }
    }
  }

  this.relationChanges = [];

  this.id = null;
  this.__inDB = false;
  this.__loaded = false;
};

/**
 * Set the Nohm global redis client.
 * Note: this will not affect models that have a client set on their own.
 */
Nohm.setClient = function (client) {
  Nohm.client = client;
};

var moduleNames = ['properties', 'retrieve', 'validation', 'store', 'relations'],
    modules = {};

moduleNames.forEach(function (name) {
  // first integrate all the modules
  modules[name] = require(__dirname+'/'+name);
  h.prototypeModule(Nohm, modules[name]);
});
moduleNames.forEach(function (name) {
  // then give them the complete Nohm.
  if (typeof(modules[name].setNohm) !== 'undefined')
    modules[name].setNohm(Nohm);
});

exports.Nohm = Nohm;

<|endoftext|>


<commit_before>var _ = require('lodash');

module.exports = (function () {
  function Argument(raw, options) {
    this.raw = raw;
    this.options = options;
  }

  Argument.prototype.toString = function() {
    return this.parse();
  };

  Argument.prototype.parse = function() {
    var argument = this.raw;

    if (argument === null) {
      return 'null';
    }

    // Check to see if the arg is referencing the graph ie. g.v(1)
    if (_.isObject(argument) && argument.hasOwnProperty('params') && this.isGraphReference(argument.script)) {
      return argument.script.toString();
    }

    if (this.isGraphReference(argument)) {
      return argument.toString();
    }

    // Cater for ids that are not numbers but pass parseFloat test
    if (this.isRegexId() || _.isNaN(parseFloat(argument))) {
      return "'" + argument + "'";
    }

    if (!_.isNaN(parseFloat(argument))) {
      return argument.toString();
    }

    return argument;
  };

  Argument.prototype.isRegexId = function() {
    return !!this.options.idRegex && _.isString(this.raw) && this.options.idRegex.test(this.raw);
  };

  Argument.prototype.isGraphReference = function() {
    var graphRegex = /^T\.(gt|gte|eq|neq|lte|lt|decr|incr|notin|in)$|^Contains\.(IN|NOT_IN)$|^g\.|^Vertex(\.class)$|^Edge(\.class)$|^String(\.class)$|^Integer(\.class)$|^Geoshape(\.class)$|^Direction\.(OUT|IN|BOTH)$|^TitanKey(\.class)$|^TitanLabel(\.class)$/;

    return _.isString(this.raw) && graphRegex.test(this.raw);
  };

  Argument.prototype.isClosure = function(val) {
    var closureRegex = /^\{.*\}$/;

    return _.isString(val) && closureRegex.test(val);
  };

  return Argument;
})();<commit_msg>Remove Argument.isClosure()<commit_after>var _ = require('lodash');

module.exports = (function () {
  function Argument(raw, options) {
    this.raw = raw;
    this.options = options;
  }

  Argument.prototype.toString = function() {
    return this.parse();
  };

  Argument.prototype.parse = function() {
    var argument = this.raw;

    if (argument === null) {
      return 'null';
    }

    // Check to see if the arg is referencing the graph ie. g.v(1)
    if (_.isObject(argument) && argument.hasOwnProperty('params') && this.isGraphReference(argument.script)) {
      return argument.script.toString();
    }

    if (this.isGraphReference(argument)) {
      return argument.toString();
    }

    // Cater for ids that are not numbers but pass parseFloat test
    if (this.isRegexId() || _.isNaN(parseFloat(argument))) {
      return "'" + argument + "'";
    }

    if (!_.isNaN(parseFloat(argument))) {
      return argument.toString();
    }

    return argument;
  };

  Argument.prototype.isRegexId = function() {
    return !!this.options.idRegex && _.isString(this.raw) && this.options.idRegex.test(this.raw);
  };

  Argument.prototype.isGraphReference = function() {
    var graphRegex = /^T\.(gt|gte|eq|neq|lte|lt|decr|incr|notin|in)$|^Contains\.(IN|NOT_IN)$|^g\.|^Vertex(\.class)$|^Edge(\.class)$|^String(\.class)$|^Integer(\.class)$|^Geoshape(\.class)$|^Direction\.(OUT|IN|BOTH)$|^TitanKey(\.class)$|^TitanLabel(\.class)$/;

    return _.isString(this.raw) && graphRegex.test(this.raw);
  };

  return Argument;
})();<|endoftext|>


<commit_before>/*
 * Copyright (C) 2007-2011 Parisson
 * Copyright (c) 2011 Riccardo Zaccarelli <riccardo.zaccarelli@gmail.com>
 *
 * This file is part of TimeSide.
 *
 * TimeSide is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * TimeSide is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TimeSide.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Author: Riccardo Zaccarelli <riccardo.zaccarelli@gmail.com>
 */

/**
 * Class for managing playlists in telemeta.
 * Requires jQuery and PopupDiv
 */

//default PopupDiv properties for playlists (mainly for css appearence)
PopupDiv.popupClass = 'control component';
PopupDiv.popupCss = {
    'border':'1px solid #999',
    'padding':'1ex'
};
PopupDiv.okButtonTitle =  'Ok';
PopupDiv.okButtonClass =  'component_icon button icon_ok';
PopupDiv.closeButtonTitle =  '';
PopupDiv.closeButtonClass =  'markersdivDelete';
PopupDiv.defaultCloseOperation = 'remove';
PopupDiv.focusable = true;
PopupDiv.listItemClass = "component_icon list_item icon_playlist";

var playlistUtils = {
    playlists : [],
    id: '', // ID var: used to edit playlist
    title: '',
    description: '',

    addPlaylist: function(name, id){
        this.playlists.push({
            'name':name,
            'id':id
        });
    },

    addEditPlaylist: function(id, title, description){
        this.playlists.push({
            'id': id,
            'title': title,
            'description': description,
        });
    },

    addNewPlaylist: function(){
        this.add({
            'title': $('#titleAdd').val(),
            'description': $('#descriptionAdd').val(),
        });
    },

    // function to change global var ID (used when edit button is pressed)
    editVar: function(id){
        this.id = id;
        for (var i=0; i<this.playlists.length; i++){
            if (this.playlists[i].id == id){
                $('#titleEdit').val(this.playlists[i].title);
                $('#descriptionEdit').val(this.playlists[i].description);
            }
        }
    },

    editPlaylist: function(){
        // Use of a function that convert params then use playlist.update
        //playlist.updateConvert(ID, this.title, DESCRIPTION);
        this.update({
            'public_id': this.id,
            'title': $('#titleEdit').val(),
            'description': $('#descriptionEdit').val(),
        });
        this.id = ""; // init ID
    },

    loadSong: function(id){
        alert(id);
        var player = $('#player').val();
        var sourceOgg = $('#player').val();
        var sourceMp3 = $('#player').val();
        for (var i=0; i<this.playlists.length; i++){
            if (this.playlists[i].id == id){
                // for resource in playlist.resources
                // if ID of the item then
                /*
                sourceOgg.src = this.playlists[i].sound;
                sourceMp3.src = this.playlists[i].sound;
                */
            }
        }
        player.load(); //just start buffering (preload)
        //player.play() doesn't work -> TODO: find another way
        //player.play(); //start playing
    },

    /**
     * Returns an uniqid by creating the current local time in millisecond + a random number. Used for markers and some json calls
     * Copied from Timeside.utils.uniqid (Timeside might NOT ALWAYS be loaded, see home.html when user is authenitcated)
     *
     */
    uniqid : function() {
        var d = new Date();
        return new String(d.getTime() + '' + Math.floor(Math.random() * 1000000)).substr(0, 18);
    },

    add : function(dictionary){

        if(dictionary.public_id===undefined){
            dictionary.public_id = this.uniqid();
        }
        if(dictionary.user===undefined){
            dictionary.user = CURRENT_USER_NAME;
        }

        json([dictionary],'telemeta.add_playlist',function(){
            window.location.reload();
        });
    },

    remove: function(id){
        json([id],'telemeta.del_playlist',function(){
            window.location.reload();
        });
    },

    removeResource: function(id){
        json([id],'telemeta.del_playlist_resource',function(){
            window.location.reload();
        });
    },

    update : function(dictionary){
        json([dictionary],'telemeta.update_playlist',function(){
        window.location.reload();
        });
    },

    /*shows the popup for adding a resource to a playlist*/
    showAddResourceToPlaylist: function(anchorElement, resourceType, objectId, optionalOkMessage){
        var ar = [];
        var pl = this;
        var playlists = this.playlists;

        for(var i=0; i< playlists.length; i++){
            ar.push(playlists[i].name);
        }

        if(!ar.length){
            this.showAdd(anchorElement);
        }

        //var addFcn = this.addResourceToPlaylist;
        new PopupDiv({
            invoker:anchorElement,
            content: ar,
            onOk:function(data){
                var val = data.selIndex;
                var callbackok = undefined;

                if(optionalOkMessage){
                    callbackok = function(){
                        var p =new PopupDiv({
                            content : "
"+optionalOkMessage+"
",
                            focusable: false

                        });
                        p.bind('show', function(){
                            this.setTimeout('close',1500); //this refers to p
                        });
                        p.show();
                    }
                }
                pl.addResourceToPlaylist.apply(pl,[playlists[val].id,resourceType,objectId,callbackok]);
            }
        }).show();

    },

    //resourceType can be: 'collection', 'item', 'marker'
    addResourceToPlaylist: function(playlistId,resourceType,objectId, callbackOnSuccess,callbackOnError){
        var send = {
            'public_id':this.uniqid(),
            'resource_type':resourceType,
            'resource_id':objectId
        };
        json([playlistId,send],'telemeta.add_playlist_resource',callbackOnSuccess,callbackOnError);
    }

}
<commit_msg>update<commit_after>/*
 * Copyright (C) 2007-2011 Parisson
 * Copyright (c) 2011 Riccardo Zaccarelli <riccardo.zaccarelli@gmail.com>
 *
 * This file is part of TimeSide.
 *
 * TimeSide is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * TimeSide is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TimeSide.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Author: Riccardo Zaccarelli <riccardo.zaccarelli@gmail.com>
 */

/**
 * Class for managing playlists in telemeta.
 * Requires jQuery and PopupDiv
 */

//default PopupDiv properties for playlists (mainly for css appearence)
PopupDiv.popupClass = 'control component';
PopupDiv.popupCss = {
    'border':'1px solid #999',
    'padding':'1ex'
};
PopupDiv.okButtonTitle =  'Ok';
PopupDiv.okButtonClass =  'component_icon button icon_ok';
PopupDiv.closeButtonTitle =  '';
PopupDiv.closeButtonClass =  'markersdivDelete';
PopupDiv.defaultCloseOperation = 'remove';
PopupDiv.focusable = true;
PopupDiv.listItemClass = "component_icon list_item icon_playlist";

var playlistUtils = {
    playlists : [],
    id: '', // ID var: used to edit playlist
    title: '',
    description: '',

    addPlaylist: function(name, id){
        this.playlists.push({
            'name':name,
            'id':id
        });
    },

    addEditPlaylist: function(id, title, description){
        this.playlists.push({
            'id': id,
            'title': title,
            'description': description,
        });
    },

    addNewPlaylist: function(){
        this.add({
            'title': $('#titleAdd').val(),
            'description': $('#descriptionAdd').val(),
        });
    },

    // function to change global var ID (used when edit button is pressed)
    editVar: function(id){
        this.id = id;
        for (var i=0; i<this.playlists.length; i++){
            if (this.playlists[i].id == id){
                $('#titleEdit').val(this.playlists[i].title);
                $('#descriptionEdit').val(this.playlists[i].description);
            }
        }
    },

    editPlaylist: function(){
        // Use of a function that convert params then use playlist.update
        //playlist.updateConvert(ID, this.title, DESCRIPTION);
        this.update({
            'public_id': this.id,
            'title': $('#titleEdit').val(),
            'description': $('#descriptionEdit').val(),
        });
        this.id = ""; // init ID
    },

    loadSong: function(id){
        var player = $('#player').val();
        var sourceOgg = $('#player').val();
        var sourceMp3 = $('#player').val();
        for (var i=0; i<this.playlists.length; i++){
            if (this.playlists[i].id == id){
                // for resource in playlist.resources
                // if ID of the item then
                /*
                sourceOgg.src = this.playlists[i].sound;
                sourceMp3.src = this.playlists[i].sound;
                */
            }
        }
        player.load(); //just start buffering (preload)
        //player.play() doesn't work -> TODO: find another way
        //player.play(); //start playing
    },

    /**
     * Returns an uniqid by creating the current local time in millisecond + a random number. Used for markers and some json calls
     * Copied from Timeside.utils.uniqid (Timeside might NOT ALWAYS be loaded, see home.html when user is authenitcated)
     *
     */
    uniqid : function() {
        var d = new Date();
        return new String(d.getTime() + '' + Math.floor(Math.random() * 1000000)).substr(0, 18);
    },

    add : function(dictionary){

        if(dictionary.public_id===undefined){
            dictionary.public_id = this.uniqid();
        }
        if(dictionary.user===undefined){
            dictionary.user = CURRENT_USER_NAME;
        }

        json([dictionary],'telemeta.add_playlist',function(){
            window.location.reload();
        });
    },

    remove: function(id){
        json([id],'telemeta.del_playlist',function(){
            window.location.reload();
        });
    },

    removeResource: function(id){
        json([id],'telemeta.del_playlist_resource',function(){
            window.location.reload();
        });
    },

    update : function(dictionary){
        json([dictionary],'telemeta.update_playlist',function(){
        window.location.reload();
        });
    },

    /*shows the popup for adding a resource to a playlist*/
    showAddResourceToPlaylist: function(anchorElement, resourceType, objectId, optionalOkMessage){
        var ar = [];
        var pl = this;
        var playlists = this.playlists;

        for(var i=0; i< playlists.length; i++){
            ar.push(playlists[i].name);
        }

        if(!ar.length){
            this.showAdd(anchorElement);
        }

        //var addFcn = this.addResourceToPlaylist;
        new PopupDiv({
            invoker:anchorElement,
            content: ar,
            onOk:function(data){
                var val = data.selIndex;
                var callbackok = undefined;

                if(optionalOkMessage){
                    callbackok = function(){
                        var p =new PopupDiv({
                            content : "
"+optionalOkMessage+"
",
                            focusable: false

                        });
                        p.bind('show', function(){
                            this.setTimeout('close',1500); //this refers to p
                        });
                        p.show();
                    }
                }
                pl.addResourceToPlaylist.apply(pl,[playlists[val].id,resourceType,objectId,callbackok]);
            }
        }).show();

    },

    //resourceType can be: 'collection', 'item', 'marker'
    addResourceToPlaylist: function(playlistId,resourceType,objectId, callbackOnSuccess,callbackOnError){
        var send = {
            'public_id':this.uniqid(),
            'resource_type':resourceType,
            'resource_id':objectId
        };
        json([playlistId,send],'telemeta.add_playlist_resource',callbackOnSuccess,callbackOnError);
    }

}
<|endoftext|>


<commit_before>define(
  [
    'underscore',
    'backbone',
    'collections/InstanceCollection',
    'models/Instance',
    'collections/VolumeCollection',
    'models/Volume',
    'globals'
  ],
  function (_, Backbone, InstanceCollection, Instance, VolumeCollection, Volume, globals) {

    var statics = {
      objectType: function (model) {
        var objectType;
        if (model instanceof Instance)
          objectType = 'instance';
        else if (model instanceof Volume)
          objectType = 'volume';
        else
          throw "Unknown model type";
        return objectType;
      }
    };

    var Project = Backbone.Model.extend({

      urlRoot: globals.API_ROOT + "/project",

      url: function () {
        var url = Backbone.Model.prototype.url.apply(this) + globals.slash();
        return url;
      },

      defaults: {
        name: 'No name provided',
        description: 'No description provided'
      },

      initialize: function(options){
        //this.set('instances', new InstanceCollection());
        //this.set('volumes', new VolumeCollection());
      },

      parse: function (response) {
        response.start_date = new Date(response.start_date);
        response.instances = new InstanceCollection(_.map(response.instances, function (model) {
          return Instance.prototype.parse(model);
        }), {provider_id: null, identity_id: null});
        response.volumes = new VolumeCollection(_.map(response.volumes, function (model) {
          return Volume.prototype.parse(model);
        }), {provider_id: null, identity_id: null});
        return response;
      },

      isEmpty: function () {
        var instances = this.get('instances');
        var volumes = this.get('volumes');
        var hasNoInstances = instances ? instances.isEmpty() : true;
        var hasNoVolumes = volumes ? volumes.isEmpty() : true;

        return hasNoInstances && hasNoVolumes;
      },

      canBeDeleted: function () {
        return this.get('name') !== 'Default';
      },

      objectUrl: function (model) {
        var objectType = Project.objectType(model);
        return this.url() + objectType + '/' + model.id + '/';
      },

      putItem: function (model, options) {
        var url = this.objectUrl(model);
        $.ajax({
          dataType: 'json',
          contentType: 'application/json',
          url: url,
          type: 'PUT'
        });
        // this is so bad. Sorry
        this.get(Project.objectType(model) + 's').add(model);
      },

      removeItem: function (model, options) {
        var url = this.objectUrl(model);
        $.ajax({
          dataType: 'json',
          contentType: 'application/json',
          url: url,
          type: 'DELETE'
        });
        // this is so bad. Sorry
        this.get(Project.objectType(model) + 's').remove(model);
      }

    }, statics);

    return Project;

  });
<commit_msg>add spacing<commit_after>define(
  [
    'underscore',
    'backbone',
    'collections/InstanceCollection',
    'models/Instance',
    'collections/VolumeCollection',
    'models/Volume',
    'globals'
  ],
  function (_, Backbone, InstanceCollection, Instance, VolumeCollection, Volume, globals) {

    var statics = {
      objectType: function (model) {
        var objectType;
        if (model instanceof Instance)
          objectType = 'instance';
        else if (model instanceof Volume)
          objectType = 'volume';
        else
          throw "Unknown model type";
        return objectType;
      }
    };

    var Project = Backbone.Model.extend({

      urlRoot: globals.API_ROOT + "/project",

      url: function () {
        var url = Backbone.Model.prototype.url.apply(this) + globals.slash();
        return url;
      },

      defaults: {
        name: 'No name provided',
        description: 'No description provided'
      },

      initialize: function(options){
        //this.set('instances', new InstanceCollection());
        //this.set('volumes', new VolumeCollection());
      },

      parse: function (response) {
        response.start_date = new Date(response.start_date);

        response.instances = new InstanceCollection(_.map(response.instances, function (model) {
          return Instance.prototype.parse(model);
        }), {provider_id: null, identity_id: null});

        response.volumes = new VolumeCollection(_.map(response.volumes, function (model) {
          return Volume.prototype.parse(model);
        }), {provider_id: null, identity_id: null});

        return response;
      },

      isEmpty: function () {
        var instances = this.get('instances');
        var volumes = this.get('volumes');
        var hasNoInstances = instances ? instances.isEmpty() : true;
        var hasNoVolumes = volumes ? volumes.isEmpty() : true;

        return hasNoInstances && hasNoVolumes;
      },

      canBeDeleted: function () {
        return this.get('name') !== 'Default';
      },

      objectUrl: function (model) {
        var objectType = Project.objectType(model);
        return this.url() + objectType + '/' + model.id + '/';
      },

      putItem: function (model, options) {
        var url = this.objectUrl(model);
        $.ajax({
          dataType: 'json',
          contentType: 'application/json',
          url: url,
          type: 'PUT'
        });
        // this is so bad. Sorry
        this.get(Project.objectType(model) + 's').add(model);
      },

      removeItem: function (model, options) {
        var url = this.objectUrl(model);
        $.ajax({
          dataType: 'json',
          contentType: 'application/json',
          url: url,
          type: 'DELETE'
        });
        // this is so bad. Sorry
        this.get(Project.objectType(model) + 's').remove(model);
      }

    }, statics);

    return Project;

  });
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * 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.
 */

/**
 FOAM Bootstrap

 FOAM uses Models to specify class definitions.
 The FOAM Model class is itself specified with a FOAM model, meaning
 that Model is defined in the same language which it defines.
 This self-modeling system requires some care to bootstrap, but results
 in a very compact, uniform, and powerful system.

 FObject -> FObject Class                     Prototype
    ^                        +-.prototype---------^
    |                        |                    |
  Model  -> buildClass()  -> Class -> create() -> instance

  FObject is the root model/class of all other classes, including Model.
  Abstract Class is the prototype of FObject's Class, which makes it the root of all Classes.
  From a Model we call buildClass() to create a Class (or the previously created Class) object.
  From the Class we call create() to create new instances of that class.
  New instances extend the classes prototype object, which is stored on the class as .prototype.

  instance ---> .cls_   -> Object's Class
       |
       +------> .model_ -> Object's Model

  All descendents of FObject have references to both their Model and Class.
    - obj.cls_ refers to an Object's Class
    - obj.model_ refers to an Object's Model

  Classes also refer to their Model with .model_.

  Model is its own definition:

    Model.buildClass().create(Model) == Model
    Model.model_ === Model

  Models are defined as a collection of Axioms.
  It is the responsibility of Axioms to install itself onto a Model's Class and/or Prototype.

  Axioms are defined with the following psedo-interface:

    public interface Axiom {
      optional installInClass(cls)
      optional installInProto(proto)
    }

  Ex. of a Model with one Axiom:

  foam.CLASS({
    name: 'Sample',

    axioms: [
      {
        name: 'axiom1',
        installInClass: function(cls) { ... },
        installInProto: function(proto) { ... }
      }
    ]
  });

  Axioms can be added either during the initial creation of a class and prototype,
  or anytime after.  This allows classes to be extended with new functionality,
  and this is very important to the bootstrap process because it allows us to
  start out with very simple definitions of Model and FObject, and then build
  them up until they're fully bootstrapped.

  However, raw axioms are rarely used directly. Instead we model higher-level
  axiom types, including:

Requires   - Require other classes

Imports    - Context imports

Exports    - Context exports

Implements - Declare interfaces implemented / mix-ins mixed-in

Constants  - Add constants to the prototype and class

Properties - High-level instance variable definitions

Methods    - Prototype methods

Topics     - Publish/sub topics

Listeners  - Like methods, but with extra features for use as callbacks

*/

/**
 Bootstrap support.

 Is discarded after use.
*/
foam.LIB({
  name: 'foam.boot',

  constants: {
    startTime: Date.now(),
  },

  methods: [
    /**
      Create or Update a Prototype from a Model definition.

      This will be added as a method on the Model class
      when it is eventually built.

      (Model is 'this').
    */
    function buildClass() {
      var context = this.__context__ || foam.__context__;
      var cls;

      if ( this.refines ) {
        cls = context.lookup(this.refines);
        foam.assert(cls, 'Unknown refinement class: ' + this.refines);
      } else {
        foam.assert(this.id, 'Missing id name.', this.name);
        foam.assert(this.name, 'Missing class name.');

        var parent = this.extends      ?
          context.lookup(this.extends) :
          foam.core.FObject            ;

        cls                  = parent.createSubClass_();
        cls.prototype.cls_   = cls;
        cls.prototype.model_ = this;
        cls.count_           = 0;            // Number of instances created
        cls.id               = this.id;
        cls.package          = this.package;
        cls.name             = this.name;
        cls.model_           = this;

        // Install an FObject on the class that we can use as a pub/sub hub.
        // We have to do this because classes aren't FObjects.
        // This is used to publish 'installAxiom' events to, so that descendents
        // properties know when they need to be re-installed.
        if ( cls !== foam.core.FObject ) {
          cls.pubsub_ = foam.core.FObject.create();

          // Relay 'installAxiom' events from parent class.
          parent.pubsub_ && parent.pubsub_.sub(
            'installAxiom',
            function(_, a1, a2, a3) { cls.pubsub_.pub(a1, a2, a3); });
        }
      }

      cls.installModel(this);

      return cls;
    },

    function start() {
      /* Start the bootstrap process. */

      var buildClass = this.buildClass;

      // Will be replaced in phase2.
      foam.CLASS = function(m) {
        m.id = m.package + '.' + m.name;
        var cls = buildClass.call(m);

        foam.assert(
          ! m.refines,
          'Refines is not supported in early bootstrap');

        foam.register(cls);

        // Register the class in the global package path.
        foam.package.registerClass(cls);

        return cls;
      };
    },

    /** Start second phase of bootstrap process. */
    function phase2() {
      // Upgrade to final CLASS() definition.
      /** Creates a Foam class from a plain-old-object definition.
          @method CLASS
          @memberof module:foam */
      foam.CLASS = function(m) {
        var model = foam.core.Model.create(m);
        model.validate();
        var cls = model.buildClass();
        cls.validate();

        if ( ! m.refines ) {
          foam.register(cls);

          // Register the class in the global package path.
          foam.package.registerClass(cls);
        }

        return cls;
      };

      // Upgrade existing classes to real classes.
      for ( var key in foam.core ) {
        var m = foam.lookup(key).model_;
        m.refines = m.id;
        foam.CLASS(m);
      }
    },

    function phase3() {
      // Substitute foam.core.installModel() with simpler axiom-only version.
      foam.core.FObject.installModel = function installModel(m) {
        this.installAxioms(m.axioms_);
      };
    },

    /** Finish the bootstrap process, deleting foam.boot when done. */
    function end() {
      var Model = foam.core.Model;

      // Update psedo-Models to real Models
      for ( var key in foam.core ) {
        var c = foam.core[key];
        c.prototype.model_ = c.model_ = Model.create(c.model_);
      }

      delete foam.boot;

      console.log('core boot time: ', Date.now() - this.startTime);
    }
  ]
});

foam.boot.start();
<commit_msg>Allow .class be specified to CLASS() to allow for selection of different kinds of Models.<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * 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.
 */

/**
 FOAM Bootstrap

 FOAM uses Models to specify class definitions.
 The FOAM Model class is itself specified with a FOAM model, meaning
 that Model is defined in the same language which it defines.
 This self-modeling system requires some care to bootstrap, but results
 in a very compact, uniform, and powerful system.

 FObject -> FObject Class                     Prototype
    ^                        +-.prototype---------^
    |                        |                    |
  Model  -> buildClass()  -> Class -> create() -> instance

  FObject is the root model/class of all other classes, including Model.
  Abstract Class is the prototype of FObject's Class, which makes it the root of all Classes.
  From a Model we call buildClass() to create a Class (or the previously created Class) object.
  From the Class we call create() to create new instances of that class.
  New instances extend the classes prototype object, which is stored on the class as .prototype.

  instance ---> .cls_   -> Object's Class
       |
       +------> .model_ -> Object's Model

  All descendents of FObject have references to both their Model and Class.
    - obj.cls_ refers to an Object's Class
    - obj.model_ refers to an Object's Model

  Classes also refer to their Model with .model_.

  Model is its own definition:

    Model.buildClass().create(Model) == Model
    Model.model_ === Model

  Models are defined as a collection of Axioms.
  It is the responsibility of Axioms to install itself onto a Model's Class and/or Prototype.

  Axioms are defined with the following psedo-interface:

    public interface Axiom {
      optional installInClass(cls)
      optional installInProto(proto)
    }

  Ex. of a Model with one Axiom:

  foam.CLASS({
    name: 'Sample',

    axioms: [
      {
        name: 'axiom1',
        installInClass: function(cls) { ... },
        installInProto: function(proto) { ... }
      }
    ]
  });

  Axioms can be added either during the initial creation of a class and prototype,
  or anytime after.  This allows classes to be extended with new functionality,
  and this is very important to the bootstrap process because it allows us to
  start out with very simple definitions of Model and FObject, and then build
  them up until they're fully bootstrapped.

  However, raw axioms are rarely used directly. Instead we model higher-level
  axiom types, including:

Requires   - Require other classes

Imports    - Context imports

Exports    - Context exports

Implements - Declare interfaces implemented / mix-ins mixed-in

Constants  - Add constants to the prototype and class

Properties - High-level instance variable definitions

Methods    - Prototype methods

Topics     - Publish/sub topics

Listeners  - Like methods, but with extra features for use as callbacks

*/

/**
 Bootstrap support.

 Is discarded after use.
*/
foam.LIB({
  name: 'foam.boot',

  constants: {
    startTime: Date.now(),
  },

  methods: [
    /**
      Create or Update a Prototype from a Model definition.

      This will be added as a method on the Model class
      when it is eventually built.

      (Model is 'this').
    */
    function buildClass() {
      var context = this.__context__ || foam.__context__;
      var cls;

      if ( this.refines ) {
        cls = context.lookup(this.refines);
        foam.assert(cls, 'Unknown refinement class: ' + this.refines);
      } else {
        foam.assert(this.id, 'Missing id name.', this.name);
        foam.assert(this.name, 'Missing class name.');

        var parent = this.extends      ?
          context.lookup(this.extends) :
          foam.core.FObject            ;

        cls                  = parent.createSubClass_();
        cls.prototype.cls_   = cls;
        cls.prototype.model_ = this;
        cls.count_           = 0;            // Number of instances created
        cls.id               = this.id;
        cls.package          = this.package;
        cls.name             = this.name;
        cls.model_           = this;

        // Install an FObject on the class that we can use as a pub/sub hub.
        // We have to do this because classes aren't FObjects.
        // This is used to publish 'installAxiom' events to, so that descendents
        // properties know when they need to be re-installed.
        if ( cls !== foam.core.FObject ) {
          cls.pubsub_ = foam.core.FObject.create();

          // Relay 'installAxiom' events from parent class.
          parent.pubsub_ && parent.pubsub_.sub(
            'installAxiom',
            function(_, a1, a2, a3) { cls.pubsub_.pub(a1, a2, a3); });
        }
      }

      cls.installModel(this);

      return cls;
    },

    function start() {
      /* Start the bootstrap process. */

      var buildClass = this.buildClass;

      // Will be replaced in phase2.
      foam.CLASS = function(m) {
        m.id = m.package + '.' + m.name;
        var cls = buildClass.call(m);

        foam.assert(
          ! m.refines,
          'Refines is not supported in early bootstrap');

        foam.register(cls);

        // Register the class in the global package path.
        foam.package.registerClass(cls);

        return cls;
      };
    },

    /** Start second phase of bootstrap process. */
    function phase2() {
      // Upgrade to final CLASS() definition.
      /** Creates a Foam class from a plain-old-object definition.
          @method CLASS
          @memberof module:foam */
      foam.CLASS = function(m) {
        var cls   = m.class ? foam.lookup(m.class) : foam.core.Model;
        var model = cls.create(m);
        model.validate();
        var cls = model.buildClass();
        cls.validate();

        if ( ! m.refines ) {
          foam.register(cls);

          // Register the class in the global package path.
          foam.package.registerClass(cls);
        }

        return cls;
      };

      // Upgrade existing classes to real classes.
      for ( var key in foam.core ) {
        var m = foam.lookup(key).model_;
        m.refines = m.id;
        foam.CLASS(m);
      }
    },

    function phase3() {
      // Substitute foam.core.installModel() with simpler axiom-only version.
      foam.core.FObject.installModel = function installModel(m) {
        this.installAxioms(m.axioms_);
      };
    },

    /** Finish the bootstrap process, deleting foam.boot when done. */
    function end() {
      var Model = foam.core.Model;

      // Update psedo-Models to real Models
      for ( var key in foam.core ) {
        var c = foam.core[key];
        c.prototype.model_ = c.model_ = Model.create(c.model_);
      }

      delete foam.boot;

      console.log('core boot time: ', Date.now() - this.startTime);
    }
  ]
});

foam.boot.start();
<|endoftext|>


<commit_before>// @dgeni developers: Why do we need canonical-path?
var path = require('canonical-path');

// What annotations do we want to use? Choose jsdoc for now.
var jsdocPackage = require('dgeni-packages/jsdoc');

module.exports = function(config) {
  // Use jsdocPackage
  config = jsdocPackage(config);

  // Set logging level
  config.set('logging.level', 'info');

  // Add your own templates to render docs
  config.prepend('rendering.templateFolders', [
    path.resolve(__dirname, 'templates')
  ]);

  // You can specifiy which tempate should be used based on a pattern.
  // Currently we just use one template and don't need a pattern
  config.prepend('rendering.templatePatterns', [
    'common.template.html'
  ]);

  // This tells dgeni where to look for stuff
  config.set('source.projectPath', '.');

  config.set('source.files', [
    {
      // Process all js files in src/.
      pattern: 'src/**/*.js',
      // @dgeni developers: Why is basePath different from config.get('source.projectPath')?
      basePath: path.resolve(__dirname, '..')
    }
  ]);

  // Our generated docs will be written here:
  // @dgeni developers: Why is both (outputFolder and contentsFolder) needed?
  config.set('rendering.outputFolder', '../build/');
  config.set('rendering.contentsFolder', 'docs');

  return config;
};<commit_msg>docs(dgeni.conf.js): add some explanatory comments<commit_after>// @dgeni developers: Why do we need canonical-path?
var path = require('canonical-path');

// What annotations do we want to use? Choose jsdoc for now.
var jsdocPackage = require('dgeni-packages/jsdoc');

module.exports = function(config) {
  // Use jsdocPackage
  config = jsdocPackage(config);

  // Set logging level
  config.set('logging.level', 'info');

  // Add your own templates to render docs
  config.prepend('rendering.templateFolders', [
    path.resolve(__dirname, 'templates')
  ]);

  // You can specifiy which tempate should be used based on a pattern.
  // Currently we just use one template and don't need a pattern
  config.prepend('rendering.templatePatterns', [
    'common.template.html'
  ]);

  // This tells dgeni where to look for stuff
  config.set('source.projectPath', '.');

  config.set('source.files', [
    {
      // Process all js files in src/.
      pattern: 'src/**/*.js',
      // Some processors use the relative path of the source file to compute properties, such as
      // the outputPath. The basePath allows us to ensure that the "relative" path to each source
      // file is accurate no matter where the source files are relative to the projectPath.
      basePath: path.resolve(__dirname, '..')
    }
  ]);

  // Our generated docs will be written here:
  config.set('rendering.outputFolder', '../build/');
  // The contentsFolder is the path relative to the outputFolder, which identifies the place where
  // the "standard" content files are stored.  For example, in the AngularJS application, the output
  // folder is `build/docs` but the way that the application is stored, means that we want the
  // content files (i.e. the files that contain the content of each "doc") to be stored in
  // `build/docs/partials`
  config.set('rendering.contentsFolder', 'docs');

  return config;
};<|endoftext|>


<commit_before>export default {
	"ar": "العربية",
	"ca-es": "Catalan",
	"cs": "Czech",
	"en": "English",
	"es": "Spanish",
	"hu": "Hungarian",
	"fa": "Persian",
	"fr": "French",
  "it": "Italiano",
	"kan": "Kannada",
	"pl": "Polish",
	"pt": "Portuguese",
	"ru": "Russian",
	"tr": "Turkish",
	"uk": "Ukrainian",
	"zh-cn": "Chinese Simplified",
	"zh-tw": "Traditional Chinese",
}
<commit_msg>Update lang-list.js<commit_after>export default {
	"ar": "العربية",
	"ca-es": "Catalan",
	"cs": "Czech",
	"en": "English",
	"es": "Spanish",
	"fa": "Persian",
	"fr": "French",
	"hu": "Hungarian",
  	"it": "Italiano",
	"kan": "Kannada",
	"pl": "Polish",
	"pt": "Portuguese",
	"ru": "Russian",
	"tr": "Turkish",
	"uk": "Ukrainian",
	"zh-cn": "Chinese Simplified",
	"zh-tw": "Traditional Chinese",
}
<|endoftext|>