Example #1
0
		 	}, function(err){

		 		synonyms = _.map(_.unique(synonyms), function(num){ return [num, wordCount.indexOf(num)] });
		 		antonyms = _.map(_.unique(antonyms), function(num){ return [num, wordCount.indexOf(num)] });

		 		synonyms = _.sortBy(synonyms, function(num){ return num[1] }).reverse()
		 		antonyms = _.sortBy(antonyms, function(num){ return num[1] }).reverse()

		 		wordnet.close()

				synonyms = _.filter(synonyms, function(num){ return (num[0].indexOf("_")==-1) })
		 		antonyms = _.filter(antonyms, function(num){ return (num[0].indexOf("_")==-1) })
		 		
				// eliminate the numbers

				synonyms = _.unique(_.flatten(_.map(synonyms, function(num){ return num[0] })))
		 		antonyms = _.unique(_.flatten(_.map(antonyms, function(num){ return num[0] })))

		 		console.vlog("DEBUGWORDNET: synonyms: "+JSON.stringify(synonyms, null, 4))
		 		console.vlog("DEBUGWORDNET: antonyms: "+JSON.stringify(antonyms, null, 4))

		 		callbackg(null, {
		 			'synonyms':_.filter(synonyms, function(num){ return (num[0].indexOf("_")==-1) }),
		 			'antonyms':_.filter(antonyms, function(num){ return (num[0].indexOf("_")==-1) })
		 		})
		})
Example #2
0
	wordnet.lookup(string, function(results) {

		results = _.filter(results, function(num){ return !_.isNull(num) });

		results = _.filter(results, function(num){ return num.pos ==  wnpos });

		async.eachSeries(results, function(synset, callbackloc) {

				synonyms = synonyms.concat(synset.synonyms)

				synset.ptrs = _.filter(synset.ptrs, function(num){ return num.pointerSymbol ==  "!" });

				async.eachSeries(synset.ptrs, function(subsynset, callbacklocloc) {

						wordnet.get(subsynset.synsetOffset, subsynset.pos, function(anton) {
							antonyms = antonyms.concat(anton.synonyms)
   							callbacklocloc(null)
						});
					
				}, function(err){
					callbackloc(null)

				})

		 	}, function(err){

		 		synonyms = _.map(_.unique(synonyms), function(num){ return [num, wordCount.indexOf(num)] });
		 		antonyms = _.map(_.unique(antonyms), function(num){ return [num, wordCount.indexOf(num)] });

		 		synonyms = _.sortBy(synonyms, function(num){ return num[1] }).reverse()
		 		antonyms = _.sortBy(antonyms, function(num){ return num[1] }).reverse()

		 		wordnet.close()

				synonyms = _.filter(synonyms, function(num){ return (num[0].indexOf("_")==-1) })
		 		antonyms = _.filter(antonyms, function(num){ return (num[0].indexOf("_")==-1) })
		 		
				// eliminate the numbers

				synonyms = _.unique(_.flatten(_.map(synonyms, function(num){ return num[0] })))
		 		antonyms = _.unique(_.flatten(_.map(antonyms, function(num){ return num[0] })))

		 		console.vlog("DEBUGWORDNET: synonyms: "+JSON.stringify(synonyms, null, 4))
		 		console.vlog("DEBUGWORDNET: antonyms: "+JSON.stringify(antonyms, null, 4))

		 		callbackg(null, {
		 			'synonyms':_.filter(synonyms, function(num){ return (num[0].indexOf("_")==-1) }),
		 			'antonyms':_.filter(antonyms, function(num){ return (num[0].indexOf("_")==-1) })
		 		})
		})

	})
Example #3
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);
  }
});
processor.startupFilter = function(data) {
	var filteredData = _.filter(data, function(d) {
		return (d.ano==2012 && d.periodo == 21) || (d.ano==2012 && d.periodo == 22) || (d.ano==2013 && d.periodo == 21); 
	});
		
	return filteredData;
};
Example #5
0
    _.each(links, function (currUrl) {
      var currUrlHostname   = urlParser.parse(currUrl).hostname,
          sameHostnamePages = [],
          hasShorterPaths   = false,
          currUrlPath, currUrlDepth;

      sameHostnamePages = _.filter(links, function (url) {
        return currUrlHostname === urlParser.parse(url).hostname && url !== currUrl;
      });

      if (_.isEmpty(sameHostnamePages)) {
        rtnArr.push(currUrl);
      } else {
        currUrlPath = fn.url.removeTrailingSlash(urlParser.parse(currUrl).path);
        currUrlDepth = currUrlPath.split('/').length;

        hasShorterPaths = _.any(sameHostnamePages, function (url) {
          var urlPath  = fn.url.removeTrailingSlash(urlParser.parse(url).path),
              urlDepth = urlPath.split('/').length;

          return urlDepth < currUrlDepth;
        });

        if (!hasShorterPaths) {
          rtnArr.push(currUrl);
        }
      }
    });
Example #6
0
 getAttackActions: function() {//(turnTime, battle)
     'use strict';
     var actions = [],
         self = this,
         enemiesInRange,
         enemyToAttack;
     if (!this.onCooldown && !this.moving && !this.dizzy) {//attack ready
         enemiesInRange = _.filter(this.ship.units,
             function(u) {
                 return u.isAlive() &&
                     self.isEnemy(u) &&
                     self.isInRange(u);
             });
         if (this.targetID !== null && this.targetID !== undefined) {
             //if targetID is set, it has attack priority
             enemyToAttack = _.where(enemiesInRange,
                 {id: this.targetID})[0] ||
                 enemiesInRange[0];
         } else {
             enemyToAttack = enemiesInRange[0];
         }
         if (enemyToAttack) {
             actions.push(new act.Attack({
                 attackerID: self.id,
                 receiverID: enemyToAttack.id,
                 damage: self.meleeDamage,
                 duration: self.attackCooldown
             }));
         }
     }
     return actions;
 },
Example #7
0
    _.each(pages, function (currPage) {
      var currPageDomain  = urlParser.parse(currPage.url).hostname,
          sameDomainPages = [],
          hasShorterPaths = false,
          currPagePath, currPageDepth;

      sameDomainPages = _.filter(pages, function (page) {
        return currPageDomain === urlParser.parse(page.url).hostname && page.url !== currPage.url;
      });

      if (_.isEmpty(sameDomainPages)) {
        rtnObj[currPage.url] = currPage;
      } else {
        currPagePath = fn.url.removeTrailingSlash(urlParser.parse(currPage.url).path);
        currPageDepth = currPagePath.split('/').length;

        hasShorterPaths = _.any(sameDomainPages, function (page) {
          var pagePath  = fn.url.removeTrailingSlash(urlParser.parse(page.url).path),
              pageDepth = pagePath.split('/').length;

          return pageDepth < currPageDepth;
        });

        if (!hasShorterPaths) {
          rtnObj[currPage.url] = currPage;
        }
      }
    });
Example #8
0
 getValidOrderForPos: function(unit, pos) {
     'use strict';
     var stuff = this.map.at(pos.x, pos.y),
         enemies,
         order;
     if (_.isArray(stuff)) {
         enemies = _.filter(stuff, function(u) {
             return u instanceof Unit && u.isEnemy(unit);
         });
         if (enemies.length > 0) {
             order = new orders.SeekAndDestroy({
                 unitID: unit.id,
                 targetID: enemies[0].id
             });
         }
     } else {
         if (stuff instanceof items.Console) {
             order = new orders.MoveToConsole({
                 unitID: unit.id,
                 destination: {x: pos.x, y: pos.y}
             });
         } else if (this.isWalkable(pos.x, pos.y)) {
             order = new orders.Move({
                 unitID: unit.id,
                 destination: {x: pos.x, y: pos.y}
             });
         }
     }
     if (order && order.isValid(this, unit.ownerID)) {
         return order;
     }
     return null;
 }
Example #9
0
  //Returns an array of interpretations. Each interpretation is a corresponding array of components.
 function processComponents(components, colIdx) {
     var component, langNodeInterps;
     if(components.length === 0 || colIdx <= 0){//colIdx?
         return [[]];
     }
     component = components.slice(-1)[0];
     if('terminal' in component) {
         return _.map(processComponents(components.slice(0, -1), colIdx - component.terminal.length), function(interpretation){
             return interpretation.concat(component);
         });
     } else if('regex' in component) {
         if(component.match){
             return _.map(processComponents(components.slice(0, -1), colIdx - component.match.length), function(interpretation){
                 return interpretation.concat(component);
             });
         }
     } else if('category' in component) {
         langNodeInterps = _.filter(chart[colIdx], function(langNode) {
             return (langNode.category === component.category) && (langNode.parseData.atComponent >= langNode.components.length);
         });
         if(langNodeInterps.length === 0 ) return [[]];
         return _.flatten(_.map(langNodeInterps, function(langNodeInterp) {
             //Might be causing stack overflow.
             var returnInterp = langNodeInterp;//_.extend({}, langNodeInterp);//TODO: Probably not necessairy.
             returnInterp.interpretations = processComponents(returnInterp.components, colIdx);
             return _.map(processComponents(components.slice(0, -1), langNodeInterp.parseData.origin), function(interpretation){
                 //TODO: remove parseData here?
                 return interpretation.concat(returnInterp);
             });
         }), true);
     } else {
         throw "Unknown component type:\n" + JSON.stringify(component);
     }
 }
Example #10
0
        getShipData: function(ship) {
            var data = this.staticShipData[ship.id],
                myUnits,
                enemies;

            //PATHFINDING GRID
            function makeUnitsUnwalkable(ship, grid) {
                var units = ship.units;
                _.each(units, function(u) {
                    if (u.x >= 0 && u.x < grid.width &&
                            u.y >= 0 && u.y < grid.height) {
                        grid.setWalkableAt(u.x, u.y, false);
                    }
                });
                return grid;
            }
            data.grid = new sh.PF.Grid(ship.width, ship.height,
                ship.getPfMatrix());
            data.gridWithUnits = makeUnitsUnwalkable(ship, data.grid.clone());

            //UNITS BY TYPE
            myUnits = ship.getPlayerUnits(this.id);
            data.allies = _.groupBy(myUnits, 'type');
            data.allies.all = myUnits;
            enemies = _.filter(ship.units, function(u) {
                return u.ownerID !== this.id;
            }, this);
            data.enemies = _.groupBy(enemies, 'type');
            data.enemies.all = enemies;
            data.ship = ship;
            return data;
        },
Example #11
0
 getStaticShipData: function(ship) {
     var data = {};
     data.weaponConsoles = _.filter(ship.built, function(item) {
         return item.type === 'Console' &&
             item.getControlled().type === 'Weapon';
     });
     data.teleporters = _.where(ship.built, {type: 'Teleporter'});
     data.teleporterTiles = {};
     _.each(data.teleporters, function(tel) {
         var outerTiles = [
             {x: tel.x - 1, y: tel.y - 1},
             {x: tel.x, y: tel.y - 1},
             {x: tel.x + 1, y: tel.y - 1},
             {x: tel.x + 2, y: tel.y - 1},
             {x: tel.x - 1, y: tel.y},
             {x: tel.x + 2, y: tel.y},
             {x: tel.x - 1, y: tel.y + 1},
             {x: tel.x + 2, y: tel.y + 1},
             {x: tel.x, y: tel.y + 2},
             {x: tel.x - 1, y: tel.y + 2},
             {x: tel.x + 1, y: tel.y + 2},
             {x: tel.x + 2, y: tel.y + 2}
         ];
         data.teleporterTiles[tel.id] = _.filter(outerTiles,
             function(tile) {
                 return ship.isInside(tile.x, tile.y);
             });
     });
     return data;
 },
Example #12
0
function audio_recode_necessary_tracks(mkv, callback) {
    var to_recode = _.filter(mkv.tracks, is_track_audio_needs_recoding);
    console.log('Need to recode: '.blue + sys.inspect(to_recode).cyan);
    async.forEachLimit(to_recode, max_audio_recoders, recode_audio_track, function (err) {
	callback(err, mkv);
    });
}
Example #13
0
exports.discussion = function (head, req) {
    start({code: 200, headers: {'Content-Type': 'text/html'}});

    var row, rows = [];
    while (row = getRow()) {
        rows.push(row);
    }
    var comments = _.filter(rows, function (r) {
        return r.doc.type === 'comment';
    });
    var doc_row = _.detect(rows, function (r) {
        return r.doc.type === 'page';
    });
    var empty_doc = !(doc_row);
    var doc = doc_row ? doc_row.doc: {};

    comments = _.map(comments, function (c) {
        c.doc.type = 'comment';
        c.doc.pptime = utils.prettyTime(c.doc.time);
        return c.doc;
    });
    // add edit events to comments
    if (doc && doc.history) {
        _.each(doc.history, function (h) {
            h.type = 'edit';
            h.is_edit = true;
            h.pptime = utils.prettyTime(h.time);
            comments.push(h);
        });
    }
    comments = _.sortBy(comments, function (c) {
        return c.time;
    });
    var participants = comments.map(function (c) {
        return c.user;
    });
    participants = _.uniq(participants);

    if (req.query.page && req.query.page[0] === '_') {
        return shows.not_found(null, req);
    }

    events.once('afterResponse', discussion_ui.bindDiscussion);

    return {
        title: doc.title || utils.idToTitle(req.query.page),
        content: templates.render('discussion.html', req, {
            doc: doc,
            page_title: doc.title || utils.idToTitle(req.query.page),
            page_subtitle: doc.subtitle,
            pageid: doc._id || req.query.page,
            participants: participants,
            comments: comments,
            current_tab: "discussion_page",
            logged_in: !!(req.userCtx.name),
            empty_doc: empty_doc
        })
    };
};
Example #14
0
 _.intersection = _.intersect = function(array) {
   var rest = slice.call(arguments, 1);
   return _.filter(_.uniq(array), function(item) {
     return _.every(rest, function(other) {
       return _.indexOf(other, item) >= 0;
     });
   });
 };
Example #15
0
function BalMult(target, substitute, context) {
  
  if (context.length > 0)
    context = _.filter(context, function(num){ return num.length>0 });
 
  var prod = _.reduce(context, function(memo, num){ return memo * pcosine_distance(substitute, num) }, 1);

  return Math.pow(prod * Math.pow(pcosine_distance(substitute, target), context.length), 2 * context.length)
}
Example #16
0
function BalAdd(target, substitute, context) {
 
  if (context.length > 0)
    context = _.filter(context, function(num){ return num.length>0 });
  
  var sum = _.reduce(context, function(memo, num){ return memo + cosine_distance(substitute, num) }, 0);
   
  return (cosine_distance(substitute, target) * context.length + sum)/(2*context.length )
}
Example #17
0
 _.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);
app.del('/api/movies/:id', function (req, res) {
   console.log('DELETE: ' + req.params.id);
   var movie = _.find(movieList.movies, function(movie) {return movie.id == req.params.id;});
   if(movie){
       movieList.movies = _.filter(movieList.movies, function(movie) {return movie.id != req.params.id});
       saveMovies();
       return res.json({"result" : "removed"}, 200);
   }
});
Example #19
0
var errsBelowPath = function (errs, path) {
    return _.filter(errs, function (e) {
        for (var i = 0, len = path.length; i < len; ++i) {
            if (!e.field || path[i] !== e.field[i]) {
                return false;
            }
        }
        return true;
    });
};
Example #20
0
 socket.on('ship.destruct', function(message, fn) {
   socket.broadcast.emit('openspace.destruct.ship', {msg: 'Ship destruction detected', type: 'self', ship: ship.getState()});
   ships = _.filter(ships, function(s) { return s.id != ship.id});
   ship = null;
   session.shipId = null;
   session.save();
   if (_.isFunction(fn)) {
     fn({status: 'success', msg: 'Your ship has self-destructed'});
   }
 });
Example #21
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 #22
0
exports.getTestModuleNames = function () {
    var ids = _.keys(kanso.moduleCache);
    var test_ids = _.filter(ids, function (id) {
        return (/^tests\//).test(id);
    });
    var test_names = _.map(test_ids, function (id) {
        return id.replace(/^tests\//, '');
    });
    return test_names.sort();
};
Example #23
0
    httpClient.getReq(function(err,res){
        if( err || res.error != 0 ){
            console.error(__dirname,err,res);
            response.redirect('/errorPage');
        } else {
            var data = res.data;
            var unuse = _.filter(data,function(c){
                return c.status == 0 && c.expiryDate>Date.now();
            });
            var used = _.filter(data, function(c){
                return c.status == 1;
            });
            var expired = _.filter(data,function(c){
                return c.status == 0 && c.expiryDate<Date.now();
            });
            response.render('web/myCoupons',{'unuse':unuse,'used':used,'expired':expired});
        }

    });
        it("Split into sentences, get word count", function() {

                var inputText = "This is not sentence 2. \"This is 'sentence 2.'\"";
                var fragments = theOneLibSynphony.stringToSentences(inputText);
                var sentences = _.filter(fragments, function(frag) {
                        return frag.isSentence;
                });
                expect(sentences[0].wordCount()).toBe(5);
                expect(sentences[1].wordCount()).toBe(4);
        });
Example #25
0
		function(err, $) {
		    if(err)
			callback(err);
		    else {
			var r = {};
			r.name = $('h1.moviename-big:first').text().trim();
			r.original_name = $('span[itemprop=alternativeHeadline]').text().trim();
			
			var info = {};
			$('table.info tr').each(function () {
			    var key = $(this).find('td:first').text();
			    var value = $(this).find('td:last').text();
			    info[key] = value;
			});
			
			r.actors = _.filter($('td.actor_list span[itemprop=actors] a').map(function () { return $(this).text() }).toArray(), 
					    function(a) { return a != '...' }).join(', ');
			r.year = info['год'].replace(/[^0-9]+/g,'');
			r.genre = info['жанр'].replace(/, .+$/, '').replace(/\s+/g,'');
			
			r.description = $('div.brand_words:first').text().trim();

			var imgsrc = '' + $('img[itemprop=image]').attr('src');
			var bigsrc = null;
			var m;
			if((m = imgsrc.match(/([0-9]+\.jpg)/ig))) {
			    bigsrc = 'http://st.kinopoisk.ru/images/film_big/' + m[0];
			} else {
			    imgsrc = null;
			}
			

			if(bigsrc || imgsrc) {
			    kinopoisk_load_poster((bigsrc || imgsrc), function(err, image) {
				if(err && imgsrc) {
				    kinopoisk_load_poster(imgsrc, function(err, image) {
					if(!err && image) {
					    r.poster = image;
					    r.poster_format = 'jpeg';
					}
					callback(null, r);
				    });
				} else {
				    if(!err && image) {
					r.poster = image;
					r.poster_format = 'jpeg';
				    } 
				    callback(null, r);
				}
			    });
			} else {
			    callback(null, r);
			}
		    }
		});
        .success( function  ( data ) {
          pendingTasks = __.filter( data.data, function  ( task ) {
              var assigned =__.find( task.assigned, function  ( assigned ) {
                return assigned === Auth.user.username;
              });
            return task.status === 'Por hacer' && assigned === Auth.user.username;
          });

          scope.numberOfPendings = pendingTasks.length;

          revisionTasks = __.filter( data.data, function  ( task ) {
              var assigned =__.find( task.creator, function  ( creator ) {
                return creator === Auth.user.username;
              });
            return task.status === 'Por revisar' && assigned === Auth.user.username;
          });

          scope.numberOfRevisions = revisionTasks.length;

        })
Example #27
0
EmbeddedList.prototype.validate = function (doc, value, raw) {
    var type = this.type;

    // don't validate empty fields, but check if required
    if (this.isEmpty(value, raw)) {
        if (this.required) {
            return [ new Error('Required field') ];
        }
        return [];
    }

    // check all values are objects
    var non_objects = _.filter(value, function (v) {

        /* Workaround for interpreter bug:
            Saving embedList() data throws an error when running in a
            CouchDB linked against js-1.8.0. We encounter a situation where
            typeof(v) === 'object', but the 'v instanceof Object' test
            incorrectly returns false. We suspect an interpreter bug.
            Please revisit this using a CouchDB linked against js-1.8.5.
            We don't currently have the infrastructure for a test case. */
        
        /* Before: return !(v instanceof Object) || _.isArray(v); */
        return (typeof(v) !== 'object' || _.isArray(v));
    });
    if (non_objects.length) {
        return _.map(non_objects, function (v) {
            return new Error(v + ' is not an object');
        });
    }

    // check for missing ids
    var missing = this.missingIDs(value);
    if (missing.length) {
        return missing;
    }

    // check for duplicate ids
    var duplicates = this.duplicateIDs(value);
    if (duplicates.length) {
        return duplicates;
    }

    // run type validation against each embedded document
    return _.reduce(value, function (errs, v, i) {
        var r = raw ? raw[i]: undefined;
        return errs.concat(
            _.map(type.validate(v, r), function (err) {
                err.field = [i].concat(err.field || []);
                return err;
            })
        );
    }, []);
};
Example #28
0
		_.each(numbers, function(number){

			var messages = _.filter(messageObjs, function(messageObj){
				return messageObj.to == number || messageObj.from == number;
			});

			corpus.push({
				number: number,
				messages: messages
			});
		});
Example #29
0
	_.each(gro, function(value, key, list){ 

		value = _.filter(value, function(num){ return num['input']['CORENLP']['sentences'].length >= minsize })
		value = _.map(value, function(num){ num["input"]["CORENLP"]["sentences"].splice(10) 
											return num });

		if (value.length < sizetrain)
			delete gro[key]
		else
			gro[key] = _.sample(value, sizetrain)
	}, this)