Example #1
0
 _.zip = function() {
   var args = slice.call(arguments);
   var length = _.max(_.pluck(args, 'length'));
   var results = new Array(length);
   for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
   return results;
 };
Example #2
0
	classify: function(sample, explain, continuous_output) {
				
		var labels = []
		var explanation = []
		var scores = {}
		
	 	_.each(this.classifier, function(classif, key, list){
	 		var value = classif.classify(sample, explain, continuous_output)
	 	 	if (explain>0)
	 	 		labels.push(value.classes)
	 	 	else
 				labels.push(value)
	 	 	explanation.push(value.explanation)
	 	 	scores = _.extend(scores, value.scores)
	 	})

		if (explain>0)
			{
				var positive = {}
				var negative = {}

				_.each(_.pluck(explanation, 'positive'), function(value, key, list){ 
					positive = _.extend(positive, value)
					}, this)

				_.each(_.pluck(explanation, 'negative'), function(value, key, list){ 
					negative = _.extend(negative, value)
					}, this)
			

			if (_.keys(negative)!=0)
				explanation = {
					positive: positive, 
					negative: negative,
				}
			}

		return (explain>0?
			{
				classes: labels, 
				scores: scores,
				explanation: explanation
			}:
			labels);

		
		// console.log(JSON.stringify(explanation, null, 4))
		// return (explain>0?
		// 	{
		// 		classes: labels, 
		// 		scores: scores,
		// 		explanation: explanation
		// 	}:
		// 	labels);

 	},
Example #3
0
    }, function (err, results){
        var primary_keys = _.pluck(results, 'pk');
        var instances = _.pluck(results, 'instance');
        if (err) {return callback_complete(err, primary_keys, instance, self, self.connection);}

        self.connection.save(function(err){
            return callback_complete(err, primary_keys, instances, self, self.connection);
        });

    });
Example #4
0
EmbeddedList.prototype.authorize = function (nDoc, oDoc, nVal, oVal, user) {
    var type = this.type;
    var perms = this.permissions;

    nVal = nVal || [];
    oVal = oVal || [];

    // a unique list of embedded ids from both the old and new document
    var ids = _.uniq(_.pluck(nVal, '_id').concat(_.pluck(oVal, '_id')));

    return _.reduce(ids, function (errs, id, i) {

        var curr_errs = [];
        var nd = _.detect(nVal, function (v) {
            return v && v._id === id;
        });
        nd = nd || {_deleted: true};
        var od = _.detect(oVal, function (v) {
            return v && v._id === id;
        });
        var args = [nDoc, oDoc, nd, od, user];

        if (_.isFunction(perms)) {
            curr_errs = utils.getErrors(perms, args);
        }
        var fn;
        // on add
        if (nd && !od) {
            fn = perms.add;
        }
        // on remove
        else if (nd._deleted) {
            fn = perms.remove;
        }
        // on update
        else if (JSON.stringify(nd) !== JSON.stringify(od)) {
            fn = perms.update;
        }
        if (fn) {
            curr_errs = curr_errs.concat(utils.getErrors(fn, args));
        }
        curr_errs = _.map(curr_errs, function (e) {
            e.field = [i].concat(e.field || []);
            return e;
        });
        return errs.concat(curr_errs);

    }, []);
};
module.exports = function (config, callback) {
    if (!intf) {
        return callback(false);
    }

    function addIp(ip, callback) {
        con.info('Adding local IP ' + ip + ' for forwards; if asked for password, give your local (sudo) password.');
        var ifconfig = pspawn('sudo', ['ifconfig', intf, 'add', ip]);
        ifconfig.on('exit', callback);
    }

    function addMissingIps(exitCode) {
        if (exitCode === 0 && missing.length > 0) {
            addIp(missing.shift(), addMissingIps);
        } else {
            callback(exitCode === 0);
        }
    }

    var allForwards = _.flatten(_.values(config.forwards).concat(_.values(config.localForwards)));
    var ips = [];
    allForwards.forEach(function (f) {
        var m = f.from.match(/^([0-9.]+):/);
        ips.push(m[1]);
    });
    ips = _.uniq(ips);

    var currentIps = _.pluck(os.networkInterfaces()[intf], 'address');
    var missing = _.difference(ips, currentIps);

    // Add any missing IP:s and finally call the callback.

    addMissingIps(0);
};
Example #6
0
  allFetched: function () {
    var statuses = _.pluck(this.pages, 'status');

    return _.all(statuses, function (status) {
      return status === "fetched" || status === "error" || status === "dontfetch" || status === "errored";
    });
  },
Example #7
0
    registerOrUpdate: function(accessToken, refreshToken, profile, done) {
        var user = this.get(profile.id);
        if (!user) {
            logger.analytics("users", {
                action: "create",
                user: user,
                totalUsers: this.length
            });
            user = new exports.ServerUser();
        } else {
            logger.analytics("users", {action: "login", user: user});
        }
        // Override any existing fields with the google+ profile info, minus
        // the parts we don't need.
        delete profile["_raw"];
        user.set(profile);

        if (!user.get("superuser")) {
            // Check if this user is a member of the hard-coded list of
            // superusers in configuration.  If so, grant them superuser status.
            _.each(_.pluck(user.get("emails"), "value"), function(email) {
                if (conf.UNHANGOUT_SUPERUSER_EMAILS.indexOf(email) > -1) {
                    logger.debug("granting superuser from config");
                    user.set("superuser", true);
                }
            });
        }
        user.save()
        this.add(user);
        done(null, user.toJSON());
    },
Example #8
0
 function(err, rows) {
     if (err) throw err;
     if (!err && rows) {
         var zooms = _.filter(rows, function(row) { return row; }),
         zooms = _.pluck(zooms, 'zoom_level');
         info.minzoom = zooms.shift();
         info.maxzoom = zooms.length ? zooms.pop() : info.minzoom;
     }
     this();
 },
Example #9
0
 async.map(os, (o, cb)=> {
     if (o.date === _date) {
         let orderTimes = [], ids = _.pluck(_.pluck(_.where(as, {_orderId: o._id}), 'arrTime'), '_id');
         _.each(o.orderTimes, ot=> {
             ot._doc.times = _.reject(ot.times, time=>time < _time);
             if (!_.isEmpty(ot.times) && !_.contains(ids, ot._id)) {
                 orderTimes.push(ot);
             }
         });
         if (!_.isEmpty(orderTimes)) {
             o._doc.orderTimes = orderTimes;
             cb(null, o);
         } else {
             cb(null, null);
         }
     } else {
         cb(null, o);
     }
 }, (err, ret)=> err ? next(err) : res.json(_.compact(ret)));
Example #10
0
 _.sortBy = function(obj, iterator, context) {
   return _.pluck(_.map(obj, function(value, index, list) {
     return {
       value : value,
       criteria : iterator.call(context, value, index, list)
     };
   }).sort(function(left, right) {
     var a = left.criteria, b = right.criteria;
     return a < b ? -1 : a > b ? 1 : 0;
   }), 'value');
 };
Example #11
0
  alreadyUsed: function (url) {
    if (this.pages[url]) {
      return true;
    } else {
      var oldUrls = _.pluck(this.pages,'url'),
          newObj  = require('url').parse(url);

      return _.any(oldUrls, function (oldUrl) {
        return fn.sameUrl(url, oldUrl);
      });
    }
  },
Example #12
0
 Arrange.findOne({_id: req.params.id}, '-_orderId').populate('_userId', 'imgUrl nick').populate('arrUser._id', `imgUrl nick mobile`).exec((err, a)=> {
     if (err) return next(err);
     if (a._userId._id !== userId && a.arrUser.length > 0) {
         _.each(a.arrUser, au=> {
             delete  au._doc.mobile;
         });
     }
     let op = 0; // 0:隐藏,1:取消约战,按钮禁用,2:已结束,3:报名,4:取消报名,5:人数已满,6:显示“取消约战”
     if (a.status === 1) {
         if (a._userId._id !== userId) {
             op = _.contains(_.pluck(_.pluck(a.arrUser, '_id'), '_id'), userId) ? 4 : (a.num > a.arrUser.length ? 3 : 5);
         } else {
             op = a.arrUser.length > 0 ? 0 : 6;
         }
     } else {
         op = a.status ? 2 : 1;
     }
     a._doc.op = op;
     delete a._doc.status;
     res.json(a);
 });
Example #13
0
 adminMatchesUser: function(admin, user) {
     var userId = user.id;
     var emails;
     if (user.get && user.get('emails')) {
         emails = _.pluck(user.get("emails"), "value");
     } else if (user.email) {
         emails = [user.email]
     } else {
         emails = [];
     }
     return ((!_.isUndefined(admin.id) && admin.id == userId) ||
             (admin.email && _.contains(emails, admin.email)));
 },
Example #14
0
File: run.js Project: nvdnkpr/tbone
monitor.stdout.on('line', function(line) {
  var match = (/(\w+) (.*)/).exec(line);
  var filename = match[2];
  var tasksToExec = _.filter(tasks, function(opts) {
    return filename.match(opts.watch);
  });
  var tasksQueued = _.filter(tasksToExec, function(opts) {
    return opts.exec();
  });
  if (tasksQueued.length) {
    info('executed [' + _.pluck(tasksQueued, 'name').join(', ') + '] due to change: ' + line);
  }
});
Example #15
0
File: web.js Project: Rob-pw/dbot
    this.onLoad = function() {
        this.reloadPages();

        var routes = _.pluck(dbot.modules.web.app.routes.get, 'path'),
            moduleNames = _.keys(dbot.modules);

        _.each(moduleNames, function(moduleName) {
            var modulePath = '/' + moduleName;
            if(_.include(routes, modulePath)) {
                moduleName = moduleName.charAt(0).toUpperCase() +
                    moduleName.slice(1);
                this.indexLinks[modulePath] = moduleName;
            }
        }.bind(this));


        this.app.get('/', function(req, res) {
            res.render('index', { 
                'name': dbot.config.name,
                'user': req.user,
                'routes': this.indexLinks
            });
        }.bind(this));

        this.app.get('/login', function(req, res) {
            res.render('login', {
                'user': req.user,
                'message': req.flash('error')
            });
        });

        this.app.post('/login', passport.authenticate('local', {
            'failureRedirect': '/login', 
            'failureFlash': true
        }), function(req, res) {
            if(req.body.redirect) {
                res.redirect(req.body.redirect);
            } else {
                res.redirect('/');
            }
        });

        this.app.get('/logout', function(req, res) {
            req.logout(); 
            res.redirect('/');
        });

        if(_.has(dbot.modules, 'log')) {
            dbot.api.log.ignoreCommand('setwebpass');
        }
    }.bind(this);
Example #16
0
	classify: function(sample, explain, continuous_output) {
				
		labels = []
		explanation = []
		
	 	_.each(this.classifier, function(classif, key, list){
	 		value = classif.classify(sample, explain)
	 	 	if (explain>0)
	 	 		labels.push(value.classes)
	 	 	else
 				labels.push(value)
	 	 	explanation.push(value.explanation)
	 	})
  			
		if (explain>0)
			{
				positive = {}
				negative = {}

				_.each(_.pluck(explanation, 'positive'), function(value, key, list){ 
					positive = _.extend(positive, value)
					}, this)

				_.each(_.pluck(explanation, 'negative'), function(value, key, list){ 
					negative = _.extend(negative, value)
					}, this)
			}

		return (explain>0?
			{
				classes: labels, 
				explanation: {
					positive: positive, 
					negative: negative, 
				}
			}:
			labels);
 	},
Example #17
0
	setConnectedParticipants: function(users) {
        if (users.length > 10) { return false; }
        // Clean incoming users..
        users = _.map(users, function(u) {
            u = (u.toJSON ? u.toJSON() : u);
            return {
                id: u.id,
                displayName: u.displayName,
                picture: u.picture || (u.image && u.image.url ? u.image.url : "")
            }
        });
        // Has anything changed?
        var current = this.get("connectedParticipants");
        var intersection = _.intersection(_.pluck(users, "id"), _.pluck(current, "id"));
        if (users.length != current.length || intersection.length != current.length) {
            // We've changed.
            this.set("connectedParticipants", users);
            return true;
        } else {
            // No change.
            return false;
        }
	},
Example #18
0
 this.api.getLibrary(s2, function(err, l2) {
     if(!err) {
         var g1 = _.pluck(l1.games, 'name'),
             g2 = _.pluck(l2.games, 'name'),
             common = _.filter(g1, function(game) {
                 return _.include(g2, game);
             }),
             examples = [];
         _.times(5, function() {
             var choice = _.random(0, common.length - 1);
             if(!_.include(examples, common[choice])) {
                 examples.push(common[choice]);
             }
         });
         event.reply(dbot.t('steam_games', {
             'u1': u1.currentNick,
             'u2': u2.currentNick,
             'count': common.length,
             'examples': examples.join(', ')
         }));
     } else {
         event.reply('Unable to fetch steam library :\'(');
     }
 });
Example #19
0
    this.fetchPages(function (err, graph) {
      // log the end of the graph build 
      var requestTimes = _.pluck(graph.pages, 'requestTime'),
          total = 0;

      _.each(requestTimes, function (x) {
        total += x;
      });
      logger.info('total html request time: ' + total + 'ms');

      var ms = new Date().getTime() - startedParse.getTime();
      logger.info('total time taken: ' + ms + 'ms');

      callback(err, graph);
    });
Example #20
0
exports.buildDocLevelSchema = function(data) {
    var tsets = {}; //: root
    var tsetName = data[0].document;
    tsets['TS_' + tsetName] = { name: tsetName, fullName: 'TS_' + tsetName, collection: {} };
    var tables = _.uniq(_.pluck(data, 'doc_table'));
    _.each(tables, function(value) {
        var tableName = 'Table_' + value;
        var curTable = { name: tableName, fullName: tableName, collection: {} };
        var curTableSegments = _.filter(data, function(segment) {
            return segment.doc_table == value;
        }, this);
        this.buildTableLevelSchema(curTable, curTableSegments);
        tsets['TS_' + tsetName].collection[tableName] = curTable;
    }, this);
    return tsets;
};
Example #21
0
 this.api.tasteCompare(event.rProfile.lastfm, lfm2, function(err, comp) {
     if(!err) {
         var artists = _.pluck(comp.artists.artist, 'name').join(', ');
         event.reply(dbot.t('common_artists', {
             'user1': event.user,
             'user2': u2.currentNick,
             'common': artists
         }));
     } else {
         if(err == 'no_user') {
             event.reply('Unknown Last.FM user.');
         } else {
             event.reply('Well something went wrong and I don\'t know what it means');
         }
     }
 });
Example #22
0
	join(playerId, gameId) {
		var game = _.find(this.activeGames, function (game) { return game.gameId === gameId });
		if (game) {
			game.players = game.players || [];

			// if the player is already joined, just return the game
			if (_.contains(_.pluck(game.players, 'id'), playerId)) {
				return game;
			}

			game.players.push({id: playerId});

			return game;
		} else {
			return null;
		}
	}
	setConnectedParticipants: function(participants) {
		client_models.Session.prototype.setConnectedParticipants.call(this, participants);

		// broadcast this change to all people in the event.
		if(this.collection.event) {
            var event = this.collection.event;
            event.trigger("broadcast", event, "session-participants", {
                id: this.id, participants: this.get("connectedParticipants")
            });
		}
        // Clear the timeout that would invalidate our hangout URL if no one
        // joined.
        if (this._hangoutConnectionTimeout) {
            clearTimeout(this._hangoutConnectionTimeout);
        }

		logger.debug("setting connected participants to: " + _.pluck(participants, "id"));
	},
Example #24
0
  logFetched: function () {
    var statuses     = _.pluck(this.pages, 'status'),
        fetchedCount = 0;
        errorCount = 0;
        dontFetchedCount = 0,
        logger = this.options.logger;

    _.each(statuses, function (s) {
      fetchedCount += (s === "fetched" ? 1 : 0);
      errorCount += (s === "error" ? 1 : 0);
      dontFetchedCount += (s === "dontfetch" ? 1 : 0);
    });

    logger.info('total pages ' + statuses.length);
    logger.info('total fetched ' + fetchedCount);
    logger.info('total errors ' + errorCount);
    logger.info('total pages outside limits ' + dontFetchedCount);
  }
Example #25
0
          db.findLinksWhere({"target":parent.rootParentId},function(sources){
            var sourceList = _.pluck(sources,"source");
            db.findNodes({"id":{inq:sourceList},"group":"html"},function(nodes){
              if(!_.isUndefined(nodes) && nodes.length > 0){
                var folder = nodes[0].name;
                var folderTemp = folder.split("/");
                if(folderTemp.length>0){
                  folderTemp.pop();
                }
                folder = folderTemp.join("/");
                var mixedPath = path.normalize(folder +"/"+filePath);
                mixedPath = mixedPath.replace(/\\/g,"\/" ).replace("//", "/"); 
                cbCorrectPath(null,mixedPath);
              }
              else{
                cbCorrectPath(null,filePath);
              } 
            });

          });
Example #26
0
LibSynphony.prototype.checkStory = function(
    aFocusWordList,
    aWordCumulativeList,
    aGPCsKnown,
    storyHTML,
    sightWords
) {
    var letters;
    var story_vocab;

    if (aGPCsKnown.length > 0) {
        letters = this.fullGPC2Regular(aGPCsKnown).join("|");
        // break the text into words
        story_vocab = this.getWordsFromHtmlString(storyHTML, letters);
    } else {
        letters = "";
        // break the text into words
        story_vocab = this.getWordsFromHtmlString(storyHTML);
    }
    // Just in case users want ? for glottal or similar nonsense with other special
    // RE characters.  See https://issues.bloomlibrary.org/youtrack/issue/BL-7075.
    if (letters.includes("\\")) letters = letters.replace("\\", "\\\\");
    if (letters.includes("?")) letters = letters.replace("?", "\\?");
    if (letters.includes("+")) letters = letters.replace("+", "\\+");
    if (letters.includes("*")) letters = letters.replace("*", "\\*");

    // get unique word list
    var story_vocab_compacted = _.uniq(story_vocab);

    // count total words in the story
    var total_words = _.filter(story_vocab, function(word) {
        return isNaN(word) === true;
    }).length;

    // if aGPCsKnown is empty, return now
    // BL-2359: Need to allow stages based on word lists rather than known graphemes
    //if (aGPCsKnown.length === 0)
    //    return new StoryCheckResults([], [], [], [], [], 0, total_words);

    // first we do diffs on aFocusWordList and aWordCumulativeList with story_vocab words
    var story_focus_words = _.intersection(
        aFocusWordList,
        story_vocab_compacted
    );
    var story_cumulative_words = _.intersection(
        _.pluck(aWordCumulativeList, "Name"),
        story_vocab
    );
    this.array_sort_length(story_focus_words);

    /* TODO: has to handle utf8 */

    // FIRST PASS: we handle words which are currently in focus
    var focus_words = _.intersection(story_focus_words, story_vocab_compacted);
    var remaining_words = _.difference(story_vocab_compacted, focus_words);
    this.array_sort_length(focus_words);

    // SECOND PASS: we handle words which are part of the cumulative word bank
    // aWordCumulativeList is an object that contains the following fields:
    // GPCForm,GPCS,GPCcount,Name,Reverse,SyllShape,Syllables
    var cumulative_words = _.intersection(
        story_cumulative_words,
        remaining_words
    );
    remaining_words = _.difference(remaining_words, cumulative_words);
    this.array_sort_length(cumulative_words);

    // THIRD PASS: we handle words which have not been matched yet to check if they are
    // decodable at this point. This can match words which are longer than the syllable
    // selectors specify but contain all the gpcs. We do this using a regular expression
    // with the array of knownGPCs. This is not the most accurate method; we should
    // first segment the word with all gpcs, then test with known gpcs. This also checks
    // for the possibility that the word is not yet in our database.
    // This only works for simple gpc notation, not complex.
    // Why not for full gpc? Once you have covered the regular spelling patterns (in English)
    // you will match all the other words, so everything gets tagged as 'possible'. Not useful!!
    var possible_words = [];
    if (
        typeof theOneLanguageDataInstance === "undefined" ||
        theOneLanguageDataInstance["UseFullGPCNotation"] === false
    ) {
        // allow punctuation characters in the words
        // BL-1216 Use negative look-ahead to keep letters from being counted as punctuation
        // even if Unicode says something is a punctuation character when the user
        // has specified it as a letter (like single quote).
        var re = new XRegExp(
            "^((" +
                letters +
                ")+((?![" +
                letters +
                "])[\\p{P}]*(" +
                letters +
                ")*)*)$",
            "gi"
        );
        possible_words = _.filter(remaining_words, function(word) {
            return word.match(re);
        });

        // BL-1217: exclude words with unknown graphemes, specifically 'aa' when only 'a' is known
        if (typeof theOneLanguageDataInstance !== "undefined") {
            // get the unknown letters
            var unknownGPCs = _.difference(
                _.pluck(theOneLanguageDataInstance["GPCS"], "GPC"),
                letters.split("|")
            ); // .join('|');
            if (Array.isArray(unknownGPCs) && unknownGPCs.length > 0) {
                // remove from the list of unknownGPCs characters used to build multi-graphs in the list aGPCsKnown
                unknownGPCs = _.filter(unknownGPCs, function(gpc) {
                    return letters.indexOf(gpc) === -1;
                });

                if (unknownGPCs.length > 0) {
                    re = new XRegExp("(" + unknownGPCs.join("|") + ")+", "gi");
                    possible_words = _.filter(possible_words, function(word) {
                        return !word.match(re);
                    });
                }
            }
        }

        remaining_words = _.difference(remaining_words, possible_words);
        this.array_sort_length(possible_words);
    }

    // FOURTH PASS: we handle sight words
    // NOTE: Handle sight words after checking for decodability, because a sight word may become decodable.
    var sight_words = [];
    if (sightWords.length > 0) {
        sight_words = _.intersection(sightWords.split(" "), remaining_words);
        remaining_words = _.difference(remaining_words, sight_words);
        this.array_sort_length(sight_words);
    }

    // FIFTH PASS: we handle everything else that's left over

    var readable =
        focus_words.length + cumulative_words.length + possible_words.length;
    return new StoryCheckResults(
        focus_words,
        cumulative_words,
        possible_words,
        sight_words,
        remaining_words,
        readable,
        total_words
    );
};
Example #27
0
 get: function (req, res, next) {
     var city = req.params.city;
     var cityObj = _.findWhere(_.flatten(_.pluck(Province.data, "cityList"), true), {name: city}) || {areaList: null};
     res.json(cityObj.areaList);
 }
Example #28
0
 return this.find(function(u) {
     return _.contains(_.pluck(u.get("emails"), "value"), email);
 });
Example #29
0
  toLiteral: function (err) {
    var self          = this,
        results       = [],
        warnings      = [],
        rtnObj        = {},
        verifiedCount = 0,
        doneTime      = new Date(),
        truthTest, propList, pages;

    if (self.options.strict) {
      propList  = ['url', 'title', 'favicon', 'links', 'inboundCount', 'aliases'];
      truthTest = function (page) {
        return page.verified && page.status === "fetched";
      }
    } else {
      propList  = ['url', 'title', 'favicon', 'links', 'verified', 'inboundCount', 'aliases'];
      truthTest = function (page) {
        return page.status === "fetched";
      }
    }

    pages = _.filter(self.pages, truthTest);
    if (self.options.stripDeeperLinks){ 
      pages = self.stripDuplicates(pages)
    };
    
    results = _.map(pages, function (page) {
      return page.toLiteral(propList)
    });

    for (var key in self.pages) {
      var page = self.pages[key];
      if(page.getWarning() !== null){
        warnings.push(page.getWarning());
      }
    }

    verifiedCount = _.reduce(_.pluck(self.pages, 'verified')
      , function(m,v){return m + (v ? 1 : 0)});

    if (err) {
      rtnObj = {
        query    : self.rootUrl,
        created  : doneTime.toJSON(),
        crawled  : _.size(self.pages),
        verified : 0
      };
    } else {
      rtnObj = {
        results  : results,
        query    : self.rootUrl,
        created  : doneTime.toJSON(),
        crawled  : _.size(self.pages),
        verified : verifiedCount
      };
    }

    if (!err && warnings.length > 0) {
      rtnObj.warnings = warnings;
    }

    return rtnObj;
  },
Example #30
0
];
console.log(_.where(list, {year: 1982}));

// contains: 判断元素是否在list中
console.log(_.contains([1,2,3,4], 8));

// invoke: 在list里的每个元素上调用名为methodName的函数,任何附加的函数传入,invoke将会转给调用的函数
var v = _.invoke([[2,1,3], [4,5,2]], 'sort')
console.log("v", v);

// pluck: 提取一个集合里指定的属性值
var users = [
    {name:'moe', age: 40},
    {name:'larry', age: 50}
];
console.log(_.pluck(users, 'name'));
// max, min, sortBy:取list中的最大,最小元素,自定义比较器
console.log(_.max(users, function(stooge){
    return stooge.age
}));
console.log(_.min(users, function(stooge){
    return stooge.age //{ name: 'moe', age: 40 }
}));
console.log(_.sortBy([3,4,1,2,6], function(num){
    return Math.max(num);//[ 1, 2, 3, 4, 6 ]
}));

// groupBy 一个集合分成多个集合
console.log(_.groupBy(['one', 'two', 'three'], 'length'));//{ '3': [ 'one', 'two' ], '5': [ 'three' ] }
// size 得到list中元素个数
console.log(_.size({one:1, two:2, three: 3})); //3