/*
Calculates the frequency of the metric (the number of data
points in one season of the metric)
514033
private int calculateFrequency(long seasonLength) {
        long startTime = timestamps[0];
        //Prevents frequency from being 0
        if (timestamps[1] - timestamps[0] > seasonLength) {
            throw new RuntimeException("Provided length of season is too small. No data points exist " +
                    "within the first season of the metric.");
        }

        int numDatapointsInSeason = 0;
        for (long timestamp : timestamps) {
            if ((timestamp - startTime) < seasonLength) {
                numDatapointsInSeason++;
            } else {
                break;
            }
        }

        return numDatapointsInSeason;
    }
686727
function(composite) {
    var url_prefix  = "https://metrics-api.librato.com/v1/metrics";

    function make_url(sdate, edate, step) {
      var params    = "compose="     + composite +
                      "&start_time=" + sdate     +
                      "&end_time="   + edate     +
                      "&resolution=" + find_librato_resolution(sdate, edate, step);
      return url_prefix + "?" + params;
    }

    /*
     * We are most likely not going to get the same number of measurements
     * cubism expects for a particular context: We have to perform down/up
     * sampling
     */
    function down_up_sampling(isdate, iedate, step, librato_mm) {
      var av = [];

      for (i=isdate; i<=iedate; i+=step) {
        var int_mes = [];
        while (librato_mm.length && librato_mm[0].measure_time <= i) {
          int_mes.push(librato_mm.shift().value);
        }

        var v;
        if (int_mes.length) { /* Compute the average */
          v = int_mes.reduce(function(a, b) { return a + b }) / int_mes.length;
        } else { /* No librato values on interval */
          v = (av.length) ? av[av.length-1] : 0;
        }
        av.push(v);
      }

      return av;
    }

    request = {};

    request.fire = function(isdate, iedate, step, callback_done) {
      var a_values = []; /* Store partial values from librato */

      /*
       * Librato has a limit in the number of measurements we get back in a request (100).
       * We recursively perform requests to the API to ensure we have all the data points
       * for the interval we are working on.
       */
      function actual_request(full_url) {
        d3.json(full_url)
          .header("X-Requested-With", "XMLHttpRequest")
          .header("Authorization", auth_string)
          .header("Librato-User-Agent", 'cubism/' + cubism.version)
          .get(function (error, data) { /* Callback; data available */
            if (!error) {
              if (data.measurements.length === 0) {
                return
              }
              data.measurements[0].series.forEach(function(o) { a_values.push(o); });

              var still_more_values = 'query' in data && 'next_time' in data.query;
              if (still_more_values) {
                actual_request(make_url(data.query.next_time, iedate, step));
              } else {
                var a_adjusted = down_up_sampling(isdate, iedate, step, a_values);
                callback_done(a_adjusted);
              }
            }
          });
      }

      actual_request(make_url(isdate, iedate, step));
    };

    return request;
  }
590275
function(points, callback, fromIndex, toIndex) {
	var i, len, index, currentDistance, currentSpeed, fastestSpeed = 0, slowestSpeed = 100000000;
	var result;
	len = points.length - 1;
	i = 0;
	if(fromIndex && fromIndex > 0 && fromIndex < len) {
		i = fromIndex;
	}
	if(toIndex && toIndex < len) {
		len = toIndex;
	}
	if(points.length < 2 || len - i < 2) {
		return callback(new Error('Result can not be calculated properly with data points less than 2'), null);
	}

	try {
		result = new TrackingResult();
		index = 0;
		result.points[index] = Trackpoint.copy(points[i]);
		result.points[index].distance = 0;
		for(; i < len; i++, index++) {
			result.points[index + 1] = Trackpoint.copy(points[i + 1]);
			currentDistance = distance.getDistance(result.points[index].lng, result.points[index].lat, result.points[index + 1].lng, result.points[index + 1].lat);
			currentSpeed = speed.calculateSpeed(currentDistance, result.points[index].time, result.points[index + 1].time);
			result.totalDistance += currentDistance;
			result.points[index + 1].distance = result.points[index].distance + currentDistance;
			result.points[index + 1].speed = currentSpeed;
			if(currentSpeed > fastestSpeed) {
				fastestSpeed = currentSpeed;
			}
			if(currentSpeed < slowestSpeed) {
				slowestSpeed = currentSpeed;
			}
		}
		result.points[0].speed = result.points[1].speed;
		result.averageSpeed = speed.calculateSpeed(result.totalDistance, result.points[0].time, result.points[index].time);
		result.fastestSpeed = fastestSpeed;
		result.slowestSpeed = slowestSpeed;
		result.totalTime = time.getDiffInSecs(result.points[0].time, result.points[index].time);
		callback(null, result);
	} catch(e) {
		callback(e, null);
	}
}
227432
function calculate() {
      var move = this.move,
          length = this.length;
      var steps = move.steps,
          direction = move.direction;


      var countableSteps = isNumber(toInt(steps)) && toInt(steps) !== 0;

      switch (direction) {
        case '>':
          if (steps === '>') {
            Glide.index = length;
          } else if (this.isEnd()) {
            if (!(Glide.isType('slider') && !Glide.settings.rewind)) {
              this._o = true;

              Glide.index = 0;
            }
          } else if (countableSteps) {
            Glide.index += Math.min(length - Glide.index, -toInt(steps));
          } else {
            Glide.index++;
          }
          break;

        case '<':
          if (steps === '<') {
            Glide.index = 0;
          } else if (this.isStart()) {
            if (!(Glide.isType('slider') && !Glide.settings.rewind)) {
              this._o = true;

              Glide.index = length;
            }
          } else if (countableSteps) {
            Glide.index -= Math.min(Glide.index, toInt(steps));
          } else {
            Glide.index--;
          }
          break;

        case '=':
          Glide.index = steps;
          break;

        default:
          warn('Invalid direction pattern [' + direction + steps + '] has been used');
          break;
      }
    }
968393
function ( divisions ) {

			if ( ! divisions ) divisions = 5;

			var points = [];

			for ( var d = 0; d <= divisions; d ++ ) {

				points.push( this.getPointAt( d / divisions ) );

			}

			return points;

		}
286312
private static Map<Long, Double> fillCalculateMetricTransform(Metric metric, String calculationType) {
        // Calculate min, max, avg, dev, or a percentile value
        Double result = calculateResult(metric, calculationType);

        // return a new time series with the constant values for each time stamp
        Map<Long, Double> resultMap = new TreeMap<>();

        for (Map.Entry<Long, Double> entry : metric.getDatapoints().entrySet()) {
            Long timestamp = entry.getKey();

            resultMap.put(timestamp, result);
        }
        return resultMap;
    }
628914
private Metric collectCounter(String dropwizardName, Counter counter) {
    String metricName = DropWizardUtils.generateFullMetricName(dropwizardName, "counter");
    String metricDescription =
        DropWizardUtils.generateFullMetricDescription(dropwizardName, counter);

    MetricDescriptor metricDescriptor =
        MetricDescriptor.create(
            metricName,
            metricDescription,
            DEFAULT_UNIT,
            Type.GAUGE_INT64,
            Collections.<LabelKey>emptyList());
    TimeSeries timeSeries =
        TimeSeries.createWithOnePoint(
            Collections.<LabelValue>emptyList(),
            Point.create(Value.longValue(counter.getCount()), clock.now()),
            null);
    return Metric.createWithOneTimeSeries(metricDescriptor, timeSeries);
  }
1217913
function countNgrams(ngram) {
  nrOfNgrams++;
  var key = arrayToKey(ngram);
  if (!frequencies[key]) {
    frequencies[key] = 0;
  }
  frequencies[key]++;
}
809075
function () {
		var series = this,
			chart = series.chart,
			options = series.options,
			stacking = options.stacking,
			borderWidth = options.borderWidth,
			columnCount = 0,
			reversedXAxis = series.xAxis.reversed,
			categories = series.xAxis.categories,
			stackGroups = {},
			stackKey,
			columnIndex;

		Series.prototype.translate.apply(series);

		// Get the total number of column type series.
		// This is called on every series. Consider moving this logic to a
		// chart.orderStacks() function and call it on init, addSeries and removeSeries
		each(chart.series, function (otherSeries) {
			if (otherSeries.type === series.type && otherSeries.visible) {
				if (otherSeries.options.stacking) {
					stackKey = otherSeries.stackKey;
					if (stackGroups[stackKey] === UNDEFINED) {
						stackGroups[stackKey] = columnCount++;
					}
					columnIndex = stackGroups[stackKey];
				} else {
					columnIndex = columnCount++;
				}
				otherSeries.columnIndex = columnIndex;
			}
		});

		// calculate the width and position of each column based on
		// the number of column series in the plot, the groupPadding
		// and the pointPadding options
		var data = series.data,
			closestPoints = series.closestPoints,
			categoryWidth = mathAbs(
				data[1] ? data[closestPoints].plotX - data[closestPoints - 1].plotX :
				chart.plotSizeX / ((categories && categories.length) || 1)
			),
			groupPadding = categoryWidth * options.groupPadding,
			groupWidth = categoryWidth - 2 * groupPadding,
			pointOffsetWidth = groupWidth / columnCount,
			optionPointWidth = options.pointWidth,
			pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 :
				pointOffsetWidth * options.pointPadding,
			pointWidth = mathMax(pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), 1),
			colIndex = (reversedXAxis ? columnCount -
				series.columnIndex : series.columnIndex) || 0,
			pointXOffset = pointPadding + (groupPadding + colIndex *
				pointOffsetWidth - (categoryWidth / 2)) *
				(reversedXAxis ? -1 : 1),
			threshold = options.threshold || 0,
			translatedThreshold = series.yAxis.getThreshold(threshold),
			minPointLength = pick(options.minPointLength, 5);

		// record the new values
		each(data, function (point) {
			var plotY = point.plotY,
				yBottom = point.yBottom || translatedThreshold,
				barX = point.plotX + pointXOffset,
				barY = mathCeil(mathMin(plotY, yBottom)),
				barH = mathCeil(mathMax(plotY, yBottom) - barY),
				stack = series.yAxis.stacks[(point.y < 0 ? '-' : '') + series.stackKey],
				trackerY,
				shapeArgs;

			// Record the offset'ed position and width of the bar to be able to align the stacking total correctly
			if (stacking && series.visible && stack && stack[point.x]) {
				stack[point.x].setOffset(pointXOffset, pointWidth);
			}

			// handle options.minPointLength and tracker for small points
			if (mathAbs(barH) < minPointLength) {
				if (minPointLength) {
					barH = minPointLength;
					barY =
						mathAbs(barY - translatedThreshold) > minPointLength ? // stacked
							yBottom - minPointLength : // keep position
							translatedThreshold - (plotY <= translatedThreshold ? minPointLength : 0);
				}
				trackerY = barY - 3;
			}

			extend(point, {
				barX: barX,
				barY: barY,
				barW: pointWidth,
				barH: barH
			});

			// create shape type and shape args that are reused in drawPoints and drawTracker
			point.shapeType = 'rect';
			shapeArgs = extend(chart.renderer.Element.prototype.crisp.apply({}, [
				borderWidth,
				barX,
				barY,
				pointWidth,
				barH
			]), {
				r: options.borderRadius
			});
			if (borderWidth % 2) { // correct for shorting in crisp method, visible in stacked columns with 1px border
				shapeArgs.y -= 1;
				shapeArgs.height += 1;
			}
			point.shapeArgs = shapeArgs;

			// make small columns responsive to mouse
			point.trackerArgs = defined(trackerY) && merge(point.shapeArgs, {
				height: mathMax(6, barH + 3),
				y: trackerY
			});
		});

	}
1026344
function() {
  var attributes = {
    repeat: {
      left: false,
      right: false
    }
  };
  var notes = [];

  /**
   * Set repeat left for measure
   */
  this.setRepeatLeft = function () {
    attributes.repeat.left = true;
  };

  /**
   * Set repeat right for measure
   */
  this.setRepeatRight = function () {
    attributes.repeat.right = true;
  };

  /**
   * Add note to measure
   * @param {object} note - The note object
   * @param {Number} divisions - The calculated divisions
   * @param {Number} beatType - The beat type
   */
  this.addNote = function(note, divisions, beatType) {
    var _note = {pitch:{}};
    var _octave = 5, _step, _alter = 0;
    if (note.hasOwnProperty('pitches')) {
      _octave--;
      _step = note.pitches[0].pitch;
      while (_step > 6) {
        _octave++;
        _step -= 7;
      }
      while (_step < 0) {
        _octave--;
        _step +=7
      }
      _note.pitch.step = pitches.abc[_step];
      _note.rest = false;
      if (note.pitches[0].hasOwnProperty('accidental')) {
        _alter = accidental.abc[note.pitches[0].accidental];
        _note.pitch.accidental = note.pitches[0].accidental;
      }
    } else {
      _note.pitch.step = "C";
      _note.pitch.octave = 5;
      _note.rest = true;
      _note.pitch.alter = 0;
    }
    _note.pitch.octave = _octave;
    _note.pitch.alter = _alter;

    for (var i = 0; i < durations.length; i++) {
      if (typeof durations[i+1] !== 'undefined') {
        if (durations[i].duration > note.duration && durations[i+1].duration <= note.duration) {
          var diff = note.duration - durations[i+1].duration;
          _note.duration = durations[i+1].duration * divisions * beatType;
          _note.type = durations[i+1].type;
          if (diff > 0) {
            if ((diff / durations[i+1].duration) === 0.5) {
              _note.dot = true;
            } else {
              throw new Error('Unknown duration: ' + note.duration);
            }
          }
          break;
        }
      } else {
        throw new Error('Unknown duration: ' + note.duration);
      }
    }

    notes.push(_note);
  };

  /**
   * Get measure object
   * @returns {{attributes: {repeat: {left: boolean, right: boolean}}, notes: Array}}
   */
  this.get = function() {
    return {
      attributes: attributes,
      notes: notes
    };
  };
}
1011651
private Metric collectCounter(MetricName dropwizardMetric, Counter counter) {
    String metricName =
        DropWizardUtils.generateFullMetricName(dropwizardMetric.getKey(), "counter");

    String metricDescription =
        DropWizardUtils.generateFullMetricDescription(dropwizardMetric.getKey(), counter);
    AbstractMap.SimpleImmutableEntry<List<LabelKey>, List<LabelValue>> labels =
        DropWizardUtils.generateLabels(dropwizardMetric);

    MetricDescriptor metricDescriptor =
        MetricDescriptor.create(
            metricName, metricDescription, DEFAULT_UNIT, Type.GAUGE_INT64, labels.getKey());

    TimeSeries timeSeries =
        TimeSeries.createWithOnePoint(
            labels.getValue(),
            Point.create(Value.longValue(counter.getCount()), clock.now()),
            null);
    return Metric.createWithOneTimeSeries(metricDescriptor, timeSeries);
  }
681633
function(time, metrics) {
	var metricTypes = ['gauges', 'timer_data', 'timers', 'counters', 'sets'];

	metricTypes.forEach(function(type, i){
		var obj;

		for (var key in metrics[type]) {
			obj = aggregate[type](time, key, metrics[type][key]);

			insert(obj.db, obj.col, obj.data, function(err){
				if (err) console.log(err);
			});
		};
	});
}
1087663
static MetricFamilySamples createMetricFamilySamples(Metric metric, String namespace) {
    MetricDescriptor metricDescriptor = metric.getMetricDescriptor();
    String name = getNamespacedName(metricDescriptor.getName(), namespace);
    Type type = getType(metricDescriptor.getType());
    List<String> labelNames = convertToLabelNames(metricDescriptor.getLabelKeys());
    List<Sample> samples = Lists.newArrayList();

    for (io.opencensus.metrics.export.TimeSeries timeSeries : metric.getTimeSeriesList()) {
      for (io.opencensus.metrics.export.Point point : timeSeries.getPoints()) {
        samples.addAll(getSamples(name, labelNames, timeSeries.getLabelValues(), point.getValue()));
      }
    }
    return new MetricFamilySamples(name, type, metricDescriptor.getDescription(), samples);
  }
1043500
private void calculateInside(int spanStart, int spanEnd, CfgParseChart chart, double[] newValues) {
    double[] binaryRuleValues = binaryDistributionWeights.getValues();
    
    int leftIndex = Ints.indexOf(binaryDistributionWeights.getDimensionNumbers(), leftVar.getOnlyVariableNum());
    int rightIndex = Ints.indexOf(binaryDistributionWeights.getDimensionNumbers(), rightVar.getOnlyVariableNum());
    
    for (int i = 0; i < spanEnd - spanStart; i++) {
      double[] left = chart.getInsideEntriesArray(spanStart, spanStart + i);
      double[] right = chart.getInsideEntriesArray(spanStart + i + 1, spanEnd);

      for (int j = 0; j < newValues.length; j++) {
        newValues[j] = binaryRuleValues[j] * left[binaryDistributionWeights.indexToPartialDimKey(j, leftIndex)]
            * right[binaryDistributionWeights.indexToPartialDimKey(j, rightIndex)];
      }

      chart.updateInsideEntry(spanStart, spanEnd, i, newValues, binaryDistribution);
    }
  }
1099563
protected function seedMetricPoints()
    {
        MetricPoint::truncate();

        $points = [];

        // Generate 24 hours of metric points
        for ($i = 0; $i <= 23; $i++) {
            for ($j = 0; $j <= 59; $j++) {
                $this->info("{$i}:{$j}");

                $pointTime = date("Y-m-d {$i}:{$j}:00");

                $points[] = [
                    'metric_id'  => 1,
                    'value'      => random_int(1, 10),
                    'created_at' => $pointTime,
                    'updated_at' => $pointTime,
                ];
            }
        }

        foreach (array_chunk($points, 100) as $chunk) {
            MetricPoint::insert($chunk);
        }
    }
825849
def FreqDist_chart (self):
        
        # Take a log of the data before plotting so that we can
        # reduce the number of points to plot evenly
        pdata = {}
        for idx, s_name in enumerate(self.tagdir_data['FreqDistribution']):
            pdata[s_name] = {}
            for x, y in self.tagdir_data['FreqDistribution'][s_name].items():
                try:
                    pdata[s_name][math.log(float(x))] = y
                except ValueError:
                    pass
        pconfig = {
            'id': 'FreqDistribution',
            'title': 'Frequency Distribution',
            'ylab': 'Fraction of Reads',
            'xlab': 'Log10(Distance between regions)',
            'data_labels': ['Reads', 'Percent'],
            'smooth_points': 500,
            'smooth_points_sumcounts': False,
            'yLog' : True
        }
        return linegraph.plot(pdata, pconfig)
813752
private void addMetric(
      List<Metric> metrics,
      String name,
      TagList tags,
      Object value) {
    long now = System.currentTimeMillis();
    if (onlyNumericMetrics) {
      value = asNumber(value);
    }
    if (value != null) {

      TagList newTags = counters.matches(MonitorConfig.builder(name).withTags(tags).build())
          ? getTagListWithAdditionalTag(tags, DataSourceType.COUNTER)
          : getTagListWithAdditionalTag(tags, DataSourceType.GAUGE);
      Metric m = new Metric(name, newTags, now, value);
      metrics.add(m);
    }
  }