Example #1
0
    createScales(fnCreateScale) {

        var config = this.config;

        this.xScale = fnCreateScale('pos', config.x, [0, config.options.width]);
        this.yScale = fnCreateScale('pos', config.y, [config.options.height, 0]);
        this.color = fnCreateScale('color', config.color, {});

        var g = config.guide;
        var isNotZero = (x => x !== 0);
        const halfPart = 0.5;
        var minFontSize = halfPart * _.min([g.x, g.y].map(n => n.tickFontHeight).filter(isNotZero));
        var minTickStep = halfPart * _.min([g.x, g.y].map(n => n.density).filter(isNotZero));
        var notLessThan = ((lim, val) => Math.max(val, lim));

        var sizeGuide = {
            min: g.size.min || (2),
            max: g.size.max || notLessThan(2, minTickStep),
            mid: g.size.mid || notLessThan(1, Math.min(minTickStep, minFontSize))
        };

        this.size = fnCreateScale('size', config.size, sizeGuide);

        return this
            .regScale('x', this.xScale)
            .regScale('y', this.yScale)
            .regScale('size', this.size)
            .regScale('color', this.color);
    }
Example #2
0
module.exports.coarse_reduce = function(keys, values, rereduce) {
  var sum = function(arr, key) {
    return _.reduce(_.pluck(arr, key), function(s, a) {return s+a;});
  };
  var count = 0;
  var lat = 0;
  var lon = 0;
  _.each(values, function(v) {
    count += v.count;
    lat += v.lat*v.count;
    lon += v.lon*v.count;
  });
  if (count>0) {
    lat /= count;
    lon /= count;
  }
  return {
    count: count,
    lat: lat,
    lon: lon,
    bbox_west: _.min(_.pluck(values, 'bbox_west')),
    bbox_east: _.max(_.pluck(values, 'bbox_east')),
    bbox_south: _.min(_.pluck(values, 'bbox_south')),
    bbox_north: _.max(_.pluck(values, 'bbox_north')),
  };
};
Example #3
0
        fixedPath: function(points, center, createPath) {
            points = _.map(points, scalePoint);
            center = center ? scalePoint(center) : null;
            createPath = createPath || svgPath;

            const pathLeft = _.min(_.pluck(points, 0));
            const pathRight = _.max(_.pluck(points, 0));
            const pathTop = _.min(_.pluck(points, 1));
            const pathBottom = _.max(_.pluck(points, 1));

            // Apply padding to line
            const padding = [4, 4];

            // Calculate and apply additional offset
            const extraOffset = [pathLeft, pathTop];

            // Apply padding and offset to points
            points = _.map(points, function(point) {
                return kvector.add(
                    kvector.subtract(
                        point,
                        extraOffset
                    ),
                    kvector.scale(padding, 0.5)
                );
            });

            // Calculate <div> dimensions
            const width = (pathRight - pathLeft) + padding[0];
            const height = (pathBottom - pathTop) + padding[1];
            const left = extraOffset[0] - padding[0] / 2;
            const top = extraOffset[1] - padding[1] / 2;

            // Create <div>
            const wrapper = document.createElement("div");
            $(wrapper).css({
                position: "absolute",
                width: width + "px",
                height: height + "px",
                left: left + "px",
                top: top + "px",
                // If user specified a center, set it
                transformOrigin: center ? (width / 2 + center[0]) + "px " +
                    (height / 2 + center[1]) + "px"
                    : null,
            });

            // Create Raphael canvas
            const localRaphael = Raphael(wrapper, width, height);

            // Calculate path
            const visibleShape = localRaphael.path(createPath(points));

            return {
                wrapper: wrapper,
                visibleShape: visibleShape,
            };
        },
Example #4
0
exports.print = function(verbose) {
  if (events.length === 0) {
    return "No Upcoming events.";
  }
  var now = new Date();
  var string = "";
  if (verbose) {
    string += "Upcoming events:\n";
    events.forEach(function(event) {
      var start = moment(event.start);
      if (event.start && event.start < now) {
        string += "NOW | " + event.description + " | " + event.url + "\n";
      } else {
        string += start.format("YYYY-MM-DD HH:mm") + " | " + event.description + " | " + event.url + "\n";
      }
    });
  } else {
    var event = _.min(events, function(i) {
      return i.start;
    });
    var start = moment(event.start);
    if (event.start && event.start < now) {
      string += "NOW | " + event.description + " | " + event.url;
    } else {
      string += start.format("YYYY-MM-DD HH:mm") + " | " + event.description + " | " + event.url;
    }
  }
  return string;
};
    getMax() {
        if(this.maxValues.length === 0) {
            return this.defaultMax;
        }

        return _.min(this.maxValues);
    }
    getMinimumCharCost() {
        let opponents = this.game.getOpponents(this.controller);
        let opponentCharacters = _.flatten(opponents.map(opponent => opponent.filterCardsInPlay(card => card.getType() === 'character')));
        let charCosts = _.map(opponentCharacters, card => card.getCost());

        return _.min(charCosts);
    }
Example #7
0
 this.metrics.getOpenWorldCount(function (open_world_count) {
   // choose the least populated world among open worlds
   world = _.min(_.first(this.worlds, open_world_count), function (w) {
     return w.playerCount;
   });
   world.connected(new Player(connection, world));
 }.bind(this));
var done = function() {
	console.log('Min: ' + _.min(times) + 'ms');
	console.log('Mean: ' + (_.reduce(times, function(memo, num) {
		return memo + num;
	}, 0) / times.length) + 'ms');
	console.log('Max: ' + _.max(times) + 'ms');
};
Example #9
0
module.exports = function alignGroup(result, rootIdea) {
	'use strict';
	const nodes = result.nodes,
		childIds = _.values(rootIdea.ideas).map(function (idea) {
			return idea.id;
		}),
		childNodes = childIds.map(function (id) {
			return nodes[id];
		}).filter(function (node) {
			return node;
		}),
		leftBorders = _.map(childNodes, function (node) {
			return node.x;
		}),
		rightBorders = _.map(childNodes, function (node) {
			return node.x + node.width;
		}),
		minLeft = _.min(leftBorders),
		maxRight = _.max(rightBorders),
		rootNode = nodes[rootIdea.id],
		sameLevelNodes = _.values(nodes).filter(function (node) {
			return node.level === rootNode.level && node.id !== rootNode.id;
		});

	if (childNodes.length) {
		rootNode.x = minLeft;
		rootNode.width = maxRight - rootNode.x;
	}
	sameLevelNodes.forEach(function (node) {
		node.verticalOffset = (node.verticalOffset || 0) + rootNode.height;
	});
};
RecipeFinder.prototype.find = function() {
    var $t = this;

    var possible = _.filter($t.recipeCollection.getRecipes(), function(recipe) {
        return _.every(recipe.getIngredients(), function(ingredient) {
            return $t.fridge.check(ingredient.name, ingredient.amount, ingredient.unit);
        });
    });

    if(possible.length === 0) {
        return 'Order Takeout';
    }

    var chosen = _.min(possible, function(recipe) {
        var inFridge = _.filter($t.fridge.getAll(), function(ingredient) {
            return recipe.getIngredient(ingredient.name);
        });

        return _.min(inFridge, function(ingredient) {
            return ingredient.useBy.format('YYYYMMDD');
        }).useBy.format('YYYYMMDD');
    });

    return chosen.name;
};
Example #11
0
fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function(line) { 
  lineIndex++;
  if (lineIndex == 1) {
    return;
  }

  var letters = {};

  for (i=0; i<line.length; i++) {
    var c = line.charAt(i).toLowerCase();
    letters[c] = isNaN(letters[c]) ? 1 : letters[c] + 1;
  }

  console.log ("Case #"+(lineIndex - 1)+": " +
  _.min([
    letters['h'] || 0, 
    letters['a'] || 0, 
    Math.floor((letters['c'] || 0) / 2), 
    letters['k'] || 0,
    letters['e'] || 0,
    letters['r'] || 0,
    letters['u'] || 0,
    letters['p'] || 0
    ])
  );
})
Example #12
0
 load_default_value:function(){
     this.current_preview = null;
     var preview_files = _.filter(this.model.get("files"), function(f){ return f.preset.display; });
     if(preview_files.length){
         this.current_preview = _.min(preview_files, function(file){return file.preset.order});
     }
 },
Example #13
0
exports.boundingBox = function(polygon, crop) {
  var xList = _.chain(polygon).pluck(0).filter(_.isNumber).value()
    , yList = _.chain(polygon).pluck(1).filter(_.isNumber).value()

  if (crop === true) {
    return [
      [Math.max(_.min(xList), 0), Math.max(_.min(yList), 0)],
      [Math.min(_.max(xList), context.width), Math.min(_.max(yList), context.height)]
    ]
  } else {
    return [
      [_.min(xList), _.min(yList)],
      [_.max(xList), _.max(yList)]
    ]
  }
}
Example #14
0
 CriticalObjectSim.prototype.checkUps = function () {
     var updateChart = false;
     var eventTimes = [];
     for (var i = 0; i < this.criticalObjects.length; i++) {
         var co = this.criticalObjects[i];
         if (!co.properties.hasOwnProperty('willFailAt'))
             continue;
         if (co.properties['willFailAt'] > this.simTime.getTime()) {
             eventTimes.push(co.properties['willFailAt']);
             continue;
         }
         else {
             delete co.properties['willFailAt'];
             this.setFeatureState(co, SimSvc.InfrastructureState.Failed, SimSvc.FailureMode.NoBackupPower, null, true);
             updateChart = true;
         }
     }
     if (eventTimes.length > 0) {
         this.nextEvent = _.min(eventTimes);
     }
     else {
         this.nextEvent = null;
     }
     if (updateChart)
         this.sendChartValues();
 };
Example #15
0
dataprocessor.prototype.updateCandleStick = function (candleStick, tick) {

    if(!candleStick.open) {

      candleStick.open = tick.price;
      candleStick.high = tick.price;
      candleStick.low = tick.price;
      candleStick.close = tick.price;
      candleStick.volume = tick.amount;
      candleStick.vwap = tick.price;

    } else {

        var currentVwap = BigNumber(candleStick.vwap).times(BigNumber(candleStick.volume));
        var newVwap = BigNumber(tick.price).times(BigNumber(tick.amount));

        candleStick.high = _.max([candleStick.high, tick.price]);
        candleStick.low = _.min([candleStick.low, tick.price]);

        candleStick.volume = Number(BigNumber(candleStick.volume).plus(BigNumber(tick.amount)).round(8));
        candleStick.vwap = Number(currentVwap.plus(newVwap).dividedBy(BigNumber(candleStick.volume)).round(2));

    }

    candleStick.close = tick.price;

    return candleStick;

};
function archiveOldestLogFile() {
	var files = fs.readdirSync(logDirectory);

	if(files.length <= 1) {
		return;
	}

	var oldestLogFile = _.min(files, function (f) {
		var fullpath = path.join(logDirectory, f);
		//function will ignore directories
		if(fs.lstatSync(fullpath).isDirectory()) {
			return;
		}
		return fs.statSync(fullpath).ctime;
	});

	// log-archive + a weeks worth of log files
	if(files.length > 8) {

		var inp = fs.createReadStream(path.join(logDirectory, oldestLogFile));
		var out = fs.createWriteStream(path.join(archiveDirectory, oldestLogFile) + '.gz');
		inp.pipe(gzip).pipe(out);

		fs.unlinkSync(path.join(logDirectory,oldestLogFile));
	} else {
		return;
	}
}
Example #17
0
	], safe.sure(cb,function () {
		if (debug) { console.log("Before stats"); console.log(trn);	}
		_(trn.splits).forEach(function (split) {
			accIds[split.accountId] = split.accountId;
		});
		self._calcStatsPartial(_.values(accIds), _.min([trn.datePosted, oldTrn.datePosted]), function () {cb(null, trn);});
	}));
    getMinimumDiscardGoldAmount() {
        let characters = this.game.filterCardsInPlay(card => card.getType() === 'character');
        let characterPrintedStrengths = _.map(characters, card => card.getPrintedStrength());
        let lowestStrength = _.min(characterPrintedStrengths);

        return _.max([lowestStrength, 1]);
    }
Example #19
0
/**
returns {
	[part group]: {
		counting_rounds: [...],
		normalized_points: [...]
	}
	[...]
}
*/
function calculateMainTeamResults(config, norm_team_results){
	var main_team_results = {};
	_.each(config.main_teams, function(member_teams, main_team){
		var rounds = 0;
		var point_sum = 0;
		_.each(member_teams, function(member_team){
			rounds += member_team.counting_rounds;
			point_sum += member_team.normalized_points;
		});
		main_team_results[main_team] = {
			"counting_rounds": rounds,
			"normalized_points": point_sum / rounds 
		};
		
	});
	if (config.ranking.normalize_overall_points){
		var point_arr = _.map(main_team_results, function(main_team_result, main_team){
			return main_team_result.normalized_points;
		})
		var min_sum = _.min(point_arr);
		var max_sum = _.max(point_arr);
		_.each(main_team_results, function(main_team_result, main_team){
			main_team_results[main_team].normalized_points = calculateNormalizedResult(config,
										min_sum, max_sum, main_team_result.normalized_points);										
		});
	}
	return main_team_results;
}
Example #20
0
/**
 * helper function, given page number and total articles, calculate start the end article number
 * @param {number} page
 * @param {number} total
 * @return {{start: number, end: number}}
 */
function pageToInterval(page, total) {
  var PER_PAGE = 10;
  if ((page-1) * PER_PAGE >= total)
    return null;
  else
    return {start: (page-1) * PER_PAGE, end: _.min([total, page * PER_PAGE])};
}
Example #21
0
MDPActuator.prototype.scaleState = function(state) {
  var min = _.min(state);		
  var max = _.max(state);
  return _(state).map(function(s) {
    return (s - min) / (max - min);
  });
}
Example #22
0
  request.get({uri:arg.uri, json:true}, function(err, res, body) {
    if (err || !res) return cbDone(err);
    if (res.statusCode !== 200) return cbDone("status code " + res.statusCode);
    if (!body || !body.meta) {
      return cbDone("invalid response: " + JSON.stringify(body));
    }
    if (body.meta.code !== 200) return cbDone(JSON.stringify(body.meta));

    if (!max) max = 0;
    var timestamps = _.pluck(body.data, 'created_time');
    var maxTimestamp = _.max(timestamps);
    max = _.max([max, maxTimestamp]);

    // we can stop if the latest item previously seen is on this page
    // this is needed to handle /users/self/feed (see feed.js)
    var since = arg.min_timestamp;
    if (since && since <= maxTimestamp && since > _.min(timestamps)) {
      body.pagination = false;
    }

    var ret = {
      posts: body.data
    };
    if (body.pagination && body.pagination.next_url &&
        body.pagination.next_url !== arg.uri) {
      ret.nextUrl = body.pagination.next_url;
      ret.nextRun = -1;
      ret.pagingSince = max;
    } else {
      ret.since = max;
    }
    cbDone(null, ret);
  });
Example #23
0
        async.map(cities, this.today.bind(this), function(err, citiesToday) {
            if (err) {
                cb(err);
                return;
            }

            report = {};

            report.numCities = citiesToday.length;

            var hottestCity = _.max(citiesToday, function(city) {
                return city.temp;
            });
            var coldestCity = _.min(citiesToday, function(city) {
                return city.temp;
            });
            var windiestCity = _.max(citiesToday, function(city) {
                return city.wind.speed;
            });

            report.hottest = _.pick(hottestCity, 'city', 'weather', 'temp');
            report.coldest = _.pick(coldestCity, 'city', 'weather', 'temp');
            report.windiest = {
                city: windiestCity.city,
                weather: windiestCity.weather,
                windSpeed: windiestCity.wind.speed
            };

            cb(null, report);
        });
Example #24
0
/**
returns {
	[team]: {
		counting_rounds: [...],
		normalized_points: [...]
	}
	[...]
}
*/
function calculateNormTeamResults(config, normalized_results){
	var non_part_zero = config.ranking.non_participation_gives_zero_points;
	var norm_ov_points = config.ranking.normalize_overall_points;
	var team_results = {};
	_.each(config.teams, function(team){
		team_results[team] = {
			"counting_rounds": 0,
			"normalized_points": 0
		};
	});
	_.each(normalized_results, function(station_map, station_name){
		_.each(config.teams, function(team){
			if (station_map[team] !== undefined){
				team_results[team].counting_rounds++;
				team_results[team].normalized_points
			} else if(non_part_zero){
				team_results[team].counting_rounds++;
			}
		});
	});
	if (norm_ov_points){
		var point_arr = _.map(team_results, function(team_result, team){
			return team_result.normalized_points;
		})
		var min_sum = _.min(point_arr);
		var max_sum = _.max(point_arr);
		_.each(team_results, function(team_result, team){
			team_results[team].normalized_points = calculateNormalizedResult(config,
										min_sum, max_sum, team_result.normalized_points);										
		});
	}
	return team_results;
}
Example #25
0
function stateMap($elm, data, width, height, min, max, addLegend, addTooltips) {
  var svg = d3.select($elm[0])
    .append('svg')
      .attr('width', width)
      .attr('height', height);
  var projection = d3.geo.albersUsa()
    .scale(450)
    .translate([220, 150]);
  var path = d3.geo.path().projection(projection);

  var results = _.reduce(
    data.results,
    function(acc, val) {
      var row = fips.fipsByState[val.state] || {};
      var code = row.STATE ? parseInt(row.STATE) : null;
      acc[code] = val.total;
      return acc;
    },
    {}
  );
  var quantiles = 4;
  var totals = _.chain(data.results)
    .pluck('total')
    .filter(function(value) {
      return !!value;
    })
    .value();
  min = min || _.min(totals);
  max = max || _.max(totals);
  var scale = chroma.scale(colorScale).domain([min, max]);
  var quantize = d3.scale.linear().domain([min, max]);
  svg.append('g')
    .selectAll('path')
      .data(stateFeatures)
    .enter().append('path')
      .attr('fill', function(d) {
        return results[d.id] ? scale(results[d.id]) : colorZero;
      })
      .attr('data-state', function(d) {
        return fips.fipsByCode[d.id].STATE_NAME;
      })
      .attr('class', 'shape')
      .attr('d', path)
    .on('mouseover', function(d) {
      if (results[d.id]) {
        this.parentNode.appendChild(this);
        this.classList.add('state--hover');
      }
    });

  if (addLegend || typeof addLegend === 'undefined') {
    var legendSVG = d3.select('.legend-container svg');
    stateLegend(legendSVG, scale, quantize, quantiles);
  }

  if (addTooltips) {
    stateTooltips(svg, path, results);
  }
}
Example #26
0
 out = _.map(_.groupBy(parser.parser(atom).documentelement.min, function(item){ return Math.ceil(item.time / interval); }), function(item) {
   return( {"row": Math.ceil(item[0].time / interval),
     "time":  _.max(item, function(item){ return item.time; }).time,
     "high":  _.max(item, function(item){ return item.price; }).price,
     "low":  _.min(item, function(item){ return item.price; }).price,
     "volume" :  _.reduceRight(item, function(memo, arr){ return memo + arr.shares; }, 0)
   });
 });
Example #27
0
 return fragments.then(function (fragments) {
   var totalCounts = fragments.map(function (f) { return f.matchCount || f.triples.length; }),
       minCount = _.min(totalCounts), maxCount = _.max(totalCounts),
       bestFragments = fragments.filter(function (f, i) { return totalCounts[i] === minCount; });
   bestFragments.minCount = minCount;
   bestFragments.maxCount = maxCount;
   return bestFragments;
 });
Example #28
0
function getFavorites(checkins, ratings) {

    var loves = [];
    var highest = _.max(_.pluck(checkins, 'rating_score'));
    var highCount = 0;
    for (var i = highest; i >= 4; i = i - 0.5) {
        var beerList = getBeerListByRating(i, loves, checkins, ratings);
        loves.push({ title: i, list: beerList });
        highCount = highCount + beerList.length;
        if (highCount >= 10) {
            break;
        }
    }
    var hates = [];
    var lowest = _.min(_.pluck(checkins, 'rating_score'));
    var lowestBound = Math.max(lowest, 2);
    var lowCount = 0;
    for (var i = lowest; i <= lowestBound; i = i + 0.5) {
        var beerList = getBeerListByRating(i, hates, checkins, ratings);
        if (beerList.length > 0) {
            hates.push({ title: i, list: beerList });
        }
        lowCount = lowCount + beerList.length;
        if (lowCount >= 10) {
            break;
        }
    }

    //beers drank most
    var mostCount = _.max(_.countBy(_.pluck(checkins, 'beer'), function (d) {
            return d.bid;
        }));
    var mostList = _.map(_.filter(_.map(_.groupBy(checkins, function (d) {
            return d.beer.bid;
        }), function (d) {
            return [d.length, d];
        }), function (arr) {
            return arr[0] === mostCount;
        }), function (d) {
            var b = d[1][0];
                var categories = getCategoriesVals(b, ratings);
            return {
                bid: b.beer.bid,
                abv: b.beer.beer_abv,
                count: mostCount,
                label: b.beer.beer_label,
                name: b.beer.beer_name,
                categories: categories,
                score: getScoreAvg(d[1])
            };
        });

    return  {
        loves: loves,
        hates: hates,
        mosts: [{ title: mostCount, list: mostList }]
    };
}
    var chosen = _.min(possible, function(recipe) {
        var inFridge = _.filter($t.fridge.getAll(), function(ingredient) {
            return recipe.getIngredient(ingredient.name);
        });

        return _.min(inFridge, function(ingredient) {
            return ingredient.useBy.format('YYYYMMDD');
        }).useBy.format('YYYYMMDD');
    });
Example #30
0
 (hash) => {
   // eslint-disable-next-line eqeqeq
   const exists = find($scope.query.visualizations, item => item.id == hash);
   let visualization = min($scope.query.visualizations, viz => viz.id);
   if (!isObject(visualization)) {
     visualization = {};
   }
   $scope.selectedTab = (exists ? hash : visualization.id) || 'table';
 },