Example #1
0
  callback: function (data) {
    if (data.method === 'create') {
      messagesCollection.add(data.model);
      if(messagesCollection.length > 50){
        messagesCollection.remove(messagesCollection.first(messagesCollection.length - 50));
      }
    } else if (data.method === 'update') {
      messagesCollection.remove(data.model);
    } else if (data.method === 'delete') {
      var record = _.find(messagesCollection.models, function (record) {
        return record.id === data.model.id;
      });

      if (record == null) {
        console.log("Could not record: " + model.id);
      }

      var diff = _.difference(_.keys(record.attributes), _.keys(data.model));
      _.each(diff, function(key) {
        return record.unset(key);
      });

      return record.set(data.model, data.options);
    }
  }
Example #2
0
File: web.js Project: Rob-pw/dbot
    passport.use(new LocalStrategy(function(username, password, callback) {
        var splitUser = username.split('@'),
            server = splitUser[1],
            username = splitUser[0];

        if(!server || !username) return callback(null, false, { 'message':
            'Please provide a username in the format of name@server (Servers: ' +
            _.keys(dbot.config.servers).join(', ') + ')' });
        if(!_.has(dbot.config.servers, server)) return callback(null, false, { 'message':
            'Please provide a valid server (Servers: ' +
            _.keys(dbot.config.servers).join(', ') + ')' });

        dbot.api.users.resolveUser(server, username, function(user) {
            if(user) {
                this.api.getWebUser(user.id, function(webUser) {
                    if(webUser) {
                        if(passHash.verify(password, webUser.password)) {
                            return callback(null, user); 
                        } else {
                            return callback(null, false, { 'message': 'Incorrect password.' });
                        }
                    } else {
                        return callback(null, false, { 'message': 'Use ~setwebpass to set up your account for web login.' });
                    }
                });
            } else {
                return callback(null, false, { 'message': 'Unknown user' });
            }
        }.bind(this)); 
    }.bind(this)));
Example #3
0
exports.package_details = function (doc, req) {
    var current = req.query.version || doc.tags.latest;

    var dependency_list = _.keys(
        doc.versions[current].dependencies || {}
    );
    var version_list = _.keys(doc.versions || {}).map(function (v) {
        return {version: v, active: v === current};
    });
    version_list = version_list.sort(semver.compare).reverse();
    var published_date = new Date(doc.time[current]).toString();

    var archive_basename = doc._id + '-' + current + '.tar.gz';
    var archive_url = dutils.getBaseURL(req) + '/_db/' + doc._id + '/' +
                      archive_basename;

    events.once('afterResponse', function (info, req, res) {
        ui.fetchREADME(doc, current);
    });

    return {
        title: doc.name,
        content: templates.render('package_details.html', req, {
            dependency_list: dependency_list,
            version_list: version_list,
            submitted_by: doc.submitted_by,
            published_date: published_date,
            cfg: doc.versions[current],
            archive_url: archive_url,
            archive_basename: archive_basename,
            doc: doc
        })
    }
};
Example #4
0
    exports.buildTrees(deps, cfg, opt, function (err, local, updated) {
        if (err) {
            return callback(err);
        }
        var all_names = _.uniq(_.keys(local).concat(_.keys(updated)));

        var changed = all_names.map(function (name) {
            var lversion = local[name] ? local[name].current_version: null;
            var uversion = updated[name] ? updated[name].current_version: null;

            if (lversion) {
                var lpkg = local[name].versions[lversion];
                if (lpkg.source === 'repository') {
                    // cannot even satisfy requirements with current package,
                    // this needs re-installing from repositories
                    return {
                        name: name,
                        version: uversion,
                        old: 'not satisfiable'
                    };
                }
            }
            if (!local[name] && updated[name] || lversion !== uversion) {
                return {name: name, version: uversion, old: lversion};
            }
        });
        callback(null, _.compact(changed), local, updated);
    });
Example #5
0
 '~rq': function(event) {
     if(_.keys(quotes).length > 0) {
         var category = _.keys(quotes)[_.random(0, _.size(quotes) -1)];
         event.reply(category + ': ' +
         this.internalAPI.interpolatedQuote(event.server, event.channel.name, event.user, category));
     } else {
         event.reply(dbot.t('no_results'));
     }
 },
Example #6
0
	socket.on('newuser',function(data,callback){
		var usersnames = _.keys(users);
		console.log(_.lastIndexOf(usersnames,data.message));
		if(_.lastIndexOf(usersnames,data.message)!=-1){
				callback({error:['error! username already taken']});
		}else{
			callback({success:['welcome to chat']});
		}
		users[data.message]= socket;
		var usersnames = _.keys(users);
		socket.broadcast.emit('newuser',usersnames);
	})
Example #7
0
 this.api.getTrackedWord(word, function(tWord) {
     if(tWord) {
         event.reply(dbot.t('sstats_word', {
             'word': word,
             'total': tWord.total,
             'channels': _.keys(tWord.channels).length, 
             'users': _.keys(tWord.users).length,
             'since': moment(tWord.creation).format('DD/MM/YYYY')
         }));
     } else {
         event.reply(word + ' isn\'t being tracked.');
     }
 });
Example #8
0
exports.save = function(operation, args, next){
  assert(_.isObject(args), "Please pass in the document for saving as an object. Include the primary key for an UPDATE.");
  //see if the args contains a PK
  var self = this;
  var sql, params = [];
  var pkName = this.primaryKeyName();
  var pkVal = args[pkName];
  if (!pkVal) {
    pkVal = genid();
  }

  //just in case
  delete args[pkName];
  params.push(pkVal);

  if (operation === 'update') {
    if (args.$set) {
      var path = _.keys(args.$set)[0];
      var val = args.$set[path];
      params.push(path, JSON.stringify(val));
      sql = util.format("select json_set('%s', $1, $2, $3::JSON);",
        this.fullname);
    } else if (args.$insert) {
      var path = _.keys(args.$insert)[0];
      var val = args.$insert[path];
      params.push(path, JSON.stringify(val));
      sql = util.format("select json_insert('%s', $1, $2, $3::JSON);",
        this.fullname);
    } else if (args.$push) {
      var path = _.keys(args.$push)[0];
      var val = args.$push[path];
      params.push(path, JSON.stringify(val));
      sql = util.format("select json_push('%s', $1, $2, $3::JSON);",
        this.fullname);
    } else if (args.$remove) {
      var path = args.$remove;
      params.push(path);
      sql = util.format("select json_remove('%s', $1, $2);", this.fullname);
    } else {
      params.push(JSON.stringify(args));
      sql = util.format("update %s set body = $2 where %s = $1 returning *;",
        this.fullname, pkName);
    }
  } else if (operation === 'insert') {
    params.push(JSON.stringify(args));
    sql = "insert into " + this.fullname + "(id, body) values($1, $2) returning *;"
  } else {
    throw("Operation must be either 'update' or 'insert'");
  }
  this.executeDocQuery(sql, params, {single : true}, next)
};
Example #9
0
exports.validate = function (fields, doc, values, raw, path, extra) {
    values = values || {};
    fields = fields || {};
    raw = raw || {};

    // Expecting sub-object, not a value
    if (typeof values !== 'object') {
        var e = new Error('Unexpected property - validation 1');
        e.field = path;
        e.has_field = false;
        return [e];
    }

    // Ensure we walk through all paths of both fields and values by combining
    // the keys of both. Otherwise, we might miss out checking for missing
    // required fields, or may not detect the presence of extra fields.

    var keys = _.uniq(_.keys(fields).concat(_.keys(values)));
    var fields_module = require('./fields');

    return _.reduce(keys, function (errs, k) {
        var f = fields[k];
        if (f === undefined) {
            // Extra value with no associated field detected
            if (!extra) {
                // ignore system properties
                if (!(path.length === 0 && k.charAt(0) === '_')) {
                    var e = new Error('Unexpected property - validation 2');
                    e.field = path.concat([k]);
                    e.has_field = false;
                    errs.push(e);
                }
            }
            return errs;
        }
        var val = values[k];
        var fn = exports.validate;
        if (f instanceof fields_module.Field ||
            f instanceof fields_module.Embedded ||
            f instanceof fields_module.EmbeddedList) {
            fn = exports.validateField;
        }
        if (f instanceof fields_module.AttachmentField) {
            val = utils.attachmentsBelowPath(doc, path.concat([k]));
        }
        return errs.concat(
            fn.call(this, f, doc, val, raw[k], path.concat([k]), extra)
        );
    }, []);
};
Example #10
0
	socket.on("joinRoom", function(id) {
		if (typeof people[socket.id] !== "undefined") {
			var room = rooms[id];
			if (socket.id === room.owner) {
				socket.emit("update", "You are the owner of this room and you have already been joined.");
			} else {
				if (_.contains((room.people), socket.id)) {
					socket.emit("update", "You have already joined this room.");
				} else {
					if (people[socket.id].inroom !== null) {
				    		socket.emit("update", "You are already in a room ("+rooms[people[socket.id].inroom].name+"), please leave it first to join another room.");
				    	} else {
						room.addPerson(socket.id);
						people[socket.id].inroom = id;
						socket.room = room.name;
						socket.join(socket.room);
						user = people[socket.id];
						io.sockets.in(socket.room).emit("update", user.name + " has connected to room '" + room.name + "'.");
						socket.emit("update", "Welcome to " + room.name + ".");
						socket.emit("sendRoomID", {id: id});
						var keys = _.keys(chatHistory);
						if (_.contains(keys, socket.room)) {
							socket.emit("history", chatHistory[socket.room]);
						}
					}
				}
			}
		} else {
			socket.emit("update", "Please enter a valid name first.");
		}
	});
Example #11
0
		_.each(usersnames,function(v){		
			if((socket.id)===users[v].id){
				delete users[v]
				var usersnames = _.keys(users);
				io.sockets.emit('newuser',usersnames);
			}
		})
Example #12
0
                        event.channel.name, event.user, key, function(quote) {
                    if(quote) {
                        event.reply(key + ': ' + quote);
                    } else if(_.has(dbot.modules, 'spelling')) {
                        var commands = _.keys(dbot.commands)
                            winner = false,
                            closestMatch = Infinity;

                        _.each(commands, function(command) {
                            var distance = dbot.api.spelling.distance(commandName, command);
                            if(distance < closestMatch) {
                                closestMatch = distance;
                                winner = command;
                            }
                        }); 

                        if(closestMatch < 1) {
                            event.reply(commandName + ' not found. Did you mean ' + winner + '?');
                            return;
                        } else if(_.has(dbot.modules, 'quotes')) {
                            dbot.api.link.udLookup(key, function(word, definition) {
                                if(word) {
                                    event.reply(key + '[UD]: ' + definition);
                                } else {
                                    event.reply(dbot.t('category_not_found', { 'category': key }));
                                }
                            });
                        } else {
                            return;
                        }
                    }
                });
// Socket client has disconnected
function onClientDisconnect() {

	util.log("Player has disconnected: "+this.id);

	var removePlayer = players[this.id];

	// Player not found
	if (!removePlayer) {
		util.log("Player not found: "+this.id);
		return;
	}

	// Remove player from players array
	delete players[this.id];
	playersCount--;

	// If there are no more connected players and a game is in progress, kill the game
	if(gameInProgress && _.keys(players).length === 0) {
		endGame();
		return;
	}

	// Reset the flag if the player was carrying the flag
	if(removePlayer.carryingFlag) {
		flagReset({team: removePlayer.team});
	}

	// Broadcast removed player to connected socket clients
	this.broadcast.emit("remove player", {id: this.id});

	// Update the waiting room message
	if(!gameInProgress) { updateWaitingMessage(); }

}
Example #14
0
exports.override = function (excludes, field_subset, fields, doc_a, doc_b, path) {
    fields = fields || {};
    doc_a = doc_a || {};

    var fields_module = require('./fields');
    var exclude_paths = _.map((excludes || []), function (p) {
        return p.split('.');
    });
    var subset_paths = _.map((field_subset || []), function (p) {
        return p.split('.');
    });

    var keys = _.keys(doc_b);

    _.each(keys, function (k) {
        if (path.length === 0 && k === '_attachments') {
            return;
        }
        var f = fields[k];
        var b = doc_b[k];
        var f_path = path.concat([k]);

        if (typeof b !== 'object' ||
            f instanceof fields_module.Field ||
            f instanceof fields_module.Embedded ||
            f instanceof fields_module.EmbeddedList) {

            if (excludes) {
                for (var i = 0; i < exclude_paths.length; i++) {
                    if (utils.isSubPath(exclude_paths[i], f_path)) {
                        return;
                    }
                }
            }
            if (field_subset) {
                var in_subset = false;
                for (var j = 0; j < subset_paths.length; j++) {
                    if (utils.isSubPath(subset_paths[j], f_path)) {
                        in_subset = true;
                    }
                }
                if (!in_subset) {
                    return;
                }
            }
            doc_a[k] = b;
        }
        else {
            doc_a[k] = exports.override(
                excludes, field_subset, fields[k], doc_a[k], b, f_path
            );
        }
    });
    if (path.length === 0) {
        return exports.overrideAttachments(
            excludes, field_subset, fields, doc_a, doc_b
        );
    }
    return doc_a;
};
Example #15
0
	socket.on("joinRoom", function(id) {
		if (typeof people[socket.id] !== "undefined") {
			var room = rooms[id];
			if (socket.id === room.owner) {
				socket.emit("messageFromServer", "You have already joined this room.");
			} else {
				if (underScore.contains((room.people), socket.id)) {
					socket.emit("messageFromServer", "You have already joined this room.");
				} else {
					if (people[socket.id].inroom !== null) {
				    		socket.emit("messageFromServer", "You are already in a room ("+rooms[people[socket.id].inroom].name+"), please leave it first to join another room.");
				    	} else {
						room.addPerson(socket.id,people[socket.id].name);
						people[socket.id].inroom = id;
						socket.room = room.name;
						socket.join(socket.room);
						io.sockets.in(socket.room).emit("messageFromServer", people[socket.id].name + " has connected to " + room.name + " room.");
						socket.emit("messageFromServer", "Welcome to " + room.name + ".");
						socket.emit("sendRoomID", {id: id});
						io.sockets.in(socket.room).emit("peopleInRoom", {roomName:room.name,people: room.persons, count: underScore.size(room.people)});
						var keys = underScore.keys(chatHistory);
						if (underScore.contains(keys, socket.room)) {
							socket.emit("history", chatHistory[socket.room]);
						}
					}
				}
			}
		} else {
			socket.emit("messageFromServer", "Please enter a valid name first.");
		}
	});
Example #16
0
	}, function(err, chores) {
		if (err) {
			apiResponse.success = false;
			apiResponse.error = "Failed to get the chores: " + JSON.stringify(err);
			res.json(apiResponse);
		}
		else {
			console.log("Chores: " + JSON.stringify(chores));

			// refactor chores data for pie chart display
			for (var i = 0; i < chores.length; i++) {
				choreData[chores[i].type.name] = choreData[chores[i].type.name] ? 
				choreData[chores[i].type.name] + 1 : 1;

				// change the date/time display of chores
				dateDone = new Date(chores[i].done_date);
				chores[i].done_date = date.format(dateDone, '%b %d %H:%M');
				chores[i].points = chores[i].time_taken;
			}
			_.each(_.keys(choreData), function(key) {
				chorePieData[chorePieData.length] = {label: key, data: choreData[key] };
			});
			apiResponse.chorePieData = chorePieData;
			apiResponse.chores = chores;
			res.json(apiResponse);
			console.log("ChorePieData: " + JSON.stringify(chorePieData));
		}
	});
Example #17
0
 }, errorHandler(cb, function(err, lists) {
   var changes = [];
   var ls1 = lists[0];
   var ls2 = lists[1];
   var deletedPaths = _.extend(ls1.byPath);
   // TODO: catch deleted files
   _.each(ls2.bySha1, function(path, sha1) {
     if (ls1.bySha1[sha1]) {
       if (ls1.bySha1[sha1] === path) {
         // no change
         delete deletedPaths[path];
       } else {
         // renamed; blob the same, though
         // note that we're not catching renames that are mostly the same... they're just counting as delete & add
         changes.push({ type: 'rename', before: { path: ls1.bySha1[sha1], sha1: sha1 }, after: { path: path, sha1: sha1 } });
         delete deletedPaths[ls1.bySha1[sha1]];
       }
     } else {
       if (ls1.byPath[path]) {
         // changed
         changes.push({ type: 'change', before: { path: path, sha1: ls1.byPath[path] }, after: { path: path, sha1: sha1 } });
         delete deletedPaths[path];
       } else {
         // added
         changes.push({ type: 'add', before: { }, after: { path: path, sha1: sha1 } });
       }
     }
   });
   _.each(_.keys(deletedPaths), function(path) {
     changes.push({ type: 'delete', before: { path: path, sha1: ls1.byPath[path] }, after: { } });
   });
   cb(null, changes);
 }));
Example #18
0
File: pages.js Project: Rob-pw/dbot
            this.db.read('poll', key, function(err, poll) {
                if(!err) {
                console.log(poll);
                    var totalVotes = _.reduce(poll.votes, function(memo, option) {
                        return memo += option;
                    }, 0);

                    var voterNicks = [];
                    async.each(_.keys(poll.votees), function(id, done) {
                        dbot.api.users.getUser(id, function(user) {
                            voterNicks.push(user.primaryNick);
                            done();
                        });
                    }, function() {
                        res.render('polls', { 
                            'name': dbot.config.name, 
                            'description': poll.description, 
                            'votees': voterNicks,
                            'options': poll.votes,
                            'totalVotes': totalVotes, 
                            locals: { 
                                'url_regex': RegExp.prototype.url_regex() 
                            }
                        });

                    });
                } else {
                    res.render('error', { 
                        'name': dbot.config.name, 
                        'message': 'No polls under that key.' 
                    });
                }
            });
Example #19
0
File: api.js Project: reality/dbot
                        }, function() {
                            // Queue notifies for offline ops
                          if(this.config.offlineReporting == true) {
                            if(!_.include(this.config.noMissingChans, cName)) {
                                _.each(offlineOps, function(op) {
                                    if(!this.pending[op.id]) this.pending[op.id] = [];
                                    this.pending[op.id].push({
                                        'time': new Date().getTime(),
                                        'channel': cName,
                                        'user': user.id,
                                        'message': message
                                    });
                                    this.pNotify[op.id] = true;
                                }, this);
                            }
                          }

                            // Send notifies to online ops
                            ops = _.difference(ops, _.keys(offlineOps));
                            message = this.internalAPI.formatNotify(type, server,
                                        user, cName, message);
                            this.internalAPI.notify(server, ops, message);
                            if(_.has(this.config.chan_redirs, cName)) {
                                dbot.say(server, this.config.chan_redirs[cName], message);
                            }
                        }.bind(this));
Example #20
0
        parseFeatherFiles: function(indexedFiles) {
          // - pre-parse all feather.html files
          // - move the stateMachine to the next state
          var sem = new Semaphore(function() {
            fsm.fire("parsingComplete");
          });

          //parse the .feather.html files in the app
          _.each(_.keys(indexedFiles.featherFiles), function(_path) {
            sem.increment();
            //guarantee all files get counted in semaphore
            process.nextTick(function() {
              parser.parseFile({
                path: _path, 
                request: {page: _path.replace(/.*\/public\/(.*)$/, "$1")} //need a dummy request object for parser since there is no real request at this point
              }, function(err, result) {
                  if (err) throw new Error(JSON.stringify(err)); else {
                    
                    //TODO: figure out gracefully re-publishing changed files w/ watchers... (commenting out for now as a placeholder)
                    // if (!indexedFiles.featherFiles[_path].watchingFile) { //only wire the watcher once
                    //   fileWatcher.watchFileMtime(_path, function(args) {
                    //     // TODO: Trigger a reparse and republish of the page (with clustered processes this could be a messy resource contention issue).
                    //   });
                    //   indexedFiles.featherFiles[_path].watchingFile = true;
                    // }

                    sem.execute();
                  }
              });
            });              
          });
        },
Example #21
0
  redis.hgetall( hashName, function( e, hash ){

    if( e ){
      console.log('ERROR with: ' + hashName );
    }else{
      var keys = _.keys( hash ), lowerCase_email, original_email, d= 0;

      for (var i =0; i < keys.length ; i++) {
        original_email = hash[ keys[i] ];
        lowerCase_email = original_email.toLowerCase();
        renameHash( hashName, keys[i], original_email, lowerCase_email , function(){
          d+= 1;



          if(d == keys.length){
            fn();
          }
        });
        

      };

    }

  })
Example #22
0
        socket.on('joinRoom', (roomId) => {
            if (typeof people[socket.id] !== 'undefined') {
                var room = rooms[roomId];
                if (socket.id === room.owner) {
                    socket.emit('update', 'You are already in the room.');
                } else if (_.contains((room.people), socket.id)) {
					socket.emit('update', 'You are already in this room.');
				} else if (people[socket.id].inroom !== null) {
					socket.emit('update', 'You are already in the room (' + rooms[people[socket.id].inroom].name + ').');
				} else {
					// add this user to the room
					var user = people[socket.id];
					user.inroom = roomId;
					room.add(socket.id);
					socket.room = room.name;
					socket.join(socket.room);

					// broadcast
					io.sockets.to(socket.room).emit('update', user.name + ' has joined room ' + room.name + '.');
					socket.emit('update', 'Welcome to ' + room.name + '.');
					socket.emit('sendRoomID', {id: roomId});

					// show past msgs
					var keys = _.keys(msgHistory);
					if (_.contains(keys, socket.room)) {
						socket.emit('history', msgHistory[socket.room]);
					}
				}
            } else {
                socket.emit('update', 'Please enter a valid name first.');
            }
        });
Example #23
0
 _.forEach(config.properties, function(prop_config, prop_name) {
   var value = obj[prop_name];
   if (prop_config.object) {
     // recurse
     errors.add(prop_name, validate(value, prop_config.object));
     return; // no other validation types should apply if validation type is 'object'
   }
   for (var i = 0; i < validation_types.length; i++) {
     var validation_type = validation_types[i];
     if (!prop_config[validation_type]) continue;
     if (validation_type != 'required' && 
         (value === undefined || value === null )) 
         continue;
     if (typeof valid_funcs[validation_type] == 'function') {
       var is_valid = test_and_add_error_message(prop_name, prop_config, 
                        validation_type, value);
       if (!is_valid && validation_type == 'required') break;
     } else {
       _.keys(valid_funcs[validation_type]).forEach(function(subtype) {
         test_and_add_error_message(prop_name, prop_config, validation_type, 
           value, subtype);
       });        
     }
   }
 });
Example #24
0
		load: function() {
			var data = JSON.parse(localStorage.telepathyWeb || '{}');
			var that = this;

			if (!data) return;

			_.each(_.keys(that._settings), function(key) {
				if (data.settings && _.has(data.settings, key))
					that._settings[key] = data.settings[key];

				that.settings[key] = that._settings[key];

				var $option = $('#settings [name=' + key + ']');

				switch ($option.prop('type')) {
					case 'radio':
						$option.each(function() {
							var $this = $(this);
							$this.prop('checked', $this.val() == that.settings[key]);
						});
						break;

					default:
						$option.val(that.settings[key]);
						break;
				}
			});

			$('#index').val(this.settings['default-index']);
			$('#length').val(this.settings['default-length']);
		},
Example #25
0
exports.parseResponse = function (req, res) {
    var ids = _.without(_.keys(res), 'title', 'code', 'headers', 'body');
    if (req.client) {
        if (res.title) {
            document.title = res.title;
        }
        _.each(ids, function (id) {
            $('#' + id).html(res[id]);
        });
    }
    else if (!res.body) {
        var context = {title: res.title || ''};
        _.each(ids, function (id) {
            context[id] = res[id];
        });
        if (!templates) {
            throw new Error(
                'Short-hand response style requires templates module'
            );
        }
        var body = templates.render(BASE_TEMPLATE, req, context);
        res = {
            body: body,
            code: res.code || 200,
            headers: res.headers
        };
    }
    return {
        body: res.body,
        code: res.code,
        headers: res.headers
    };
};
Example #26
0
QueryString.stringify = QueryString.encode = function (obj, sep, eq, name) {
    sep = sep || '&';
    eq = eq || '=';
    obj = (obj === null) ? undefined : obj;

    if (typeof obj === 'object') {
        return _.map(_.keys(obj), function (k) {
            if (_.isArray(obj[k])) {
                return _.map(obj[k], function (v) {
                    return QueryString.escape(stringifyPrimitive(k)) +
                           eq +
                           QueryString.escape(stringifyPrimitive(v));
                }).join(sep);
            }
            else {
                return QueryString.escape(stringifyPrimitive(k)) +
                       eq +
                       QueryString.escape(stringifyPrimitive(obj[k]));
            }
        }).join(sep);
    }
    if (!name) {
        return '';
    }
    return QueryString.escape(stringifyPrimitive(name)) + eq +
           QueryString.escape(stringifyPrimitive(obj));
};
	it('supports ranking with scores', function() {
		var a = classifier.classify({I:1 , want:1 , aa:1 }, /*explain=*/5, /*withScores=*/true);
		_.keys(a.scores).should.have.lengthOf(3);
		_.keys(a.scores)[0].should.eql('A');
		a.scores['A'].should.be.above(0);
		a.scores['B'].should.be.below(0);
		var b = classifier.classify({I:1 , want:1 , bb:1 }, /*explain=*/5, /*withScores=*/true)
		_.keys(b.scores).should.have.lengthOf(3);
		b.scores['B'].should.be.above(0);
		b.scores['A'].should.be.below(0);
		var c = classifier.classify({I:1 , want:1 , cc:1 }, /*explain=*/5, /*withScores=*/true);
		_.keys(c.scores).should.have.lengthOf(3);
		c.scores['{"C":"c"}'].should.be.above(0);
		c.scores['A'].should.be.below(0);
		c.scores['B'].should.be.below(0);

	});
Example #28
0
function shiftTime(startEndTime) {
  var shiftedTime = new Object();
  _.each(_.keys(startEndTime), function(key) {
    var date = new Date(startEndTime[key])
    date.setHours(date.getHours()-1);
    shiftedTime[key] = date;
  });
  return shiftedTime;
}
Example #29
0
File: api.js Project: treesus/dbot
 'getRandomChannelUser': function(server, cName, callback) {
     if(_.has(dbot.instance.connections[server].channels, cName)) {
         var nicks = _.keys(dbot.instance.connections[server].channels[cName].nicks);
         var randomUser = nicks[_.random(0, nicks.length -1)]
         callback(randomUser);
     } else {
         callback(false);
     }
 },
Example #30
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);

 	},