method2testcases
stringlengths
118
6.63k
### Question: Optionals { public static <T> Optional<Collection<T>> of(Collection<T> collection) { return collection.isEmpty() ? Optional.empty() : Optional.of(collection); } static Optional<Collection<T>> of(Collection<T> collection); static Stream<T> stream(Optional<T> optional); }### Answer: @Test public void testOfEmptyCollection() { assertThat(Optionals.of(Collections.emptyList())).isEmpty(); } @Test public void testOfCollection() { Assert.assertThat(Optionals.of(Arrays.asList(1, 2)), isPresentAnd(hasSize(2))); Assert.assertThat(Optionals.of(Arrays.asList(1, 2)), isPresentAnd(hasItems(1, 2))); }
### Question: Optionals { public static <T> Stream<T> stream(Optional<T> optional) { return optional.map(Stream::of) .orElseGet(Stream::empty); } static Optional<Collection<T>> of(Collection<T> collection); static Stream<T> stream(Optional<T> optional); }### Answer: @Test public void testStream() { assertThat(Optionals.stream(Optional.of("foo")).count()).isEqualTo(1L); assertThat(Optionals.stream(Optional.of("foo")).findFirst()).hasValue("foo"); } @Test public void testEmptyStream() { assertThat(Optionals.stream(Optional.empty()).count()).isEqualTo(0L); }
### Question: DiskCache { public T get(boolean store) { final T obj; if (store) { obj = readOrCreate(); } else { obj = create(); } return obj; } T get(boolean store); }### Answer: @Test public void testNoStore() { when(supplier.get()).thenReturn(1); File f = folder.getRoot(); DiskCache<Integer> cache = new DiskCache<>(supplier, f); assertThat(cache.get(false)).isEqualTo(1); verify(supplier).get(); assertThat(f.list()).isEmpty(); } @Test public void testStore() { HashCode hash = Hashing.sha256().newHasher() .putBoolean(true) .hash(); when(supplier.get()).thenReturn(1); when(supplier.hash()).thenReturn(hash); File f = folder.getRoot(); DiskCache<Integer> cache = new DiskCache<>(supplier, f); assertThat(cache.get(true)).isEqualTo(1); verify(supplier).get(); assertThat(f.list()).hasSize(1); assertThat(cache.get(true)).isEqualTo(1); verify(supplier).get(); } @Test public void testStoreAndDelete() { HashCode hash = Hashing.sha256().newHasher() .putBoolean(true) .hash(); when(supplier.get()).thenReturn(1); when(supplier.hash()).thenReturn(hash); File f = folder.getRoot(); DiskCache<Integer> cache = new DiskCache<>(supplier, f); assertThat(cache.get(true)).isEqualTo(1); verify(supplier).get(); folder.delete(); assertThat(cache.get(true)).isEqualTo(1); verify(supplier, times(2)).get(); } @SuppressWarnings("unchecked") @Test public void testStoreAndGetDifferent() { CacheableSupplier<Integer> supplier2 = Mockito.mock(CacheableSupplier.class); HashCode hash1 = Hashing.sha256().newHasher() .putBoolean(true) .hash(); HashCode hash2 = Hashing.sha256().newHasher() .putBoolean(false) .hash(); when(supplier.hash()).thenReturn(hash1); when(supplier2.hash()).thenReturn(hash2); when(supplier.get()).thenReturn(1); when(supplier2.get()).thenReturn(2); File f = folder.getRoot(); DiskCache<Integer> cache = new DiskCache<>(supplier, f); assertThat(cache.get(true)).isEqualTo(1); DiskCache<Integer> cache2 = new DiskCache<>(supplier2, f); assertThat(cache2.get(true)).isEqualTo(2); }
### Question: LazyArray implements LazyMap<Integer, T> { @Deprecated @Override public Optional<T> get(Integer key) { int k = key.intValue(); return get(k); } void forEach(IntObjectBiConsumer<T> action); @Deprecated @Override void forEach(BiConsumer<Integer, T> action); @Deprecated @Override Optional<T> get(Integer key); Optional<T> get(int id); @Deprecated @Override T getOrCreate(Integer key); T getOrCreate(int id); int size(); }### Answer: @Test(expected = IndexOutOfBoundsException.class) public void testGetElementOutOfBounds() { LazyMap<Integer, String> array = create(() -> null, 3); array.get(4); fail(); }
### Question: LazyArray implements LazyMap<Integer, T> { @Deprecated @Override public T getOrCreate(Integer key) { int k = key.intValue(); return getOrCreate(k); } void forEach(IntObjectBiConsumer<T> action); @Deprecated @Override void forEach(BiConsumer<Integer, T> action); @Deprecated @Override Optional<T> get(Integer key); Optional<T> get(int id); @Deprecated @Override T getOrCreate(Integer key); T getOrCreate(int id); int size(); }### Answer: @Test(expected = IndexOutOfBoundsException.class) public void testGetOrCreateElementOutOfBounds() { LazyMap<Integer, String> array = create(() -> null, 3); array.getOrCreate(4); fail(); }
### Question: Hasher { public Hasher put(Hashable hashable) { Optional.ofNullable(hashable) .ifPresent(this::hash); return this; } static Hasher of(HashFunction function); HashCode hash(); Hasher put(Hashable hashable); Hasher putAll(Iterable<? extends Hashable> hashables); Hasher putBoolean(boolean b); Hasher putByte(byte b); Hasher putBytes(byte[] bytes); Hasher putChar(char c); Hasher putClass(Class<?> type); Hasher putDouble(double d); Hasher putFloat(float f); Hasher putInt(int i); Hasher putLong(long l); Hasher putShort(short s); Hasher putUnencodedChars(CharSequence charSequence); }### Answer: @Test public void testPut() { assertThat(Hasher.of(HASH_FUNCTION) .put(new TestHashable(0)) .put(new TestHashable(1)) .hash()).isEqualTo(HASH_FUNCTION.newHasher().putInt(0).putInt(1).hash()); }
### Question: Hasher { public Hasher putAll(Iterable<? extends Hashable> hashables) { Optional.ofNullable(hashables) .ifPresent(this::hashAll); return this; } static Hasher of(HashFunction function); HashCode hash(); Hasher put(Hashable hashable); Hasher putAll(Iterable<? extends Hashable> hashables); Hasher putBoolean(boolean b); Hasher putByte(byte b); Hasher putBytes(byte[] bytes); Hasher putChar(char c); Hasher putClass(Class<?> type); Hasher putDouble(double d); Hasher putFloat(float f); Hasher putInt(int i); Hasher putLong(long l); Hasher putShort(short s); Hasher putUnencodedChars(CharSequence charSequence); }### Answer: @Test public void testPutAll() { assertThat(Hasher.of(HASH_FUNCTION) .putAll(Arrays.asList(new TestHashable(0), new TestHashable(1))) .putAll(Collections.singletonList(new TestHashable(2))) .hash()).isEqualTo(HASH_FUNCTION.newHasher().putInt(0).putInt(1).putInt(2).hash()); }
### Question: CandidateGenerator { public List<SimpleInd> createCombinedCandidates(List<SimpleInd> inds, boolean isCombineNull, AbstractColumnStore[] stores) { Map<SimpleColumnCombination, SimpleColumnCombination> columnCombinations = new HashMap<>(); if (!isCombineNull) { inds = inds.stream() .filter(ind -> { AbstractColumnStore store = stores[ind.left.getTable()]; for (int column : ind.left.getColumns()) { if (store.isNullColumn(column)) return false; } return true; }) .collect(Collectors.toList()); } List<SimpleInd> newIndCandidates = new ArrayList<>(); HashSet<SimpleInd> lastResults = new HashSet<>(inds); inds.sort(SimpleInd.prefixBlockComparator); for (int i = 0; i < inds.size(); i++) { SimpleInd a = inds.get(i); for (int j = i + 1; j < inds.size(); j++) { SimpleInd b = inds.get(j); if (!a.left.startsWith(b.left) || !a.right.startsWith(b.right)) break; if (a.left.lastColumn() == b.left.lastColumn() || a.right.lastColumn() == b.right.lastColumn()) { continue; } SimpleInd newCandidate = a.combineWith(b, columnCombinations); if (isPotentiallyValid(newCandidate, lastResults)) { newIndCandidates.add(newCandidate); } } } return newIndCandidates; } List<SimpleInd> createCombinedCandidates(List<SimpleInd> inds, boolean isCombineNull, AbstractColumnStore[] stores); }### Answer: @Test public void testCreateCombinedCandidatesTrinary() throws Exception { List<SimpleInd> inds = Arrays.asList( SimpleInd.left(TABLE, 0, 1).right(TABLE, 3, 4), SimpleInd.left(TABLE, 1, 2).right(TABLE, 4, 5), SimpleInd.left(TABLE, 0, 2).right(TABLE, 3, 5) ); List<SimpleInd> candidates = gen.createCombinedCandidates(inds, true, null); assertThat(candidates, contains(SimpleInd.left(TABLE, 0, 1, 2).right(TABLE, 3, 4, 5))); } @Test public void testCreateCombinedCandidatesBinary() throws Exception { List<SimpleInd> candidates = gen.createCombinedCandidates(Arrays.asList( SimpleInd.left(TABLE, 0).right(TABLE, 3), SimpleInd.left(TABLE, 1).right(TABLE, 4) ), true, null); assertThat(candidates, contains(SimpleInd.left(TABLE, 0, 1).right(TABLE, 3, 4))); }
### Question: Hasher { public Hasher putBoolean(boolean b) { hasher.putBoolean(b); return this; } static Hasher of(HashFunction function); HashCode hash(); Hasher put(Hashable hashable); Hasher putAll(Iterable<? extends Hashable> hashables); Hasher putBoolean(boolean b); Hasher putByte(byte b); Hasher putBytes(byte[] bytes); Hasher putChar(char c); Hasher putClass(Class<?> type); Hasher putDouble(double d); Hasher putFloat(float f); Hasher putInt(int i); Hasher putLong(long l); Hasher putShort(short s); Hasher putUnencodedChars(CharSequence charSequence); }### Answer: @Test public void testPutBoolean() { assertThat(Hasher.of(HASH_FUNCTION).putBoolean(true).putBoolean(false).hash()) .isEqualTo(HASH_FUNCTION.newHasher().putBoolean(true).putBoolean(false).hash()); }
### Question: Hasher { public Hasher putByte(byte b) { hasher.putByte(b); return this; } static Hasher of(HashFunction function); HashCode hash(); Hasher put(Hashable hashable); Hasher putAll(Iterable<? extends Hashable> hashables); Hasher putBoolean(boolean b); Hasher putByte(byte b); Hasher putBytes(byte[] bytes); Hasher putChar(char c); Hasher putClass(Class<?> type); Hasher putDouble(double d); Hasher putFloat(float f); Hasher putInt(int i); Hasher putLong(long l); Hasher putShort(short s); Hasher putUnencodedChars(CharSequence charSequence); }### Answer: @Test public void testPutByte() { assertThat(Hasher.of(HASH_FUNCTION).putByte((byte) 0).putByte((byte) 1).hash()) .isEqualTo(HASH_FUNCTION.newHasher().putByte((byte) 0).putByte((byte) 1).hash()); }
### Question: Hasher { public Hasher putBytes(byte[] bytes) { Optional.ofNullable(bytes) .ifPresent(hasher::putBytes); return this; } static Hasher of(HashFunction function); HashCode hash(); Hasher put(Hashable hashable); Hasher putAll(Iterable<? extends Hashable> hashables); Hasher putBoolean(boolean b); Hasher putByte(byte b); Hasher putBytes(byte[] bytes); Hasher putChar(char c); Hasher putClass(Class<?> type); Hasher putDouble(double d); Hasher putFloat(float f); Hasher putInt(int i); Hasher putLong(long l); Hasher putShort(short s); Hasher putUnencodedChars(CharSequence charSequence); }### Answer: @Test public void testPutBytes() { assertThat(Hasher.of(HASH_FUNCTION) .putBytes(new byte[]{0, 1}) .putBytes(new byte[]{2}) .hash()) .isEqualTo(HASH_FUNCTION.newHasher().putBytes(new byte[]{0, 1}).putBytes(new byte[]{2}) .hash()); }
### Question: Hasher { public Hasher putChar(char c) { hasher.putChar(c); return this; } static Hasher of(HashFunction function); HashCode hash(); Hasher put(Hashable hashable); Hasher putAll(Iterable<? extends Hashable> hashables); Hasher putBoolean(boolean b); Hasher putByte(byte b); Hasher putBytes(byte[] bytes); Hasher putChar(char c); Hasher putClass(Class<?> type); Hasher putDouble(double d); Hasher putFloat(float f); Hasher putInt(int i); Hasher putLong(long l); Hasher putShort(short s); Hasher putUnencodedChars(CharSequence charSequence); }### Answer: @Test public void testPutChar() { assertThat(Hasher.of(HASH_FUNCTION).putChar('a').putChar('b').hash()) .isEqualTo(HASH_FUNCTION.newHasher().putChar('a').putChar('b').hash()); }
### Question: Hasher { public Hasher putClass(Class<?> type) { Optional.ofNullable(type) .map(Class::getName) .ifPresent(hasher::putUnencodedChars); return this; } static Hasher of(HashFunction function); HashCode hash(); Hasher put(Hashable hashable); Hasher putAll(Iterable<? extends Hashable> hashables); Hasher putBoolean(boolean b); Hasher putByte(byte b); Hasher putBytes(byte[] bytes); Hasher putChar(char c); Hasher putClass(Class<?> type); Hasher putDouble(double d); Hasher putFloat(float f); Hasher putInt(int i); Hasher putLong(long l); Hasher putShort(short s); Hasher putUnencodedChars(CharSequence charSequence); }### Answer: @Test public void testPutClass() { assertThat(Hasher.of(HASH_FUNCTION) .putClass(HasherTest.class) .putClass(Hasher.class) .hash()) .isEqualTo(HASH_FUNCTION.newHasher().putUnencodedChars(HasherTest.class.getName()) .putUnencodedChars(Hasher.class.getName()).hash()); }
### Question: Hasher { public Hasher putDouble(double d) { hasher.putDouble(d); return this; } static Hasher of(HashFunction function); HashCode hash(); Hasher put(Hashable hashable); Hasher putAll(Iterable<? extends Hashable> hashables); Hasher putBoolean(boolean b); Hasher putByte(byte b); Hasher putBytes(byte[] bytes); Hasher putChar(char c); Hasher putClass(Class<?> type); Hasher putDouble(double d); Hasher putFloat(float f); Hasher putInt(int i); Hasher putLong(long l); Hasher putShort(short s); Hasher putUnencodedChars(CharSequence charSequence); }### Answer: @Test public void testPutDouble() { assertThat(Hasher.of(HASH_FUNCTION).putDouble(0.0).putDouble(1.0).hash()) .isEqualTo(HASH_FUNCTION.newHasher().putDouble(0.0).putDouble(1.0).hash()); }
### Question: Hasher { public Hasher putFloat(float f) { hasher.putFloat(f); return this; } static Hasher of(HashFunction function); HashCode hash(); Hasher put(Hashable hashable); Hasher putAll(Iterable<? extends Hashable> hashables); Hasher putBoolean(boolean b); Hasher putByte(byte b); Hasher putBytes(byte[] bytes); Hasher putChar(char c); Hasher putClass(Class<?> type); Hasher putDouble(double d); Hasher putFloat(float f); Hasher putInt(int i); Hasher putLong(long l); Hasher putShort(short s); Hasher putUnencodedChars(CharSequence charSequence); }### Answer: @Test public void testPutFloat() { assertThat(Hasher.of(HASH_FUNCTION).putFloat(0.0f).putFloat(1.0f).hash()) .isEqualTo(HASH_FUNCTION.newHasher().putFloat(0.0f).putFloat(1.0f).hash()); }
### Question: Hasher { public Hasher putInt(int i) { hasher.putInt(i); return this; } static Hasher of(HashFunction function); HashCode hash(); Hasher put(Hashable hashable); Hasher putAll(Iterable<? extends Hashable> hashables); Hasher putBoolean(boolean b); Hasher putByte(byte b); Hasher putBytes(byte[] bytes); Hasher putChar(char c); Hasher putClass(Class<?> type); Hasher putDouble(double d); Hasher putFloat(float f); Hasher putInt(int i); Hasher putLong(long l); Hasher putShort(short s); Hasher putUnencodedChars(CharSequence charSequence); }### Answer: @Test public void testPutInt() { assertThat(Hasher.of(HASH_FUNCTION).putInt(0).putInt(1).hash()) .isEqualTo(HASH_FUNCTION.newHasher().putInt(0).putInt(1).hash()); }
### Question: Hasher { public Hasher putLong(long l) { hasher.putLong(l); return this; } static Hasher of(HashFunction function); HashCode hash(); Hasher put(Hashable hashable); Hasher putAll(Iterable<? extends Hashable> hashables); Hasher putBoolean(boolean b); Hasher putByte(byte b); Hasher putBytes(byte[] bytes); Hasher putChar(char c); Hasher putClass(Class<?> type); Hasher putDouble(double d); Hasher putFloat(float f); Hasher putInt(int i); Hasher putLong(long l); Hasher putShort(short s); Hasher putUnencodedChars(CharSequence charSequence); }### Answer: @Test public void testPutLong() { assertThat(Hasher.of(HASH_FUNCTION).putLong(0L).putLong(1L).hash()) .isEqualTo(HASH_FUNCTION.newHasher().putLong(0L).putLong(1L).hash()); }
### Question: Hasher { public Hasher putShort(short s) { hasher.putShort(s); return this; } static Hasher of(HashFunction function); HashCode hash(); Hasher put(Hashable hashable); Hasher putAll(Iterable<? extends Hashable> hashables); Hasher putBoolean(boolean b); Hasher putByte(byte b); Hasher putBytes(byte[] bytes); Hasher putChar(char c); Hasher putClass(Class<?> type); Hasher putDouble(double d); Hasher putFloat(float f); Hasher putInt(int i); Hasher putLong(long l); Hasher putShort(short s); Hasher putUnencodedChars(CharSequence charSequence); }### Answer: @Test public void testPutShort() { assertThat(Hasher.of(HASH_FUNCTION).putShort((short) 0).putShort((short) 1).hash()) .isEqualTo(HASH_FUNCTION.newHasher().putShort((short) 0).putShort((short) 1).hash()); }
### Question: SimpleColumnCombination implements Comparable<SimpleColumnCombination> { public int getTable() { return table; } SimpleColumnCombination(int table, int[] columns); private SimpleColumnCombination(int table, int[] columns, int additionalColumn); boolean isActive(); void setActive(boolean active); long getDistinctCount(); static SimpleColumnCombination create(int table, int... columns); SimpleColumnCombination flipOff(int position); int getTable(); int getColumn(int index); int[] getColumns(); boolean startsWith(SimpleColumnCombination other); SimpleColumnCombination combineWith(SimpleColumnCombination other, Map<SimpleColumnCombination, SimpleColumnCombination> columnCombinations); int lastColumn(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(SimpleColumnCombination o); @Override String toString(); int setIndex(); void setIndex(int index); }### Answer: @Test public void testGetTable() throws Exception { SimpleColumnCombination a = SimpleColumnCombination.create(TABLE, 2,3,4); assertThat(a.getTable(), equalTo(TABLE)); }
### Question: Hasher { public Hasher putUnencodedChars(CharSequence charSequence) { Optional.ofNullable(charSequence) .ifPresent(hasher::putUnencodedChars); return this; } static Hasher of(HashFunction function); HashCode hash(); Hasher put(Hashable hashable); Hasher putAll(Iterable<? extends Hashable> hashables); Hasher putBoolean(boolean b); Hasher putByte(byte b); Hasher putBytes(byte[] bytes); Hasher putChar(char c); Hasher putClass(Class<?> type); Hasher putDouble(double d); Hasher putFloat(float f); Hasher putInt(int i); Hasher putLong(long l); Hasher putShort(short s); Hasher putUnencodedChars(CharSequence charSequence); }### Answer: @Test public void testPutUnencodedChars() { assertThat(Hasher.of(HASH_FUNCTION) .putUnencodedChars("foo") .putUnencodedChars("bar") .hash()).isEqualTo( HASH_FUNCTION.newHasher().putUnencodedChars("foo").putUnencodedChars("bar").hash()); }
### Question: JdbcUtils { public static Optional<Class<?>> getColumnClass(ResultSetMetaData metaData, int column) throws SQLException { String className = metaData.getColumnClassName(column); try { Class<?> clazz = Class.forName(className); return Optional.of(clazz); } catch (ClassNotFoundException e) { return Optional.empty(); } } static Optional<Class<?>> getColumnClass(ResultSetMetaData metaData, int column); }### Answer: @Test public void testGetColumnClass() throws SQLException { String notExistingClassName = "foo.bar.MyClass"; doReturn(String.class.getName()).when(metaData).getColumnClassName(0); doReturn(notExistingClassName).when(metaData).getColumnClassName(1); assertThat(JdbcUtils.getColumnClass(metaData, 0)).hasValue(String.class); assertThat(JdbcUtils.getColumnClass(metaData, 1)).isEmpty(); }
### Question: MathUtils { public static double divide(double dividend, double divisor) { return divisor == 0.0 ? 0.0 : dividend / divisor; } static double divide(double dividend, double divisor); static long increment(long l); static double[] max(double[] d1, double[] d2); static long multiply(long factor1, long factor2); static int roundToInt(double d); }### Answer: @Test public void testDivide() { assertThat(MathUtils.divide(8.0, 2.0)).isEqualTo(4.0); assertThat(MathUtils.divide(0.0, 2.0)).isEqualTo(0.0); assertThat(MathUtils.divide(8.0, 0.0)).isEqualTo(0.0); }
### Question: MathUtils { public static long increment(long l) { return l + 1; } static double divide(double dividend, double divisor); static long increment(long l); static double[] max(double[] d1, double[] d2); static long multiply(long factor1, long factor2); static int roundToInt(double d); }### Answer: @Test public void testIncrement() { assertThat(MathUtils.increment(8L)).isEqualTo(9L); assertThat(MathUtils.increment(0L)).isEqualTo(1L); assertThat(MathUtils.increment(-8L)).isEqualTo(-7L); }
### Question: MathUtils { public static long multiply(long factor1, long factor2) { return factor1 * factor2; } static double divide(double dividend, double divisor); static long increment(long l); static double[] max(double[] d1, double[] d2); static long multiply(long factor1, long factor2); static int roundToInt(double d); }### Answer: @Test public void testMultiply() { assertThat(MathUtils.multiply(8L, 2L)).isEqualTo(16L); assertThat(MathUtils.multiply(0L, 2L)).isEqualTo(0L); assertThat(MathUtils.multiply(8L, 0L)).isEqualTo(0L); }
### Question: NullComparator implements Comparator<T> { @Override public int compare(T o1, T o2) { if (o1 == null) { return o2 == null ? 0 : -1; } if (o2 == null) { return 1; } return underlying.compare(o1, o2); } @Override int compare(T o1, T o2); }### Answer: @Test public void test() { Comparator<Integer> comparator = new NullComparator<>(Integer::compare); assertThat(comparator.compare(1, 2)).isEqualTo(Integer.compare(1, 2)); assertThat(comparator.compare(null, null)).isEqualTo(0); assertThat(comparator.compare(null, 1)).isLessThan(0); assertThat(comparator.compare(1, null)).isGreaterThan(0); }
### Question: IteratorUtils { public static <T> Optional<T> next(Iterator<T> it) { if (it.hasNext()) { T entry = it.next(); return Optional.of(entry); } return Optional.empty(); } static Optional<T> next(Iterator<T> it); static OptionalDouble next(OfDouble it); }### Answer: @Test public void testNext() { List<Integer> list = Collections.singletonList(1); Iterator<Integer> it = list.iterator(); assertThat(IteratorUtils.next(it)).hasValue(1); assertThat(IteratorUtils.next(it)).isEmpty(); } @Test public void testNextDouble() { DoubleList list = DoubleLists.singleton(1.0); OfDouble it = list.iterator(); assertThat(IteratorUtils.next(it).boxed()).hasValue(1.0); assertThat(IteratorUtils.next(it).boxed()).isEmpty(); }
### Question: CollectionUtils { public static <V> void forEach(Double2ObjectMap<V> map, DoubleObjectBiConsumer<V> action) { map.double2ObjectEntrySet().forEach(e -> action.accept(e.getDoubleKey(), e.getValue())); } static List<T> asList(T obj); static IntSet mutableSingleton(int i); static Optional<Entry<V>> ceilingEntry(Double2ObjectSortedMap<V> sortedMap, double from); static Optional<V> ceilingValue(Double2ObjectSortedMap<V> sortedMap, double from); static Collection<Tuple2<T, T>> crossProduct(List<T> list); static OptionalDouble first(DoubleSortedSet set); static void forEach(Double2ObjectMap<V> map, DoubleObjectBiConsumer<V> action); static void forEach(Int2ObjectMap<V> map, IntObjectBiConsumer<V> action); static Optional<T> head(List<T> clusters); static Optional<IntCollection> intersection(Collection<IntCollection> clusters); static IntSet merge(IntSet left, IntCollection right); static IntCollection merge(IntCollection left, IntCollection right); static Collection<T> merge(Collection<T> left, Collection<T> right); static Predicate<Collection<T>> sizeBelow(int maxSize); static List<T> sort(Collection<T> collection, Comparator<T> comparator); static Collection<T> tail(List<T> clusters); static Collection<String> toString(Iterable<T> objects); }### Answer: @Test public void forEachDouble2ObjectMap() { Double2ObjectMap<String> map = new Double2ObjectOpenHashMap<>(); Double2ObjectMap<String> target = new Double2ObjectOpenHashMap<>(); map.put(1.0, "foo"); map.put(2.0, "bar"); forEach(map, target::put); assertThat(target).hasSize(2); assertThat(target).containsEntry(1.0, "foo"); assertThat(target).containsEntry(2.0, "bar"); } @Test public void forEachInt2ObjectMap() { Int2ObjectMap<String> map = new Int2ObjectOpenHashMap<>(); Int2ObjectMap<String> target = new Int2ObjectOpenHashMap<>(); map.put(1, "foo"); map.put(2, "bar"); forEach(map, target::put); assertThat(target).hasSize(2); assertThat(target).containsEntry(1, "foo"); assertThat(target).containsEntry(2, "bar"); }
### Question: SimpleColumnCombination implements Comparable<SimpleColumnCombination> { public int[] getColumns() { return columns; } SimpleColumnCombination(int table, int[] columns); private SimpleColumnCombination(int table, int[] columns, int additionalColumn); boolean isActive(); void setActive(boolean active); long getDistinctCount(); static SimpleColumnCombination create(int table, int... columns); SimpleColumnCombination flipOff(int position); int getTable(); int getColumn(int index); int[] getColumns(); boolean startsWith(SimpleColumnCombination other); SimpleColumnCombination combineWith(SimpleColumnCombination other, Map<SimpleColumnCombination, SimpleColumnCombination> columnCombinations); int lastColumn(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(SimpleColumnCombination o); @Override String toString(); int setIndex(); void setIndex(int index); }### Answer: @Test public void testGetColumns() throws Exception { SimpleColumnCombination a = SimpleColumnCombination.create(TABLE, 2,3,4); assertThat(a.getColumns(), equalTo(new int[]{2, 3, 4})); }
### Question: CollectionUtils { public static IntSet mutableSingleton(int i) { IntSet set = new IntOpenHashSet(); set.add(i); return set; } static List<T> asList(T obj); static IntSet mutableSingleton(int i); static Optional<Entry<V>> ceilingEntry(Double2ObjectSortedMap<V> sortedMap, double from); static Optional<V> ceilingValue(Double2ObjectSortedMap<V> sortedMap, double from); static Collection<Tuple2<T, T>> crossProduct(List<T> list); static OptionalDouble first(DoubleSortedSet set); static void forEach(Double2ObjectMap<V> map, DoubleObjectBiConsumer<V> action); static void forEach(Int2ObjectMap<V> map, IntObjectBiConsumer<V> action); static Optional<T> head(List<T> clusters); static Optional<IntCollection> intersection(Collection<IntCollection> clusters); static IntSet merge(IntSet left, IntCollection right); static IntCollection merge(IntCollection left, IntCollection right); static Collection<T> merge(Collection<T> left, Collection<T> right); static Predicate<Collection<T>> sizeBelow(int maxSize); static List<T> sort(Collection<T> collection, Comparator<T> comparator); static Collection<T> tail(List<T> clusters); static Collection<String> toString(Iterable<T> objects); }### Answer: @Test public void testAsSet() { IntSet set = mutableSingleton(1); assertThat(set).hasSize(1); assertThat(set).contains(1); set.add(2); assertThat(set).hasSize(2); assertThat(set).contains(1, 2); }
### Question: CollectionUtils { public static <V> Optional<Entry<V>> ceilingEntry(Double2ObjectSortedMap<V> sortedMap, double from) { Iterable<Entry<V>> entrySet = ceilingEntrySet(sortedMap, from); Iterator<Entry<V>> it = entrySet.iterator(); return IteratorUtils.next(it); } static List<T> asList(T obj); static IntSet mutableSingleton(int i); static Optional<Entry<V>> ceilingEntry(Double2ObjectSortedMap<V> sortedMap, double from); static Optional<V> ceilingValue(Double2ObjectSortedMap<V> sortedMap, double from); static Collection<Tuple2<T, T>> crossProduct(List<T> list); static OptionalDouble first(DoubleSortedSet set); static void forEach(Double2ObjectMap<V> map, DoubleObjectBiConsumer<V> action); static void forEach(Int2ObjectMap<V> map, IntObjectBiConsumer<V> action); static Optional<T> head(List<T> clusters); static Optional<IntCollection> intersection(Collection<IntCollection> clusters); static IntSet merge(IntSet left, IntCollection right); static IntCollection merge(IntCollection left, IntCollection right); static Collection<T> merge(Collection<T> left, Collection<T> right); static Predicate<Collection<T>> sizeBelow(int maxSize); static List<T> sort(Collection<T> collection, Comparator<T> comparator); static Collection<T> tail(List<T> clusters); static Collection<String> toString(Iterable<T> objects); }### Answer: @Test public void testCeilingEntry() { Double2ObjectSortedMap<String> map = new Double2ObjectRBTreeMap<>(); map.put(0.1, "foo"); map.put(0.2, "bar"); assertThat(ceilingEntry(map, 0.05).map(Entry::getDoubleKey)).hasValue(0.1); assertThat(ceilingEntry(map, 0.1).map(Entry::getDoubleKey)).hasValue(0.1); assertThat(ceilingEntry(map, 0.15).map(Entry::getDoubleKey)).hasValue(0.2); assertThat(ceilingEntry(map, 0.2).map(Entry::getDoubleKey)).hasValue(0.2); assertThat(ceilingEntry(map, 0.25)).isEmpty(); }
### Question: CollectionUtils { public static <V> Optional<V> ceilingValue(Double2ObjectSortedMap<V> sortedMap, double from) { return ceilingEntry(sortedMap, from) .map(Entry::getValue); } static List<T> asList(T obj); static IntSet mutableSingleton(int i); static Optional<Entry<V>> ceilingEntry(Double2ObjectSortedMap<V> sortedMap, double from); static Optional<V> ceilingValue(Double2ObjectSortedMap<V> sortedMap, double from); static Collection<Tuple2<T, T>> crossProduct(List<T> list); static OptionalDouble first(DoubleSortedSet set); static void forEach(Double2ObjectMap<V> map, DoubleObjectBiConsumer<V> action); static void forEach(Int2ObjectMap<V> map, IntObjectBiConsumer<V> action); static Optional<T> head(List<T> clusters); static Optional<IntCollection> intersection(Collection<IntCollection> clusters); static IntSet merge(IntSet left, IntCollection right); static IntCollection merge(IntCollection left, IntCollection right); static Collection<T> merge(Collection<T> left, Collection<T> right); static Predicate<Collection<T>> sizeBelow(int maxSize); static List<T> sort(Collection<T> collection, Comparator<T> comparator); static Collection<T> tail(List<T> clusters); static Collection<String> toString(Iterable<T> objects); }### Answer: @Test public void testCeilingValue() { Double2ObjectSortedMap<String> map = new Double2ObjectRBTreeMap<>(); map.put(0.1, "foo"); map.put(0.2, "bar"); assertThat(ceilingValue(map, 0.05)).hasValue("foo"); assertThat(ceilingValue(map, 0.1)).hasValue("foo"); assertThat(ceilingValue(map, 0.15)).hasValue("bar"); assertThat(ceilingValue(map, 0.2)).hasValue("bar"); assertThat(ceilingValue(map, 0.25)).isEmpty(); }
### Question: CollectionUtils { public static <T> Collection<Tuple2<T, T>> crossProduct(List<T> list) { Builder<Tuple2<T, T>> result = ImmutableList.builder(); int size = list.size(); for (int i = 0; i < size; i++) { T left = list.get(i); Iterable<T> remaining = list.subList(i, size); Seq.of(left) .crossJoin(remaining) .forEach(result::add); } return result.build(); } static List<T> asList(T obj); static IntSet mutableSingleton(int i); static Optional<Entry<V>> ceilingEntry(Double2ObjectSortedMap<V> sortedMap, double from); static Optional<V> ceilingValue(Double2ObjectSortedMap<V> sortedMap, double from); static Collection<Tuple2<T, T>> crossProduct(List<T> list); static OptionalDouble first(DoubleSortedSet set); static void forEach(Double2ObjectMap<V> map, DoubleObjectBiConsumer<V> action); static void forEach(Int2ObjectMap<V> map, IntObjectBiConsumer<V> action); static Optional<T> head(List<T> clusters); static Optional<IntCollection> intersection(Collection<IntCollection> clusters); static IntSet merge(IntSet left, IntCollection right); static IntCollection merge(IntCollection left, IntCollection right); static Collection<T> merge(Collection<T> left, Collection<T> right); static Predicate<Collection<T>> sizeBelow(int maxSize); static List<T> sort(Collection<T> collection, Comparator<T> comparator); static Collection<T> tail(List<T> clusters); static Collection<String> toString(Iterable<T> objects); }### Answer: @Test public void testCrossProduct() { assertThat(CollectionUtils.crossProduct(Arrays.asList(1, 2, 3))).hasSize(1 + 2 + 3); assertThat(CollectionUtils.crossProduct(Arrays.asList(1, 2, 3))) .contains(Tuple.tuple(1, 1)); assertThat(CollectionUtils.crossProduct(Arrays.asList(1, 2, 3))) .contains(Tuple.tuple(1, 2)); assertThat(CollectionUtils.crossProduct(Arrays.asList(1, 2, 3))) .contains(Tuple.tuple(1, 3)); assertThat(CollectionUtils.crossProduct(Arrays.asList(1, 2, 3))) .contains(Tuple.tuple(2, 2)); assertThat(CollectionUtils.crossProduct(Arrays.asList(1, 2, 3))) .contains(Tuple.tuple(2, 3)); assertThat(CollectionUtils.crossProduct(Arrays.asList(1, 2, 3))) .contains(Tuple.tuple(3, 3)); }
### Question: CollectionUtils { public static OptionalDouble first(DoubleSortedSet set) { if (set.isEmpty()) { return OptionalDouble.empty(); } double first = set.firstDouble(); return OptionalDouble.of(first); } static List<T> asList(T obj); static IntSet mutableSingleton(int i); static Optional<Entry<V>> ceilingEntry(Double2ObjectSortedMap<V> sortedMap, double from); static Optional<V> ceilingValue(Double2ObjectSortedMap<V> sortedMap, double from); static Collection<Tuple2<T, T>> crossProduct(List<T> list); static OptionalDouble first(DoubleSortedSet set); static void forEach(Double2ObjectMap<V> map, DoubleObjectBiConsumer<V> action); static void forEach(Int2ObjectMap<V> map, IntObjectBiConsumer<V> action); static Optional<T> head(List<T> clusters); static Optional<IntCollection> intersection(Collection<IntCollection> clusters); static IntSet merge(IntSet left, IntCollection right); static IntCollection merge(IntCollection left, IntCollection right); static Collection<T> merge(Collection<T> left, Collection<T> right); static Predicate<Collection<T>> sizeBelow(int maxSize); static List<T> sort(Collection<T> collection, Comparator<T> comparator); static Collection<T> tail(List<T> clusters); static Collection<String> toString(Iterable<T> objects); }### Answer: @Test public void testFirst() { assertThat(CollectionUtils.first(DoubleSortedSets.EMPTY_SET).boxed()).isEmpty(); assertThat( CollectionUtils.first(new DoubleRBTreeSet(Sets.newTreeSet(Arrays.asList(2.0, 1.0)))) .boxed()).hasValue(1.0); }
### Question: CollectionUtils { public static Optional<IntCollection> intersection(Collection<IntCollection> clusters) { List<IntCollection> sorted = sort(clusters, CLUSTER_COMPARATOR); return createIntersector(sorted).map(HeadAndTailIntersector::intersect); } static List<T> asList(T obj); static IntSet mutableSingleton(int i); static Optional<Entry<V>> ceilingEntry(Double2ObjectSortedMap<V> sortedMap, double from); static Optional<V> ceilingValue(Double2ObjectSortedMap<V> sortedMap, double from); static Collection<Tuple2<T, T>> crossProduct(List<T> list); static OptionalDouble first(DoubleSortedSet set); static void forEach(Double2ObjectMap<V> map, DoubleObjectBiConsumer<V> action); static void forEach(Int2ObjectMap<V> map, IntObjectBiConsumer<V> action); static Optional<T> head(List<T> clusters); static Optional<IntCollection> intersection(Collection<IntCollection> clusters); static IntSet merge(IntSet left, IntCollection right); static IntCollection merge(IntCollection left, IntCollection right); static Collection<T> merge(Collection<T> left, Collection<T> right); static Predicate<Collection<T>> sizeBelow(int maxSize); static List<T> sort(Collection<T> collection, Comparator<T> comparator); static Collection<T> tail(List<T> clusters); static Collection<String> toString(Iterable<T> objects); }### Answer: @Test public void testIntersection() { List<IntCollection> clusters = ImmutableList.<IntCollection>builder() .add(new IntOpenHashSet(Arrays.asList(1, 2, 3, 4))) .add(new IntOpenHashSet(Arrays.asList(2, 3, 4, 5))) .add(new IntOpenHashSet(Arrays.asList(1, 3, 4))) .build(); Assert.assertThat(CollectionUtils.intersection(clusters), isPresentAnd(hasSize(2))); Assert.assertThat(CollectionUtils.intersection(clusters), isPresentAnd(hasItems(3, 4))); } @Test public void testIntersectionOfEmpty() { assertThat(CollectionUtils.intersection(Collections.emptyList())).isEmpty(); }
### Question: CollectionUtils { public static IntSet merge(IntSet left, IntCollection right) { left.addAll(right); return left; } static List<T> asList(T obj); static IntSet mutableSingleton(int i); static Optional<Entry<V>> ceilingEntry(Double2ObjectSortedMap<V> sortedMap, double from); static Optional<V> ceilingValue(Double2ObjectSortedMap<V> sortedMap, double from); static Collection<Tuple2<T, T>> crossProduct(List<T> list); static OptionalDouble first(DoubleSortedSet set); static void forEach(Double2ObjectMap<V> map, DoubleObjectBiConsumer<V> action); static void forEach(Int2ObjectMap<V> map, IntObjectBiConsumer<V> action); static Optional<T> head(List<T> clusters); static Optional<IntCollection> intersection(Collection<IntCollection> clusters); static IntSet merge(IntSet left, IntCollection right); static IntCollection merge(IntCollection left, IntCollection right); static Collection<T> merge(Collection<T> left, Collection<T> right); static Predicate<Collection<T>> sizeBelow(int maxSize); static List<T> sort(Collection<T> collection, Comparator<T> comparator); static Collection<T> tail(List<T> clusters); static Collection<String> toString(Iterable<T> objects); }### Answer: @Test public void testMerge() { IntSet set1 = mutableSingleton(1); IntSet set2 = mutableSingleton(2); IntSet merged = merge(set1, set2); assertThat(merged).hasSize(2); assertThat(merged).contains(1, 2); set1.add(3); assertThat(set1).hasSize(3); assertThat(set1).contains(1, 2, 3); }
### Question: BigDecimalUtils { public static BigDecimal valueOf(int number) { return 0 <= number && number < NUMBERS.length ? NUMBERS[number] : BigDecimal.valueOf(number); } static BigDecimal valueOf(int number); }### Answer: @Test public void test() { assertThat(BigDecimalUtils.valueOf(0).intValue()).isEqualTo(0); assertThat(BigDecimalUtils.valueOf(100).intValue()).isEqualTo(100); assertThat(BigDecimalUtils.valueOf(1000).intValue()).isEqualTo(1000); }
### Question: RowImpl extends AbstractRow { @Override public <T> Optional<T> get(Column<T> column) { return values.get(column) .map(CastUtils::as); } private RowImpl(Schema schema, Map<Column<?>, Object> values); @Override Optional<T> get(Column<T> column); }### Answer: @Test public void testGet() { Row row = createRow(); Optional<String> a = row.get(A); assertThat(a).hasValue("foo"); Optional<Integer> b = row.get(B); assertThat(b).hasValue(Integer.valueOf(0)); assertThat(row.get(C)).isEmpty(); } @Test public void testWrongType() { Row row = createRow(); Column<String> wrongB = Column.of("b", String.class); assertThat(row.get(wrongB)).isEmpty(); }
### Question: SimpleColumnCombination implements Comparable<SimpleColumnCombination> { public boolean startsWith(SimpleColumnCombination other) { if (table != other.table) { return false; } Verify.verify(columns.length == other.columns.length); for (int i = 0; i < columns.length - 1; i++) { if (columns[i] != other.columns[i]) { return false; } } return true; } SimpleColumnCombination(int table, int[] columns); private SimpleColumnCombination(int table, int[] columns, int additionalColumn); boolean isActive(); void setActive(boolean active); long getDistinctCount(); static SimpleColumnCombination create(int table, int... columns); SimpleColumnCombination flipOff(int position); int getTable(); int getColumn(int index); int[] getColumns(); boolean startsWith(SimpleColumnCombination other); SimpleColumnCombination combineWith(SimpleColumnCombination other, Map<SimpleColumnCombination, SimpleColumnCombination> columnCombinations); int lastColumn(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(SimpleColumnCombination o); @Override String toString(); int setIndex(); void setIndex(int index); }### Answer: @Test public void testStartsWith() throws Exception { SimpleColumnCombination a = SimpleColumnCombination.create(TABLE, 2,3,5); SimpleColumnCombination b = SimpleColumnCombination.create(TABLE+1, 2,3,5); SimpleColumnCombination c = SimpleColumnCombination.create(TABLE, 2,3,7); SimpleColumnCombination d = SimpleColumnCombination.create(TABLE, 1,3,5); assertThat(a.startsWith(a), is(true)); assertThat(a.startsWith(b), is(false)); assertThat(a.startsWith(c), is(true)); assertThat(a.startsWith(d), is(false)); assertThat(b.startsWith(a), is(false)); assertThat(b.startsWith(b), is(true)); assertThat(b.startsWith(c), is(false)); assertThat(b.startsWith(d), is(false)); assertThat(c.startsWith(a), is(true)); assertThat(c.startsWith(b), is(false)); assertThat(c.startsWith(c), is(true)); assertThat(c.startsWith(d), is(false)); }
### Question: ColumnPair implements Serializable, Hashable { public Class<T> getType() { return left.getType(); } Class<T> getType(); @Override void hash(Hasher hasher); @Override String toString(); }### Answer: @Test public void test() { Column<Integer> left = Column.of("a", Integer.class); Column<Integer> right = Column.of("a", Integer.class); ColumnPair<Integer> pair = new ColumnPair<>(left, right); assertThat(pair.getType()).isEqualTo(Integer.class); assertThat(pair.getType()).isEqualTo(left.getType()); assertThat(pair.getType()).isEqualTo(right.getType()); }
### Question: ResultSetRelation implements Relation { @Override public RelationalInput open() throws InputOpenException { return open(query); } @Override Schema getSchema(); @Override long getSize(); @Override RelationalInput open(); @Override void hash(Hasher hasher); }### Answer: @Test public void testOpen() throws SQLException, InputCloseException, InputOpenException { try (Statement statement = connection.createStatement()) { String query = "SELECT * FROM Person"; Relation relation = new ResultSetRelation(statement, query); try (RelationalInput input = relation.open()) { Row bob = input.iterator().next(); assertThat(bob.get(NAME)).hasValue("Bob"); } try (RelationalInput input = relation.open()) { Row bob = input.iterator().next(); assertThat(bob.get(NAME)).hasValue("Bob"); } } }
### Question: ResultSetRelation implements Relation { @Override public long getSize() throws InputException { try (ResultSet resultSet = executeQuery("SELECT COUNT(*) FROM (" + query + ") rel")) { if (resultSet.next()) { return resultSet.getLong(1); } throw new IllegalStateException("No count returned"); } catch (SQLException e) { throw new InputOpenException(e); } } @Override Schema getSchema(); @Override long getSize(); @Override RelationalInput open(); @Override void hash(Hasher hasher); }### Answer: @Test public void testSize() throws SQLException, InputException { try (Statement statement = connection.createStatement()) { String query = "SELECT * FROM Person"; Relation relation = new ResultSetRelation(statement, query); assertThat(relation.getSize()).isEqualTo(3L); } try (Statement statement = connection.createStatement()) { String query = "SELECT * FROM PERSON WHERE name IS NULL"; Relation relation = new ResultSetRelation(statement, query); assertThat(relation.getSize()).isEqualTo(0L); } }
### Question: ResultSetInput implements RelationalInput { static RelationalInput create(ResultSet resultSet) { ResultSetIterator rows = ResultSetIterator.create(resultSet); return new ResultSetInput(rows); } @Override void close(); @Override Schema getSchema(); @Override Iterator<Row> iterator(); }### Answer: @Test public void testNumberOfRows() throws SQLException, InputCloseException { try (Statement statement = connection.createStatement()) { ResultSet resultSet = statement.executeQuery("SELECT * FROM Person"); try (RelationalInput input = ResultSetInput.create(resultSet)) { assertThat(Iterables.size(input)).isEqualTo(3); } } }
### Question: ResultSetSchemaFactory { static Schema createSchema(ResultSetMetaData metaData) throws SQLException { return new ResultSetSchemaFactory(metaData).createSchema(); } }### Answer: @Test public void test() throws SQLException { when(Integer.valueOf(metaData.getColumnCount())).thenReturn(Integer.valueOf(2)); doReturn(String.class.getName()).when(metaData).getColumnClassName(1); doReturn(Integer.class.getName()).when(metaData).getColumnClassName(2); doReturn("a").when(metaData).getColumnName(1); doReturn("b").when(metaData).getColumnName(2); Schema schema = ResultSetSchemaFactory.createSchema(metaData); assertThat(schema.getColumns()).hasSize(2); assertThat(schema.getColumns()).contains(Column.of("a", String.class)); assertThat(schema.getColumns()).contains(Column.of("b", Integer.class)); } @Test public void testClassNotFound() throws SQLException { when(Integer.valueOf(metaData.getColumnCount())).thenReturn(Integer.valueOf(1)); when(metaData.getColumnClassName(1)).thenReturn("foo.bar.Baz"); Schema schema = ResultSetSchemaFactory.createSchema(metaData); assertThat(schema.getColumns()).isEmpty(); } @Test public void testTableName() throws SQLException { when(Integer.valueOf(metaData.getColumnCount())).thenReturn(Integer.valueOf(1)); when(metaData.getColumnClassName(1)).thenReturn(String.class.getName()); when(metaData.getColumnName(1)).thenReturn("a"); when(metaData.getTableName(1)).thenReturn("t"); Schema schema = ResultSetSchemaFactory.createSchema(metaData); assertThat(schema.getColumns()).hasSize(1); assertThat(schema.getColumns()).contains(Column.of("a", String.class, "t")); }
### Question: ResultTransformer { MatchingDependencyResult transform(SupportedMD supportedMD) { return with(supportedMD).toResult(); } }### Answer: @Test public void test() { ResultTransformer transformer = createConsumer(); MD md = new MDImpl(new MDSiteImpl(2).set(0, 0.8), new MDElementImpl(1, 0.7)); SupportedMD result = new SupportedMD(md, 10); MatchingDependencyResult transformed = transformer.transform(result); MatchingDependency dependency = new MatchingDependency( Collections.singletonList( new ColumnMatchWithThreshold<>(new ColumnMapping<>(AB, similarityMeasure), 0.8)), new ColumnMatchWithThreshold<>(new ColumnMapping<>(AC, similarityMeasure), 0.7) ); assertThat(transformed).isEqualTo(new MatchingDependencyResult(dependency, 10)); }
### Question: SimilaritySet { public double get(int attr) { return similaritySet[attr]; } double get(int attr); boolean isViolated(MDElement element); int size(); @Override String toString(); }### Answer: @Test public void testGet() { SimilaritySet similaritySet = new SimilaritySet(new double[]{0.2, 0.3}); assertThat(similaritySet.get(0)).isEqualTo(0.2); assertThat(similaritySet.get(1)).isEqualTo(0.3); }
### Question: SimpleColumnCombination implements Comparable<SimpleColumnCombination> { public SimpleColumnCombination combineWith(SimpleColumnCombination other, Map<SimpleColumnCombination, SimpleColumnCombination> columnCombinations) { Verify.verify(table == other.table, "only merge inside a table"); SimpleColumnCombination combinedCombination = new SimpleColumnCombination(table, columns, other.lastColumn()); if (columnCombinations != null) { SimpleColumnCombination existingCombination = columnCombinations.get(combinedCombination); if (existingCombination == null) { columnCombinations.put(combinedCombination, combinedCombination); } else { combinedCombination = existingCombination; } } return combinedCombination; } SimpleColumnCombination(int table, int[] columns); private SimpleColumnCombination(int table, int[] columns, int additionalColumn); boolean isActive(); void setActive(boolean active); long getDistinctCount(); static SimpleColumnCombination create(int table, int... columns); SimpleColumnCombination flipOff(int position); int getTable(); int getColumn(int index); int[] getColumns(); boolean startsWith(SimpleColumnCombination other); SimpleColumnCombination combineWith(SimpleColumnCombination other, Map<SimpleColumnCombination, SimpleColumnCombination> columnCombinations); int lastColumn(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(SimpleColumnCombination o); @Override String toString(); int setIndex(); void setIndex(int index); }### Answer: @Test public void testCombineWith() throws Exception { SimpleColumnCombination a = SimpleColumnCombination.create(TABLE, 2,3,6); SimpleColumnCombination b = SimpleColumnCombination.create(TABLE, 2,3,7); SimpleColumnCombination result = SimpleColumnCombination.create(TABLE, 2, 3, 6, 7); assertThat(a.combineWith(b, null), equalTo(result)); }
### Question: SimilaritySet { public boolean isViolated(MDElement element) { int attr = element.getId(); return element.getThreshold() > similaritySet[attr]; } double get(int attr); boolean isViolated(MDElement element); int size(); @Override String toString(); }### Answer: @Test public void testIsViolated() { SimilaritySet similaritySet = new SimilaritySet(new double[]{0.2, 0.3}); assertThat(similaritySet.isViolated(new MDElementImpl(0, 0.1))).isFalse(); assertThat(similaritySet.isViolated(new MDElementImpl(0, 0.2))).isFalse(); assertThat(similaritySet.isViolated(new MDElementImpl(0, 0.3))).isTrue(); }
### Question: LatticeHelper { static Lattice createLattice(LevelFunction levelFunction) { int columnPairs = levelFunction.size(); Lattice lattice = new LatticeImpl(levelFunction); MDSite lhs = new MDSiteImpl(columnPairs); for (int rhsAttr = 0; rhsAttr < columnPairs; rhsAttr++) { MD md = createMD(lhs, rhsAttr); lattice.add(md); } return lattice; } }### Answer: @Test public void testCreate() { int columnPairs = 4; Lattice lattice = LatticeHelper.createLattice(new Cardinality(columnPairs)); assertThat(lattice.getDepth()).isEqualTo(0); assertThat(lattice.getLevel(0)).hasSize(1); assertThat(lattice.containsMdOrGeneralization( new MDImpl(new MDSiteImpl(columnPairs), new MDElementImpl(0, SimilarityMeasure.MAX_SIMILARITY)))).isEqualTo(true); assertThat(lattice.containsMdOrGeneralization( new MDImpl(new MDSiteImpl(columnPairs), new MDElementImpl(1, SimilarityMeasure.MAX_SIMILARITY)))).isEqualTo(true); assertThat(lattice.containsMdOrGeneralization( new MDImpl(new MDSiteImpl(columnPairs), new MDElementImpl(2, SimilarityMeasure.MAX_SIMILARITY)))).isEqualTo(true); assertThat(lattice.containsMdOrGeneralization( new MDImpl(new MDSiteImpl(columnPairs), new MDElementImpl(3, SimilarityMeasure.MAX_SIMILARITY)))).isEqualTo(true); }
### Question: Classifier { public boolean isValidAndMinimal(double similarity) { return isValid(similarity) && isMinimal(similarity); } boolean isValidAndMinimal(double similarity); }### Answer: @Test public void testLowerBound() { Classifier classifier = new Classifier(0.0, 0.5); assertThat(classifier.isValidAndMinimal(0.6)).isTrue(); assertThat(classifier.isValidAndMinimal(0.5)).isFalse(); } @Test public void testMinThreshold() { Classifier classifier = new Classifier(0.5, 0.0); assertThat(classifier.isValidAndMinimal(0.5)).isTrue(); assertThat(classifier.isValidAndMinimal(0.4)).isFalse(); } @Test public void testMinThresholdAndLowerBound() { Classifier classifier = new Classifier(0.5, 0.5); assertThat(classifier.isValidAndMinimal(0.6)).isTrue(); assertThat(classifier.isValidAndMinimal(0.5)).isFalse(); }
### Question: FullLattice { public Optional<LatticeMD> addIfMinimalAndSupported(MD md) { MDSite lhs = md.getLhs(); if (notSupported.containsMdOrGeneralization(lhs)) { return Optional.empty(); } return lattice.addIfMinimal(md); } Optional<LatticeMD> addIfMinimalAndSupported(MD md); Collection<LatticeMD> findViolated(SimilaritySet similaritySet); int getDepth(); Collection<LatticeMD> getLevel(int level); void markNotSupported(MDSite lhs); int size(); }### Answer: @Test public void testAddNotSupported() { FullLattice fullLattice = new FullLattice(lattice, notSupported); int columnPairs = 4; MDSite lhs = new MDSiteImpl(columnPairs).set(0, 0.5); when(Boolean.valueOf(notSupported.containsMdOrGeneralization(lhs))).thenReturn(Boolean.TRUE); MD md = new MDImpl(lhs, new MDElementImpl(1, 0.7)); Optional<LatticeMD> latticeMD = fullLattice.addIfMinimalAndSupported(md); assertThat(latticeMD).isEmpty(); verify(lattice, never()).addIfMinimal(md); } @Test public void testAddSupported() { FullLattice fullLattice = new FullLattice(lattice, notSupported); int columnPairs = 4; MDSite lhs = new MDSiteImpl(columnPairs).set(0, 0.5); when(Boolean.valueOf(notSupported.containsMdOrGeneralization(lhs))).thenReturn(Boolean.FALSE); MD md = new MDImpl(lhs, new MDElementImpl(1, 0.7)); LatticeMD latticeMD = Mockito.mock(LatticeMD.class); when(lattice.addIfMinimal(md)).thenReturn(Optional.of(latticeMD)); assertThat(fullLattice.addIfMinimalAndSupported(md)).hasValue(latticeMD); verify(lattice).addIfMinimal(md); }
### Question: FullLattice { public Collection<LatticeMD> findViolated(SimilaritySet similaritySet) { return lattice.findViolated(similaritySet); } Optional<LatticeMD> addIfMinimalAndSupported(MD md); Collection<LatticeMD> findViolated(SimilaritySet similaritySet); int getDepth(); Collection<LatticeMD> getLevel(int level); void markNotSupported(MDSite lhs); int size(); }### Answer: @Test public void testFindViolated() { FullLattice fullLattice = new FullLattice(lattice, notSupported); LatticeMD latticeMD = Mockito.mock(LatticeMD.class); SimilaritySet similaritySet = Mockito.mock(SimilaritySet.class); when(lattice.findViolated(similaritySet)).thenReturn(Collections.singletonList(latticeMD)); Collection<LatticeMD> violated = fullLattice.findViolated(similaritySet); assertThat(violated).hasSize(1); assertThat(violated).contains(latticeMD); verify(lattice).findViolated(similaritySet); }
### Question: FullLattice { public int getDepth() { return lattice.getDepth(); } Optional<LatticeMD> addIfMinimalAndSupported(MD md); Collection<LatticeMD> findViolated(SimilaritySet similaritySet); int getDepth(); Collection<LatticeMD> getLevel(int level); void markNotSupported(MDSite lhs); int size(); }### Answer: @Test public void testGetDepth() { FullLattice fullLattice = new FullLattice(lattice, notSupported); when(Integer.valueOf(lattice.getDepth())).thenReturn(Integer.valueOf(2)); assertThat(fullLattice.getDepth()).isEqualTo(2); verify(lattice).getDepth(); }
### Question: FullLattice { public Collection<LatticeMD> getLevel(int level) { Collection<LatticeMD> candidates = lattice.getLevel(level); return StreamUtils.seq(candidates) .filter(this::isSupported) .toList(); } Optional<LatticeMD> addIfMinimalAndSupported(MD md); Collection<LatticeMD> findViolated(SimilaritySet similaritySet); int getDepth(); Collection<LatticeMD> getLevel(int level); void markNotSupported(MDSite lhs); int size(); }### Answer: @Test public void testGetLevel() { FullLattice fullLattice = new FullLattice(lattice, notSupported); LatticeMD latticeMD = Mockito.mock(LatticeMD.class); when(lattice.getLevel(1)).thenReturn(Collections.singletonList(latticeMD)); Collection<LatticeMD> level = fullLattice.getLevel(1); assertThat(level).hasSize(1); assertThat(level).contains(latticeMD); verify(lattice).getLevel(1); }
### Question: SimpleColumnCombination implements Comparable<SimpleColumnCombination> { public SimpleColumnCombination flipOff(int position) { int[] newColumns = new int[columns.length - 1]; System.arraycopy(columns, 0, newColumns, 0, position); System.arraycopy(columns, position + 1, newColumns, position, columns.length - position - 1); return new SimpleColumnCombination(table, newColumns); } SimpleColumnCombination(int table, int[] columns); private SimpleColumnCombination(int table, int[] columns, int additionalColumn); boolean isActive(); void setActive(boolean active); long getDistinctCount(); static SimpleColumnCombination create(int table, int... columns); SimpleColumnCombination flipOff(int position); int getTable(); int getColumn(int index); int[] getColumns(); boolean startsWith(SimpleColumnCombination other); SimpleColumnCombination combineWith(SimpleColumnCombination other, Map<SimpleColumnCombination, SimpleColumnCombination> columnCombinations); int lastColumn(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(SimpleColumnCombination o); @Override String toString(); int setIndex(); void setIndex(int index); }### Answer: @Test public void testFlipOff() throws Exception { SimpleColumnCombination a = SimpleColumnCombination.create(TABLE, 1,2,3); SimpleColumnCombination b = a.flipOff(0); SimpleColumnCombination c = a.flipOff(1); SimpleColumnCombination d = a.flipOff(2); assertThat(b, equalTo(SimpleColumnCombination.create(TABLE, 2, 3))); assertThat(c, equalTo(SimpleColumnCombination.create(TABLE, 1, 3))); assertThat(d, equalTo(SimpleColumnCombination.create(TABLE, 1, 2))); }
### Question: FullLattice { public void markNotSupported(MDSite lhs) { notSupported.addIfMinimal(lhs); } Optional<LatticeMD> addIfMinimalAndSupported(MD md); Collection<LatticeMD> findViolated(SimilaritySet similaritySet); int getDepth(); Collection<LatticeMD> getLevel(int level); void markNotSupported(MDSite lhs); int size(); }### Answer: @Test public void testMarkNotSupported() { FullLattice fullLattice = new FullLattice(lattice, notSupported); int columnPairs = 4; MDSite lhs = new MDSiteImpl(columnPairs).set(0, 0.5); fullLattice.markNotSupported(lhs); verify(notSupported).addIfMinimal(lhs); }
### Question: ThresholdLowerer { public void lowerThreshold(int rhsAttr, double threshold) { MDElement rhs = new MDElementImpl(rhsAttr, threshold); lowerThreshold(rhs); } void lowerThreshold(int rhsAttr, double threshold); void lowerThreshold(MDElement rhs, boolean minimal); }### Answer: @Test public void testMinimal() { int rhsAttr = 0; double threshold = 0.1; ThresholdLowerer task = new ThresholdLowerer(latticeMd); when(Boolean.valueOf(latticeMd.wouldBeMinimal(new MDElementImpl(rhsAttr, threshold)))).thenReturn(Boolean.TRUE); when(latticeMd.getLhs()).thenReturn(lhs); task.lowerThreshold(rhsAttr, threshold); verify(latticeMd).setRhs(rhsAttr, threshold); } @Test public void testNotMinimal() { int rhsAttr = 0; double threshold = 0.1; ThresholdLowerer task = new ThresholdLowerer(latticeMd); when(Boolean.valueOf(latticeMd.wouldBeMinimal(new MDElementImpl(rhsAttr, threshold)))).thenReturn(Boolean.FALSE); when(latticeMd.getLhs()).thenReturn(lhs); task.lowerThreshold(rhsAttr, threshold); verify(latticeMd).removeRhs(rhsAttr); verify(latticeMd, never()).setRhs(rhsAttr, threshold); } @Test public void testTrivial() { int rhsAttr = 0; double threshold = 0.1; ThresholdLowerer task = new ThresholdLowerer(latticeMd); when(Boolean.valueOf(latticeMd.wouldBeMinimal(new MDElementImpl(rhsAttr, threshold)))).thenReturn(Boolean.TRUE); when(latticeMd.getLhs()).thenReturn(lhs); when(Double.valueOf(lhs.getOrDefault(0))).thenReturn(Double.valueOf(0.1)); task.lowerThreshold(rhsAttr, threshold); verify(latticeMd).removeRhs(rhsAttr); verify(latticeMd, never()).setRhs(rhsAttr, threshold); }
### Question: SimilaritySetProcessor { @Timed Statistics process(SimilaritySet similaritySet) { return with(similaritySet).process(); } }### Answer: @SuppressWarnings("unchecked") @Test public void test() { SimilaritySetProcessor processor = createProcessor(); SimilaritySet similaritySet = Mockito.mock(SimilaritySet.class); LatticeMD latticeMD = Mockito.mock(LatticeMD.class); MDSite lhs = Mockito.mock(MDSite.class); when(latticeMD.getLhs()).thenReturn(lhs); when(lattice.findViolated(similaritySet)) .thenReturn(Collections.singletonList(latticeMD), Collections.emptyList()); int rhsAttr = 0; MDElement rhs = new MDElementImpl(rhsAttr, 0.5); when(latticeMD.getRhs()).thenReturn(Collections.singletonList(rhs)); when(Boolean.valueOf(similaritySet.isViolated(rhs))).thenReturn(Boolean.TRUE); when(Double.valueOf(similaritySet.get(rhsAttr))).thenReturn(Double.valueOf(0.4)); when(specializer.specialize(lhs, rhs, similaritySet)).thenReturn(Collections.emptyList()); when(Boolean.valueOf(latticeMD.wouldBeMinimal(new MDElementImpl(rhsAttr, 0.4)))).thenReturn(Boolean.FALSE); processor.process(similaritySet); verify(latticeMD).removeRhs(rhsAttr); verify(lattice, never()).addIfMinimalAndSupported(any()); }
### Question: SamplerImpl implements Sampler { @Timed @Override public Optional<Set<SimilaritySet>> sample() { return IteratorUtils.next(left) .map(this::sample); } @Timed @Override Set<SimilaritySet> processRecommendations(Collection<IntArrayPair> recommendations); @Timed @Override Optional<Set<SimilaritySet>> sample(); }### Answer: @Test public void test() { Collection<int[]> left = ImmutableList.<int[]>builder() .add(new int[]{0, 0}) .build(); when(leftRecords.iterator()).thenReturn(left.iterator()); Sampler sampler = createSampler(); doReturn(Double.valueOf(1.0)).when(col1).getSimilarity(new int[]{0, 0}, new int[]{0, 0}); doReturn(Double.valueOf(0.0)).when(col1).getSimilarity(new int[]{0, 0}, new int[]{1, 1}); doReturn(Double.valueOf(0.5)).when(col2).getSimilarity(new int[]{0, 0}, new int[]{0, 0}); doReturn(Double.valueOf(0.3)).when(col2).getSimilarity(new int[]{0, 0}, new int[]{1, 1}); Optional<Set<SimilaritySet>> similaritySets = sampler.sample(); Assert.assertThat(similaritySets, isPresentAnd(hasSize(2))); Assert.assertThat(similaritySets, isPresentAnd(hasItem(new SimilaritySet(new double[]{1.0, 0.5})))); Assert.assertThat(similaritySets, isPresentAnd(hasItem(new SimilaritySet(new double[]{0.0, 0.3})))); } @Test public void testMultiple() { Collection<int[]> left = ImmutableList.<int[]>builder() .add(new int[]{0, 0}) .build(); when(leftRecords.iterator()).thenReturn(left.iterator()); Sampler sampler = createSampler(); doReturn(Double.valueOf(1.0)).when(col1).getSimilarity(new int[]{0, 0}, new int[]{0, 0}); doReturn(Double.valueOf(0.0)).when(col1).getSimilarity(new int[]{0, 0}, new int[]{1, 1}); doReturn(Double.valueOf(0.5)).when(col2).getSimilarity(new int[]{0, 0}, new int[]{0, 0}); doReturn(Double.valueOf(0.3)).when(col2).getSimilarity(new int[]{0, 0}, new int[]{1, 1}); sampler.sample(); Optional<Set<SimilaritySet>> similaritySets = sampler.sample(); assertThat(similaritySets).isEmpty(); }
### Question: SamplerImpl implements Sampler { @Timed @Override public Set<SimilaritySet> processRecommendations(Collection<IntArrayPair> recommendations) { return StreamUtils.stream(recommendations, parallel) .map(this::calculateSimilaritySet) .collect(Collectors.toSet()); } @Timed @Override Set<SimilaritySet> processRecommendations(Collection<IntArrayPair> recommendations); @Timed @Override Optional<Set<SimilaritySet>> sample(); }### Answer: @Test public void testDuplicateRecommendations() { when(leftRecords.iterator()).thenReturn(Collections.emptyIterator()); Sampler sampler = createSampler(); doReturn(Double.valueOf(1.0)).when(col1).getSimilarity(new int[]{0, 0}, new int[]{0, 0}); doReturn(Double.valueOf(0.5)).when(col2).getSimilarity(new int[]{0, 0}, new int[]{0, 0}); Collection<SimilaritySet> similaritySets = sampler .processRecommendations( Arrays.asList(new IntArrayPair(new int[]{0, 0}, new int[]{0, 0}), new IntArrayPair(new int[]{0, 0}, new int[]{0, 0}))); assertThat(similaritySets).hasSize(1); assertThat(similaritySets).contains(new SimilaritySet(new double[]{1.0, 0.5})); } @Test public void testWithRecommendations() { when(leftRecords.iterator()).thenReturn(Collections.emptyIterator()); Sampler sampler = createSampler(); doReturn(Double.valueOf(1.0)).when(col1).getSimilarity(new int[]{0, 0}, new int[]{0, 0}); doReturn(Double.valueOf(0.0)).when(col1).getSimilarity(new int[]{0, 0}, new int[]{1, 1}); doReturn(Double.valueOf(0.5)).when(col2).getSimilarity(new int[]{0, 0}, new int[]{0, 0}); doReturn(Double.valueOf(0.3)).when(col2).getSimilarity(new int[]{0, 0}, new int[]{1, 1}); Collection<SimilaritySet> similaritySets = sampler .processRecommendations( Arrays.asList(new IntArrayPair(new int[]{0, 0}, new int[]{0, 0}), new IntArrayPair(new int[]{0, 0}, new int[]{1, 1}))); assertThat(similaritySets).hasSize(2); assertThat(similaritySets).contains(new SimilaritySet(new double[]{1.0, 0.5})); assertThat(similaritySets).contains(new SimilaritySet(new double[]{0.0, 0.3})); }
### Question: MDSpecializer { Collection<MD> specialize(MDSite lhs, MDElement rhs, SimilaritySet similaritySet) { return specializer.specialize(lhs, rhs, similaritySet::get); } }### Answer: @Test public void test() { MDSpecializer specializer = buildSpecializer(); int columnPairs = 4; MDSite lhs = new MDSiteImpl(columnPairs).set(1, 0.7); SimilaritySet similaritySet = new SimilaritySet(new double[]{0.7, 0.8, 0.6, 0.5}); doReturn(Optional.of(new MDSiteImpl(columnPairs).set(0, 0.8))).when(lhsSpecializer) .specialize(lhs, 0, similaritySet.get(0)); doReturn(Optional.empty()).when(lhsSpecializer) .specialize(lhs, 1, similaritySet.get(1)); doReturn(Optional.of(new MDSiteImpl(columnPairs).set(2, 0.7))).when(lhsSpecializer) .specialize(lhs, 2, similaritySet.get(2)); doReturn(Optional.of(new MDSiteImpl(columnPairs).set(3, 0.9))).when(lhsSpecializer) .specialize(lhs, 3, similaritySet.get(3)); when(Boolean.valueOf(specializationFilter.filter(any(), any()))).thenReturn(Boolean.TRUE); int rhsAttr = 3; MDElement rhs = new MDElementImpl(rhsAttr, 0.8); Collection<MD> specialized = specializer.specialize(lhs, rhs, similaritySet); assertThat(specialized).hasSize(3); assertThat(specialized).contains(new MDImpl(new MDSiteImpl(columnPairs).set(0, 0.8), new MDElementImpl(rhsAttr, 0.8))); assertThat(specialized).contains(new MDImpl(new MDSiteImpl(columnPairs).set(2, 0.7), new MDElementImpl(rhsAttr, 0.8))); assertThat(specialized).contains(new MDImpl(new MDSiteImpl(columnPairs).set(3, 0.9), new MDElementImpl(rhsAttr, 0.8))); }
### Question: Statistics { void add(Statistics statistics) { this.count += statistics.count; this.processed += statistics.processed; this.newDeduced += statistics.newDeduced; this.recommendations += statistics.recommendations; } }### Answer: @Test public void testAdd() { Statistics statistics = new Statistics(); statistics.count(); Statistics toAdd = new Statistics(); toAdd.count(); toAdd.newDeduced(); statistics.add(toAdd); assertThat(statistics.getCount()).isEqualTo(2); assertThat(statistics.getNewDeduced()).isEqualTo(1); }
### Question: Statistics { void count() { count++; } }### Answer: @Test public void testCount() { Statistics statistics = new Statistics(); assertThat(statistics.getCount()).isEqualTo(0); statistics.count(); assertThat(statistics.getCount()).isEqualTo(1); }
### Question: Statistics { void newDeduced() { newDeduced++; } }### Answer: @Test public void testNewDeduced() { Statistics statistics = new Statistics(); assertThat(statistics.getNewDeduced()).isEqualTo(0); statistics.newDeduced(); assertThat(statistics.getNewDeduced()).isEqualTo(1); }
### Question: Compressor { CompressedRelation compress(Iterable<Row> input) { input.forEach(this::add); return toRelation(); } }### Answer: @Test public void testDictionaryA() { mock(); CompressedRelation compressed = compress(); CompressedColumn<String> column = compressed.getColumn(0); Dictionary<String> dictionary = column.getDictionary(); assertThat(dictionary.values()).hasSize(3); assertThat(dictionary.values()).contains("foo"); assertThat(dictionary.values()).contains("bar"); assertThat(dictionary.values()).contains("baz"); assertThat(dictionary.getOrAdd("foo")).isEqualTo(0); assertThat(dictionary.getOrAdd("bar")).isEqualTo(1); assertThat(dictionary.getOrAdd("baz")).isEqualTo(2); } @Test public void testDictionaryB() { mock(); CompressedRelation compressed = compress(); CompressedColumn<Integer> column = compressed.getColumn(1); Dictionary<Integer> dictionary = column.getDictionary(); assertThat(dictionary.values()).hasSize(2); assertThat(dictionary.values()).contains(Integer.valueOf(2)); assertThat(dictionary.values()).contains(Integer.valueOf(1)); assertThat(dictionary.getOrAdd(Integer.valueOf(2))).isEqualTo(0); assertThat(dictionary.getOrAdd(Integer.valueOf(1))).isEqualTo(1); } @Test public void testDictionaryRecords() { mock(); CompressedRelation compressed = compress(); DictionaryRecords dictionaryRecords = compressed.getDictionaryRecords(); assertThat(dictionaryRecords.getAll()).hasSize(3); assertThat(dictionaryRecords.get(0).length).isEqualTo(2); assertThat(dictionaryRecords.get(1)[1]).isNotEqualTo(dictionaryRecords.get(0)[1]); assertThat(dictionaryRecords.get(1)[1]).isEqualTo(dictionaryRecords.get(2)[1]); } @Test public void testIndexOf() { mock(); CompressedRelation compressed = compress(); assertThat(compressed.indexOf(A)).isEqualTo(0); assertThat(compressed.indexOf(B)).isEqualTo(1); } @Test(expected = RuntimeException.class) public void testInputCloseException() throws InputCloseException { doThrow(InputCloseException.class).when(input).close(); mock(); compress(); fail(); } @Test(expected = RuntimeException.class) public void testInputOpenException() throws InputOpenException { doThrow(InputOpenException.class).when(relation).open(); compress(); fail(); } @Test public void testPliA() { mock(); CompressedRelation compressed = compress(); CompressedColumn<String> column = compressed.getColumn(0); PositionListIndex pli = column.getPli(); assertThat(pli.get(0)).hasSize(1); assertThat(pli.get(1)).hasSize(1); assertThat(pli.get(2)).hasSize(1); assertThat(pli.get(0)).contains(Integer.valueOf(0)); assertThat(pli.get(1)).contains(Integer.valueOf(1)); assertThat(pli.get(2)).contains(Integer.valueOf(2)); } @Test public void testPliB() { mock(); CompressedRelation compressed = compress(); CompressedColumn<Integer> column = compressed.getColumn(1); PositionListIndex pli = column.getPli(); assertThat(pli.get(0)).hasSize(1); assertThat(pli.get(1)).hasSize(2); assertThat(pli.get(0)).contains(Integer.valueOf(0)); assertThat(pli.get(1)).contains(Integer.valueOf(1)); assertThat(pli.get(1)).contains(Integer.valueOf(2)); }
### Question: PreprocessedColumnPairImpl implements PreprocessedColumnPair { @Timed @Override public IntCollection getAllSimilarRightRecords(int[] left, double threshold) { int leftValue = left[leftColumn]; return getAllSimilarRightRecords(leftValue, threshold); } @Timed @Override IntCollection getAllSimilarRightRecords(int[] left, double threshold); @Override IntCollection getAllSimilarRightRecords(int leftValue, double threshold); @Override double getMinSimilarity(); @Override Iterable<Double> getThresholds(ThresholdFilter thresholdFilter); @Override double getSimilarity(int leftValue, int rightValue); @Override int getRightValue(int[] right); @Override int getLeftValue(int[] left); }### Answer: @Test public void testGetAllSimilarRightRecords() { List<PreprocessedColumnPair> columnPairs = create(); PreprocessedColumnPair ab = columnPairs.get(0); assertThat(ab.getAllSimilarRightRecords(new int[]{4}, 0.5)).hasSize(4); assertThat(ab.getAllSimilarRightRecords(new int[]{4}, 0.5)).contains(Integer.valueOf(51)); assertThat(ab.getAllSimilarRightRecords(new int[]{4}, 0.5)).contains(Integer.valueOf(52)); assertThat(ab.getAllSimilarRightRecords(new int[]{4}, 0.5)).contains(Integer.valueOf(81)); assertThat(ab.getAllSimilarRightRecords(new int[]{4}, 0.5)).contains(Integer.valueOf(82)); assertThat(ab.getAllSimilarRightRecords(new int[]{4}, 0.6)).hasSize(2); assertThat(ab.getAllSimilarRightRecords(new int[]{4}, 0.6)).contains(Integer.valueOf(51)); assertThat(ab.getAllSimilarRightRecords(new int[]{4}, 0.6)).contains(Integer.valueOf(52)); }
### Question: PreprocessedColumnPairImpl implements PreprocessedColumnPair { @Override public double getSimilarity(int leftValue, int rightValue) { return similarityIndex.getSimilarity(leftValue, rightValue); } @Timed @Override IntCollection getAllSimilarRightRecords(int[] left, double threshold); @Override IntCollection getAllSimilarRightRecords(int leftValue, double threshold); @Override double getMinSimilarity(); @Override Iterable<Double> getThresholds(ThresholdFilter thresholdFilter); @Override double getSimilarity(int leftValue, int rightValue); @Override int getRightValue(int[] right); @Override int getLeftValue(int[] left); }### Answer: @Test public void testGetSimilarity() { List<PreprocessedColumnPair> columnPairs = create(); PreprocessedColumnPair ab = columnPairs.get(0); assertThat(ab.getSimilarity(new int[]{4}, new int[]{5, 0})).isEqualTo(0.8); assertThat(ab.getSimilarity(new int[]{4}, new int[]{8, 0})).isEqualTo(0.5); }
### Question: ValidationTask { AnalyzeTask validate() { ValidationResult results = validator.validate(lhs, rhs); return new AnalyzeTask(results, lowerer); } }### Answer: @Test public void test() { int columnPairs = 4; Collection<Rhs> rhs = Arrays .asList(Rhs.builder().rhsAttr(0).threshold(1.0).lowerBound(0.0).build(), Rhs.builder().rhsAttr(1).threshold(1.0).lowerBound(0.0).build()); MDSite lhs = new MDSiteImpl(columnPairs); RhsResult expected1 = RhsResult.builder() .rhsAttr(0) .threshold(0.5) .violations(Collections.emptyList()) .validAndMinimal(false) .build(); RhsResult expected2 = RhsResult.builder() .rhsAttr(1) .threshold(0.6) .violations(Collections.emptyList()) .validAndMinimal(true) .build(); when(validator.validate(lhs, rhs)) .thenReturn(new ValidationResult(Mockito.mock(LhsResult.class), Arrays.asList(expected1, expected2))); ValidationTask task = createTask(lhs, rhs); AnalyzeTask analyzeTask = task.validate(); ValidationResult result = analyzeTask.getResult(); assertThat(result.getRhsResults()).contains(expected1); assertThat(result.getRhsResults()).contains(expected2); }
### Question: CandidateProcessor { Statistics validateAndAnalyze(Collection<Candidate> candidates) { log.debug("Will perform {} validations", Integer.valueOf(candidates.size())); Iterable<AnalyzeTask> results = validator.validate(candidates); results.forEach(violationHandler::addViolations); return analyzer.analyze(results); } }### Answer: @Test public void test() { CandidateProcessor processor = createProcessor(); Collection<Candidate> candidates = Collections.singletonList(Mockito.mock(Candidate.class)); AnalyzeTask task = Mockito.mock(AnalyzeTask.class); Collection<AnalyzeTask> results = Collections .singletonList(task); when(task.getResult()).thenReturn(Mockito.mock(ValidationResult.class)); when(validator.validate(candidates)).thenReturn(results); when(analyzer.analyze(results)).thenReturn(Mockito.mock(Statistics.class)); processor.validateAndAnalyze(candidates); verify(validator).validate(candidates); verify(analyzer).analyze(results); }
### Question: CandidateProcessor { Collection<IntArrayPair> getRecommendations() { return violationHandler.pollViolations(); } }### Answer: @Test public void testGetRecommendations() { CandidateProcessor processor = createProcessor(); Collection<Candidate> candidates = Collections.singletonList(Mockito.mock(Candidate.class)); ValidationResult validationResult = Mockito.mock(ValidationResult.class); Collection<AnalyzeTask> results = Collections .singletonList(new AnalyzeTask(validationResult, Mockito.mock(ThresholdLowerer.class))); RhsResult rhsResult = Mockito.mock(RhsResult.class); when(validationResult.getRhsResults()).thenReturn(Collections.singletonList(rhsResult)); IntArrayPair violation = Mockito.mock(IntArrayPair.class); when(rhsResult.getViolations()).thenReturn(Collections.singletonList(violation)); when(validator.validate(candidates)).thenReturn(results); when(analyzer.analyze(results)).thenReturn(Mockito.mock(Statistics.class)); processor.validateAndAnalyze(candidates); Collection<IntArrayPair> recommendations = processor.getRecommendations(); assertThat(recommendations).hasSize(1); assertThat(recommendations).contains(violation); }
### Question: CandidateBuilder { Collection<Candidate> toCandidates(Iterable<LatticeMD> latticeMDs) { Collection<IntermediateCandidate> preCandidates = toIntermediateCandidates(latticeMDs); Collection<Candidate> candidates = minimizer.toCandidates(preCandidates); candidates.forEach(this::addToValidated); return candidates; } }### Answer: @Test public void test() { CandidateBuilder builder = new CandidateBuilder(0.0, new SimpleMinimizer()); when(latticeMD.getRhs()).thenReturn(new MDSiteImpl(4).set(0, 0.6).set(1, 0.7)); when(latticeMD.getLhs()).thenReturn(Mockito.mock(MDSite.class)); when(latticeMD.getMaxGenThresholds(new int[]{0, 1})).thenReturn(new double[]{0.0, 0.5}); Collection<Candidate> candidates = builder .toCandidates(Collections.singletonList(latticeMD)); assertThat(candidates).hasSize(1); Candidate candidate = Iterables.get(candidates, 0); assertThat(candidate.getRhs()).hasSize(2); assertThat(candidate.getRhs()) .contains(Rhs.builder().rhsAttr(0).threshold(0.6).lowerBound(0.0).build()); assertThat(candidate.getRhs()) .contains(Rhs.builder().rhsAttr(1).threshold(0.7).lowerBound(0.5).build()); assertThat(candidate.getLatticeMd()).isEqualTo(latticeMD); } @Test public void testEmpty() { CandidateBuilder builder = new CandidateBuilder(0.0, new SimpleMinimizer()); when(latticeMD.getRhs()).thenReturn(new MDSiteImpl(4)); Collection<Candidate> candidates = builder .toCandidates(Collections.singletonList(latticeMD)); assertThat(candidates).isEmpty(); } @Test public void testInvalid() { CandidateBuilder builder = new CandidateBuilder(0.7, new SimpleMinimizer()); int columnPairs = 4; when(latticeMD.getLhs()).thenReturn(new MDSiteImpl(columnPairs)); when(latticeMD.getRhs()).thenReturn(new MDSiteImpl(columnPairs).set(0, 0.6).set(1, 0.7)); when(latticeMD.getMaxGenThresholds(new int[]{1})).thenReturn(new double[]{0.5}); Collection<Candidate> candidates = builder .toCandidates(Collections.singletonList(latticeMD)); Candidate candidate = Iterables.get(candidates, 0); Collection<Rhs> rhs = Lists.newArrayList(candidate.getRhs()); assertThat(rhs).hasSize(1); assertThat(rhs).contains(Rhs.builder().rhsAttr(1).threshold(0.7).lowerBound(0.5).build()); assertThat(candidate.getLatticeMd()).isEqualTo(latticeMD); } @Test public void testValidatedBefore() { CandidateBuilder builder = new CandidateBuilder(0.0, new SimpleMinimizer()); when(latticeMD.getRhs()).thenReturn(new MDSiteImpl(4).set(0, 0.6)); when(latticeMD.getLhs()).thenReturn(Mockito.mock(MDSite.class)); builder.toCandidates(Collections.singletonList(latticeMD)); Collection<Candidate> candidates = builder .toCandidates(Collections.singletonList(latticeMD)); assertThat(candidates).isEmpty(); }
### Question: BatchValidator { Iterable<AnalyzeTask> validate(Iterable<Candidate> candidates) { return StreamUtils.stream(candidates, parallel) .map(this::createTask) .map(ValidationTask::validate) .collect(Collectors.toList()); } }### Answer: @Test public void test() { BatchValidator batchValidator = new BatchValidator(validator, parallel); Candidate candidate = Mockito.mock(Candidate.class); LatticeMD latticeMD = Mockito.mock(LatticeMD.class); MDSite lhs = Mockito.mock(MDSite.class); Collection<Rhs> rhs = Collections.emptyList(); ValidationResult validationResult = Mockito.mock(ValidationResult.class); when(candidate.getLatticeMd()).thenReturn(latticeMD); when(candidate.getRhs()).thenReturn(rhs); when(latticeMD.getLhs()).thenReturn(lhs); when(validator.validate(lhs, rhs)).thenReturn(validationResult); Iterable<AnalyzeTask> results = batchValidator .validate(Arrays.asList(candidate, candidate)); assertThat(results).hasSize(2); verify(validator, times(2)).validate(lhs, rhs); }
### Question: SupportBasedFactory implements Factory { @Override public AnalyzeStrategy create(LhsResult lhsResult) { if (isSupported(lhsResult)) { return supportedFactory.create(lhsResult); } return notSupportedFactory.create(lhsResult); } @Override AnalyzeStrategy create(LhsResult lhsResult); }### Answer: @Test public void testNotSupported() { Factory factory = createFactory(); assertThat(factory.create(new LhsResult(Mockito.mock(MDSite.class), 9))) .isInstanceOf(NotSupportedStrategy.class); } @Test public void testSupported() { Factory factory = createFactory(); assertThat(factory.create(new LhsResult(Mockito.mock(MDSite.class), 10))) .isInstanceOf(SupportedStrategy.class); }
### Question: MDSpecializer { Collection<MD> specialize(MD md) { MDSite lhs = md.getLhs(); MDElement rhs = md.getRhs(); return specializer.specialize(lhs, rhs, lhs::getOrDefault); } }### Answer: @Test public void test() { doReturn(OptionalDouble.of(0.8)).when(provider).getNext(0, 0.7); doReturn(OptionalDouble.empty()).when(provider).getNext(1, 1.0); doReturn(OptionalDouble.of(1.0)).when(provider).getNext(2, 0.0); doReturn(OptionalDouble.of(0.6)).when(provider).getNext(3, 0.0); doReturn(OptionalDouble.empty()).when(provider).getNext(4, 0.0); when(Boolean.valueOf(specializationFilter.filter(any(), any()))).thenReturn(Boolean.TRUE); int columnPairs = 5; MDSite lhs = new MDSiteImpl(columnPairs) .set(0, 0.7) .set(1, 1.0); MDElement rhs = new MDElementImpl(3, 0.8); Collection<MD> result = buildSpecializer() .specialize(new MDImpl(lhs, rhs)); assertThat(result).hasSize(3); assertThat(result).contains(new MDImpl(lhs.clone().set(0, 0.8), new MDElementImpl(3, 0.8))); assertThat(result).contains(new MDImpl(lhs.clone().set(2, 1.0), new MDElementImpl(3, 0.8))); assertThat(result).contains(new MDImpl(lhs.clone().set(3, 0.6), new MDElementImpl(3, 0.8))); }
### Question: ViolationHandler { Collection<IntArrayPair> pollViolations() { return violations.poll(); } }### Answer: @Test public void testEmpty() { ViolationHandler violationHandler = new ViolationHandler(); assertThat(violationHandler.pollViolations()).isEmpty(); }
### Question: Statistics { public void add(Statistics statistics) { this.invalid += statistics.invalid; this.notSupported += statistics.notSupported; this.newDeduced += statistics.newDeduced; this.found += statistics.found; this.validated += statistics.validated; this.groupedValidations += statistics.groupedValidations; this.rounds += statistics.rounds; } void add(Statistics statistics); void found(); void groupedValidation(); void invalid(); void newDeduced(); void notSupported(); void round(); void validated(); }### Answer: @Test public void testAdd() { Statistics statistics = new Statistics(); statistics.found(); statistics.invalid(); statistics.newDeduced(); Statistics toAdd = new Statistics(); toAdd.found(); toAdd.found(); toAdd.invalid(); toAdd.validated(); toAdd.groupedValidation(); toAdd.groupedValidation(); toAdd.round(); statistics.add(toAdd); assertThat(statistics.getRounds()).isEqualTo(1); assertThat(statistics.getInvalid()).isEqualTo(2); assertThat(statistics.getNewDeduced()).isEqualTo(1); assertThat(statistics.getNotSupported()).isEqualTo(0); assertThat(statistics.getFound()).isEqualTo(3); assertThat(statistics.getValidated()).isEqualTo(1); assertThat(statistics.getGroupedValidations()).isEqualTo(2); }
### Question: Statistics { public void found() { found++; } void add(Statistics statistics); void found(); void groupedValidation(); void invalid(); void newDeduced(); void notSupported(); void round(); void validated(); }### Answer: @Test public void testFound() { Statistics statistics = new Statistics(); assertThat(statistics.getFound()).isEqualTo(0); statistics.found(); assertThat(statistics.getFound()).isEqualTo(1); }
### Question: Statistics { public void groupedValidation() { groupedValidations++; } void add(Statistics statistics); void found(); void groupedValidation(); void invalid(); void newDeduced(); void notSupported(); void round(); void validated(); }### Answer: @Test public void testGroupedValidations() { Statistics statistics = new Statistics(); assertThat(statistics.getGroupedValidations()).isEqualTo(0); statistics.groupedValidation(); assertThat(statistics.getGroupedValidations()).isEqualTo(1); }
### Question: Statistics { public void invalid() { invalid++; } void add(Statistics statistics); void found(); void groupedValidation(); void invalid(); void newDeduced(); void notSupported(); void round(); void validated(); }### Answer: @Test public void testInvalid() { Statistics statistics = new Statistics(); assertThat(statistics.getInvalid()).isEqualTo(0); statistics.invalid(); assertThat(statistics.getInvalid()).isEqualTo(1); }
### Question: Statistics { public void newDeduced() { newDeduced++; } void add(Statistics statistics); void found(); void groupedValidation(); void invalid(); void newDeduced(); void notSupported(); void round(); void validated(); }### Answer: @Test public void testNewDeduced() { Statistics statistics = new Statistics(); assertThat(statistics.getNewDeduced()).isEqualTo(0); statistics.newDeduced(); assertThat(statistics.getNewDeduced()).isEqualTo(1); }
### Question: HashedColumnStore extends AbstractColumnStore { public ColumnIterator getRows(SimpleColumnCombination activeColumns) { FileInputStream[] in = new FileInputStream[activeColumns.getColumns().length]; int i = 0; for (int col : activeColumns.getColumns()) { try { in[i++] = new FileInputStream(columnFiles[col]); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } return new HashedColumnStore.ColumnIterator(in); } HashedColumnStore(int numColumns, int sampleGoal, boolean isReuseColumnFiles); List<long[]> getSampleFile(); ColumnIterator getRows(SimpleColumnCombination activeColumns); static HashedColumnStore[] create(RelationalInputGenerator[] fileInputGenerators, int sampleGoal, boolean isReuseColumnFiles, boolean isCloseConnectionsRigorously); }### Answer: @Test public void testGetRows() throws Exception { rb.setHeader("col1", "col2", "col3") .addRow("a", "a", "b") .addRow("1", "2", "2"); HashedColumnStore cs = createColumnStore(rb.build().generateNewCopy()); ColumnIterator rows = cs.getRows(); long[] row = rows.next(); assertThat(row[0], equalTo(row[1])); assertThat(row[0], not(equalTo(row[2]))); row = rows.next(); assertThat(row[0], not(equalTo(row[1]))); assertThat(row[1], equalTo(row[2])); assertThat(rows.hasNext(), is(false)); } @Test public void testHasNextTwice() throws Exception { rb.setHeader("col1", "col2").addRow("a", "a"); HashedColumnStore cs = createColumnStore(rb.build().generateNewCopy()); ColumnIterator rows = cs.getRows(); assertThat(rows.hasNext(), is(true)); assertThat(rows.hasNext(), is(true)); long[] row = rows.next(); assertThat(row[0], equalTo(row[1])); assertThat(rows.hasNext(), is(false)); assertThat(rows.hasNext(), is(false)); assertThat(rows.hasNext(), is(false)); } @Test public void testHashCache() throws Exception { rb.setHeader("col1").addRow("a").addRow("a"); HashedColumnStore cs = createColumnStore(rb.build().generateNewCopy()); ColumnIterator rows = cs.getRows(); assertThat(rows.hasNext(), is(true)); long[] row1 = rows.next().clone(); assertThat(rows.hasNext(), is(true)); long[] row2 = rows.next().clone(); assertThat(row1[0], equalTo(row2[0])); assertThat(rows.hasNext(), is(false)); } @Test public void testGetLongRows() throws Exception { int count = 500_000; rb.setHeader("long_col"); for (int i = 0; i < count; i++) { rb.addRow(Integer.toString(i)); } HashedColumnStore cs = createColumnStore(rb.build().generateNewCopy()); ColumnIterator rows = cs.getRows(); HashFunction hashFunction = Hashing.murmur3_128(); int i = 0; while (rows.hasNext()) { long[] row = rows.next(); long hash = hashFunction.hashString(Integer.toString(i), Charsets.UTF_8).asLong(); assertThat("rowindex: " + i, row[0], equalTo(hash)); i++; } assertThat(i, equalTo(count)); }
### Question: Statistics { public void notSupported() { notSupported++; } void add(Statistics statistics); void found(); void groupedValidation(); void invalid(); void newDeduced(); void notSupported(); void round(); void validated(); }### Answer: @Test public void testNotSupported() { Statistics statistics = new Statistics(); assertThat(statistics.getNotSupported()).isEqualTo(0); statistics.notSupported(); assertThat(statistics.getNotSupported()).isEqualTo(1); }
### Question: Statistics { public void round() { rounds++; } void add(Statistics statistics); void found(); void groupedValidation(); void invalid(); void newDeduced(); void notSupported(); void round(); void validated(); }### Answer: @Test public void testRounds() { Statistics statistics = new Statistics(); assertThat(statistics.getRounds()).isEqualTo(0); statistics.round(); assertThat(statistics.getRounds()).isEqualTo(1); }
### Question: Statistics { public void validated() { validated++; } void add(Statistics statistics); void found(); void groupedValidation(); void invalid(); void newDeduced(); void notSupported(); void round(); void validated(); }### Answer: @Test public void testValidated() { Statistics statistics = new Statistics(); assertThat(statistics.getValidated()).isEqualTo(0); statistics.validated(); assertThat(statistics.getValidated()).isEqualTo(1); }
### Question: FileResultWriter implements ResultListener<T>, Closeable { @Override public void receiveResult(T result) { out.println(result); out.flush(); } FileResultWriter(File file); @Override void close(); @Override void receiveResult(T result); }### Answer: @Test public void test() throws IOException { File file = folder.newFile(); try (FileResultWriter<String> resultWriter = new FileResultWriter<>(file)) { resultWriter.receiveResult("foo"); resultWriter.receiveResult("bar"); } try (BufferedReader in = new BufferedReader(new FileReader(file))) { assertThat(in.readLine()).isEqualTo("foo"); assertThat(in.readLine()).isEqualTo("bar"); } } @Test public void testWriteNull() throws IOException { File file = folder.newFile(); try (FileResultWriter<String> resultWriter = new FileResultWriter<>(file)) { resultWriter.receiveResult(null); } try (BufferedReader in = new BufferedReader(new FileReader(file))) { assertThat(in.readLine()).isEqualTo(Objects.toString(null)); } }
### Question: MultiThresholdProvider implements ThresholdProvider { @Override public OptionalDouble getNext(int attr, double threshold) { checkElementIndex(attr, providers.length); return providers[attr].getNext(threshold); } static ThresholdProvider create(Iterable<? extends Iterable<Double>> thresholds); @Override List<DoubleSortedSet> getAll(); @Override OptionalDouble getNext(int attr, double threshold); }### Answer: @Test public void testGetNext() { List<DoubleSet> similarities = Arrays .asList(new DoubleOpenHashSet(Sets.newHashSet(Double.valueOf(0.7), Double.valueOf(0.6))), new DoubleOpenHashSet(Sets.newHashSet(Double.valueOf(0.8)))); ThresholdProvider provider = create(similarities); assertThat(provider.getNext(0, 0.5).boxed()).hasValue(Double.valueOf(0.6)); assertThat(provider.getNext(0, 0.6).boxed()).hasValue(Double.valueOf(0.7)); assertThat(provider.getNext(1, 0.8).boxed()).isEmpty(); }
### Question: SelfSchemaMapper implements SchemaMapper { @Override public Collection<ColumnPair<?>> create(Schema schema) { List<Column<?>> columns = schema.getColumns(); return columns.stream() .map(SelfSchemaMapper::toPair) .collect(Collectors.toList()); } @Override Collection<ColumnPair<?>> create(Schema schema); @Override Collection<ColumnPair<?>> create(Schema schema1, Schema schema2); }### Answer: @Test public void test() { SchemaMapper schemaMapper = new SelfSchemaMapper(); List<Column<?>> columns = Arrays.asList(A, B, C); Schema schema = Schema.of(columns); when(relation.getSchema()).thenReturn(schema); Collection<ColumnPair<?>> mapping = schemaMapper.create(relation); assertThat(mapping).hasSize(3); assertThat(mapping).contains(new ColumnPair<>(A, A)); assertThat(mapping).contains(new ColumnPair<>(B, B)); assertThat(mapping).contains(new ColumnPair<>(C, C)); }
### Question: FixedSchemaMapper implements SchemaMapper { @Override public Collection<ColumnPair<?>> create(Schema schema1, Schema schema2) { List<Column<?>> columns = schema1.getColumns(); return columns.stream() .flatMap(this::getMatching) .collect(Collectors.toList()); } @Override Collection<ColumnPair<?>> create(Schema schema1, Schema schema2); }### Answer: @Test public void test() { Multimap<Column<?>, Column<?>> map = ImmutableMultimap.<Column<?>, Column<?>>builder() .put(A, B) .put(A, C) .put(B, A) .build(); SchemaMapper schemaMapper = new FixedSchemaMapper(map); List<Column<?>> columns = Arrays.asList(A, B, C); Schema schema = Schema.of(columns); when(relation.getSchema()).thenReturn(schema); Collection<ColumnPair<?>> mapping = schemaMapper.create(relation); assertThat(mapping).hasSize(3); assertThat(mapping).contains(new ColumnPair<>(A, B)); assertThat(mapping).contains(new ColumnPair<>(A, C)); assertThat(mapping).contains(new ColumnPair<>(B, A)); }
### Question: TypeSchemaMapper implements SchemaMapper { private static Collection<ColumnPair<?>> create(Iterable<Column<?>> columns1, Iterable<Column<?>> columns2) { return StreamUtils.seq(columns1).crossJoin(columns2) .map(t -> t.map(SchemaMapperHelper::toPair)) .flatMap(Optionals::stream) .collect(Collectors.toList()); } @Override Collection<ColumnPair<?>> create(Schema schema); @Override Collection<ColumnPair<?>> create(Schema schema1, Schema schema2); }### Answer: @Test public void testSingleRelation() { SchemaMapper schemaMapper = new TypeSchemaMapper(); List<Column<?>> columns = Arrays.asList(A, B, C); Schema schema = Schema.of(columns); when(relation.getSchema()).thenReturn(schema); Collection<ColumnPair<?>> mapping = schemaMapper.create(relation); assertThat(mapping).hasSize(4); assertThat(mapping).contains(new ColumnPair<>(A, A)); assertThat(mapping).contains(new ColumnPair<>(B, B)); Assert.assertThat(mapping, either(hasItem(new ColumnPair<>(A, B))).or(hasItem(new ColumnPair<>(B, A)))); assertThat(mapping).contains(new ColumnPair<>(C, C)); } @Test public void testTwoRelations() { SchemaMapper schemaMapper = new TypeSchemaMapper(); List<Column<?>> columns = Arrays.asList(A, B, C); Schema schema = Schema.of(columns); when(relation.getSchema()).thenReturn(schema); Collection<ColumnPair<?>> mapping = schemaMapper.create(relation, relation); assertThat(mapping).hasSize(5); assertThat(mapping).contains(new ColumnPair<>(A, A)); assertThat(mapping).contains(new ColumnPair<>(B, B)); assertThat(mapping).contains(new ColumnPair<>(A, B)); assertThat(mapping).contains(new ColumnPair<>(B, A)); assertThat(mapping).contains(new ColumnPair<>(C, C)); }
### Question: JCommanderRunner { public void run(String... args) { boolean success = parse(args); if (!success || needsHelp()) { printUsage(); return; } app.run(); } static JCommanderRunnerBuilder create(Application app); void run(String... args); }### Answer: @Test public void testRunWithHelp() { TestApplication app = new TestApplication(); JCommanderRunner runner = createRunner(app); runner.run("--help"); assertThat(app.ran).isFalse(); } @Test public void testRunWithRequired() { TestApplication app = new TestApplication(); JCommanderRunner runner = createRunner(app); runner.run("-r"); assertThat(app.ran).isTrue(); } @Test public void testRunWithoutRequired() { TestApplication app = new TestApplication(); JCommanderRunner runner = createRunner(app); runner.run(); assertThat(app.ran).isFalse(); }
### Question: FDTree extends FDTreeElement { public void addFunctionalDependency(BitSet lhs, int a) { FDTreeElement fdTreeEl; FDTreeElement currentNode = this; currentNode.addRhsAttribute(a); for (int i = lhs.nextSetBit(0); i >= 0; i = lhs.nextSetBit(i + 1)) { if (currentNode.children[i - 1] == null) { fdTreeEl = new FDTreeElement(maxAttributeNumber); currentNode.children[i - 1] = fdTreeEl; } currentNode = currentNode.getChild(i - 1); currentNode.addRhsAttribute(a); } currentNode.markAsLastVertex(a - 1); } FDTree(int maxAttributeNumber); void addMostGeneralDependencies(); void addFunctionalDependency(BitSet lhs, int a); boolean isEmpty(); void filterSpecializations(); void filterGeneralizations(); void printDependencies(); }### Answer: @Test public void testContainsSpezialization() { FDTree fdtree = new FDTree(5); BitSet lhs = new BitSet(); lhs.set(1); lhs.set(3); lhs.set(5); fdtree.addFunctionalDependency(lhs, 4); lhs.clear(1); lhs.set(2); fdtree.addFunctionalDependency(lhs, 4); lhs.clear(3); boolean result = fdtree.containsSpecialization(lhs, 4, 0); assertTrue(result); }
### Question: Fun implements FunctionalDependencyAlgorithm, RelationalInputParameterAlgorithm { @Override public ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements() { ArrayList<ConfigurationRequirement<?>> configurationSpecifications = new ArrayList<>(); configurationSpecifications.add(new ConfigurationRequirementRelationalInput(INPUT_FILE_TAG)); return configurationSpecifications; } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setResultReceiver(FunctionalDependencyResultReceiver resultReceiver); @Override String getAuthors(); @Override String getDescription(); }### Answer: @Test public void testGetConfigurationRequirements() { assertThat(algorithm.getConfigurationRequirements(), hasItem(isA(ConfigurationRequirementRelationalInput.class))); }
### Question: Fun implements FunctionalDependencyAlgorithm, RelationalInputParameterAlgorithm { @Override public void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values) { if (identifier.equals(INPUT_FILE_TAG)) { this.inputGenerator = values[0]; } } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setResultReceiver(FunctionalDependencyResultReceiver resultReceiver); @Override String getAuthors(); @Override String getDescription(); }### Answer: @Test public void testSetConfigurationValueStringRelationalInputGenerator() { RelationalInputGenerator expectedInputGenerator = mock(RelationalInputGenerator.class); algorithm.setRelationalInputConfigurationValue(Fun.INPUT_FILE_TAG, expectedInputGenerator); assertSame(expectedInputGenerator, algorithm.inputGenerator); }
### Question: Fun implements FunctionalDependencyAlgorithm, RelationalInputParameterAlgorithm { @Override public void execute() throws InputGenerationException, InputIterationException, CouldNotReceiveResultException, AlgorithmConfigurationException, ColumnNameMismatchException { RelationalInput input = inputGenerator.generateNewCopy(); PLIBuilder pliBuilder = new PLIBuilder(input); List<PositionListIndex> pliList = pliBuilder.getPLIList(); this.fun = new FunAlgorithm(input.relationName(), input.columnNames(), this.resultReceiver); this.fun.run(pliList); } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setResultReceiver(FunctionalDependencyResultReceiver resultReceiver); @Override String getAuthors(); @Override String getDescription(); }### Answer: @Test public void testExecute() throws InputGenerationException, InputIterationException, CouldNotReceiveResultException, AlgorithmConfigurationException, ColumnNameMismatchException { AlgorithmTestFixture fixture = new AlgorithmTestFixture(); algorithm.setRelationalInputConfigurationValue(Fun.INPUT_FILE_TAG, fixture.getInputGenerator()); algorithm.setResultReceiver(fixture.getFunctionalDependencyResultReceiver()); algorithm.execute(); fixture.verifyFunctionalDependencyResultReceiver(); }
### Question: Fun implements FunctionalDependencyAlgorithm, RelationalInputParameterAlgorithm { @Override public void setResultReceiver(FunctionalDependencyResultReceiver resultReceiver) { this.resultReceiver = resultReceiver; } @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void execute(); @Override void setResultReceiver(FunctionalDependencyResultReceiver resultReceiver); @Override String getAuthors(); @Override String getDescription(); }### Answer: @Test public void testSetResultReceiverFunctionalDependencyResultReceiver() { FunctionalDependencyResultReceiver expectedResultReceiver = mock(FunctionalDependencyResultReceiver.class); algorithm.setResultReceiver(expectedResultReceiver); assertSame(expectedResultReceiver, algorithm.resultReceiver); }
### Question: HoleFinder { public void update(ColumnCombinationBitset maximalNegative) { ColumnCombinationBitset singleComplementMaxNegative = this.allBitsSet.minus(maximalNegative); if (this.complementarySet.size() == 0) { for (ColumnCombinationBitset combination : singleComplementMaxNegative.getContainedOneColumnCombinations()) { this.complementarySet.add(combination); } return; } ArrayList<ColumnCombinationBitset> complementarySetsArray = new ArrayList<>(); this.addPossibleCombinationsToComplementArray(complementarySetsArray, singleComplementMaxNegative); this.removeSubsetsFromComplementarySetsArray(complementarySetsArray); this.complementarySet.clear(); for (ColumnCombinationBitset c : complementarySetsArray) { if (c != null) { this.complementarySet.add(c); } } } HoleFinder(int numberOfColumns); List<ColumnCombinationBitset> getHoles(); List<ColumnCombinationBitset> getHolesWithoutGivenColumnCombinations(Set<ColumnCombinationBitset> columnCombinationSet); void removeMinimalPositivesFromComplementarySet(List<ColumnCombinationBitset> sets); void removeMinimalPositiveFromComplementarySet(ColumnCombinationBitset set); void update(ColumnCombinationBitset maximalNegative); }### Answer: @Test public void testUpdateFirst() { HoleFinder finder = new HoleFinder(5); ColumnCombinationBitset mNUCC = new ColumnCombinationBitset(1, 3, 4); finder.update(mNUCC); ColumnCombinationBitset oneColumn0 = new ColumnCombinationBitset(0); ColumnCombinationBitset oneColumn2 = new ColumnCombinationBitset(2); assertEquals(2, finder.complementarySet.size()); assertTrue(finder.complementarySet.contains(oneColumn0)); assertTrue(finder.complementarySet.contains(oneColumn2)); } @Test public void testUpdateAllOther() { HoleFinder finder = new HoleFinder(5); ColumnCombinationBitset firstCombi = new ColumnCombinationBitset(1, 3, 4); finder.update(firstCombi); ColumnCombinationBitset nextCombi = new ColumnCombinationBitset(2, 3, 4); finder.update(nextCombi); ColumnCombinationBitset column10000 = new ColumnCombinationBitset(0); ColumnCombinationBitset column01100 = new ColumnCombinationBitset(1, 2); ColumnCombinationBitset column10100 = new ColumnCombinationBitset(0, 2); assertEquals(2, finder.complementarySet.size()); assertTrue(finder.complementarySet.contains(column10000)); assertTrue(finder.complementarySet.contains(column01100)); assertFalse(finder.complementarySet.contains(column10100)); }
### Question: FunAlgorithm { protected LinkedList<FunQuadruple> generateCandidates(List<FunQuadruple> lk) { LinkedList<FunQuadruple> lkPlus1 = new LinkedList<>(); if (lk.isEmpty()) { return lkPlus1; } Set<ColumnCombinationBitset> subsets = new HashSet<>(); int k = lk.get(0).candidate.size(); ColumnCombinationBitset union = new ColumnCombinationBitset(); for (FunQuadruple subsetQuadruple : lk) { if (subsetQuadruple.count == 0) { continue; } union = subsetQuadruple.candidate.union(union); subsets.add(subsetQuadruple.candidate); } Map<ColumnCombinationBitset, Integer> candidateGenerationCount = new HashMap<>(); List<ColumnCombinationBitset> lkPlus1Candidates; FunQuadruple lkPlus1Member; for (ColumnCombinationBitset subset : subsets) { lkPlus1Candidates = union.getNSubsetColumnCombinationsSupersetOf( subset, k + 1); for (ColumnCombinationBitset candidate : lkPlus1Candidates) { if (candidateGenerationCount.containsKey(candidate)) { int count = candidateGenerationCount.get(candidate); count++; candidateGenerationCount.put(candidate, count); } else { candidateGenerationCount.put(candidate, 1); } } } for (ColumnCombinationBitset candidate : candidateGenerationCount .keySet()) { if (candidateGenerationCount.get(candidate) == (k + 1)) { lkPlus1Member = new FunQuadruple(candidate, addPliGenerate( candidate).getRawKeyError()); lkPlus1.add(lkPlus1Member); } } return lkPlus1; } FunAlgorithm(String relationName, List<String> columnNames, FunctionalDependencyResultReceiver fdReceiver); FunAlgorithm(String relationName, List<String> columnNames, FunctionalDependencyResultReceiver fdReceiver, UniqueColumnCombinationResultReceiver uccReceiver); void run(List<PositionListIndex> pliList); }### Answer: @Test public void testGenerateCandidate() { FixtureCandidateGeneration fixture = new FixtureCandidateGeneration(); List<FunQuadruple> l2 = fixture.getL2(); FunAlgorithm fun = fixture.getFunAlgorithmMockedAddPliGenerate(); assertThat(fun.generateCandidates(l2), IsIterableContainingInAnyOrder.containsInAnyOrder(fixture.getExpectedL3Array())); assertThat(l2, IsIterableContainingInAnyOrder.containsInAnyOrder(fixture.getExpectedL2Array())); }
### Question: FunAlgorithm { public void run(List<PositionListIndex> pliList) throws InputIterationException, CouldNotReceiveResultException, ColumnNameMismatchException { LinkedList<FunQuadruple> lkminusOne = new LinkedList<>(); lkminusOne.add(new FunQuadruple(new ColumnCombinationBitset(), Long.MAX_VALUE, new ColumnCombinationBitset(), new ColumnCombinationBitset())); LinkedList<FunQuadruple> lk = new LinkedList<>(); for (int i = 0; i < numberOfColumns; i++) { PositionListIndex currentPli = pliList.get(i); plis.put(new ColumnCombinationBitset(i), currentPli); lk.add(new FunQuadruple( new ColumnCombinationBitset(i), currentPli .getRawKeyError(), new ColumnCombinationBitset(i), new ColumnCombinationBitset(i))); if (!currentPli.isUnique()) { rDash.addColumn(i); } } while (!lk.isEmpty()) { computeClosure(lkminusOne); computeQuasiClosure(lk, lkminusOne); displayFD(lkminusOne); purePrune(lk, lkminusOne); lkminusOne = lk; lk = generateCandidates(lk); } computeClosure(lkminusOne); displayFD(lkminusOne); } FunAlgorithm(String relationName, List<String> columnNames, FunctionalDependencyResultReceiver fdReceiver); FunAlgorithm(String relationName, List<String> columnNames, FunctionalDependencyResultReceiver fdReceiver, UniqueColumnCombinationResultReceiver uccReceiver); void run(List<PositionListIndex> pliList); }### Answer: @Test public void testYieldsAllFDsAndUCCs() throws InputIterationException, CouldNotReceiveResultException, InputGenerationException, AlgorithmConfigurationException, ColumnNameMismatchException { AlgorithmTestFixture fixture = new AlgorithmTestFixture(); RelationalInput relationalInput = fixture.getInputGenerator().generateNewCopy(); FunAlgorithm funAlgorithm = new FunAlgorithm( relationalInput.relationName(), relationalInput.columnNames(), fixture.getFunctionalDependencyResultReceiver(), fixture.getUniqueColumnCombinationResultReceiver()); funAlgorithm.run(new PLIBuilder(relationalInput).getPLIList()); fixture.verifyFunctionalDependencyResultReceiver(); fixture.verifyUniqueColumnCombinationResultReceiver(); } @Test public void testFunFastCount() throws CouldNotReceiveResultException, InputGenerationException, InputIterationException, AlgorithmConfigurationException, ColumnNameMismatchException { FunFastCountFixture fixture = new FunFastCountFixture(); RelationalInput relationalInput = fixture.getInputGenerator().generateNewCopy(); FunAlgorithm funAlgorithm = new FunAlgorithm( relationalInput.relationName(), relationalInput.columnNames(), fixture.getFunctionalDependencyResultReceiver()); funAlgorithm.run(new PLIBuilder(relationalInput).getPLIList()); fixture.verifyFunctionalDependencyResultReceiver(); }
### Question: MvDDetector extends MvDDetectorAlgorithm implements MultivaluedDependencyAlgorithm, // Defines the type of the algorithm, i.e., the result type, for instance, FunctionalDependencyAlgorithm or InclusionDependencyAlgorithm; implementing multiple types is possible RelationalInputParameterAlgorithm, // Defines the input type of the algorithm; relational input is any relational input from files or databases; more specific input specifications are possible BooleanParameterAlgorithm, IntegerParameterAlgorithm { @Override public ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements() { ArrayList<ConfigurationRequirement<?>> conf = new ArrayList<>(); conf.add(new ConfigurationRequirementRelationalInput(MvDDetector.Identifier.INPUT_GENERATOR.name())); ConfigurationRequirementInteger pruningType = new ConfigurationRequirementInteger(MvDDetector.Identifier.PRUNING_TYPE.name()); Integer[] defaultPruningType = new Integer[1]; defaultPruningType[0] = Integer.valueOf(5); pruningType.setDefaultValues(defaultPruningType); pruningType.setRequired(true); conf.add(pruningType); ConfigurationRequirementBoolean removeDuplicates = new ConfigurationRequirementBoolean(MvDDetector.Identifier.REMOVE_DUPLICATES.name()); Boolean[] defaultRemoveDuplicates = new Boolean[1]; defaultRemoveDuplicates[0] = Boolean.valueOf(true); removeDuplicates.setDefaultValues(defaultRemoveDuplicates); removeDuplicates.setRequired(true); conf.add(removeDuplicates); ConfigurationRequirementBoolean markUniqueValues = new ConfigurationRequirementBoolean(MvDDetector.Identifier.MARK_UNIQUE_VALUES.name()); Boolean[] defaultMarkUniqueValues = new Boolean[1]; defaultMarkUniqueValues[0] = Boolean.valueOf(true); markUniqueValues.setDefaultValues(defaultMarkUniqueValues); markUniqueValues.setRequired(true); conf.add(markUniqueValues); ConfigurationRequirementBoolean convertToIntTuples = new ConfigurationRequirementBoolean(MvDDetector.Identifier.CONVERT_TO_INT_TUPLES.name()); Boolean[] defaultConvertToIntTuples = new Boolean[1]; defaultConvertToIntTuples[0] = Boolean.valueOf(true); convertToIntTuples.setDefaultValues(defaultConvertToIntTuples); convertToIntTuples.setRequired(true); conf.add(convertToIntTuples); ConfigurationRequirementBoolean usePLIs = new ConfigurationRequirementBoolean(MvDDetector.Identifier.USE_PLIS.name()); Boolean[] defaultUsePLIs = new Boolean[1]; defaultUsePLIs[0] = Boolean.valueOf(true); usePLIs.setDefaultValues(defaultUsePLIs); usePLIs.setRequired(true); conf.add(usePLIs); return conf; } @Override String getAuthors(); @Override String getDescription(); @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setIntegerConfigurationValue(String identifier, Integer... values); @Override void setBooleanConfigurationValue(String identifier, Boolean... values); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void setResultReceiver(MultivaluedDependencyResultReceiver resultReceiver); @Override void execute(); }### Answer: @Test public void testGetConfigurationRequirements() { }
### Question: MvDDetector extends MvDDetectorAlgorithm implements MultivaluedDependencyAlgorithm, // Defines the type of the algorithm, i.e., the result type, for instance, FunctionalDependencyAlgorithm or InclusionDependencyAlgorithm; implementing multiple types is possible RelationalInputParameterAlgorithm, // Defines the input type of the algorithm; relational input is any relational input from files or databases; more specific input specifications are possible BooleanParameterAlgorithm, IntegerParameterAlgorithm { @Override public void execute() throws AlgorithmExecutionException { super.algorithmConfig = this.algorithmConfig; super.execute(); } @Override String getAuthors(); @Override String getDescription(); @Override ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements(); @Override void setIntegerConfigurationValue(String identifier, Integer... values); @Override void setBooleanConfigurationValue(String identifier, Boolean... values); @Override void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values); @Override void setResultReceiver(MultivaluedDependencyResultReceiver resultReceiver); @Override void execute(); }### Answer: @Test public void testExecute() { }
### Question: ResultTree { public boolean insert(Result result) { ResultTree parent = getInsertPosition(result); if (parent != null) { parent.getChildren().add(new ResultTree(result)); return true; } return false; } ResultTree(Result root); Result getNode(); void setNode(Result node); List<ResultTree> getChildren(); void setChildren(List<ResultTree> children); boolean insert(Result result); ResultTree getInsertPosition(Result result); boolean contains(BitSet lhs, int rhs); List<Result> getLeaves(); }### Answer: @Test public void testInsertNotPossibleForDifferentRhs() { Result node = mockResult(mockFD(new int[]{0, 4, 7, 9}, 3)); Result child = mockResult(mockFD(new int[]{4, 7, 9}, 3)); Result offendingResult = mockResult(mockFD(new int[] {4, 7}, 1)); ResultTree tree = new ResultTree(node); tree.insert(child); boolean inserted = tree.insert(offendingResult); Assert.assertFalse(inserted); } @Test public void testInsertNotPossibleForNonDescendants() { Result node = mockResult(mockFD(new int[]{0, 4, 7, 9}, 3)); Result child = mockResult(mockFD(new int[]{4, 7, 9}, 3)); Result offendingResult = mockResult(mockFD(new int[] {5, 7}, 3)); ResultTree tree = new ResultTree(node); tree.insert(child); boolean inserted = tree.insert(offendingResult); Assert.assertFalse(inserted); }