Flink's AggregateFunction's getResult() can change Accumulator value? - apache-flink

Can the getResult() function change the value of the accumulator?It still takes effect value when accumulating.
The code is in below:
public class WeightedAverage implements AggregateFunction<Datum, AverageAccumulator, Double> {
public AverageAccumulator createAccumulator() {
return new AverageAccumulator();
}
public AverageAccumulator merge(AverageAccumulator a, AverageAccumulator b) {
a.count += b.count;
a.sum += b.sum;
return a;
}
public AverageAccumulator add(Datum value, AverageAccumulator acc) {
acc.count += value.getWeight();
acc.sum += value.getValue();
return acc;
}
public Double getResult(AverageAccumulator acc) {
int result = acc.sum / (double) acc.count;
acc.count = 0; //here
acc.sum = 0; //here
return result;
}
}

No, you cannot modify the accumulator during getResult.
Flink will create new accumulators as necessary (e.g., for each new window).

Related

How do i use the for-loop to access certain object values from another class

I have an arrayList of objects, and want to calculate the average height of all the objects stored in said arraylist. However I do not know how to access those values or how to store them.
Currently i have done:
public class class1
{
public double height;
public class1(double height)
{
this.height = height;
}
}
puplic Class Class2
{
public ArrayList<Class1> objects;
public Class2()
{
objects = new ArrayList<Class1>();
}
public double averageHeight()
{
for(int i = 0; i < objects.size(); i++)
{
whatToDo??
}
}
Hopefully this isn't as big a problem as i see it as.
In Java do like this:
public double averageHeight() {
double avgHeight = 0;
for(int i = 0; i < objects.size(); i++)
double height = objects.get(i).height;
avgHeight+= height;
}
return avgHeight / (double)objects.size();
}
If this is Java, you can do the following if averageHeight is part of Class2 and you have public access to everything:
public double averageHeight() {
double avgHeight = 0;
for(Class1 o : objects) {
avgHeight += o.height;
}
return avgHeight / (double)objects.size();
}
or
public double averageHeight() {
double avgHeight = 0;
for(int i = 0; i < objects.size(); i++)
Class1 o = objects.get(i);
avgHeight += o.height;
}
return avgHeight / (double)objects.size();
}

Null Pointer Exception in array passed class

So I have a project that requires a generic class that extends Number and also finds the largest and smallest value in the array, the average of all the values, and the size of the array. This seems easy enough to implement, but I have a problem before even putting the generic part of this in place, I get a runtime error of Null Pointer Exception at x.length, regardless of which method I call, always in the same place.
import java.util.Comparator;
public class test
{
public int x[];
public test(int x[])
{
}
public void setx(int newx[])
{
x = newx;
}
public int[] getx()
{
return x;
}
public int findSmallest()
{
int i = 0;
int temp = x[i];
while (i < x.length)
{
i++;
if(x[i] < temp)
{
temp = x[i];
}
else
{
}
}
return temp;
}
public int findLargest()
{
int i = 0;
int temp = x[i];
while (i < x.length)
{
i++;
if(x[i] > temp)
{
temp = x[i];
}
else
{
}
}
return temp;
}
public double findMean()
{
int i = 0;
double sum = 0.0;
double avg = 0.0;
while (i < x.length)
{
sum += x[i];
i++;
}
avg = sum / x.length;
return avg;
}
public int findTotal()
{
int i = x.length;
return i;
}
public static void main (String args[])
{
int[] ia = {1, 2, 3, 4, 5, 6};
test intTest = new test(ia);
System.out.println(intTest.findTotal());
}
}
Any help on how to fix this would be amazing.
You forgot use the setx method in the constructor. You're passing the integer array to constructor but not actually initializing the integer array inside the class. You can do this by calling the setx method in your constructor and passing the integer array x to setx method.
Hope this helps.

Sorting 2D Points in an array...what am I missing?

So here is the deal: I got a code from my colleague who cant figure out the mistakes he made. He wanted to sort the array first by Y, then by X (if Y=Y). Can you help?
using System;
using System.Collections;
public class Point {
public int x;
public int y;
public Point(int x, int y) {
x = x;
y = y;
}
public string ToString() {
return x + "," + y;
}
}
public class PointList {
public static void Main(string [] args) {
ArrayList AL = new ArrayList();
Random R = new Random();
for (int i = 0; i < 10; i++) {
Point p = new Point(R.Next(50), R.Next(50));
AL.Add(p);
}
PrintValues(AL);
AL.Sort();
PrintValues(AL);
}
public static void PrintValues( IEnumerable myList ) {
foreach ( Object obj in myList )
Console.WriteLine( "{0}", obj );
Console.WriteLine();
}
}
Any ideas?
You can try with:
AL.Sort(delegate(Point a, Point b) {
if (a.y < b.y ) return -1;
else if (a.y > b.y ) return 1;
else {
if ( a.x < b.x ) return -1;
else if ( a.x > b.x ) return 1;
else return 0;
}
});
You could implement ICompareable and add the following code:
public class Point : IComparable
public int CompareTo(object obj)
{
if (obj == null) return 1;
Point otherPoint = obj as Point;
if (otherPoint != null)
{
if(this.y == otherPoint.y)
{
return this.x.CompareTo(otherPoint.x);
}
return this.y.CompareTo(otherPoint.y);
}
else
throw new ArgumentException("Object is not a Point");
}

WPF Listbox Collection custom sort

I have a listbox
DropPrice
MyPrice
Price1
Price2
I want to sort it like this
Price1
Price2
DropPrice
MyPrice
I mean, if there's an item that starts with the sequence "price", it gets priority, else the smallest string should get the priority.
My source code:
var lcv = (ListCollectionView)(CollectionViewSource.GetDefaultView(_itemsSource));
var customSort = new PrioritySorting("price");
lcv.CustomSort = customSort;
internal class PrioritySorting : IComparer
{
private string _text;
public PrioritySorting(string text)
{
_text = text;
}
public int Compare(object x, object y)
{
//my sorting code here
}
}
How can i write compare method. I know, that it can return 1,0 or -1. How can i set priorities.
You just have to check if it starts with "price".
Note that I don't think that ToString() is appropriate; you should rather implement IComparer<T> and strongly type your objects in your listbox.
public int Compare(object x, object y)
{
// test for equality
if (x.ToString() == y.ToString())
{
return 0;
}
// if x is "price" but not y, x goes above
if (x.ToString().StartsWith("Price") && !y.ToString().StartsWith("Price"))
{
return -1;
}
// if y is "price" but not x, y goes above
if (!x.ToString().StartsWith("Price") && y.ToString().StartsWith("Price"))
{
return 1;
}
// otherwise, compare normally (this way PriceXXX are also compared among themselves)
return string.Compare(x.ToString(), y.ToString());
}
Here is sample code snippet for IComparer.
private class sortYearAscendingHelper : IComparer
{
int IComparer.Compare(object a, object b)
{
car c1=(car)a;
car c2=(car)b;
if (c1.year > c2.year)
return 1;
if (c1.year < c2.year)
return -1;
else
return 0;
}
}
This is more specific to your Question
internal class PrioritySorting : IComparer
{
private string _text;
public PrioritySorting(string text)
{
_text = text;
}
public int Compare(object x, object y)
{
var str1 = x as string;
var str2 = y as string;
if (str1.StartsWith("price") )
{
if (str2.StartsWith("price"))
return 0;
return 1;
}
return -1;
}
}

WPF: Create XpsDocument Pagination

I am trying to create a Paginator that will in turn create an XpsDocument that I can preview with the and then print. I have the following code that I found on the web but do not understand how it is working.
The issue I am having is that if I run this as is, the pages are generated successfully. If I comment out the lines within OnRender() that generate the actual values of data (all the lines after Random...) I get pages that are about one row high and no text on them but they appear to be the correct length. What is it that is keeping the values of "Row Number" & "Column i" from being shown?
I have included 2 screen shots to illustrate.
public class TaxCodePrintPaginator : DocumentPaginator
{
private int _RowsPerPage;
private Size _PageSize;
private int _Rows;
private List<TaxCode> _dataList;
public TaxCodePrintPaginator(List<TaxCode> dt, int rows, Size pageSize)
{
_dataList = dt;
_Rows = rows;
PageSize = pageSize;
}
public override DocumentPage GetPage(int pageNumber)
{
int currentRow = _RowsPerPage * pageNumber;
var page = new PageElement(currentRow, Math.Min(_RowsPerPage, _Rows - currentRow))
{
Width = PageSize.Width,
Height = PageSize.Height
};
page.Arrange(new Rect(new Point(0, 0), PageSize));
return new DocumentPage(page);
}
public override bool IsPageCountValid
{ get { return true; } }
public override int PageCount
{ get { return (int)Math.Ceiling(_Rows / (double)_RowsPerPage); } }
public override Size PageSize
{
get { return _PageSize; }
set
{
_PageSize = value;
_RowsPerPage = 40;
//Can't print anything if you can't fit a row on a page
Debug.Assert(_RowsPerPage > 0);
}
}
public override IDocumentPaginatorSource Source
{ get { return null; } }
}
public class PageElement : UserControl
{
private const int PageMargin = 75;
private const int HeaderHeight = 25;
private const int LineHeight = 20;
private const int ColumnWidth = 140;
private int _CurrentRow;
private int _Rows;
public PageElement(int currentRow, int rows)
{
Margin = new Thickness(PageMargin);
_CurrentRow = currentRow;
_Rows = rows;
}
private static FormattedText MakeText(string text)
{
return new FormattedText(text, CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface("Tahoma"), 14, Brushes.Black);
}
public static int RowsPerPage(double height)
{
return (int)Math.Floor((height - (2 * PageMargin)
- HeaderHeight) / LineHeight);
}
protected override void OnRender(DrawingContext dc)
{
Point curPoint = new Point(0, 0);
dc.DrawText(MakeText("Row Number"), curPoint);
curPoint.X += ColumnWidth;
for (int i = 1; i < 4; i++)
{
dc.DrawText(MakeText("Column " + i), curPoint);
curPoint.X += ColumnWidth;
}
curPoint.X = 0;
curPoint.Y += LineHeight;
dc.DrawRectangle(Brushes.Black, null, new Rect(curPoint, new Size(Width, 2)));
curPoint.Y += HeaderHeight - LineHeight;
Random numberGen = new Random();
for (int i = _CurrentRow; i < _CurrentRow + _Rows; i++)
{
dc.DrawText(MakeText(i.ToString()), curPoint);
curPoint.X += ColumnWidth;
for (int j = 1; j < 4; j++)
{
dc.DrawText(MakeText(numberGen.Next().ToString()), curPoint);
curPoint.X += ColumnWidth;
}
curPoint.Y += LineHeight;
curPoint.X = 0;
}
}
}
Before
After

Resources